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
1302b24ece5f3ad2094546cf57109ca68790d45f
d751a70f46ed26dc0111a87f5bbe83e5c6648904
/Code/src/topo.lean
ab54f1477604d7c4a3d1cefadf2476a45fabb8d5
[]
no_license
marcusrossel/bachelors-thesis
92cb12ae8436c10fbfab9bfe4929a0081e615b37
d1ec2c2b5c3c6700a506f2e3cc93f1160e44b422
refs/heads/main
1,682,873,547,703
1,619,795,735,000
1,619,795,735,000
306,041,494
2
0
null
null
null
null
UTF-8
Lean
false
false
3,438
lean
import lgraph import mathlib variables {ι δ ε : Type*} variables [decidable_eq ι] [decidable_eq δ] [lgraph.edge ε ι] -- The definition of what it means for a given list to be a topological ordering for a given graph. -- Note that this is not the same as a "complete" topological ordering (`list.is_complete_topo_over`). def list.is_topo_over (l : list ι) (g : lgraph ι δ ε) : Prop := l.nodup ∧ ∀ i i' ∈ l, (i~g~>i') → (l.index_of i < l.index_of i') namespace topo -- Removing an element from a topological ordering does not break the property of it being a topological ordering. lemma erase_is_topo (i : ι) {t : list ι} {g : lgraph ι δ ε} (h : t.is_topo_over g) : (t.erase i).is_topo_over g := begin unfold list.is_topo_over at h ⊢, split, exact list.nodup_erase_of_nodup _ h.left, { intros x x' hₓ hₓ' hₚ, have hᵢ, from h.right x x' (list.mem_of_mem_erase hₓ) (list.mem_of_mem_erase hₓ') hₚ, exact list.index_of_erase_lt hᵢ hₓ hₓ' h.left } end -- If a list is a topological ordering for some graph, then so is its tail. lemma cons_is_topo {hd : ι} {tl : list ι} {g : lgraph ι δ ε} (h : (hd :: tl).is_topo_over g) : tl.is_topo_over g := begin rw ←list.erase_cons_head hd tl, exact erase_is_topo hd h end end topo -- A topological ordering is "complete" if it contains all of its graph's vertices. def list.is_complete_topo_over (l : list ι) (g : lgraph ι δ ε) : Prop := l.is_topo_over g ∧ ∀ i : ι, i ∈ l ↔ i ∈ g namespace topo -- Complete topological orderings are permutations of each other. lemma complete_perm {g : lgraph ι δ ε} {l l' : list ι} (h : l.is_complete_topo_over g) (h' : l'.is_complete_topo_over g) : l ~ l' := begin rw list.perm_ext h.left.left h'.left.left, intro x, unfold list.is_complete_topo_over at h h', rw [h.right x, h'.right x] end -- An item `i` in a topological ordering is independent if the corresponding graph contains no path -- that starts with an element in the ordering and ends in `i`. def indep (i : ι) (t : list ι) (g : lgraph ι δ ε) : Prop := ∀ i' ∈ t, ¬(i'~g~>i) -- The head of a topological ordering is always independent. lemma indep_head (hd : ι) (tl : list ι) {g : lgraph ι δ ε} (h : (hd :: tl).is_topo_over g) : indep hd (hd :: tl) g := begin unfold indep, unfold list.is_topo_over at h, intros x hₓ, by_contradiction hc, have hᵢ, from h.right x hd hₓ (list.mem_cons_self hd tl) hc, rw list.index_of_cons_self hd tl at hᵢ, exact nat.not_lt_zero _ hᵢ end -- If an element is independent in a list, then it is also independent in its tail. lemma indep_cons {i hd : ι} {tl : list ι} {g : lgraph ι δ ε} (h : indep i (hd :: tl) g) : indep i tl g := begin unfold indep at h ⊢, intros x hₓ, exact h x (list.mem_cons_of_mem _ hₓ) end -- If an element is independent in a list, then if is also independent in a permutation of that list. lemma indep_perm {i : ι} {t t' : list ι} {g : lgraph ι δ ε} (hₚ : t ~ t') (hᵢ : indep i t g) : indep i t' g := begin unfold indep at hᵢ ⊢, intros x hₓ, have hₘ, from (list.perm.mem_iff hₚ).mpr hₓ, exact hᵢ x hₘ end end topo
0d8edd8387ec72368133a1583301ab2c240304cb
9dc8cecdf3c4634764a18254e94d43da07142918
/src/logic/relation.lean
7a86397f898919e0f8b1cd6c7bae2f0ed406a81c
[ "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
21,590
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import tactic.basic import logic.relator /-! # Relation closures This file defines the reflexive, transitive, and reflexive transitive closures of relations. It also proves some basic results on definitions in core, such as `eqv_gen`. Note that this is about unbundled relations, that is terms of types of the form `α → β → Prop`. For the bundled version, see `rel`. ## Definitions * `relation.refl_gen`: Reflexive closure. `refl_gen r` relates everything `r` related, plus for all `a` it relates `a` with itself. So `refl_gen r a b ↔ r a b ∨ a = b`. * `relation.trans_gen`: Transitive closure. `trans_gen r` relates everything `r` related transitively. So `trans_gen r a b ↔ ∃ x₀ ... xₙ, r a x₀ ∧ r x₀ x₁ ∧ ... ∧ r xₙ b`. * `relation.refl_trans_gen`: Reflexive transitive closure. `refl_trans_gen r` relates everything `r` related transitively, plus for all `a` it relates `a` with itself. So `refl_trans_gen r a b ↔ (∃ x₀ ... xₙ, r a x₀ ∧ r x₀ x₁ ∧ ... ∧ r xₙ b) ∨ a = b`. It is the same as the reflexive closure of the transitive closure, or the transitive closure of the reflexive closure. In terms of rewriting systems, this means that `a` can be rewritten to `b` in a number of rewrites. * `relation.comp`: Relation composition. We provide notation `∘r`. For `r : α → β → Prop` and `s : β → γ → Prop`, `r ∘r s`relates `a : α` and `c : γ` iff there exists `b : β` that's related to both. * `relation.map`: Image of a relation under a pair of maps. For `r : α → β → Prop`, `f : α → γ`, `g : β → δ`, `map r f g` is the relation `γ → δ → Prop` relating `f a` and `g b` for all `a`, `b` related by `r`. * `relation.join`: Join of a relation. For `r : α → α → Prop`, `join r a b ↔ ∃ c, r a c ∧ r b c`. In terms of rewriting systems, this means that `a` and `b` can be rewritten to the same term. -/ open function variables {α β γ δ : Type*} section ne_imp variable {r : α → α → Prop} lemma is_refl.reflexive [is_refl α r] : reflexive r := λ x, is_refl.refl x /-- To show a reflexive relation `r : α → α → Prop` holds over `x y : α`, it suffices to show it holds when `x ≠ y`. -/ lemma reflexive.rel_of_ne_imp (h : reflexive r) {x y : α} (hr : x ≠ y → r x y) : r x y := begin by_cases hxy : x = y, { exact hxy ▸ h x }, { exact hr hxy } end /-- If a reflexive relation `r : α → α → Prop` holds over `x y : α`, then it holds whether or not `x ≠ y`. -/ lemma reflexive.ne_imp_iff (h : reflexive r) {x y : α} : (x ≠ y → r x y) ↔ r x y := ⟨h.rel_of_ne_imp, λ hr _, hr⟩ /-- If a reflexive relation `r : α → α → Prop` holds over `x y : α`, then it holds whether or not `x ≠ y`. Unlike `reflexive.ne_imp_iff`, this uses `[is_refl α r]`. -/ lemma reflexive_ne_imp_iff [is_refl α r] {x y : α} : (x ≠ y → r x y) ↔ r x y := is_refl.reflexive.ne_imp_iff protected lemma symmetric.iff (H : symmetric r) (x y : α) : r x y ↔ r y x := ⟨λ h, H h, λ h, H h⟩ lemma symmetric.flip_eq (h : symmetric r) : flip r = r := funext₂ $ λ _ _, propext $ h.iff _ _ lemma symmetric.swap_eq : symmetric r → swap r = r := symmetric.flip_eq lemma flip_eq_iff : flip r = r ↔ symmetric r := ⟨λ h x y, (congr_fun₂ h _ _).mp, symmetric.flip_eq⟩ lemma swap_eq_iff : swap r = r ↔ symmetric r := flip_eq_iff end ne_imp section comap variables {r : β → β → Prop} lemma reflexive.comap (h : reflexive r) (f : α → β) : reflexive (r on f) := λ a, h (f a) lemma symmetric.comap (h : symmetric r) (f : α → β) : symmetric (r on f) := λ a b hab, h hab lemma transitive.comap (h : transitive r) (f : α → β) : transitive (r on f) := λ a b c hab hbc, h hab hbc lemma equivalence.comap (h : equivalence r) (f : α → β) : equivalence (r on f) := ⟨h.1.comap f, h.2.1.comap f, h.2.2.comap f⟩ end comap namespace relation section comp variables {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop} /-- The composition of two relations, yielding a new relation. The result relates a term of `α` and a term of `γ` if there is an intermediate term of `β` related to both. -/ def comp (r : α → β → Prop) (p : β → γ → Prop) (a : α) (c : γ) : Prop := ∃ b, r a b ∧ p b c local infixr ` ∘r ` : 80 := relation.comp lemma comp_eq : r ∘r (=) = r := funext $ λ a, funext $ λ b, propext $ iff.intro (λ ⟨c, h, eq⟩, eq ▸ h) (λ h, ⟨b, h, rfl⟩) lemma eq_comp : (=) ∘r r = r := funext $ λ a, funext $ λ b, propext $ iff.intro (λ ⟨c, eq, h⟩, eq.symm ▸ h) (λ h, ⟨a, rfl, h⟩) lemma iff_comp {r : Prop → α → Prop} : (↔) ∘r r = r := have (↔) = (=), by funext a b; exact iff_eq_eq, by rw [this, eq_comp] lemma comp_iff {r : α → Prop → Prop} : r ∘r (↔) = r := have (↔) = (=), by funext a b; exact iff_eq_eq, by rw [this, comp_eq] lemma comp_assoc : (r ∘r p) ∘r q = r ∘r p ∘r q := begin funext a d, apply propext, split, exact λ ⟨c, ⟨b, hab, hbc⟩, hcd⟩, ⟨b, hab, c, hbc, hcd⟩, exact λ ⟨b, hab, c, hbc, hcd⟩, ⟨c, ⟨b, hab, hbc⟩, hcd⟩ end lemma flip_comp : flip (r ∘r p) = (flip p) ∘r (flip r) := begin funext c a, apply propext, split, exact λ ⟨b, hab, hbc⟩, ⟨b, hbc, hab⟩, exact λ ⟨b, hbc, hab⟩, ⟨b, hab, hbc⟩ end end comp /-- The map of a relation `r` through a pair of functions pushes the relation to the codomains of the functions. The resulting relation is defined by having pairs of terms related if they have preimages related by `r`. -/ protected def map (r : α → β → Prop) (f : α → γ) (g : β → δ) : γ → δ → Prop := λ c d, ∃ a b, r a b ∧ f a = c ∧ g b = d variables {r : α → α → Prop} {a b c d : α} /-- `refl_trans_gen r`: reflexive transitive closure of `r` -/ @[mk_iff relation.refl_trans_gen.cases_tail_iff] inductive refl_trans_gen (r : α → α → Prop) (a : α) : α → Prop | refl : refl_trans_gen a | tail {b c} : refl_trans_gen b → r b c → refl_trans_gen c attribute [refl] refl_trans_gen.refl /-- `refl_gen r`: reflexive closure of `r` -/ @[mk_iff] inductive refl_gen (r : α → α → Prop) (a : α) : α → Prop | refl : refl_gen a | single {b} : r a b → refl_gen b /-- `trans_gen r`: transitive closure of `r` -/ @[mk_iff] inductive trans_gen (r : α → α → Prop) (a : α) : α → Prop | single {b} : r a b → trans_gen b | tail {b c} : trans_gen b → r b c → trans_gen c attribute [refl] refl_gen.refl namespace refl_gen lemma to_refl_trans_gen : ∀ {a b}, refl_gen r a b → refl_trans_gen r a b | a _ refl := by refl | a b (single h) := refl_trans_gen.tail refl_trans_gen.refl h lemma mono {p : α → α → Prop} (hp : ∀ a b, r a b → p a b) : ∀ {a b}, refl_gen r a b → refl_gen p a b | a _ refl_gen.refl := by refl | a b (single h) := single (hp a b h) instance : is_refl α (refl_gen r) := ⟨@refl α r⟩ end refl_gen namespace refl_trans_gen @[trans] lemma trans (hab : refl_trans_gen r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := begin induction hbc, case refl_trans_gen.refl { assumption }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma single (hab : r a b) : refl_trans_gen r a b := refl.tail hab lemma head (hab : r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := begin induction hbc, case refl_trans_gen.refl { exact refl.tail hab }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma symmetric (h : symmetric r) : symmetric (refl_trans_gen r) := begin intros x y h, induction h with z w a b c, { refl }, { apply relation.refl_trans_gen.head (h b) c } end lemma cases_tail : refl_trans_gen r a b → b = a ∨ (∃ c, refl_trans_gen r a c ∧ r c b) := (cases_tail_iff r a b).1 @[elab_as_eliminator] lemma head_induction_on {P : ∀ (a:α), refl_trans_gen r a b → Prop} {a : α} (h : refl_trans_gen r a b) (refl : P b refl) (head : ∀ {a c} (h' : r a c) (h : refl_trans_gen r c b), P c h → P a (h.head h')) : P a h := begin induction h generalizing P, case refl_trans_gen.refl { exact refl }, case refl_trans_gen.tail : b c hab hbc ih { apply ih, show P b _, from head hbc _ refl, show ∀ a a', r a a' → refl_trans_gen r a' b → P a' _ → P a _, from λ a a' hab hbc, head hab _ } end @[elab_as_eliminator] lemma trans_induction_on {P : ∀ {a b : α}, refl_trans_gen r a b → Prop} {a b : α} (h : refl_trans_gen r a b) (ih₁ : ∀ a, @P a a refl) (ih₂ : ∀ {a b} (h : r a b), P (single h)) (ih₃ : ∀ {a b c} (h₁ : refl_trans_gen r a b) (h₂ : refl_trans_gen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) : P h := begin induction h, case refl_trans_gen.refl { exact ih₁ a }, case refl_trans_gen.tail : b c hab hbc ih { exact ih₃ hab (single hbc) ih (ih₂ hbc) } end lemma cases_head (h : refl_trans_gen r a b) : a = b ∨ (∃ c, r a c ∧ refl_trans_gen r c b) := begin induction h using relation.refl_trans_gen.head_induction_on, { left, refl }, { right, existsi _, split; assumption } end lemma cases_head_iff : refl_trans_gen r a b ↔ a = b ∨ (∃ c, r a c ∧ refl_trans_gen r c b) := begin use cases_head, rintro (rfl | ⟨c, hac, hcb⟩), { refl }, { exact head hac hcb } end lemma total_of_right_unique (U : relator.right_unique r) (ab : refl_trans_gen r a b) (ac : refl_trans_gen r a c) : refl_trans_gen r b c ∨ refl_trans_gen r c b := begin induction ab with b d ab bd IH, { exact or.inl ac }, { rcases IH with IH | IH, { rcases cases_head IH with rfl | ⟨e, be, ec⟩, { exact or.inr (single bd) }, { cases U bd be, exact or.inl ec } }, { exact or.inr (IH.tail bd) } } end end refl_trans_gen namespace trans_gen lemma to_refl {a b} (h : trans_gen r a b) : refl_trans_gen r a b := begin induction h with b h b c _ bc ab, exact refl_trans_gen.single h, exact refl_trans_gen.tail ab bc end @[trans] lemma trans_left (hab : trans_gen r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c := begin induction hbc, case refl_trans_gen.refl : { assumption }, case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end @[trans] lemma trans (hab : trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c := trans_left hab hbc.to_refl lemma head' (hab : r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c := trans_left (single hab) hbc lemma tail' (hab : refl_trans_gen r a b) (hbc : r b c) : trans_gen r a c := begin induction hab generalizing c, case refl_trans_gen.refl : c hac { exact single hac }, case refl_trans_gen.tail : d b hab hdb IH { exact tail (IH hdb) hbc } end lemma head (hab : r a b) (hbc : trans_gen r b c) : trans_gen r a c := head' hab hbc.to_refl @[elab_as_eliminator] lemma head_induction_on {P : ∀ (a:α), trans_gen r a b → Prop} {a : α} (h : trans_gen r a b) (base : ∀ {a} (h : r a b), P a (single h)) (ih : ∀ {a c} (h' : r a c) (h : trans_gen r c b), P c h → P a (h.head h')) : P a h := begin induction h generalizing P, case single : a h { exact base h }, case tail : b c hab hbc h_ih { apply h_ih, show ∀ a, r a b → P a _, from λ a h, ih h (single hbc) (base hbc), show ∀ a a', r a a' → trans_gen r a' b → P a' _ → P a _, from λ a a' hab hbc, ih hab _ } end @[elab_as_eliminator] lemma trans_induction_on {P : ∀ {a b : α}, trans_gen r a b → Prop} {a b : α} (h : trans_gen r a b) (base : ∀ {a b} (h : r a b), P (single h)) (ih : ∀ {a b c} (h₁ : trans_gen r a b) (h₂ : trans_gen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) : P h := begin induction h, case single : a h { exact base h }, case tail : b c hab hbc h_ih { exact ih hab (single hbc) h_ih (base hbc) } end @[trans] lemma trans_right (hab : refl_trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c := begin induction hbc, case trans_gen.single : c hbc { exact tail' hab hbc }, case trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd } end lemma tail'_iff : trans_gen r a c ↔ ∃ b, refl_trans_gen r a b ∧ r b c := begin refine ⟨λ h, _, λ ⟨b, hab, hbc⟩, tail' hab hbc⟩, cases h with _ hac b _ hab hbc, { exact ⟨_, by refl, hac⟩ }, { exact ⟨_, hab.to_refl, hbc⟩ } end lemma head'_iff : trans_gen r a c ↔ ∃ b, r a b ∧ refl_trans_gen r b c := begin refine ⟨λ h, _, λ ⟨b, hab, hbc⟩, head' hab hbc⟩, induction h, case trans_gen.single : c hac { exact ⟨_, hac, by refl⟩ }, case trans_gen.tail : b c hab hbc IH { rcases IH with ⟨d, had, hdb⟩, exact ⟨_, had, hdb.tail hbc⟩ } end end trans_gen lemma _root_.acc.trans_gen {α} {r : α → α → Prop} {a : α} (h : acc r a) : acc (trans_gen r) a := begin induction h with x _ H, refine acc.intro x (λ y hy, _), cases hy with _ hyx z _ hyz hzx, exacts [H y hyx, (H z hzx).inv hyz], end lemma _root_.well_founded.trans_gen {α} {r : α → α → Prop} (h : well_founded r) : well_founded (trans_gen r) := ⟨λ a, (h.apply a).trans_gen⟩ section trans_gen lemma trans_gen_eq_self (trans : transitive r) : trans_gen r = r := funext $ λ a, funext $ λ b, propext $ ⟨λ h, begin induction h, case trans_gen.single : c hc { exact hc }, case trans_gen.tail : c d hac hcd hac { exact trans hac hcd } end, trans_gen.single⟩ lemma transitive_trans_gen : transitive (trans_gen r) := λ a b c, trans_gen.trans instance : is_trans α (trans_gen r) := ⟨@trans_gen.trans α r⟩ lemma trans_gen_idem : trans_gen (trans_gen r) = trans_gen r := trans_gen_eq_self transitive_trans_gen lemma trans_gen.lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → p (f a) (f b)) (hab : trans_gen r a b) : trans_gen p (f a) (f b) := begin induction hab, case trans_gen.single : c hac { exact trans_gen.single (h a c hac) }, case trans_gen.tail : c d hac hcd hac { exact trans_gen.tail hac (h c d hcd) } end lemma trans_gen.lift' {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → trans_gen p (f a) (f b)) (hab : trans_gen r a b) : trans_gen p (f a) (f b) := by simpa [trans_gen_idem] using hab.lift f h lemma trans_gen.closed {p : α → α → Prop} : (∀ a b, r a b → trans_gen p a b) → trans_gen r a b → trans_gen p a b := trans_gen.lift' id lemma trans_gen.mono {p : α → α → Prop} : (∀ a b, r a b → p a b) → trans_gen r a b → trans_gen p a b := trans_gen.lift id lemma trans_gen.swap (h : trans_gen r b a) : trans_gen (swap r) a b := by { induction h with b h b c hab hbc ih, { exact trans_gen.single h }, exact ih.head hbc } lemma trans_gen_swap : trans_gen (swap r) a b ↔ trans_gen r b a := ⟨trans_gen.swap, trans_gen.swap⟩ end trans_gen section refl_trans_gen open refl_trans_gen lemma refl_trans_gen_iff_eq (h : ∀ b, ¬ r a b) : refl_trans_gen r a b ↔ b = a := by rw [cases_head_iff]; simp [h, eq_comm] lemma refl_trans_gen_iff_eq_or_trans_gen : refl_trans_gen r a b ↔ b = a ∨ trans_gen r a b := begin refine ⟨λ h, _, λ h, _⟩, { cases h with c _ hac hcb, { exact or.inl rfl }, { exact or.inr (trans_gen.tail' hac hcb) } }, { rcases h with rfl | h, {refl}, {exact h.to_refl} } end lemma refl_trans_gen.lift {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) := refl_trans_gen.trans_induction_on hab (λ a, refl) (λ a b, refl_trans_gen.single ∘ h _ _) (λ a b c _ _, trans) lemma refl_trans_gen.mono {p : α → α → Prop} : (∀ a b, r a b → p a b) → refl_trans_gen r a b → refl_trans_gen p a b := refl_trans_gen.lift id lemma refl_trans_gen_eq_self (refl : reflexive r) (trans : transitive r) : refl_trans_gen r = r := funext $ λ a, funext $ λ b, propext $ ⟨λ h, begin induction h with b c h₁ h₂ IH, {apply refl}, exact trans IH h₂, end, single⟩ lemma reflexive_refl_trans_gen : reflexive (refl_trans_gen r) := λ a, refl lemma transitive_refl_trans_gen : transitive (refl_trans_gen r) := λ a b c, trans instance : is_refl α (refl_trans_gen r) := ⟨@refl_trans_gen.refl α r⟩ instance : is_trans α (refl_trans_gen r) := ⟨@refl_trans_gen.trans α r⟩ lemma refl_trans_gen_idem : refl_trans_gen (refl_trans_gen r) = refl_trans_gen r := refl_trans_gen_eq_self reflexive_refl_trans_gen transitive_refl_trans_gen lemma refl_trans_gen.lift' {p : β → β → Prop} {a b : α} (f : α → β) (h : ∀ a b, r a b → refl_trans_gen p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) := by simpa [refl_trans_gen_idem] using hab.lift f h lemma refl_trans_gen_closed {p : α → α → Prop} : (∀ a b, r a b → refl_trans_gen p a b) → refl_trans_gen r a b → refl_trans_gen p a b := refl_trans_gen.lift' id lemma refl_trans_gen.swap (h : refl_trans_gen r b a) : refl_trans_gen (swap r) a b := by { induction h with b c hab hbc ih, { refl }, exact ih.head hbc } lemma refl_trans_gen_swap : refl_trans_gen (swap r) a b ↔ refl_trans_gen r b a := ⟨refl_trans_gen.swap, refl_trans_gen.swap⟩ end refl_trans_gen /-- The join of a relation on a single type is a new relation for which pairs of terms are related if there is a third term they are both related to. For example, if `r` is a relation representing rewrites in a term rewriting system, then *confluence* is the property that if `a` rewrites to both `b` and `c`, then `join r` relates `b` and `c` (see `relation.church_rosser`). -/ def join (r : α → α → Prop) : α → α → Prop := λ a b, ∃ c, r a c ∧ r b c section join open refl_trans_gen refl_gen /-- A sufficient condition for the Church-Rosser property. -/ lemma church_rosser (h : ∀ a b c, r a b → r a c → ∃ d, refl_gen r b d ∧ refl_trans_gen r c d) (hab : refl_trans_gen r a b) (hac : refl_trans_gen r a c) : join (refl_trans_gen r) b c := begin induction hab, case refl_trans_gen.refl { exact ⟨c, hac, refl⟩ }, case refl_trans_gen.tail : d e had hde ih { clear hac had a, rcases ih with ⟨b, hdb, hcb⟩, have : ∃ a, refl_trans_gen r e a ∧ refl_gen r b a, { clear hcb, induction hdb, case refl_trans_gen.refl { exact ⟨e, refl, refl_gen.single hde⟩ }, case refl_trans_gen.tail : f b hdf hfb ih { rcases ih with ⟨a, hea, hfa⟩, cases hfa with _ hfa, { exact ⟨b, hea.tail hfb, refl_gen.refl⟩ }, { rcases h _ _ _ hfb hfa with ⟨c, hbc, hac⟩, exact ⟨c, hea.trans hac, hbc⟩ } } }, rcases this with ⟨a, hea, hba⟩, cases hba with _ hba, { exact ⟨b, hea, hcb⟩ }, { exact ⟨a, hea, hcb.tail hba⟩ } } end lemma join_of_single (h : reflexive r) (hab : r a b) : join r a b := ⟨b, hab, h b⟩ lemma symmetric_join : symmetric (join r) := λ a b ⟨c, hac, hcb⟩, ⟨c, hcb, hac⟩ lemma reflexive_join (h : reflexive r) : reflexive (join r) := λ a, ⟨a, h a, h a⟩ lemma transitive_join (ht : transitive r) (h : ∀ a b c, r a b → r a c → join r b c) : transitive (join r) := λ a b c ⟨x, hax, hbx⟩ ⟨y, hby, hcy⟩, let ⟨z, hxz, hyz⟩ := h b x y hbx hby in ⟨z, ht hax hxz, ht hcy hyz⟩ lemma equivalence_join (hr : reflexive r) (ht : transitive r) (h : ∀ a b c, r a b → r a c → join r b c) : equivalence (join r) := ⟨reflexive_join hr, symmetric_join, transitive_join ht h⟩ lemma equivalence_join_refl_trans_gen (h : ∀ a b c, r a b → r a c → ∃ d, refl_gen r b d ∧ refl_trans_gen r c d) : equivalence (join (refl_trans_gen r)) := equivalence_join reflexive_refl_trans_gen transitive_refl_trans_gen (λ a b c, church_rosser h) lemma join_of_equivalence {r' : α → α → Prop} (hr : equivalence r) (h : ∀ a b, r' a b → r a b) : join r' a b → r a b | ⟨c, hac, hbc⟩ := hr.2.2 (h _ _ hac) (hr.2.1 $ h _ _ hbc) lemma refl_trans_gen_of_transitive_reflexive {r' : α → α → Prop} (hr : reflexive r) (ht : transitive r) (h : ∀ a b, r' a b → r a b) (h' : refl_trans_gen r' a b) : r a b := begin induction h' with b c hab hbc ih, { exact hr _ }, { exact ht ih (h _ _ hbc) } end lemma refl_trans_gen_of_equivalence {r' : α → α → Prop} (hr : equivalence r) : (∀ a b, r' a b → r a b) → refl_trans_gen r' a b → r a b := refl_trans_gen_of_transitive_reflexive hr.1 hr.2.2 end join end relation section eqv_gen variables {r : α → α → Prop} {a b : α} lemma equivalence.eqv_gen_iff (h : equivalence r) : eqv_gen r a b ↔ r a b := iff.intro begin intro h, induction h, case eqv_gen.rel { assumption }, case eqv_gen.refl { exact h.1 _ }, case eqv_gen.symm { apply h.2.1, assumption }, case eqv_gen.trans : a b c _ _ hab hbc { exact h.2.2 hab hbc } end (eqv_gen.rel a b) lemma equivalence.eqv_gen_eq (h : equivalence r) : eqv_gen r = r := funext $ λ _, funext $ λ _, propext $ h.eqv_gen_iff lemma eqv_gen.mono {r p : α → α → Prop} (hrp : ∀ a b, r a b → p a b) (h : eqv_gen r a b) : eqv_gen p a b := begin induction h, case eqv_gen.rel : a b h { exact eqv_gen.rel _ _ (hrp _ _ h) }, case eqv_gen.refl : { exact eqv_gen.refl _ }, case eqv_gen.symm : a b h ih { exact eqv_gen.symm _ _ ih }, case eqv_gen.trans : a b c ih1 ih2 hab hbc { exact eqv_gen.trans _ _ _ hab hbc } end end eqv_gen
d346ed138fd93a649339f1bef4856bd1e29e3092
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/filtered_colimit_commutes_finite_limit.lean
c31d3a8a162f3376a9524ab3f7d468412cb95b24
[ "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
16,877
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.colimit_limit import category_theory.limits.preserves.functor_category import category_theory.limits.preserves.finite import category_theory.limits.shapes.finite_limits import category_theory.limits.preserves.filtered import category_theory.concrete_category.basic /-! # Filtered colimits commute with finite limits. We show that for a functor `F : J × K ⥤ Type v`, when `J` is finite and `K` is filtered, the universal morphism `colimit_limit_to_limit_colimit F` comparing the colimit (over `K`) of the limits (over `J`) with the limit of the colimits is an isomorphism. (In fact, to prove that it is injective only requires that `J` has finitely many objects.) ## References * Borceux, Handbook of categorical algebra 1, Theorem 2.13.4 * [Stacks: Filtered colimits](https://stacks.math.columbia.edu/tag/002W) -/ universes v u open category_theory open category_theory.category open category_theory.limits.types open category_theory.limits.types.filtered_colimit namespace category_theory.limits variables {J K : Type v} [small_category J] [small_category K] variables (F : J × K ⥤ Type v) open category_theory.prod variables [is_filtered K] section /-! Injectivity doesn't need that we have finitely many morphisms in `J`, only that there are finitely many objects. -/ variables [fintype J] /-- This follows this proof from * Borceux, Handbook of categorical algebra 1, Theorem 2.13.4 -/ lemma colimit_limit_to_limit_colimit_injective : function.injective (colimit_limit_to_limit_colimit F) := begin classical, -- Suppose we have two terms `x y` in the colimit (over `K`) of the limits (over `J`), -- and that these have the same image under `colimit_limit_to_limit_colimit F`. intros x y h, -- These elements of the colimit have representatives somewhere: obtain ⟨kx, x, rfl⟩ := jointly_surjective'.{v v} x, obtain ⟨ky, y, rfl⟩ := jointly_surjective'.{v v} y, dsimp at x y, -- Since the images of `x` and `y` are equal in a limit, they are equal componentwise -- (indexed by `j : J`), replace h := λ j, congr_arg (limit.π ((curry.obj F) ⋙ colim) j) h, -- and they are equations in a filtered colimit, -- so for each `j` we have some place `k j` to the right of both `kx` and `ky` simp [colimit_eq_iff.{v v}] at h, let k := λ j, (h j).some, let f : Π j, kx ⟶ k j := λ j, (h j).some_spec.some, let g : Π j, ky ⟶ k j := λ j, (h j).some_spec.some_spec.some, -- where the images of the components of the representatives become equal: have w : Π j, F.map ((𝟙 j, f j) : (j, kx) ⟶ (j, k j)) (limit.π ((curry.obj (swap K J ⋙ F)).obj kx) j x) = F.map ((𝟙 j, g j) : (j, ky) ⟶ (j, k j)) (limit.π ((curry.obj (swap K J ⋙ F)).obj ky) j y) := λ j, (h j).some_spec.some_spec.some_spec, -- We now use that `K` is filtered, picking some point to the right of all these -- morphisms `f j` and `g j`. let O : finset K := (finset.univ).image k ∪ {kx, ky}, have kxO : kx ∈ O := finset.mem_union.mpr (or.inr (by simp)), have kyO : ky ∈ O := finset.mem_union.mpr (or.inr (by simp)), have kjO : ∀ j, k j ∈ O := λ j, finset.mem_union.mpr (or.inl (by simp)), let H : finset (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := (finset.univ).image (λ j : J, ⟨kx, k j, kxO, finset.mem_union.mpr (or.inl (by simp)), f j⟩) ∪ (finset.univ).image (λ j : J, ⟨ky, k j, kyO, finset.mem_union.mpr (or.inl (by simp)), g j⟩), obtain ⟨S, T, W⟩ := is_filtered.sup_exists O H, have fH : ∀ j, (⟨kx, k j, kxO, kjO j, f j⟩ : (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H := λ j, (finset.mem_union.mpr (or.inl begin simp only [true_and, finset.mem_univ, eq_self_iff_true, exists_prop_of_true, finset.mem_image, heq_iff_eq], refine ⟨j, rfl, _⟩, simp only [heq_iff_eq], exact ⟨rfl, rfl, rfl⟩, end)), have gH : ∀ j, (⟨ky, k j, kyO, kjO j, g j⟩ : (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H := λ j, (finset.mem_union.mpr (or.inr begin simp only [true_and, finset.mem_univ, eq_self_iff_true, exists_prop_of_true, finset.mem_image, heq_iff_eq], refine ⟨j, rfl, _⟩, simp only [heq_iff_eq], exact ⟨rfl, rfl, rfl⟩, end)), -- Our goal is now an equation between equivalence classes of representatives of a colimit, -- and so it suffices to show those representative become equal somewhere, in particular at `S`. apply colimit_sound'.{v v} (T kxO) (T kyO), -- We can check if two elements of a limit (in `Type`) are equal by comparing them componentwise. ext, -- Now it's just a calculation using `W` and `w`. simp only [functor.comp_map, limit.map_π_apply, curry.obj_map_app, swap_map], rw ←W _ _ (fH j), rw ←W _ _ (gH j), simp [w], end end variables [fin_category J] /-- This follows this proof from * Borceux, Handbook of categorical algebra 1, Theorem 2.13.4 although with different names. -/ lemma colimit_limit_to_limit_colimit_surjective : function.surjective (colimit_limit_to_limit_colimit F) := begin classical, -- We begin with some element `x` in the limit (over J) over the colimits (over K), intro x, -- This consists of some coherent family of elements in the various colimits, -- and so our first task is to pick representatives of these elements. have z := λ j, jointly_surjective'.{v v} (limit.π (curry.obj F ⋙ limits.colim) j x), -- `k : J ⟶ K` records where the representative of the element in the `j`-th element of `x` lives let k : J → K := λ j, (z j).some, -- `y j : F.obj (j, k j)` is the representative let y : Π j, F.obj (j, k j) := λ j, (z j).some_spec.some, -- and we record that these representatives, when mapped back into the relevant colimits, -- are actually the components of `x`. have e : ∀ j, colimit.ι ((curry.obj F).obj j) (k j) (y j) = limit.π (curry.obj F ⋙ limits.colim) j x := λ j, (z j).some_spec.some_spec, clear_value k y, -- A little tidying up of things we no longer need. clear z, -- As a first step, we use that `K` is filtered to pick some point `k' : K` above all the `k j` let k' : K := is_filtered.sup (finset.univ.image k) ∅, -- and name the morphisms as `g j : k j ⟶ k'`. have g : Π j, k j ⟶ k' := λ j, is_filtered.to_sup (finset.univ.image k) ∅ (by simp), clear_value k', -- Recalling that the components of `x`, which are indexed by `j : J`, are "coherent", -- in other words preserved by morphisms in the `J` direction, -- we see that for any morphism `f : j ⟶ j'` in `J`, -- the images of `y j` and `y j'`, when mapped to `F.obj (j', k')` respectively by -- `(f, g j)` and `(𝟙 j', g j')`, both represent the same element in the colimit. have w : ∀ {j j' : J} (f : j ⟶ j'), colimit.ι ((curry.obj F).obj j') k' (F.map ((𝟙 j', g j') : (j', k j') ⟶ (j', k')) (y j')) = colimit.ι ((curry.obj F).obj j') k' (F.map ((f, g j) : (j, k j) ⟶ (j', k')) (y j)), { intros j j' f, have t : (f, g j) = (((f, 𝟙 (k j)) : (j, k j) ⟶ (j', k j)) ≫ (𝟙 j', g j) : (j, k j) ⟶ (j', k')), { simp only [id_comp, comp_id, prod_comp], }, erw [colimit.w_apply', t, functor_to_types.map_comp_apply, colimit.w_apply', e, ←limit.w_apply' f, ←e], simp, }, -- Because `K` is filtered, we can restate this as saying that -- for each such `f`, there is some place to the right of `k'` -- where these images of `y j` and `y j'` become equal. simp_rw colimit_eq_iff.{v v} at w, -- We take a moment to restate `w` more conveniently. let kf : Π {j j'} (f : j ⟶ j'), K := λ _ _ f, (w f).some, let gf : Π {j j'} (f : j ⟶ j'), k' ⟶ kf f := λ _ _ f, (w f).some_spec.some, let hf : Π {j j'} (f : j ⟶ j'), k' ⟶ kf f := λ _ _ f, (w f).some_spec.some_spec.some, have wf : Π {j j'} (f : j ⟶ j'), F.map ((𝟙 j', g j' ≫ gf f) : (j', k j') ⟶ (j', kf f)) (y j') = F.map ((f, g j ≫ hf f) : (j, k j) ⟶ (j', kf f)) (y j) := λ j j' f, begin have q : ((curry.obj F).obj j').map (gf f) (F.map _ (y j')) = ((curry.obj F).obj j').map (hf f) (F.map _ (y j)) := (w f).some_spec.some_spec.some_spec, dsimp at q, simp_rw ←functor_to_types.map_comp_apply at q, convert q; simp only [comp_id], end, clear_value kf gf hf, -- and clean up some things that are no longer needed. clear w, -- We're now ready to use the fact that `K` is filtered a second time, -- picking some place to the right of all of -- the morphisms `gf f : k' ⟶ kh f` and `hf f : k' ⟶ kf f`. -- At this point we're relying on there being only finitely morphisms in `J`. let O := finset.univ.bUnion (λ j, finset.univ.bUnion (λ j', finset.univ.image (@kf j j'))) ∪ {k'}, have kfO : ∀ {j j'} (f : j ⟶ j'), kf f ∈ O := λ j j' f, finset.mem_union.mpr (or.inl ( begin rw [finset.mem_bUnion], refine ⟨j, finset.mem_univ j, _⟩, rw [finset.mem_bUnion], refine ⟨j', finset.mem_univ j', _⟩, rw [finset.mem_image], refine ⟨f, finset.mem_univ _, _⟩, refl, end)), have k'O : k' ∈ O := finset.mem_union.mpr (or.inr (finset.mem_singleton.mpr rfl)), let H : finset (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := finset.univ.bUnion (λ j : J, finset.univ.bUnion (λ j' : J, finset.univ.bUnion (λ f : j ⟶ j', {⟨k', kf f, k'O, kfO f, gf f⟩, ⟨k', kf f, k'O, kfO f, hf f⟩}))), obtain ⟨k'', i', s'⟩ := is_filtered.sup_exists O H, -- We then restate this slightly more conveniently, as a family of morphism `i f : kf f ⟶ k''`, -- satisfying `gf f ≫ i f = hf f' ≫ i f'`. let i : Π {j j'} (f : j ⟶ j'), kf f ⟶ k'' := λ j j' f, i' (kfO f), have s : ∀ {j₁ j₂ j₃ j₄} (f : j₁ ⟶ j₂) (f' : j₃ ⟶ j₄), gf f ≫ i f = hf f' ≫ i f' := begin intros, rw [s', s'], swap 2, exact k'O, swap 2, { rw [finset.mem_bUnion], refine ⟨j₁, finset.mem_univ _, _⟩, rw [finset.mem_bUnion], refine ⟨j₂, finset.mem_univ _, _⟩, rw [finset.mem_bUnion], refine ⟨f, finset.mem_univ _, _⟩, simp only [true_or, eq_self_iff_true, and_self, finset.mem_insert, heq_iff_eq], }, { rw [finset.mem_bUnion], refine ⟨j₃, finset.mem_univ _, _⟩, rw [finset.mem_bUnion], refine ⟨j₄, finset.mem_univ _, _⟩, rw [finset.mem_bUnion], refine ⟨f', finset.mem_univ _, _⟩, simp only [eq_self_iff_true, or_true, and_self, finset.mem_insert, finset.mem_singleton, heq_iff_eq], } end, clear_value i, clear s' i' H kfO k'O O, -- We're finally ready to construct the pre-image, and verify it really maps to `x`. fsplit, { -- We construct the pre-image (which, recall is meant to be a point -- in the colimit (over `K`) of the limits (over `J`)) via a representative at `k''`. apply colimit.ι (curry.obj (swap K J ⋙ F) ⋙ limits.lim) k'' _, dsimp, -- This representative is meant to be an element of a limit, -- so we need to construct a family of elements in `F.obj (j, k'')` for varying `j`, -- then show that are coherent with respect to morphisms in the `j` direction. apply limit.mk.{v v}, swap, { -- We construct the elements as the images of the `y j`. exact λ j, F.map (⟨𝟙 j, g j ≫ gf (𝟙 j) ≫ i (𝟙 j)⟩ : (j, k j) ⟶ (j, k'')) (y j), }, { -- After which it's just a calculation, using `s` and `wf`, to see they are coherent. dsimp, intros j j' f, simp only [←functor_to_types.map_comp_apply, prod_comp, id_comp, comp_id], calc F.map ((f, g j ≫ gf (𝟙 j) ≫ i (𝟙 j)) : (j, k j) ⟶ (j', k'')) (y j) = F.map ((f, g j ≫ hf f ≫ i f) : (j, k j) ⟶ (j', k'')) (y j) : by rw s (𝟙 j) f ... = F.map ((𝟙 j', i f) : (j', kf f) ⟶ (j', k'')) (F.map ((f, g j ≫ hf f) : (j, k j) ⟶ (j', kf f)) (y j)) : by rw [←functor_to_types.map_comp_apply, prod_comp, comp_id, assoc] ... = F.map ((𝟙 j', i f) : (j', kf f) ⟶ (j', k'')) (F.map ((𝟙 j', g j' ≫ gf f) : (j', k j') ⟶ (j', kf f)) (y j')) : by rw ←wf f ... = F.map ((𝟙 j', g j' ≫ gf f ≫ i f) : (j', k j') ⟶ (j', k'')) (y j') : by rw [←functor_to_types.map_comp_apply, prod_comp, id_comp, assoc] ... = F.map ((𝟙 j', g j' ≫ gf (𝟙 j') ≫ i (𝟙 j')) : (j', k j') ⟶ (j', k'')) (y j') : by rw [s f (𝟙 j'), ←s (𝟙 j') (𝟙 j')], }, }, -- Finally we check that this maps to `x`. { -- We can do this componentwise: apply limit_ext', intro j, -- and as each component is an equation in a colimit, we can verify it by -- pointing out the morphism which carries one representative to the other: simp only [←e, colimit_eq_iff.{v v}, curry.obj_obj_map, limit.π_mk', bifunctor.map_id_comp, id.def, types_comp_apply, limits.ι_colimit_limit_to_limit_colimit_π_apply], refine ⟨k'', 𝟙 k'', g j ≫ gf (𝟙 j) ≫ i (𝟙 j), _⟩, simp only [bifunctor.map_id_comp, types_comp_apply, bifunctor.map_id, types_id_apply], }, end instance colimit_limit_to_limit_colimit_is_iso : is_iso (colimit_limit_to_limit_colimit F) := (is_iso_iff_bijective _).mpr ⟨colimit_limit_to_limit_colimit_injective F, colimit_limit_to_limit_colimit_surjective F⟩ instance colimit_limit_to_limit_colimit_cone_iso (F : J ⥤ K ⥤ Type v) : is_iso (colimit_limit_to_limit_colimit_cone F) := begin haveI : is_iso (colimit_limit_to_limit_colimit_cone F).hom, { dsimp only [colimit_limit_to_limit_colimit_cone], apply_instance }, apply cones.cone_iso_of_hom_iso, end noncomputable instance filtered_colim_preserves_finite_limits_of_types : preserves_finite_limits (colim : (K ⥤ Type v) ⥤ _) := ⟨λ J _ _, by exactI ⟨λ F, ⟨λ c hc, begin apply is_limit.of_iso_limit (limit.is_limit _), symmetry, transitivity (colim.map_cone (limit.cone F)), exact functor.map_iso _ (hc.unique_up_to_iso (limit.is_limit F)), exact as_iso (colimit_limit_to_limit_colimit_cone F), end ⟩⟩⟩ variables {C : Type u} [category.{v} C] [concrete_category.{v} C] section variables [has_limits_of_shape J C] [has_colimits_of_shape K C] variables [reflects_limits_of_shape J (forget C)] [preserves_colimits_of_shape K (forget C)] variables [preserves_limits_of_shape J (forget C)] noncomputable instance filtered_colim_preserves_finite_limits : preserves_limits_of_shape J (colim : (K ⥤ C) ⥤ _) := begin haveI : preserves_limits_of_shape J ((colim : (K ⥤ C) ⥤ _) ⋙ forget C) := preserves_limits_of_shape_of_nat_iso (preserves_colimit_nat_iso _).symm, exactI preserves_limits_of_shape_of_reflects_of_preserves _ (forget C) end end local attribute [instance] reflects_limits_of_shape_of_reflects_isomorphisms noncomputable instance [preserves_finite_limits (forget C)] [preserves_filtered_colimits (forget C)] [has_finite_limits C] [has_colimits_of_shape K C] [reflects_isomorphisms (forget C)] : preserves_finite_limits (colim : (K ⥤ C) ⥤ _) := ⟨λ _ _ _, by exactI category_theory.limits.filtered_colim_preserves_finite_limits⟩ section variables [has_limits_of_shape J C] [has_colimits_of_shape K C] variables [reflects_limits_of_shape J (forget C)] [preserves_colimits_of_shape K (forget C)] variables [preserves_limits_of_shape J (forget C)] /-- A curried version of the fact that filtered colimits commute with finite limits. -/ noncomputable def colimit_limit_iso (F : J ⥤ K ⥤ C) : colimit (limit F) ≅ limit (colimit F.flip) := (is_limit_of_preserves colim (limit.is_limit _)).cone_point_unique_up_to_iso (limit.is_limit _) ≪≫ (has_limit.iso_of_nat_iso (colimit_flip_iso_comp_colim _).symm) @[simp, reassoc] lemma ι_colimit_limit_iso_limit_π (F : J ⥤ K ⥤ C) (a) (b) : colimit.ι (limit F) a ≫ (colimit_limit_iso F).hom ≫ limit.π (colimit F.flip) b = (limit.π F b).app a ≫ (colimit.ι F.flip a).app b := begin dsimp [colimit_limit_iso], simp only [functor.map_cone_π_app, iso.symm_hom, limits.limit.cone_point_unique_up_to_iso_hom_comp_assoc, limits.limit.cone_π, limits.colimit.ι_map_assoc, limits.colimit_flip_iso_comp_colim_inv_app, assoc, limits.has_limit.iso_of_nat_iso_hom_π], congr' 1, simp only [← category.assoc, iso.comp_inv_eq, limits.colimit_obj_iso_colimit_comp_evaluation_ι_app_hom, limits.has_colimit.iso_of_nat_iso_ι_hom, nat_iso.of_components.hom_app], dsimp, simp, end end end category_theory.limits
6d9a2d6cf50bfd0db3a23c207b177d9858d04fc4
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/logic/unique.lean
dfca62c3ac3568c04fcedc39a1542129f8fb6198
[ "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
1,253
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 logic.basic universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} structure unique (α : Sort u) extends inhabited α := (uniq : ∀ a:α, a = default) attribute [class] unique instance punit.unique : unique punit.{u} := { default := punit.star, uniq := λ x, punit_eq x _ } namespace unique open function section variables [unique α] instance : inhabited α := to_inhabited ‹unique α› lemma eq_default (a : α) : a = default α := uniq _ a lemma default_eq (a : α) : default α = a := (uniq _ a).symm instance : subsingleton α := ⟨λ a b, by rw [eq_default a, eq_default b]⟩ end protected lemma subsingleton_unique' : ∀ (h₁ h₂ : unique α), h₁ = h₂ | ⟨⟨x⟩, h⟩ ⟨⟨y⟩, _⟩ := by congr; rw [h x, h y] instance subsingleton_unique : subsingleton (unique α) := ⟨unique.subsingleton_unique'⟩ def of_surjective {f : α → β} (hf : surjective f) [unique α] : unique β := { default := f (default _), uniq := λ b, begin cases hf b with a ha, subst ha, exact congr_arg f (eq_default a) end } end unique
d9b26c321e4014d876d1162c23c0fbd59bdc4bc6
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Meta/Match/Match.lean
090625e99f17aa79125e53942aba4ba9481534a5
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,639
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectLevelParams import Lean.Meta.Check import Lean.Meta.Closure import Lean.Meta.Tactic.Cases import Lean.Meta.GeneralizeTelescope import Lean.Meta.Match.MVarRenaming import Lean.Meta.Match.CaseValues import Lean.Meta.Match.CaseArraySizes namespace Lean namespace Meta namespace Match inductive Pattern : Type | inaccessible (e : Expr) : Pattern | var (fvarId : FVarId) : Pattern | ctor (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern | val (e : Expr) : Pattern | arrayLit (type : Expr) (xs : List Pattern) : Pattern | as (varId : FVarId) (p : Pattern) : Pattern namespace Pattern instance : Inhabited Pattern := ⟨Pattern.inaccessible (arbitrary _)⟩ partial def toMessageData : Pattern → MessageData | inaccessible e => ".(" ++ e ++ ")" | var varId => mkFVar varId | ctor ctorName _ _ [] => ctorName | ctor ctorName _ _ pats => "(" ++ ctorName ++ pats.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil ++ ")" | val e => e | arrayLit _ pats => "#[" ++ MessageData.joinSep (pats.map toMessageData) ", " ++ "]" | as varId p => mkFVar varId ++ "@" ++toMessageData p partial def toExpr : Pattern → MetaM Expr | inaccessible e => pure e | var fvarId => pure $ mkFVar fvarId | val e => pure e | as _ p => toExpr p | arrayLit type xs => do xs ← xs.mapM toExpr; mkArrayLit type xs | ctor ctorName us params fields => do fields ← fields.mapM toExpr; pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray /- Apply the free variable substitution `s` to the given pattern -/ partial def applyFVarSubst (s : FVarSubst) : Pattern → Pattern | inaccessible e => inaccessible $ s.apply e | ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map applyFVarSubst | val e => val $ s.apply e | arrayLit t xs => arrayLit (s.apply t) $ xs.map applyFVarSubst | var fvarId => match s.find? fvarId with | some e => inaccessible e | none => var fvarId | as fvarId p => match s.find? fvarId with | none => as fvarId $ applyFVarSubst p | some _ => applyFVarSubst p def replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern := let s : FVarSubst := {}; p.applyFVarSubst (s.insert fvarId v) end Pattern structure AltLHS := (ref : Syntax) (fvarDecls : List LocalDecl) -- Free variables used in the patterns. (patterns : List Pattern) -- We use `List Pattern` since we have nary match-expressions. structure Alt := (ref : Syntax) (idx : Nat) -- for generating error messages (rhs : Expr) (fvarDecls : List LocalDecl) (patterns : List Pattern) namespace Alt instance : Inhabited Alt := ⟨⟨arbitrary _, 0, arbitrary _, [], []⟩⟩ partial def toMessageData (alt : Alt) : MetaM MessageData := do withExistingLocalDecls alt.fvarDecls do let msg : List MessageData := alt.fvarDecls.map fun d => d.toExpr ++ ":(" ++ d.type ++ ")"; let msg : MessageData := msg ++ " |- " ++ (alt.patterns.map Pattern.toMessageData) ++ " => " ++ alt.rhs; addMessageDataContext msg def applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.applyFVarSubst s, fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s, rhs := alt.rhs.applyFVarSubst s } def replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.replaceFVarId fvarId v, fvarDecls := let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId; decls.map $ replaceFVarIdAtLocalDecl fvarId v, rhs := alt.rhs.replaceFVarId fvarId v } def isDefEqGuarded (a b : Expr) : MetaM Bool := catch (isDefEq a b) (fun _ => pure false) /- Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`. This extra check is necessary when performing dependent elimination and inaccessible terms have been used. For example, consider the following code fragment: ``` inductive Vec (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) inductive VecPred {α : Type u} (P : α → Prop) : {n : Nat} → Vec α n → Prop | nil : VecPred P Vec.nil | cons {n : Nat} {head : α} {tail : Vec α n} : P head → VecPred P tail → VecPred P (Vec.cons head tail) theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` Recall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term. The elaborator uses an inaccessible term when typing constraints restrict its value. Thus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)` because the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`. After elaboration the alternative becomes: ``` | .(0), @Vec.cons .(α) .(0) head .(Vec.nil), @VecPred.cons .(α) .(P) .(0) .(head) .(Vec.nil) h w => ⟨head, h⟩ ``` where ``` (head : α), (h: P head), (w : VecPred P Vec.nil) ``` Then, when we process this alternative in this module, the following check will detect that `w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`. Note that if we had written ``` theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` we would get the easier to digest error message ``` missing cases: _, (Vec.cons _ _ (Vec.cons _ _ _)), _ ``` -/ def checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with | none => throwErrorAt alt.ref "unknown free pattern variable" | some fvarDecl => do vType ← inferType v; unlessM (isDefEqGuarded fvarDecl.type vType) $ throwErrorAt alt.ref $ "type mismatch during dependent match-elimination at pattern variable '" ++ fvarDecl.userName.simpMacroScopes ++ "' with type" ++ indentExpr fvarDecl.type ++ Format.line ++ "expected type" ++ indentExpr vType; pure $ replaceFVarId fvarId v alt end Alt inductive Example | var : FVarId → Example | underscore : Example | ctor : Name → List Example → Example | val : Expr → Example | arrayLit : List Example → Example namespace Example partial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example → Example | var x => if x == fvarId then ex else var x | ctor n exs => ctor n $ exs.map replaceFVarId | arrayLit exs => arrayLit $ exs.map replaceFVarId | ex => ex partial def applyFVarSubst (s : FVarSubst) : Example → Example | var fvarId => match s.get fvarId with | Expr.fvar fvarId' _ => var fvarId' | _ => underscore | ctor n exs => ctor n $ exs.map applyFVarSubst | arrayLit exs => arrayLit $ exs.map applyFVarSubst | ex => ex partial def varsToUnderscore : Example → Example | var x => underscore | ctor n exs => ctor n $ exs.map varsToUnderscore | arrayLit exs => arrayLit $ exs.map varsToUnderscore | ex => ex partial def toMessageData : Example → MessageData | var fvarId => mkFVar fvarId | ctor ctorName [] => mkConst ctorName | ctor ctorName exs => "(" ++ mkConst ctorName ++ exs.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil ++ ")" | arrayLit exs => "#" ++ MessageData.ofList (exs.map toMessageData) | val e => e | underscore => "_" end Example def examplesToMessageData (cex : List Example) : MessageData := MessageData.joinSep (cex.map (Example.toMessageData ∘ Example.varsToUnderscore)) ", " structure Problem := (mvarId : MVarId) (vars : List Expr) (alts : List Alt) (examples : List Example) def withGoalOf {α} (p : Problem) (x : MetaM α) : MetaM α := withMVarContext p.mvarId x namespace Problem instance : Inhabited Problem := ⟨{ mvarId := arbitrary _, vars := [], alts := [], examples := []}⟩ def toMessageData (p : Problem) : MetaM MessageData := withGoalOf p do alts ← p.alts.mapM Alt.toMessageData; vars : List MessageData ← p.vars.mapM fun x => do { xType ← inferType x; pure (x ++ ":(" ++ xType ++ ")" : MessageData) }; pure $ "vars " ++ vars -- ++ Format.line ++ "var ids " ++ toString (p.vars.map (fun x => match x with | Expr.fvar id _ => toString id | _ => "[nonvar]")) ++ Format.line ++ MessageData.joinSep alts Format.line ++ Format.line ++ "examples: " ++ examplesToMessageData p.examples ++ Format.line end Problem abbrev CounterExample := List Example def counterExampleToMessageData (cex : CounterExample) : MessageData := examplesToMessageData cex def counterExamplesToMessageData (cexs : List CounterExample) : MessageData := MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line structure MatcherResult := (matcher : Expr) -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables. (counterExamples : List CounterExample) (unusedAltIdxs : List Nat) /- The number of patterns in each AltLHS must be equal to majors.length -/ private def checkNumPatterns (majors : Array Expr) (lhss : List AltLHS) : MetaM Unit := let num := majors.size; when (lhss.any (fun lhs => lhs.patterns.length != num)) $ throwError "incorrect number of patterns" private partial def withAltsAux {α} (motive : Expr) : List AltLHS → List Alt → Array Expr → (List Alt → Array Expr → MetaM α) → MetaM α | [], alts, minors, k => k alts.reverse minors | lhs::lhss, alts, minors, k => do let xs := lhs.fvarDecls.toArray.map LocalDecl.toExpr; minorType ← withExistingLocalDecls lhs.fvarDecls do { args ← lhs.patterns.toArray.mapM Pattern.toExpr; let minorType := mkAppN motive args; mkForallFVars xs minorType }; let minorType := if minorType.isForall then minorType else mkThunkType minorType; let idx := alts.length; let minorName := (`h).appendIndexAfter (idx+1); trace! `Meta.Match.debug ("minor premise " ++ minorName ++ " : " ++ minorType); withLocalDeclD minorName minorType fun minor => do let rhs := if xs.isEmpty then mkApp minor (mkConst `Unit.unit) else mkAppN minor xs; let minors := minors.push minor; fvarDecls ← lhs.fvarDecls.mapM instantiateLocalDeclMVars; let alts := { ref := lhs.ref, idx := idx, rhs := rhs, fvarDecls := fvarDecls, patterns := lhs.patterns : Alt } :: alts; withAltsAux lhss alts minors k /- Given a list of `AltLHS`, create a minor premise for each one, convert them into `Alt`, and then execute `k` -/ private partial def withAlts {α} (motive : Expr) (lhss : List AltLHS) (k : List Alt → Array Expr → MetaM α) : MetaM α := withAltsAux motive lhss [] #[] k def assignGoalOf (p : Problem) (e : Expr) : MetaM Unit := withGoalOf p (assignExprMVar p.mvarId e) structure State := (used : Std.HashSet Nat := {}) -- used alternatives (counterExamples : List (List Example) := []) /-- Return true if the given (sub-)problem has been solved. -/ private def isDone (p : Problem) : Bool := p.vars.isEmpty /-- Return true if the next element on the `p.vars` list is a variable. -/ private def isNextVar (p : Problem) : Bool := match p.vars with | Expr.fvar _ _ :: _ => true | _ => false private def hasAsPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.as _ _ :: _ => true | _ => false private def hasCtorPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.ctor _ _ _ _ :: _ => true | _ => false private def hasValPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.val _ :: _ => true | _ => false private def hasNatValPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.val v :: _ => v.isNatLit | _ => false private def hasVarPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.var _ :: _ => true | _ => false private def hasArrayLitPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.arrayLit _ _ :: _ => true | _ => false private def isVariableTransition (p : Problem) : Bool := p.alts.all fun alt => match alt.patterns with | Pattern.inaccessible _ :: _ => true | Pattern.var _ :: _ => true | _ => false private def isConstructorTransition (p : Problem) : Bool := (hasCtorPattern p || p.alts.isEmpty) && p.alts.all fun alt => match alt.patterns with | Pattern.ctor _ _ _ _ :: _ => true | Pattern.var _ :: _ => true | Pattern.inaccessible _ :: _ => true | _ => false private def isValueTransition (p : Problem) : Bool := hasVarPattern p && hasValPattern p && p.alts.all fun alt => match alt.patterns with | Pattern.val _ :: _ => true | Pattern.var _ :: _ => true | _ => false private def isArrayLitTransition (p : Problem) : Bool := hasArrayLitPattern p && hasVarPattern p && p.alts.all fun alt => match alt.patterns with | Pattern.arrayLit _ _ :: _ => true | Pattern.var _ :: _ => true | _ => false private def isNatValueTransition (p : Problem) : Bool := hasNatValPattern p && p.alts.any fun alt => match alt.patterns with | Pattern.ctor _ _ _ _ :: _ => true | Pattern.inaccessible _ :: _ => true | _ => false private def processNonVariable (p : Problem) : Problem := match p.vars with | [] => unreachable! | x :: xs => let alts := p.alts.map fun alt => match alt.patterns with | _ :: ps => { alt with patterns := ps } | _ => unreachable!; { p with alts := alts, vars := xs } private def processLeaf (p : Problem) : StateRefT State MetaM Unit := match p.alts with | [] => do liftM $ admit p.mvarId; modify fun s => { s with counterExamples := p.examples :: s.counterExamples } | alt :: _ => do -- TODO: check whether we have unassigned metavars in rhs liftM $ assignGoalOf p alt.rhs; modify fun s => { s with used := s.used.insert alt.idx } private def processAsPattern (p : Problem) : MetaM Problem := match p.vars with | [] => unreachable! | x :: xs => withGoalOf p do alts ← p.alts.mapM fun alt => match alt.patterns with | Pattern.as fvarId p :: ps => { alt with patterns := p :: ps }.checkAndReplaceFVarId fvarId x | _ => pure alt; pure { p with alts := alts } private def processVariable (p : Problem) : MetaM Problem := match p.vars with | [] => unreachable! | x :: xs => withGoalOf p do alts ← p.alts.mapM fun alt => match alt.patterns with | Pattern.inaccessible _ :: ps => pure { alt with patterns := ps } | Pattern.var fvarId :: ps => { alt with patterns := ps }.checkAndReplaceFVarId fvarId x | _ => unreachable!; pure { p with alts := alts, vars := xs } private def throwInductiveTypeExpected {α} (e : Expr) : MetaM α := do t ← inferType e; throwError ("failed to compile pattern matching, inductive type expected" ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr t) private def inLocalDecls (localDecls : List LocalDecl) (fvarId : FVarId) : Bool := localDecls.any fun d => d.fvarId == fvarId namespace Unify structure Context := (altFVarDecls : List LocalDecl) structure State := (fvarSubst : FVarSubst := {}) abbrev M := ReaderT Context $ StateRefT State MetaM def isAltVar (fvarId : FVarId) : M Bool := do ctx ← read; pure $ inLocalDecls ctx.altFVarDecls fvarId def expandIfVar (e : Expr) : M Expr := do match e with | Expr.fvar _ _ => do s ← get; pure $ s.fvarSubst.apply e | _ => pure e def occurs (fvarId : FVarId) (v : Expr) : Bool := (v.find? fun e => match e with | Expr.fvar fvarId' _ => fvarId == fvarId' | _=> false).isSome def assign (fvarId : FVarId) (v : Expr) : M Bool := if occurs fvarId v then do trace! `Meta.Match.unify ("assign occurs check failed, " ++ mkFVar fvarId ++ " := " ++ v); pure false else do ctx ← read; condM (isAltVar fvarId) (do trace! `Meta.Match.unify (mkFVar fvarId ++ " := " ++ v); modify fun s => { s with fvarSubst := s.fvarSubst.insert fvarId v }; pure true) (do trace! `Meta.Match.unify ("assign failed variable is not local, " ++ mkFVar fvarId ++ " := " ++ v); pure false) partial def unify : Expr → Expr → M Bool | a, b => do trace! `Meta.Match.unify (a ++ " =?= " ++ b); condM (isDefEq a b) (pure true) do a' ← expandIfVar a; b' ← expandIfVar b; if a != a' || b != b' then unify a' b' else match a, b with | Expr.mdata _ a _, b => unify a b | a, Expr.mdata _ b _ => unify a b | Expr.fvar aFvarId _, Expr.fvar bFVarId _ => assign aFvarId b <||> assign bFVarId a | Expr.fvar aFvarId _, b => assign aFvarId b | a, Expr.fvar bFVarId _ => assign bFVarId a | Expr.app aFn aArg _, Expr.app bFn bArg _ => unify aFn bFn <&&> unify aArg bArg | _, _ => do trace! `Meta.Match.unify ("unify failed @" ++ a ++ " =?= " ++ b); pure false end Unify private def unify? (altFVarDecls : List LocalDecl) (a b : Expr) : MetaM (Option FVarSubst) := do a ← instantiateMVars a; b ← instantiateMVars b; (b, s) ← (Unify.unify a b { altFVarDecls := altFVarDecls}).run {}; if b then pure s.fvarSubst else pure none private def expandVarIntoCtor? (alt : Alt) (fvarId : FVarId) (ctorName : Name) : MetaM (Option Alt) := withExistingLocalDecls alt.fvarDecls do env ← getEnv; ldecl ← getLocalDecl fvarId; expectedType ← inferType (mkFVar fvarId); expectedType ← whnfD expectedType; (ctorLevels, ctorParams) ← getInductiveUniverseAndParams expectedType; let ctor := mkAppN (mkConst ctorName ctorLevels) ctorParams; ctorType ← inferType ctor; forallTelescopeReducing ctorType fun ctorFields resultType => do let ctor := mkAppN ctor ctorFields; let alt := alt.replaceFVarId fvarId ctor; ctorFieldDecls ← ctorFields.mapM fun ctorField => getLocalDecl ctorField.fvarId!; let newAltDecls := ctorFieldDecls.toList ++ alt.fvarDecls; subst? ← unify? newAltDecls resultType expectedType; match subst? with | none => pure none | some subst => do let newAltDecls := newAltDecls.filter fun d => !subst.contains d.fvarId; -- remove declarations that were assigned let newAltDecls := newAltDecls.map fun d => d.applyFVarSubst subst; -- apply substitution to remaining declaration types let patterns := alt.patterns.map fun p => p.applyFVarSubst subst; let rhs := subst.apply alt.rhs; let ctorFieldPatterns := ctorFields.toList.map fun ctorField => match subst.get ctorField.fvarId! with | e@(Expr.fvar fvarId _) => if inLocalDecls newAltDecls fvarId then Pattern.var fvarId else Pattern.inaccessible e | e => Pattern.inaccessible e; pure $ some { alt with fvarDecls := newAltDecls, rhs := rhs, patterns := ctorFieldPatterns ++ patterns } private def getInductiveVal? (x : Expr) : MetaM (Option InductiveVal) := do xType ← inferType x; xType ← whnfD xType; match xType.getAppFn with | Expr.const constName _ _ => do cinfo ← getConstInfo constName; match cinfo with | ConstantInfo.inductInfo val => pure (some val) | _ => pure none | _ => pure none private def hasRecursiveType (x : Expr) : MetaM Bool := do val? ← getInductiveVal? x; match val? with | some val => pure val.isRec | _ => pure false private def processConstructor (p : Problem) : MetaM (Array Problem) := do trace! `Meta.Match.match ("constructor step"); env ← getEnv; match p.vars with | [] => unreachable! | x :: xs => do subgoals? ← commitWhenSome? do { subgoals ← cases p.mvarId x.fvarId!; if subgoals.isEmpty then /- Easy case: we have solved problem `p` since there are no subgoals -/ pure (some #[]) else if !p.alts.isEmpty then pure (some subgoals) else do isRec ← withGoalOf p $ hasRecursiveType x; /- If there are no alternatives and the type of the current variable is recursive, we do NOT consider a constructor-transition to avoid nontermination. TODO: implement a more general approach if this is not sufficient in practice -/ if isRec then pure none else pure (some subgoals) }; match subgoals? with | none => pure #[{ p with vars := xs }] | some subgoals => subgoals.mapM fun subgoal => withMVarContext subgoal.mvarId do let subst := subgoal.subst; let fields := subgoal.fields.toList; let newVars := fields ++ xs; let newVars := newVars.map fun x => x.applyFVarSubst subst; let subex := Example.ctor subgoal.ctorName $ fields.map fun field => match field with | Expr.fvar fvarId _ => Example.var fvarId | _ => Example.underscore; -- This case can happen due to dependent elimination let examples := p.examples.map $ Example.replaceFVarId x.fvarId! subex; let examples := examples.map $ Example.applyFVarSubst subst; let newAlts := p.alts.filter fun alt => match alt.patterns with | Pattern.ctor n _ _ _ :: _ => n == subgoal.ctorName | Pattern.var _ :: _ => true | Pattern.inaccessible _ :: _ => true | _ => false; let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst; newAlts ← newAlts.filterMapM fun alt => match alt.patterns with | Pattern.ctor _ _ _ fields :: ps => pure $ some { alt with patterns := fields ++ ps } | Pattern.var fvarId :: ps => expandVarIntoCtor? { alt with patterns := ps } fvarId subgoal.ctorName | p@(Pattern.inaccessible e) :: ps => do trace! `Meta.Match.match ("inaccessible in ctor step " ++ e); withExistingLocalDecls alt.fvarDecls do -- Try to push inaccessible annotations. e ← whnfD e; match e.constructorApp? env with | some (ctorVal, ctorArgs) => do if ctorVal.name == subgoal.ctorName then let fields := ctorArgs.extract ctorVal.nparams ctorArgs.size; let fields := fields.toList.map Pattern.inaccessible; pure $ some { alt with patterns := fields ++ ps } else pure none | _ => throwErrorAt alt.ref $ "dependent match elimination failed, inaccessible pattern found " ++ indentD p.toMessageData ++ Format.line ++ "constructor expected" | _ => unreachable!; pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } private def collectValues (p : Problem) : Array Expr := p.alts.foldl (fun (values : Array Expr) alt => match alt.patterns with | Pattern.val v :: _ => if values.contains v then values else values.push v | _ => values) #[] private def isFirstPatternVar (alt : Alt) : Bool := match alt.patterns with | Pattern.var _ :: _ => true | _ => false private def processValue (p : Problem) : MetaM (Array Problem) := do trace! `Meta.Match.match ("value step"); match p.vars with | [] => unreachable! | x :: xs => do let values := collectValues p; subgoals ← caseValues p.mvarId x.fvarId! values; subgoals.mapIdxM fun i subgoal => if h : i < values.size then do let value := values.get ⟨i, h⟩; -- (x = value) branch let subst := subgoal.subst; let examples := p.examples.map $ Example.replaceFVarId x.fvarId! (Example.val value); let examples := examples.map $ Example.applyFVarSubst subst; let newAlts := p.alts.filter fun alt => match alt.patterns with | Pattern.val v :: _ => v == value | Pattern.var _ :: _ => true | _ => false; let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst; let newAlts := newAlts.map fun alt => match alt.patterns with | Pattern.val _ :: ps => { alt with patterns := ps } | Pattern.var fvarId :: ps => do let alt := { alt with patterns := ps }; alt.replaceFVarId fvarId value | _ => unreachable!; let newVars := xs.map fun x => x.applyFVarSubst subst; pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } else do -- else branch let newAlts := p.alts.filter isFirstPatternVar; pure { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs } private def collectArraySizes (p : Problem) : Array Nat := p.alts.foldl (fun (sizes : Array Nat) alt => match alt.patterns with | Pattern.arrayLit _ ps :: _ => let sz := ps.length; if sizes.contains sz then sizes else sizes.push sz | _ => sizes) #[] private def expandVarIntoArrayLitAux (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (varNamePrefix : Name) : Nat → Array Expr → MetaM Alt | n+1, newVars => withLocalDeclD (varNamePrefix.appendIndexAfter (n+1)) arrayElemType fun x => expandVarIntoArrayLitAux n (newVars.push x) | 0, newVars => do arrayLit ← mkArrayLit arrayElemType newVars.toList; let alt := alt.replaceFVarId fvarId arrayLit; newDecls ← newVars.toList.mapM fun newVar => getLocalDecl newVar.fvarId!; let newPatterns := newVars.toList.map fun newVar => Pattern.var newVar.fvarId!; pure { alt with fvarDecls := newDecls ++ alt.fvarDecls, patterns := newPatterns ++ alt.patterns } private def expandVarIntoArrayLit (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (arraySize : Nat) : MetaM Alt := withExistingLocalDecls alt.fvarDecls do fvarDecl ← getLocalDecl fvarId; expandVarIntoArrayLitAux alt fvarId arrayElemType fvarDecl.userName arraySize #[] private def processArrayLit (p : Problem) : MetaM (Array Problem) := do trace! `Meta.Match.match ("array literal step"); match p.vars with | [] => unreachable! | x :: xs => do let sizes := collectArraySizes p; subgoals ← caseArraySizes p.mvarId x.fvarId! sizes; subgoals.mapIdxM fun i subgoal => if h : i < sizes.size then do let size := sizes.get! i; let subst := subgoal.subst; let elems := subgoal.elems.toList; let newVars := elems.map mkFVar ++ xs; let newVars := newVars.map fun x => x.applyFVarSubst subst; let subex := Example.arrayLit $ elems.map Example.var; let examples := p.examples.map $ Example.replaceFVarId x.fvarId! subex; let examples := examples.map $ Example.applyFVarSubst subst; let newAlts := p.alts.filter fun alt => match alt.patterns with | Pattern.arrayLit _ ps :: _ => ps.length == size | Pattern.var _ :: _ => true | _ => false; let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst; newAlts ← newAlts.mapM fun alt => match alt.patterns with | Pattern.arrayLit _ pats :: ps => pure { alt with patterns := pats ++ ps } | Pattern.var fvarId :: ps => do α ← getArrayArgType x; expandVarIntoArrayLit { alt with patterns := ps } fvarId α size | _ => unreachable!; pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } else do -- else branch let newAlts := p.alts.filter isFirstPatternVar; pure { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs } private def expandNatValuePattern (p : Problem) : Problem := do let alts := p.alts.map fun alt => match alt.patterns with | Pattern.val (Expr.lit (Literal.natVal 0) _) :: ps => { alt with patterns := Pattern.ctor `Nat.zero [] [] [] :: ps } | Pattern.val (Expr.lit (Literal.natVal (n+1)) _) :: ps => { alt with patterns := Pattern.ctor `Nat.succ [] [] [Pattern.val (mkNatLit n)] :: ps } | _ => alt; { p with alts := alts } private def traceStep (msg : String) : StateRefT State MetaM Unit := liftM (trace! `Meta.Match.match (msg ++ " step") : MetaM Unit) private def traceState (p : Problem) : MetaM Unit := withGoalOf p (traceM `Meta.Match.match p.toMessageData) private def throwNonSupported (p : Problem) : MetaM Unit := do msg ← p.toMessageData; throwError ("not implement yet " ++ msg) def isCurrVarInductive (p : Problem) : MetaM Bool := do match p.vars with | [] => pure false | x::_ => withGoalOf p do val? ← getInductiveVal? x; pure val?.isSome private partial def process : Problem → StateRefT State MetaM Unit | p => withIncRecDepth do liftM $ traceState p; isInductive ← liftM $ isCurrVarInductive p; if isDone p then processLeaf p else if hasAsPattern p then do traceStep ("as-pattern"); p ← liftM $ processAsPattern p; process p else if !isNextVar p then do traceStep ("non variable"); process (processNonVariable p) else if isInductive && isConstructorTransition p then do ps ← liftM $ processConstructor p; ps.forM process else if isVariableTransition p then do traceStep ("variable"); p ← liftM $ processVariable p; process p else if isValueTransition p then do ps ← liftM $ processValue p; ps.forM process else if isArrayLitTransition p then do ps ← liftM $ processArrayLit p; ps.forM process else if isNatValueTransition p then do traceStep ("nat value to constructor"); process (expandNatValuePattern p) else liftM $ throwNonSupported p /-- A "matcher" auxiliary declaration has the following structure: - `numParams` parameters - motive - `numDiscrs` discriminators (aka major premises) - `numAlts` alternatives (aka minor premises) -/ structure MatcherInfo := (numParams : Nat) (numDiscrs : Nat) (numAlts : Nat) namespace Extension structure Entry := (name : Name) (info : MatcherInfo) structure State := (map : SMap Name MatcherInfo := {}) instance State.inhabited : Inhabited State := ⟨{}⟩ def State.addEntry (s : State) (e : Entry) : State := { s with map := s.map.insert e.name e.info } def State.switch (s : State) : State := { s with map := s.map.switch } def mkExtension : IO (SimplePersistentEnvExtension Entry State) := registerSimplePersistentEnvExtension { name := `matcher, addEntryFn := State.addEntry, addImportedFn := fun es => (mkStateFromImportedEntries State.addEntry {} es).switch } @[init mkExtension] constant extension : SimplePersistentEnvExtension Entry State := arbitrary _ def addMatcherInfo (env : Environment) (matcherName : Name) (info : MatcherInfo) : Environment := extension.addEntry env { name := matcherName, info := info } def getMatcherInfo? (env : Environment) (declName : Name) : Option MatcherInfo := (extension.getState env).map.find? declName end Extension def addMatcherInfo (matcherName : Name) (info : MatcherInfo) : MetaM Unit := modifyEnv fun env => Extension.addMatcherInfo env matcherName info def getMatcherInfo? (declName : Name) : MetaM (Option MatcherInfo) := do env ← getEnv; pure $ Extension.getMatcherInfo? env declName def isMatcher (declName : Name) : MetaM Bool := do info? ← getMatcherInfo? declName; pure info?.isSome def mkMatcher (matcherName : Name) (motiveType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : MetaM MatcherResult := withLocalDeclD `motive motiveType fun motive => do trace! `Meta.Match.debug ("motiveType: " ++ motiveType); forallBoundedTelescope motiveType numDiscrs fun majors _ => do checkNumPatterns majors lhss; let mvarType := mkAppN motive majors; trace! `Meta.Match.debug ("target: " ++ mvarType); withAlts motive lhss fun alts minors => do mvar ← mkFreshExprMVar mvarType; let examples := majors.toList.map fun major => Example.var major.fvarId!; (_, s) ← (process { mvarId := mvar.mvarId!, vars := majors.toList, alts := alts, examples := examples }).run {}; let args := #[motive] ++ majors ++ minors; type ← mkForallFVars args mvarType; val ← mkLambdaFVars args mvar; trace! `Meta.Match.debug ("matcher value: " ++ val ++ "\ntype: " ++ type); matcher ← mkAuxDefinition matcherName type val; addMatcherInfo matcherName { numParams := matcher.getAppNumArgs, numDiscrs := majors.size, numAlts := minors.size }; setInlineAttribute matcherName; trace! `Meta.Match.debug ("matcher: " ++ matcher); let unusedAltIdxs : List Nat := lhss.length.fold (fun i r => if s.used.contains i then r else i::r) []; pure { matcher := matcher, counterExamples := s.counterExamples, unusedAltIdxs := unusedAltIdxs.reverse } @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta.Match.match; registerTraceClass `Meta.Match.debug; registerTraceClass `Meta.Match.unify; pure () end Match end Meta end Lean
912a684316f621bf191433d90f8ffc003875b467
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/psub.lean
f9b9d539694dc824a885d421adee4c6c26ca25ec
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,820
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.basic /-! # Partial predecessor and partial subtraction on the natural numbers The usual definition of natural number subtraction (`nat.sub`) returns 0 as a "garbage value" for `a - b` when `a < b`. Similarly, `nat.pred 0` is defined to be `0`. The functions in this file wrap the result in an `option` type instead: ## Main definitions - `nat.ppred`: a partial predecessor operation - `nat.psub`: a partial subtraction operation -/ namespace nat /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := begin dsimp, apply option.bind_eq_some.trans, simp [psub_eq_some, add_comm, add_left_comm, nat.succ_eq_add_one] end theorem psub_eq_none {m n : ℕ} : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply nat.le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ tsub_add_cancel_of_le h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] /-- Same as `psub`, but with a more efficient implementation. -/ @[inline] def psub' (m n : ℕ) : option ℕ := if n ≤ m then some (m - n) else none theorem psub'_eq_psub (m n) : psub' m n = psub m n := by rw [psub']; split_ifs; [exact (psub_eq_sub h).symm, exact (psub_eq_none.2 (not_le.1 h)).symm] end nat
a229ac106463e04d8db54b53d6ba49f9b8dfe935
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Init/Data/Nat/Basic.lean
56bb2c919948deb3436e0f65614cc9c7ba21ba00
[ "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
13,708
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import Init.SimpLemmas universes u namespace Nat @[specialize] def foldAux {α : Type u} (f : Nat → α → α) (s : Nat) : Nat → α → α | 0, a => a | succ n, a => foldAux f s n (f (s - (succ n)) a) @[inline] def fold {α : Type u} (f : Nat → α → α) (n : Nat) (init : α) : α := foldAux f n n init @[inline] def foldRev {α : Type u} (f : Nat → α → α) (n : Nat) (init : α) : α := let rec @[specialize] loop | 0, a => a | succ n, a => loop n (f n a) loop n init @[specialize] def anyAux (f : Nat → Bool) (s : Nat) : Nat → Bool | 0 => false | succ n => f (s - (succ n)) || anyAux f s n /- `any f n = true` iff there is `i in [0, n-1]` s.t. `f i = true` -/ @[inline] def any (f : Nat → Bool) (n : Nat) : Bool := anyAux f n n @[inline] def all (f : Nat → Bool) (n : Nat) : Bool := !any (fun i => !f i) n @[inline] def repeat {α : Type u} (f : α → α) (n : Nat) (a : α) : α := let rec @[specialize] loop | 0, a => a | succ n, a => loop n (f a) loop n a /- Nat.add theorems -/ @[simp] theorem zero_Eq : Nat.zero = 0 := rfl @[simp] protected theorem zero_add : ∀ (n : Nat), 0 + n = n | 0 => rfl | n+1 => congrArg succ (Nat.zero_add n) theorem succ_add : ∀ (n m : Nat), (succ n) + m = succ (n + m) | n, 0 => rfl | n, m+1 => congrArg succ (succ_add n m) theorem add_succ (n m : Nat) : n + succ m = succ (n + m) := rfl @[simp] protected theorem add_zero (n : Nat) : n + 0 = n := rfl theorem add_one (n : Nat) : n + 1 = succ n := rfl theorem succ_Eq_add_one (n : Nat) : succ n = n + 1 := rfl protected theorem add_comm : ∀ (n m : Nat), n + m = m + n | n, 0 => Eq.symm (Nat.zero_add n) | n, m+1 => by have succ (n + m) = succ (m + n) by apply congrArg; apply Nat.add_comm rw [succ_add m n] apply this protected theorem add_assoc : ∀ (n m k : Nat), (n + m) + k = n + (m + k) | n, m, 0 => rfl | n, m, succ k => congrArg succ (Nat.add_assoc n m k) protected theorem add_left_comm (n m k : Nat) : n + (m + k) = m + (n + k) := by rw [← Nat.add_assoc, Nat.add_comm n m, Nat.add_assoc] protected theorem add_right_comm (n m k : Nat) : (n + m) + k = (n + k) + m := by rw [Nat.add_assoc, Nat.add_comm m k, ← Nat.add_assoc] protected theorem add_left_cancel {n m k : Nat} : n + m = n + k → m = k := by induction n with | zero => simp; intros; assumption | succ n ih => simp [succ_add]; intro h; injection h with h; apply ih h protected theorem add_right_cancel {n m k : Nat} (h : n + m = k + m) : n = k := by rw [Nat.add_comm n m, Nat.add_comm k m] at h apply Nat.add_left_cancel h /- Nat.mul theorems -/ @[simp] protected theorem mul_zero (n : Nat) : n * 0 = 0 := rfl theorem mul_succ (n m : Nat) : n * succ m = n * m + n := rfl @[simp] protected theorem zero_mul : ∀ (n : Nat), 0 * n = 0 | 0 => rfl | succ n => mul_succ 0 n ▸ (Nat.zero_mul n).symm ▸ rfl theorem succ_mul (n m : Nat) : (succ n) * m = (n * m) + m := by induction m with | zero => rfl | succ m ih => rw [mul_succ, add_succ, ih, mul_succ, add_succ, Nat.add_right_comm] protected theorem mul_comm : ∀ (n m : Nat), n * m = m * n | n, 0 => (Nat.zero_mul n).symm ▸ (Nat.mul_zero n).symm ▸ rfl | n, succ m => (mul_succ n m).symm ▸ (succ_mul m n).symm ▸ (Nat.mul_comm n m).symm ▸ rfl @[simp] protected theorem mul_one : ∀ (n : Nat), n * 1 = n := Nat.zero_add @[simp] protected theorem one_mul (n : Nat) : 1 * n = n := Nat.mul_comm n 1 ▸ Nat.mul_one n protected theorem left_distrib (n m k : Nat) : n * (m + k) = n * m + n * k := by induction n generalizing m k with | zero => repeat rw [Nat.zero_mul] | succ n ih => simp [succ_mul, ih]; rw [Nat.add_assoc, Nat.add_assoc (n*m)]; apply congrArg; apply Nat.add_left_comm protected theorem right_distrib (n m k : Nat) : (n + m) * k = n * k + m * k := have h₁ : (n + m) * k = k * (n + m) from Nat.mul_comm .. have h₂ : k * (n + m) = k * n + k * m from Nat.left_distrib .. have h₃ : k * n + k * m = n * k + k * m from Nat.mul_comm n k ▸ rfl have h₄ : n * k + k * m = n * k + m * k from Nat.mul_comm m k ▸ rfl ((h₁.trans h₂).trans h₃).trans h₄ protected theorem mul_assoc : ∀ (n m k : Nat), (n * m) * k = n * (m * k) | n, m, 0 => rfl | n, m, succ k => have h₁ : n * m * succ k = n * m * (k + 1) from rfl have h₂ : n * m * (k + 1) = (n * m * k) + n * m * 1 from Nat.left_distrib .. have h₃ : (n * m * k) + n * m * 1 = (n * m * k) + n * m by rw [Nat.mul_one (n*m)] have h₄ : (n * m * k) + n * m = (n * (m * k)) + n * m by rw [Nat.mul_assoc n m k] have h₅ : (n * (m * k)) + n * m = n * (m * k + m) from (Nat.left_distrib n (m*k) m).symm have h₆ : n * (m * k + m) = n * (m * succ k) from Nat.mul_succ m k ▸ rfl ((((h₁.trans h₂).trans h₃).trans h₄).trans h₅).trans h₆ /- Inequalities -/ theorem succ_lt_succ {n m : Nat} : n < m → succ n < succ m := succLeSucc theorem lt_succ_of_le {n m : Nat} : n ≤ m → n < succ m := succLeSucc @[simp] protected theorem sub_zero (n : Nat) : n - 0 = n := rfl theorem succ_sub_succ_eq_sub (n m : Nat) : succ n - succ m = n - m := by induction m with | zero => exact rfl | succ m ih => apply congrArg pred ih theorem notSuccLeSelf (n : Nat) : ¬succ n ≤ n := by induction n with | zero => intro h; apply notSuccLeZero 0 h | succ n ih => intro h; exact ih (leOfSuccLeSucc h) protected theorem ltIrrefl (n : Nat) : ¬n < n := notSuccLeSelf n theorem predLe : ∀ (n : Nat), pred n ≤ n | zero => rfl | succ n => leSucc _ theorem predLt : ∀ {n : Nat}, n ≠ 0 → pred n < n | zero, h => absurd rfl h | succ n, h => lt_succ_of_le (Nat.leRefl _) theorem subLe (n m : Nat) : n - m ≤ n := by induction m with | zero => exact Nat.leRefl (n - 0) | succ m ih => apply Nat.leTrans (predLe (n - m)) ih theorem subLt : ∀ {n m : Nat}, 0 < n → 0 < m → n - m < n | 0, m, h1, h2 => absurd h1 (Nat.ltIrrefl 0) | n+1, 0, h1, h2 => absurd h2 (Nat.ltIrrefl 0) | n+1, m+1, h1, h2 => Eq.symm (succ_sub_succ_eq_sub n m) ▸ show n - m < succ n from lt_succ_of_le (subLe n m) theorem sub_succ (n m : Nat) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : Nat) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : Nat), n - n = 0 | 0 => by rw Nat.sub_zero | (succ n) => by rw [succ_sub_succ, Nat.sub_self n] protected theorem ltOfLtOfLe {n m k : Nat} : n < m → m ≤ k → n < k := Nat.leTrans protected theorem ltOfLtOfEq {n m k : Nat} : n < m → m = k → n < k := fun h₁ h₂ => h₂ ▸ h₁ protected theorem leOfEq {n m : Nat} (p : n = m) : n ≤ m := p ▸ Nat.leRefl n theorem leOfSuccLe {n m : Nat} (h : succ n ≤ m) : n ≤ m := Nat.leTrans (leSucc n) h protected theorem leOfLt {n m : Nat} (h : n < m) : n ≤ m := leOfSuccLe h def lt.step {n m : Nat} : n < m → n < succ m := leStep def succPos := zeroLtSucc theorem eqZeroOrPos : ∀ (n : Nat), n = 0 ∨ n > 0 | 0 => Or.inl rfl | n+1 => Or.inr (succPos _) protected theorem ltOfLeOfLt {n m k : Nat} (h₁ : n ≤ m) : m < k → n < k := Nat.leTrans (succLeSucc h₁) def lt.base (n : Nat) : n < succ n := Nat.leRefl (succ n) theorem ltSuccSelf (n : Nat) : n < succ n := lt.base n protected theorem leTotal (m n : Nat) : m ≤ n ∨ n ≤ m := match Nat.ltOrGe m n with | Or.inl h => Or.inl (Nat.leOfLt h) | Or.inr h => Or.inr h protected theorem ltOfLeAndNe {m n : Nat} (h₁ : m ≤ n) (h₂ : m ≠ n) : m < n := match Nat.eqOrLtOfLe h₁ with | Or.inl h => absurd h h₂ | Or.inr h => h theorem eqZeroOfLeZero {n : Nat} (h : n ≤ 0) : n = 0 := Nat.leAntisymm h (zeroLe _) theorem ltOfSuccLt {n m : Nat} : succ n < m → n < m := leOfSuccLe theorem lt_of_succ_lt_succ {n m : Nat} : succ n < succ m → n < m := leOfSuccLeSucc theorem ltOfSuccLe {n m : Nat} (h : succ n ≤ m) : n < m := h theorem succLeOfLt {n m : Nat} (h : n < m) : succ n ≤ m := h theorem ltOrEqOrLeSucc {m n : Nat} (h : m ≤ succ n) : m ≤ n ∨ m = succ n := Decidable.byCases (fun (h' : m = succ n) => Or.inr h') (fun (h' : m ≠ succ n) => have m < succ n from Nat.ltOfLeAndNe h h' have succ m ≤ succ n from succLeOfLt this Or.inl (leOfSuccLeSucc this)) theorem leAddRight : ∀ (n k : Nat), n ≤ n + k | n, 0 => Nat.leRefl n | n, k+1 => leSuccOfLe (leAddRight n k) theorem leAddLeft (n m : Nat): n ≤ m + n := Nat.add_comm n m ▸ leAddRight n m theorem le.dest : ∀ {n m : Nat}, n ≤ m → Exists (fun k => n + k = m) | zero, zero, h => ⟨0, rfl⟩ | zero, succ n, h => ⟨succ n, Nat.add_comm 0 (succ n) ▸ rfl⟩ | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have n ≤ m from h have Exists (fun k => n + k = m) from dest this match this with | ⟨k, h⟩ => ⟨k, show succ n + k = succ m from ((succ_add n k).symm ▸ h ▸ rfl)⟩ theorem le.intro {n m k : Nat} (h : n + k = m) : n ≤ m := h ▸ leAddRight n k protected theorem notLeOfGt {n m : Nat} (h : n > m) : ¬ n ≤ m := fun h₁ => match Nat.ltOrGe n m with | Or.inl h₂ => absurd (Nat.ltTrans h h₂) (Nat.ltIrrefl _) | Or.inr h₂ => have Heq : n = m from Nat.leAntisymm h₁ h₂ absurd (@Eq.subst _ _ _ _ Heq h) (Nat.ltIrrefl m) theorem gtOfNotLe {n m : Nat} (h : ¬ n ≤ m) : n > m := match Nat.ltOrGe m n with | Or.inl h₁ => h₁ | Or.inr h₁ => absurd h₁ h protected theorem addLeAddLeft {n m : Nat} (h : n ≤ m) (k : Nat) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ => have h₁ : k + n + w = k + (n + w) from Nat.add_assoc .. have h₂ : k + (n + w) = k + m from congrArg _ hw le.intro <| h₁.trans h₂ protected theorem addLeAddRight {n m : Nat} (h : n ≤ m) (k : Nat) : n + k ≤ m + k := by rw [Nat.add_comm n k, Nat.add_comm m k] apply Nat.addLeAddLeft assumption protected theorem addLtAddLeft {n m : Nat} (h : n < m) (k : Nat) : k + n < k + m := ltOfSuccLe (add_succ k n ▸ Nat.addLeAddLeft (succLeOfLt h) k) protected theorem addLtAddRight {n m : Nat} (h : n < m) (k : Nat) : n + k < m + k := Nat.add_comm k m ▸ Nat.add_comm k n ▸ Nat.addLtAddLeft h k protected theorem zeroLtOne : 0 < (1:Nat) := zeroLtSucc 0 theorem addLeAdd {a b c d : Nat} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := Nat.leTrans (Nat.addLeAddRight h₁ c) (Nat.addLeAddLeft h₂ b) theorem addLtAdd {a b c d : Nat} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := Nat.ltTrans (Nat.addLtAddRight h₁ c) (Nat.addLtAddLeft h₂ b) /- Basic theorems for comparing numerals -/ theorem natZeroEqZero : Nat.zero = 0 := rfl protected theorem oneNeZero : 1 ≠ (0 : Nat) := fun h => Nat.noConfusion h protected theorem zeroNeOne : 0 ≠ (1 : Nat) := fun h => Nat.noConfusion h theorem succNeZero (n : Nat) : succ n ≠ 0 := fun h => Nat.noConfusion h /- mul + order -/ theorem mulLeMulLeft {n m : Nat} (k : Nat) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ => have k * n + k * l = k * m from Nat.left_distrib k n l ▸ hl.symm ▸ rfl le.intro this theorem mulLeMulRight {n m : Nat} (k : Nat) (h : n ≤ m) : n * k ≤ m * k := Nat.mul_comm k m ▸ Nat.mul_comm k n ▸ mulLeMulLeft k h protected theorem mulLeMul {n₁ m₁ n₂ m₂ : Nat} (h₁ : n₁ ≤ n₂) (h₂ : m₁ ≤ m₂) : n₁ * m₁ ≤ n₂ * m₂ := Nat.leTrans (mulLeMulRight _ h₁) (mulLeMulLeft _ h₂) protected theorem mulLtMulOfPosLeft {n m k : Nat} (h : n < m) (hk : k > 0) : k * n < k * m := Nat.ltOfLtOfLe (Nat.addLtAddLeft hk _) (Nat.mul_succ k n ▸ Nat.mulLeMulLeft k (succLeOfLt h)) protected theorem mulLtMulOfPosRight {n m k : Nat} (h : n < m) (hk : k > 0) : n * k < m * k := Nat.mul_comm k m ▸ Nat.mul_comm k n ▸ Nat.mulLtMulOfPosLeft h hk protected theorem mulPos {n m : Nat} (ha : n > 0) (hb : m > 0) : n * m > 0 := have h : 0 * m < n * m from Nat.mulLtMulOfPosRight ha hb Nat.zero_mul m ▸ h /- power -/ theorem powSucc (n m : Nat) : n^(succ m) = n^m * n := rfl theorem powZero (n : Nat) : n^0 = 1 := rfl theorem powLePowOfLeLeft {n m : Nat} (h : n ≤ m) : ∀ (i : Nat), n^i ≤ m^i | 0 => Nat.leRefl _ | succ i => Nat.mulLeMul (powLePowOfLeLeft h i) h theorem powLePowOfLeRight {n : Nat} (hx : n > 0) {i : Nat} : ∀ {j}, i ≤ j → n^i ≤ n^j | 0, h => have i = 0 from eqZeroOfLeZero h this.symm ▸ Nat.leRefl _ | succ j, h => match ltOrEqOrLeSucc h with | Or.inl h => show n^i ≤ n^j * n from have n^i * 1 ≤ n^j * n from Nat.mulLeMul (powLePowOfLeRight hx h) hx Nat.mul_one (n^i) ▸ this | Or.inr h => h.symm ▸ Nat.leRefl _ theorem posPowOfPos {n : Nat} (m : Nat) (h : 0 < n) : 0 < n^m := powLePowOfLeRight h (Nat.zeroLe _) /- min/max -/ protected def min (n m : Nat) : Nat := if n ≤ m then n else m protected def max (n m : Nat) : Nat := if n ≤ m then m else n end Nat namespace Prod @[inline] def foldI {α : Type u} (f : Nat → α → α) (i : Nat × Nat) (a : α) : α := Nat.foldAux f i.2 (i.2 - i.1) a @[inline] def anyI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux f i.2 (i.2 - i.1) @[inline] def allI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux (fun a => !f a) i.2 (i.2 - i.1) end Prod
96fcad2f9c8c1daa5804fa55bd898a99806b349a
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/implicitApplyIssue.lean
77bf5b34cd92ea5477a09c42977502bfc921046e
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
771
lean
def Set α := α → Prop class HasMem (α : outParam $ Type u) (β : Type v) where mem : α → β → Prop infix:50 " ∈ " => HasMem.mem instance : HasMem α (Set α) := ⟨λ a s => s a⟩ instance : LE (Set α) := ⟨λ s t => ∀ {x : α}, x ∈ s → x ∈ t⟩ class HasInf (P : Type u) where inf : P → P → P infix:70 " ⊓ " => HasInf.inf instance : HasInf (Set α) := ⟨λ s t x => x ∈ s ∧ x ∈ t⟩ theorem infLeLeft {s t : Set α} : s ⊓ t ≤ s := And.left theorem infLeRight {s t : Set α} : s ⊓ t ≤ t := And.right theorem inter_mem_sets_iff (f : Set (Set α)) (hf : ∀ {s t}, s ∈ f → s ≤ t → t ∈ f) : x ⊓ y ∈ f → x ∈ f ∧ y ∈ f := by intro h refine ⟨hf h infLeLeft, hf h ?_⟩ apply infLeRight
ebcb2c712862291be351dfce3369d6099cf48a31
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/auto_param2.lean
18ae7393a1cbe9d5dd55122b110be5faf0180d9b
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
622
lean
open tactic meta def my_tac : tactic unit := assumption <|> abstract (comp_val >> skip) <|> fail "my_tac failed to synthesize auto_param" def f (x : nat) (h : x > 0 . my_tac) : nat := nat.pred x #check f 12 #check f 13 lemma f_inj {x₁ x₂ : nat} {h₁ : x₁ > 0} {h₂ : x₂ > 0} : f x₁ = f x₂ → x₁ = x₂ := begin unfold f, intro h, cases x₁, exact absurd h₁ (lt_irrefl _), cases x₂, exact absurd h₂ (lt_irrefl _), apply congr_arg nat.succ, assumption end #check @f_inj lemma f_def {x : nat} (h : x > 0) : f x = nat.pred x := rfl -- The following is an error -- #check λ x, f x
e988d2cef1a5280a7f075aa041de5d34d4c6b4f5
367134ba5a65885e863bdc4507601606690974c1
/src/data/padics/padic_numbers.lean
5fa857dd6085b0c25985b6e41bc0a4fdd2486bc9
[ "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
38,234
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.padics.padic_norm import analysis.normed_space.basic /-! # p-adic numbers This file defines the p-adic numbers (rationals) `ℚ_p` as the completion of `ℚ` with respect to the p-adic norm. We show that the p-adic norm on ℚ extends to `ℚ_p`, that `ℚ` is embedded in `ℚ_p`, and that `ℚ_p` is Cauchy complete. ## Important definitions * `padic` : the type of p-adic numbers * `padic_norm_e` : the rational valued p-adic norm on `ℚ_p` ## Notation We introduce the notation `ℚ_[p]` for the p-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct ℝ. `ℚ_p` inherits a field structure from this construction. The extension of the norm on ℚ to `ℚ_p` is *not* analogous to extending the absolute value to ℝ, and hence the proof that `ℚ_p` is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued p-adic norm on `ℚ_p`. To instantiate `ℚ_p` as a normed field, we must cast this into a ℝ-valued norm. The `ℝ`-valued norm, using notation `∥ ∥` from normed spaces, is the canonical representation of this norm. `simp` prefers `padic_norm` to `padic_norm_e` when possible. Since `padic_norm_e` and `∥ ∥` have different types, `simp` does not rewrite one to the other. Coercions from `ℚ` to `ℚ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ noncomputable theory open_locale classical open nat multiplicity padic_norm cau_seq cau_seq.completion metric /-- The type of Cauchy sequences of rationals with respect to the p-adic norm. -/ @[reducible] def padic_seq (p : ℕ) := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [fact p.prime] /-- The p-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, N ≤ m → N ≤ n → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw [←hnam, sub_eq_add_neg, add_comm] at this, apply _root_.lt_irrefl _ this end ⟩ /-- For all n ≥ stationary_point f hf, the p-adic norm of f n is the same. -/ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, stationary_point hf ≤ m → stationary_point hf ≤ n → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [fact p.prime] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : 0 ≤ f.norm := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding section valuation open cau_seq variables {p : ℕ} [fact p.prime] /-! ### Valuation on `padic_seq` -/ /-- The `p`-adic valuation on `ℚ` lifts to `padic_seq p`. `valuation f` is defined to be the valuation of the (`ℚ`-valued) stationary point of `f`. -/ def valuation (f : padic_seq p) : ℤ := if hf : f ≈ 0 then 0 else padic_val_rat p (f (stationary_point hf)) lemma norm_eq_pow_val {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm = p^(-f.valuation : ℤ) := begin rw [norm, valuation, dif_neg hf, dif_neg hf, padic_norm, if_neg], intro H, apply cau_seq.not_lim_zero_of_not_congr_zero hf, intros ε hε, use (stationary_point hf), intros n hn, rw stationary_point_spec hf (le_refl _) hn, simpa [H] using hε, end lemma val_eq_iff_norm_eq {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : f.valuation = g.valuation ↔ f.norm = g.norm := begin rw [norm_eq_pow_val hf, norm_eq_pow_val hg, ← neg_inj, fpow_inj], { exact_mod_cast nat.prime.pos ‹_› }, { exact_mod_cast nat.prime.ne_one ‹_› }, end end valuation end padic_seq section open padic_seq private meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl >> tactic.skip), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : fact p.prime] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp only [hf, hg, norm, dif_pos, zero_mul] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp only [hf, hg, norm, dif_pos, mul_zero] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_values_discrete (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (z : ℤ), a.norm = ↑p ^ (-z)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.values_discrete p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.one_lt] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hlt : padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf))) : false := begin have hpn : 0 < padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)), from sub_pos_of_lt hlt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : N ≤ i, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hlt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hlt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf)))) with hlt hnlt, { exact norm_eq_of_equiv_aux hf hg hfg h hlt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hnlt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa only [hfg, norm, ne.def, le_max_iff, cau_seq.add_apply, not_true, dif_pos] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa only [sub_zero, add_sub_cancel] using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa only [add_sub_cancel', sub_zero] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp only [hf, hg, norm, dif_pos] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp only [h, forall_const, eq_self_iff_true]) hg, begin simp only [hg, hf, norm, dif_neg, not_false_iff], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa only [sub_zero, sub_neg_eq_add], have f.norm = (-g).norm, from norm_equiv this, by simpa only [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa only [sub_zero, add_sub_cancel], have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa only [sub_zero], have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, exact padic_norm.add_eq_max_of_ne p hfgne end end embedding end padic_seq /-- The p-adic numbers `Q_[p]` are the Cauchy completion of `ℚ` with respect to the p-adic norm. -/ def padic (p : ℕ) [fact p.prime] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [fact p.prime] /-- The discrete field structure on `ℚ_p` is inherited from the Cauchy completion construction. -/ instance field : field (ℚ_[p]) := cau_seq.completion.field instance : inhabited ℚ_[p] := ⟨0⟩ -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [fact p.prime] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq /-- Embeds the rational numbers in the p-adic numbers. -/ def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp [cast_eq_of_rat_of_nat] lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom', by simp [this, rat.mk_eq_div, of_rat_div, cast_eq_of_rat_of_int, cast_eq_of_rat_of_nat] @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[norm_cast] lemma coe_zero : (↑0 : ℚ_[p]) = 0 := rfl lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := by simp [cast_eq_of_rat, of_rat_eq] instance : char_zero ℚ_[p] := ⟨λ m n, by { rw ← rat.cast_coe_nat, norm_cast, exact id }⟩ end completion end padic /-- The rational-valued p-adic norm on `ℚ_p` is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `∥ ∥`. -/ def padic_norm_e {p : ℕ} [hp : fact p.prime] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [fact p.prime] lemma defn (f : padic_seq p) {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, ε ≤ (f - const _ (f i)).norm, by simpa only [not_forall, not_exists, not_lt] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em (N ≤ stationary_point hne) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : 0 ≤ padic_norm_e q := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_values_discrete f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [fact p.prime] (q : ℚ_[p]) {ε : ℚ} (hε : 0 < ε) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (stationary_point hne' ≤ N) with hle hle, { have := eq.symm (this (le_refl _) hle), simp only [const_apply, sub_apply, padic_norm.zero, sub_self] at this, simpa only [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [fact p.prime] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma div_nat_pos (n : ℕ) : 0 < (1 / ((n + 1): ℚ)) := div_pos zero_lt_one (by exact_mod_cast succ_pos _) /-- `lim_seq f`, for `f` a Cauchy sequence of `p`-adic numbers, is a sequence of rationals with the same limit point as `f`. -/ def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - ((lim_seq f) i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h ((div_le_iff' $ by exact_mod_cast succ_pos _).mpr _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact (div_le_iff hε).mp (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : 0 < ε / 3, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring at this ⊢, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { field_simp [this], simp only [bit0, bit1, mul_add, mul_one] }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa only [sub_add_sub_cancel], apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev], apply_mod_cast hN, exact le_of_max_le_left hj }, { apply hN2, exact le_of_max_le_right hj, apply le_max_right }}}, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show 0 < ε / 2, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show 0 < ε / 2, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, exact le_of_max_le_right hi }, { rw_mod_cast [padic_norm_e.sub_rev], apply hN, exact le_of_max_le_left hi }}} end ⟩ end complete section normed_space variables (p : ℕ) [fact p.prime] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, exact_mod_cast padic_norm_e.triangle_ineq _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul' := by simp [has_norm.norm, padic_norm_e.mul'] } instance is_absolute_value : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : fact p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : 0 < ε) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt_trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : fact p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥(↑q : ℚ_[p])∥ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat] end instance : nondiscrete_normed_field ℚ_[p] := { non_trivial := ⟨padic.of_rat p (p⁻¹), begin have h0 : p ≠ 0 := ne_of_gt (hp.pos), have h1 : 1 < p := hp.one_lt, rw [← padic.cast_eq_of_rat, eq_padic_norm], simp only [padic_norm, inv_eq_zero], simp only [if_neg] {discharger := `[exact_mod_cast h0]}, norm_cast, simp only [padic_val_rat.inv] {discharger := `[exact_mod_cast h0]}, rw [neg_neg, padic_val_rat.padic_val_rat_self h1], erw _root_.pow_one, exact_mod_cast h1, end⟩ } @[simp] lemma norm_p : ∥(p : ℚ_[p])∥ = p⁻¹ := begin have p₀ : p ≠ 0 := nat.prime.ne_zero ‹_›, have p₁ : p ≠ 1 := nat.prime.ne_one ‹_›, simp [p₀, p₁, norm, padic_norm, padic_val_rat, fpow_neg, padic.cast_eq_of_rat_of_nat], end lemma norm_p_lt_one : ∥(p : ℚ_[p])∥ < 1 := begin rw [norm_p, inv_eq_one_div, div_lt_iff, one_mul], { exact_mod_cast nat.prime.one_lt ‹_› }, { exact_mod_cast nat.prime.pos ‹_› } end @[simp] lemma norm_p_pow (n : ℤ) : ∥(p^n : ℚ_[p])∥ = p^-n := by rw [normed_field.norm_fpow, norm_p]; field_simp protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_values_discrete f this in ⟨n, congr_arg coe hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ /--`rat_norm q`, for a `p`-adic number `q` is the `p`-adic norm of `q`, as rational number. The lemma `padic_norm_e.eq_rat_norm` asserts `∥q∥ = rat_norm q`. -/ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : { rat . num := n, denom := d, pos := hn, cop := hd } ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_fpow_of_nonzero p hnz', padic_val_rat_def p hnz'], have h : (multiplicity p d).get _ = 0, by simp [multiplicity_eq_zero_of_not_dvd, hq], simp only, norm_cast, rw_mod_cast [h, sub_zero], apply fpow_le_one_of_nonpos, { exact_mod_cast le_of_lt hp.one_lt, }, { apply neg_nonpos_of_nonneg, norm_cast, simp, } end theorem norm_int_le_one (z : ℤ) : ∥(z : ℚ_[p])∥ ≤ 1 := suffices ∥((z : ℚ) : ℚ_[p])∥ ≤ 1, by simpa, norm_rat_le_one $ by simp [nat.prime.ne_one ‹_›] lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k := begin split, { intro h, contrapose! h, apply le_of_eq, rw eq_comm, calc ∥(k : ℚ_[p])∥ = ∥((k : ℚ) : ℚ_[p])∥ : by { norm_cast } ... = padic_norm p k : padic_norm_e.eq_padic_norm _ ... = 1 : _, rw padic_norm, split_ifs with H, { exfalso, apply h, norm_cast at H, rw H, apply dvd_zero }, { norm_cast at H ⊢, convert fpow_zero _, simp only [neg_eq_zero], rw padic_val_rat.padic_val_rat_of_int _ (nat.prime.ne_one ‹_›) H, norm_cast, rw [← enat.coe_inj, enat.coe_get, enat.coe_zero], apply multiplicity.multiplicity_eq_zero_of_not_dvd h } }, { rintro ⟨x, rfl⟩, push_cast, rw padic_norm_e.mul, calc _ ≤ ∥(p : ℚ_[p])∥ * 1 : mul_le_mul (le_refl _) (by simpa using norm_int_le_one _) (norm_nonneg _) (norm_nonneg _) ... < 1 : _, { rw [mul_one, padic_norm_e.norm_p], apply inv_lt_one, exact_mod_cast nat.prime.one_lt ‹_› }, }, end lemma norm_int_le_pow_iff_dvd (k : ℤ) (n : ℕ) : ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k := begin have : (p : ℝ) ^ (-n : ℤ) = ↑((p ^ (-n : ℤ) : ℚ)), {simp}, rw [show (k : ℚ_[p]) = ((k : ℚ) : ℚ_[p]), by norm_cast, eq_padic_norm, this], norm_cast, rw padic_norm.dvd_iff_norm_le, end lemma eq_of_norm_add_lt_right {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [fact p.prime] set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [cau_seq.sub_apply, padic_norm_e.sub_rev], refine lt_trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : 0 < a) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) /-! ### Valuation on `ℚ_[p]` -/ /-- `padic.valuation` lifts the p-adic valuation on rationals to `ℚ_[p]`. -/ def valuation : ℚ_[p] → ℤ := quotient.lift (@padic_seq.valuation p _) (λ f g h, begin by_cases hf : f ≈ 0, { have hg : g ≈ 0, from setoid.trans (setoid.symm h) hf, simp [hf, hg, padic_seq.valuation] }, { have hg : ¬ g ≈ 0, from (λ hg, hf (setoid.trans h hg)), rw padic_seq.val_eq_iff_norm_eq hf hg, exact padic_seq.norm_equiv h }, end) @[simp] lemma valuation_zero : valuation (0 : ℚ_[p]) = 0 := dif_pos ((const_equiv p).2 rfl) @[simp] lemma valuation_one : valuation (1 : ℚ_[p]) = 0 := begin change dite (cau_seq.const (padic_norm p) 1 ≈ _) _ _ = _, have h : ¬ cau_seq.const (padic_norm p) 1 ≈ 0, { assume H, erw const_equiv p at H, exact one_ne_zero H }, rw dif_neg h, simp, end lemma norm_eq_pow_val {x : ℚ_[p]} : x ≠ 0 → ∥x∥ = p^(-x.valuation) := begin apply quotient.induction_on' x, clear x, intros f hf, change (padic_seq.norm _ : ℝ) = (p : ℝ) ^ -padic_seq.valuation _, rw padic_seq.norm_eq_pow_val, change ↑((p : ℚ) ^ -padic_seq.valuation f) = (p : ℝ) ^ -padic_seq.valuation f, { rw rat.cast_fpow, congr' 1, norm_cast }, { apply cau_seq.not_lim_zero_of_not_congr_zero, contrapose! hf, apply quotient.sound, simpa using hf, } end @[simp] lemma valuation_p : valuation (p : ℚ_[p]) = 1 := begin have h : (1 : ℝ) < p := by exact_mod_cast nat.prime.one_lt ‹_›, rw ← neg_inj, apply (fpow_strict_mono h).injective, dsimp only, rw ← norm_eq_pow_val, { simp }, { exact_mod_cast nat.prime.ne_zero ‹_›, } end end padic
642c5b86d169d60b3e3b0d9e0ed42a6739ab3ef7
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/test/tactics.lean
1d068e1fe1957b6e3fabf80ecf1940aadb9af607
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
18,788
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import tactic data.set.lattice data.prod data.vector tactic.rewrite data.stream.basic tactic.tfae tactic.converter.interactive tactic.ring tactic.ring2 section tauto₀ variables p q r : Prop variables h : p ∧ q ∨ p ∧ r include h example : p ∧ p := by tauto end tauto₀ section tauto₁ variables α : Type variables p q r : α → Prop variables h : (∃ x, p x ∧ q x) ∨ (∃ x, p x ∧ r x) include h example : ∃ x, p x := by tauto end tauto₁ section tauto₂ variables α : Type variables x : α variables p q r : α → Prop variables h₀ : (∀ x, p x → q x → r x) ∨ r x variables h₁ : p x variables h₂ : q x include h₀ h₁ h₂ example : ∃ x, r x := by tauto end tauto₂ section tauto₃ example (p : Prop) : p ∧ true ↔ p := by tauto example (p : Prop) : p ∨ false ↔ p := by tauto example (p q r : Prop) [decidable p] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto example (p q r : Prop) [decidable q] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ p) : q := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : p) : ¬ q := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : q) : ¬ p := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ q) : p := by tauto example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ q) (h'' : ¬ p) : false := by tauto example (p q r : Prop) [decidable q] [decidable p] (h : p ↔ q) (h' : r ↔ q) (h'' : ¬ r) : ¬ p := by tauto example (p q r : Prop) (h : p ↔ q) (h' : r ↔ q) : p ↔ r := by tauto! example (p q r : Prop) (h : ¬ p = q) (h' : r = q) : p ↔ ¬ r := by tauto! section modulo_symmetry variables {p q r : Prop} {α : Type} {x y : α} variables (h : x = y) variables (h'' : (p ∧ q ↔ q ∨ r) ↔ (r ∧ p ↔ r ∨ q)) include h include h'' example (h' : ¬ y = x) : p ∧ q := by tauto example (h' : p ∧ ¬ y = x) : p ∧ q := by tauto example : y = x := by tauto example (h' : ¬ x = y) : p ∧ q := by tauto example : x = y := by tauto end modulo_symmetry end tauto₃ section wlog example {x y : ℕ} (a : x = 1) : true := begin suffices : false, trivial, wlog h : x = y, { guard_target x = y ∨ y = x, admit }, { guard_hyp h := x = y, guard_hyp a := x = 1, admit } end example {x y : ℕ} : true := begin suffices : false, trivial, wlog h : x ≤ y, { guard_hyp h := x ≤ y, guard_target false, admit } end example {x y z : ℕ} : true := begin suffices : false, trivial, wlog : x ≤ y + z using x y, { guard_target x ≤ y + z ∨ y ≤ x + z, admit }, { guard_hyp case := x ≤ y + z, guard_target false, admit }, end example {x : ℕ} (S₀ S₁ : set ℕ) (P : ℕ → Prop) (h : x ∈ S₀ ∪ S₁) : true := begin suffices : false, trivial, wlog h' : x ∈ S₀ using S₀ S₁, { guard_target x ∈ S₀ ∨ x ∈ S₁, admit }, { guard_hyp h := x ∈ S₀ ∪ S₁, guard_hyp h' := x ∈ S₀, admit } end example {n m i : ℕ} {p : ℕ → ℕ → ℕ → Prop} : true := begin suffices : false, trivial, wlog : p n m i using [n m i, n i m, i n m], { guard_target p n m i ∨ p n i m ∨ p i n m, admit }, { guard_hyp case := p n m i, admit } end example {n m i : ℕ} {p : ℕ → Prop} : true := begin suffices : false, trivial, wlog : p n using [n m i, m n i, i n m], { guard_target p n ∨ p m ∨ p i, admit }, { guard_hyp case := p n, admit } end example {n m i : ℕ} {p : ℕ → ℕ → Prop} {q : ℕ → ℕ → ℕ → Prop} : true := begin suffices : q n m i, trivial, have h : p n i ∨ p i m ∨ p m i, from sorry, wlog : p n i := h using n m i, { guard_hyp h := p n i, guard_target q n m i, admit }, { guard_hyp h := p i m, guard_hyp this := q i m n, guard_target q n m i, admit }, { guard_hyp h := p m i, guard_hyp this := q m i n, guard_target q n m i, admit }, end example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := begin ext x, split, { intro hyp, cases hyp, wlog x_in : x ∈ B using B C, { assumption }, { exact or.inl ⟨hyp_left, x_in⟩ } }, { intro hyp, wlog x_in : x ∈ A ∩ B using B C, { assumption }, { exact ⟨x_in.left, or.inl x_in.right⟩ } } end example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := begin ext x, split, { intro hyp, wlog x_in : x ∈ B := hyp.2 using B C, { exact or.inl ⟨hyp.1, x_in⟩ } }, { intro hyp, wlog x_in : x ∈ A ∩ B := hyp using B C, { exact ⟨x_in.left, or.inl x_in.right⟩ } } end example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) := begin ext x, split, { intro hyp, cases hyp, wlog x_in : x ∈ B := hyp_right using B C, { exact or.inl ⟨hyp_left, x_in⟩ }, }, { intro hyp, wlog x_in : x ∈ A ∩ B := hyp using B C, { exact ⟨x_in.left, or.inl x_in.right⟩ } } end end wlog example (m n p q : nat) (h : m + n = p) : true := begin have : m + n = q, { generalize_hyp h' : m + n = x at h, guard_hyp h' := m + n = x, guard_hyp h := x = p, guard_target m + n = q, admit }, have : m + n = q, { generalize_hyp h' : m + n = x at h ⊢, guard_hyp h' := m + n = x, guard_hyp h := x = p, guard_target x = q, admit }, trivial end example (α : Sort*) (L₁ L₂ L₃ : list α) (H : L₁ ++ L₂ = L₃) : true := begin have : L₁ ++ L₂ = L₂, { generalize_hyp h : L₁ ++ L₂ = L at H, induction L with hd tl ih, case list.nil { tactic.cleanup, change list.nil = L₃ at H, admit }, case list.cons { change list.cons hd tl = L₃ at H, admit } }, trivial end section convert open set variables {α β : Type} local attribute [simp] private lemma singleton_inter_singleton_eq_empty {x y : α} : ({x} ∩ {y} = (∅ : set α)) ↔ x ≠ y := by simp [singleton_inter_eq_empty] example {f : β → α} {x y : α} (h : x ≠ y) : f ⁻¹' {x} ∩ f ⁻¹' {y} = ∅ := begin have : {x} ∩ {y} = (∅ : set α) := by simpa using h, convert preimage_empty, rw [←preimage_inter,this], end end convert section rcases universe u variables {α β γ : Type u} example (x : α × β × γ) : true := begin rcases x with ⟨a, b, c⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example (x : α × β × γ) : true := begin rcases x with ⟨a, ⟨b, c⟩⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example (x : (α × β) × γ) : true := begin rcases x with ⟨⟨a, b⟩, c⟩, { guard_hyp a := α, guard_hyp b := β, guard_hyp c := γ, trivial } end example (x : inhabited α × option β ⊕ γ) : true := begin rcases x with ⟨⟨a⟩, _ | b⟩ | c, { guard_hyp a := α, trivial }, { guard_hyp a := α, guard_hyp b := β, trivial }, { guard_hyp c := γ, trivial } end example (x y : ℕ) (h : x = y) : true := begin rcases x with _|⟨⟩|z, { guard_hyp h := nat.zero = y, trivial }, { guard_hyp h := nat.succ nat.zero = y, trivial }, { guard_hyp z := ℕ, guard_hyp h := z.succ.succ = y, trivial }, end -- from equiv.sum_empty example (s : α ⊕ empty) : true := begin rcases s with _ | ⟨⟨⟩⟩, { guard_hyp s := α, trivial } end end rcases section ext @[extensionality] lemma unit.ext (x y : unit) : x = y := begin cases x, cases y, refl end example : subsingleton unit := begin split, intros, ext end example (x y : ℕ) : true := begin have : x = y, { ext <|> admit }, have : x = y, { ext i <|> admit }, have : x = y, { ext : 1 <|> admit }, trivial end example (X Y : ℕ × ℕ) (h : X.1 = Y.1) (h : X.2 = Y.2) : X = Y := begin ext; assumption end example (X Y : (ℕ → ℕ) × ℕ) (h : ∀ i, X.1 i = Y.1 i) (h : X.2 = Y.2) : X = Y := begin ext x; solve_by_elim, end example (X Y : ℕ → ℕ × ℕ) (h : ∀ i, X i = Y i) : true := begin have : X = Y, { ext i : 1, guard_target X i = Y i, admit }, have : X = Y, { ext i, guard_target (X i).fst = (Y i).fst, admit, guard_target (X i).snd = (Y i).snd, admit, }, have : X = Y, { ext : 1, guard_target X x = Y x, admit }, trivial, end example (s₀ s₁ : set ℕ) (h : s₁ = s₀) : s₀ = s₁ := by { ext1, guard_target x ∈ s₀ ↔ x ∈ s₁, simp * } example (s₀ s₁ : stream ℕ) (h : s₁ = s₀) : s₀ = s₁ := by { ext1, guard_target s₀.nth n = s₁.nth n, simp * } example (s₀ s₁ : ℤ → set (ℕ × ℕ)) (h : ∀ i a b, (a,b) ∈ s₀ i ↔ (a,b) ∈ s₁ i) : s₀ = s₁ := begin ext i ⟨a,b⟩, apply h end def my_foo {α} (x : semigroup α) (y : group α) : true := trivial example {α : Type} : true := begin have : true, { refine_struct (@my_foo α { .. } { .. } ), -- 9 goals guard_tags _field mul semigroup, admit, -- case semigroup, mul -- α : Type -- ⊢ α → α → α guard_tags _field mul_assoc semigroup, admit, -- case semigroup, mul_assoc -- α : Type -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) guard_tags _field mul group, admit, -- case group, mul -- α : Type -- ⊢ α → α → α guard_tags _field mul_assoc group, admit, -- case group, mul_assoc -- α : Type -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) guard_tags _field one group, admit, -- case group, one -- α : Type -- ⊢ α guard_tags _field one_mul group, admit, -- case group, one_mul -- α : Type -- ⊢ ∀ (a : α), 1 * a = a guard_tags _field mul_one group, admit, -- case group, mul_one -- α : Type -- ⊢ ∀ (a : α), a * 1 = a guard_tags _field inv group, admit, -- case group, inv -- α : Type -- ⊢ α → α guard_tags _field mul_left_inv group, admit, -- case group, mul_left_inv -- α : Type -- ⊢ ∀ (a : α), a⁻¹ * a = 1 }, trivial end def my_bar {α} (x : semigroup α) (y : group α) (i j : α) : α := i example {α : Type} : true := begin have : monoid α, { refine_struct { mul := my_bar { .. } { .. } }, guard_tags _field mul semigroup, admit, guard_tags _field mul_assoc semigroup, admit, guard_tags _field mul group, admit, guard_tags _field mul_assoc group, admit, guard_tags _field one group, admit, guard_tags _field one_mul group, admit, guard_tags _field mul_one group, admit, guard_tags _field inv group, admit, guard_tags _field mul_left_inv group, admit, guard_tags _field mul_assoc monoid, admit, guard_tags _field one monoid, admit, guard_tags _field one_mul monoid, admit, guard_tags _field mul_one monoid, admit, }, trivial end structure dependent_fields := (a : bool) (v : if a then ℕ else ℤ) @[extensionality] lemma df.ext (s t : dependent_fields) (h : s.a = t.a) (w : (@eq.rec _ s.a (λ b, if b then ℕ else ℤ) s.v t.a h) = t.v): s = t := begin cases s, cases t, dsimp at *, congr, exact h, subst h, simp, simp at w, exact w, end example (s : dependent_fields) : s = s := begin tactic.ext1 [] {tactic.apply_cfg . new_goals := tactic.new_goals.all}, guard_target s.a = s.a, refl, refl, end end ext section apply_rules example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules [mono_rules] example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules mono_rules end apply_rules section h_generalize variables {α β γ φ ψ : Type} (f : α → α → α → φ → γ) (x y : α) (a b : β) (z : φ) (h₀ : β = α) (h₁ : β = α) (h₂ : φ = β) (hx : x == a) (hy : y == b) (hz : z == a) include f x y z a b hx hy hz example : f x y x z = f (eq.rec_on h₀ a) (cast h₀ b) (eq.mpr h₁.symm a) (eq.mpr h₂ a) := begin guard_hyp_nums 16, h_generalize hp : a == p with hh, guard_hyp_nums 19, guard_hyp' hh := β = α, guard_target f x y x z = f p (cast h₀ b) p (eq.mpr h₂ a), h_generalize hq : _ == q, guard_hyp_nums 21, guard_target f x y x z = f p q p (eq.mpr h₂ a), h_generalize _ : _ == r, guard_hyp_nums 23, guard_target f x y x z = f p q p r, casesm* [_ == _, _ = _], refl end end h_generalize section h_generalize variables {α β γ φ ψ : Type} (f : list α → list α → γ) (x : list α) (a : list β) (z : φ) (h₀ : β = α) (h₁ : list β = list α) (hx : x == a) include f x z a hx h₀ h₁ example : true := begin have : f x x = f (eq.rec_on h₀ a) (cast h₁ a), { guard_hyp_nums 11, h_generalize : a == p with _, guard_hyp_nums 13, guard_hyp' h := β = α, guard_target f x x = f p (cast h₁ a), h_generalize! : a == q , guard_hyp_nums 13, guard_target ∀ q, f x x = f p q, casesm* [_ == _, _ = _], success_if_fail { refl }, admit }, trivial end end h_generalize section assoc_rw open tactic example : ∀ x y z a b c : ℕ, true := begin intros, have : x + (y + z) = 3 + y, admit, have : a + (b + x) + y + (z + b + c) ≤ 0, (do this ← get_local `this, tgt ← to_expr ```(a + (b + x) + y + (z + b + c)), assoc ← mk_mapp ``add_monoid.add_assoc [`(ℕ),none], (l,p) ← assoc_rewrite_intl assoc this tgt, note `h none p ), erw h, guard_target a + b + 3 + y + b + c ≤ 0, admit, trivial end example : ∀ x y z a b c : ℕ, true := begin intros, have : ∀ y, x + (y + z) = 3 + y, admit, have : a + (b + x) + y + (z + b + c) ≤ 0, (do this ← get_local `this, tgt ← to_expr ```(a + (b + x) + y + (z + b + c)), assoc_rewrite_target this ), guard_target a + b + 3 + y + b + c ≤ 0, admit, trivial end variables x y z a b c : ℕ variables h₀ : ∀ (y : ℕ), x + (y + z) = 3 + y variables h₁ : a + (b + x) + y + (z + b + a) ≤ 0 variables h₂ : y + b + c = y + b + a include h₀ h₁ h₂ example : a + (b + x) + y + (z + b + c) ≤ 0 := by { assoc_rw [h₀,h₂] at *, guard_hyp _inst := is_associative ℕ has_add.add, -- keep a local instance of is_associative to cache -- type class queries exact h₁ } end assoc_rw -- section tfae -- example (p q r s : Prop) -- (h₀ : p ↔ q) -- (h₁ : q ↔ r) -- (h₂ : r ↔ s) : -- p ↔ s := -- begin -- scc, -- end -- example (p' p q r r' s s' : Prop) -- (h₀ : p' → p) -- (h₀ : p → q) -- (h₁ : q → r) -- (h₁ : r' → r) -- (h₂ : r ↔ s) -- (h₂ : s → p) -- (h₂ : s → s') : -- p ↔ s := -- begin -- scc, -- end -- example (p' p q r r' s s' : Prop) -- (h₀ : p' → p) -- (h₀ : p → q) -- (h₁ : q → r) -- (h₁ : r' → r) -- (h₂ : r ↔ s) -- (h₂ : s → p) -- (h₂ : s → s') : -- p ↔ s := -- begin -- scc', -- assumption -- end -- example : tfae [true, ∀ n : ℕ, 0 ≤ n * n, true, true] := begin -- tfae_have : 3 → 1, { intro h, constructor }, -- tfae_have : 2 → 3, { intro h, constructor }, -- tfae_have : 2 ← 1, { intros h n, apply nat.zero_le }, -- tfae_have : 4 ↔ 2, { tauto }, -- tfae_finish, -- end -- example : tfae [] := begin -- tfae_finish, -- end -- end tfae section conv example : 0 + 0 = 0 := begin conv_lhs {erw [add_zero]} end example : 0 + 0 = 0 := begin conv_lhs {simp} end example : 0 = 0 + 0 := begin conv_rhs {simp} end -- Example with ring discharging the goal example : 22 + 7 * 4 + 3 * 8 = 0 + 7 * 4 + 46 := begin conv { ring, }, end -- Example with ring failing to discharge, to normalizing the goal example : (22 + 7 * 4 + 3 * 8 = 0 + 7 * 4 + 47) = (74 = 75) := begin conv { ring, }, end -- Example with ring discharging the goal example (x : ℕ) : 22 + 7 * x + 3 * 8 = 0 + 7 * x + 46 := begin conv { ring, }, end -- Example with ring failing to discharge, to normalizing the goal example (x : ℕ) : (22 + 7 * x + 3 * 8 = 0 + 7 * x + 46 + 1) = (7 * x + 46 = 7 * x + 47) := begin conv { ring, }, end -- norm_num examples: example : 22 + 7 * 4 + 3 * 8 = 74 := begin conv { norm_num, }, end example (x : ℕ) : 22 + 7 * x + 3 * 8 = 7 * x + 46 := begin conv { norm_num, }, end end conv section clear_aux_decl example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n := let ⟨a, ha⟩ := h₂ in begin clear_aux_decl, -- subst will fail without this line subst h₁ end example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, -- finish produces an error without this line finish end end clear_aux_decl private meta def get_exception_message (t : lean.parser unit) : lean.parser string | s := match t s with | result.success a s' := result.success "No exception" s | result.exception none pos s' := result.success "Exception no msg" s | result.exception (some msg) pos s' := result.success (msg ()).to_string s end @[user_command] meta def test_parser1_fail_cmd (_ : interactive.parse (lean.parser.tk "test_parser1")) : lean.parser unit := do let msg := "oh, no!", let t : lean.parser unit := tactic.fail msg, s ← get_exception_message t, if s = msg then tactic.skip else interaction_monad.fail "Message was corrupted while being passed through `lean.parser.of_tactic`" . -- Due to `lean.parser.of_tactic'` priority, the following *should not* fail with -- a VM check error, and instead catch the error gracefully and just -- run and succeed silently. test_parser1
e1fc09b73a0bd5c698ddfaf2b5464cfb5904670e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/dep_coe_to_fn3.lean
279b752a1ccd670899125507625e18f3f321189a
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
684
lean
universe variables u v structure Func := (A : Type u) (B : A → Type v) (fn : Π a, B a → B a) instance F_to_fn : has_coe_to_fun Func _:= { coe := λ f a b, f^.fn a (f^.fn a b) } variables (f : Func) (a : f^.A) (b : f^.B a) #check (f a b) def f1 : Func := { A := nat, B := λ a, nat, fn := (+) } -- set_option trace.type_context.is_def_eq_detail true /- We need to mark 10 as a nat. Reason: f1 is not reducible, then type class resolution cannot find an instance for `has_one (Func.A f1)` -/ example : f1 (10:nat) (30:nat) = (50:nat) := rfl /- #exit attribute [reducible] f1 example : f1 10 30 = 50 := rfl example (n m : nat) : f1 n m = n + (n + m) := rfl -/
41b9373460f5ceb2274eaaf1639401029a6e33e3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/multilinear_auto.lean
ffafd6bcbc24d25af61754f2261290e39ee8946b
[]
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
55,989
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.basic import Mathlib.algebra.algebra.basic import Mathlib.tactic.omega.default import Mathlib.data.fintype.sort import Mathlib.PostPort universes u v w u' l v₁ v₂ u_1 v₃ v' u_2 u_3 u_5 u_6 u_7 u_4 namespace Mathlib /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w) [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] where to_fun : ((i : ι) → M₁ i) → M₂ map_add' : ∀ (m : (i : ι) → M₁ i) (i : ι) (x y : M₁ i), to_fun (function.update m i (x + y)) = to_fun (function.update m i x) + to_fun (function.update m i y) map_smul' : ∀ (m : (i : ι) → M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (function.update m i (c • x)) = c • to_fun (function.update m i x) namespace multilinear_map protected instance has_coe_to_fun {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] : has_coe_to_fun (multilinear_map R M₁ M₂) := has_coe_to_fun.mk (fun (x : multilinear_map R M₁ M₂) => ((i : ι) → M₁ i) → M₂) to_fun @[simp] theorem to_fun_eq_coe {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) : to_fun f = ⇑f := rfl @[simp] theorem coe_mk {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : ((i : ι) → M₁ i) → M₂) (h₁ : ∀ (m : (i : ι) → M₁ i) (i : ι) (x y : M₁ i), f (function.update m i (x + y)) = f (function.update m i x) + f (function.update m i y)) (h₂ : ∀ (m : (i : ι) → M₁ i) (i : ι) (c : R) (x : M₁ i), f (function.update m i (c • x)) = c • f (function.update m i x)) : ⇑(mk f h₁ h₂) = f := rfl theorem congr_fun {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {f : multilinear_map R M₁ M₂} {g : multilinear_map R M₁ M₂} (h : f = g) (x : (i : ι) → M₁ i) : coe_fn f x = coe_fn g x := congr_arg (fun (h : multilinear_map R M₁ M₂) => coe_fn h x) h theorem congr_arg {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) {x : (i : ι) → M₁ i} {y : (i : ι) → M₁ i} (h : x = y) : coe_fn f x = coe_fn f y := congr_arg (fun (x : (i : ι) → M₁ i) => coe_fn f x) h theorem coe_inj {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {f : multilinear_map R M₁ M₂} {g : multilinear_map R M₁ M₂} (h : ⇑f = ⇑g) : f = g := sorry theorem ext {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {f : multilinear_map R M₁ M₂} {f' : multilinear_map R M₁ M₂} (H : ∀ (x : (i : ι) → M₁ i), coe_fn f x = coe_fn f' x) : f = f' := coe_inj (funext H) theorem ext_iff {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {f : multilinear_map R M₁ M₂} {g : multilinear_map R M₁ M₂} : f = g ↔ ∀ (x : (i : ι) → M₁ i), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : (i : ι) → M₁ i) => h ▸ rfl, mpr := fun (h : ∀ (x : (i : ι) → M₁ i), coe_fn f x = coe_fn g x) => ext h } @[simp] theorem map_add {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) (i : ι) (x : M₁ i) (y : M₁ i) : coe_fn f (function.update m i (x + y)) = coe_fn f (function.update m i x) + coe_fn f (function.update m i y) := map_add' f m i x y @[simp] theorem map_smul {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) (i : ι) (c : R) (x : M₁ i) : coe_fn f (function.update m i (c • x)) = c • coe_fn f (function.update m i x) := map_smul' f m i c x theorem map_coord_zero {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) {m : (i : ι) → M₁ i} (i : ι) (h : m i = 0) : coe_fn f m = 0 := sorry @[simp] theorem map_update_zero {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) (i : ι) : coe_fn f (function.update m i 0) = 0 := map_coord_zero f i (function.update_same i 0 m) @[simp] theorem map_zero {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) [Nonempty ι] : coe_fn f 0 = 0 := Exists.dcases_on (set.exists_mem_of_nonempty ι) fun (i : ι) (h : i ∈ set.univ) => map_coord_zero f i rfl protected instance has_add {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] : Add (multilinear_map R M₁ M₂) := { add := fun (f f' : multilinear_map R M₁ M₂) => mk (fun (x : (i : ι) → M₁ i) => coe_fn f x + coe_fn f' x) sorry sorry } @[simp] theorem add_apply {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (f' : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) : coe_fn (f + f') m = coe_fn f m + coe_fn f' m := rfl protected instance has_zero {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] : HasZero (multilinear_map R M₁ M₂) := { zero := mk (fun (_x : (i : ι) → M₁ i) => 0) sorry sorry } protected instance inhabited {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] : Inhabited (multilinear_map R M₁ M₂) := { default := 0 } @[simp] theorem zero_apply {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (m : (i : ι) → M₁ i) : coe_fn 0 m = 0 := rfl protected instance add_comm_monoid {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] : add_comm_monoid (multilinear_map R M₁ M₂) := add_comm_monoid.mk Add.add sorry 0 sorry sorry sorry @[simp] theorem sum_apply {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {α : Type u_1} (f : α → multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) {s : finset α} : coe_fn (finset.sum s fun (a : α) => f a) m = finset.sum s fun (a : α) => coe_fn (f a) m := sorry /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) (i : ι) : linear_map R (M₁ i) M₂ := linear_map.mk (fun (x : M₁ i) => coe_fn f (function.update m i x)) sorry sorry /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := mk (fun (m : (i : ι) → M₁ i) => (coe_fn f m, coe_fn g m)) sorry sorry /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {R : Type u} {M₂ : Type v₂} {M' : Type v'} [semiring R] [add_comm_monoid M₂] [add_comm_monoid M'] [semimodule R M₂] [semimodule R M'] {k : ℕ} {n : ℕ} (f : multilinear_map R (fun (i : fin n) => M') M₂) (s : finset (fin n)) (hk : finset.card s = k) (z : M') : multilinear_map R (fun (i : fin k) => M') M₂ := mk (fun (v : fin k → M') => coe_fn f fun (j : fin n) => dite (j ∈ s) (fun (h : j ∈ s) => v (coe_fn (order_iso.symm (finset.order_iso_of_fin s hk)) { val := j, property := h })) fun (h : ¬j ∈ s) => z) sorry sorry /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ theorem cons_add {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) (m : (i : fin n) → M (fin.succ i)) (x : M 0) (y : M 0) : coe_fn f (fin.cons (x + y) m) = coe_fn f (fin.cons x m) + coe_fn f (fin.cons y m) := sorry /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ theorem cons_smul {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) (m : (i : fin n) → M (fin.succ i)) (c : R) (x : M 0) : coe_fn f (fin.cons (c • x) m) = c • coe_fn f (fin.cons x m) := sorry /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ theorem snoc_add {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) (m : (i : fin n) → M (coe_fn fin.cast_succ i)) (x : M (fin.last n)) (y : M (fin.last n)) : coe_fn f (fin.snoc m (x + y)) = coe_fn f (fin.snoc m x) + coe_fn f (fin.snoc m y) := sorry /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ theorem snoc_smul {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) (m : (i : fin n) → M (coe_fn fin.cast_succ i)) (c : R) (x : M (fin.last n)) : coe_fn f (fin.snoc m (c • x)) = c • coe_fn f (fin.snoc m x) := sorry /-- If `g` is a multilinear map and `f` is a collection of linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a multilinear map, that we call `g.comp_linear_map f`. -/ def comp_linear_map {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {M₁' : ι → Type u_1} [(i : ι) → add_comm_monoid (M₁' i)] [(i : ι) → semimodule R (M₁' i)] (g : multilinear_map R M₁' M₂) (f : (i : ι) → linear_map R (M₁ i) (M₁' i)) : multilinear_map R M₁ M₂ := mk (fun (m : (i : ι) → M₁ i) => coe_fn g fun (i : ι) => coe_fn (f i) (m i)) sorry sorry @[simp] theorem comp_linear_map_apply {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {M₁' : ι → Type u_1} [(i : ι) → add_comm_monoid (M₁' i)] [(i : ι) → semimodule R (M₁' i)] (g : multilinear_map R M₁' M₂) (f : (i : ι) → linear_map R (M₁ i) (M₁' i)) (m : (i : ι) → M₁ i) : coe_fn (comp_linear_map g f) m = coe_fn g fun (i : ι) => coe_fn (f i) (m i) := rfl /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ theorem map_piecewise_add {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) (m' : (i : ι) → M₁ i) (t : finset ι) : coe_fn f (finset.piecewise t (m + m') m') = finset.sum (finset.powerset t) fun (s : finset ι) => coe_fn f (finset.piecewise s m m') := sorry /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ theorem map_add_univ {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) [fintype ι] (m : (i : ι) → M₁ i) (m' : (i : ι) → M₁ i) : coe_fn f (m + m') = finset.sum finset.univ fun (s : finset ι) => coe_fn f (finset.piecewise s m m') := sorry /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ theorem map_sum_finset_aux {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) {α : ι → Type u_1} (g : (i : ι) → α i → M₁ i) (A : (i : ι) → finset (α i)) [fintype ι] {n : ℕ} (h : (finset.sum finset.univ fun (i : ι) => finset.card (A i)) = n) : (coe_fn f fun (i : ι) => finset.sum (A i) fun (j : α i) => g i j) = finset.sum (fintype.pi_finset A) fun (r : (a : ι) → α a) => coe_fn f fun (i : ι) => g i (r i) := sorry /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ theorem map_sum_finset {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) {α : ι → Type u_1} (g : (i : ι) → α i → M₁ i) (A : (i : ι) → finset (α i)) [fintype ι] : (coe_fn f fun (i : ι) => finset.sum (A i) fun (j : α i) => g i j) = finset.sum (fintype.pi_finset A) fun (r : (a : ι) → α a) => coe_fn f fun (i : ι) => g i (r i) := map_sum_finset_aux f (fun (i : ι) (j : α i) => g i j) (fun (i : ι) => A i) rfl /-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ theorem map_sum {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) {α : ι → Type u_1} (g : (i : ι) → α i → M₁ i) [fintype ι] [(i : ι) → fintype (α i)] : (coe_fn f fun (i : ι) => finset.sum finset.univ fun (j : α i) => g i j) = finset.sum finset.univ fun (r : (i : ι) → α i) => coe_fn f fun (i : ι) => g i (r i) := map_sum_finset f g fun (i : ι) => finset.univ theorem map_update_sum {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) {α : Type u_1} (t : finset α) (i : ι) (g : α → M₁ i) (m : (i : ι) → M₁ i) : coe_fn f (function.update m i (finset.sum t fun (a : α) => g a)) = finset.sum t fun (a : α) => coe_fn f (function.update m i (g a)) := sorry /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved semimodules agree with the action of `R` on `A`. -/ def restrict_scalars (R : Type u) {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {A : Type u_1} [semiring A] [has_scalar R A] [(i : ι) → semimodule A (M₁ i)] [semimodule A M₂] [∀ (i : ι), is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] (f : multilinear_map A M₁ M₂) : multilinear_map R M₁ M₂ := mk ⇑f sorry sorry @[simp] theorem coe_restrict_scalars (R : Type u) {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] {A : Type u_1} [semiring A] [has_scalar R A] [(i : ι) → semimodule A (M₁ i)] [semimodule A M₂] [∀ (i : ι), is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] (f : multilinear_map A M₁ M₂) : ⇑(restrict_scalars R f) = ⇑f := rfl /-- Transfer the arguments to a map along an equivalence between argument indices. The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the domain of the domain. -/ @[simp] theorem dom_dom_congr_apply {R : Type u} {M₂ : Type v₂} {M₃ : Type v₃} [semiring R] [add_comm_monoid M₂] [add_comm_monoid M₃] [semimodule R M₂] [semimodule R M₃] {ι₁ : Type u_1} {ι₂ : Type u_2} [DecidableEq ι₁] [DecidableEq ι₂] (σ : ι₁ ≃ ι₂) (m : multilinear_map R (fun (i : ι₁) => M₂) M₃) (v : ι₂ → M₂) : coe_fn (dom_dom_congr σ m) v = coe_fn m fun (i : ι₁) => v (coe_fn σ i) := Eq.refl (coe_fn (dom_dom_congr σ m) v) theorem dom_dom_congr_trans {R : Type u} {M₂ : Type v₂} {M₃ : Type v₃} [semiring R] [add_comm_monoid M₂] [add_comm_monoid M₃] [semimodule R M₂] [semimodule R M₃] {ι₁ : Type u_1} {ι₂ : Type u_2} {ι₃ : Type u_3} [DecidableEq ι₁] [DecidableEq ι₂] [DecidableEq ι₃] (σ₁ : ι₁ ≃ ι₂) (σ₂ : ι₂ ≃ ι₃) (m : multilinear_map R (fun (i : ι₁) => M₂) M₃) : dom_dom_congr (equiv.trans σ₁ σ₂) m = dom_dom_congr σ₂ (dom_dom_congr σ₁ m) := rfl theorem dom_dom_congr_mul {R : Type u} {M₂ : Type v₂} {M₃ : Type v₃} [semiring R] [add_comm_monoid M₂] [add_comm_monoid M₃] [semimodule R M₂] [semimodule R M₃] {ι₁ : Type u_1} [DecidableEq ι₁] (σ₁ : equiv.perm ι₁) (σ₂ : equiv.perm ι₁) (m : multilinear_map R (fun (i : ι₁) => M₂) M₃) : dom_dom_congr (σ₂ * σ₁) m = dom_dom_congr σ₂ (dom_dom_congr σ₁ m) := rfl /-- `multilinear_map.dom_dom_congr` as an equivalence. This is declared separately because it does not work with dot notation. -/ def dom_dom_congr_equiv {R : Type u} {M₂ : Type v₂} {M₃ : Type v₃} [semiring R] [add_comm_monoid M₂] [add_comm_monoid M₃] [semimodule R M₂] [semimodule R M₃] {ι₁ : Type u_1} {ι₂ : Type u_2} [DecidableEq ι₁] [DecidableEq ι₂] (σ : ι₁ ≃ ι₂) : multilinear_map R (fun (i : ι₁) => M₂) M₃ ≃+ multilinear_map R (fun (i : ι₂) => M₂) M₃ := add_equiv.mk (dom_dom_congr σ) (dom_dom_congr (equiv.symm σ)) sorry sorry sorry end multilinear_map namespace linear_map /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] (g : linear_map R M₂ M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := multilinear_map.mk (⇑g ∘ ⇑f) sorry sorry @[simp] theorem coe_comp_multilinear_map {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] (g : linear_map R M₂ M₃) (f : multilinear_map R M₁ M₂) : ⇑(comp_multilinear_map g f) = ⇑g ∘ ⇑f := rfl theorem comp_multilinear_map_apply {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] [semimodule R M₃] (g : linear_map R M₂ M₃) (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) : coe_fn (comp_multilinear_map g f) m = coe_fn g (coe_fn f m) := rfl @[simp] theorem comp_multilinear_map_dom_dom_congr {R : Type u} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [semiring R] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [semimodule R M₂] [semimodule R M₃] [semimodule R M'] {ι₁ : Type u_1} {ι₂ : Type u_2} [DecidableEq ι₁] [DecidableEq ι₂] (σ : ι₁ ≃ ι₂) (g : linear_map R M₂ M₃) (f : multilinear_map R (fun (i : ι₁) => M') M₂) : multilinear_map.dom_dom_congr σ (comp_multilinear_map g f) = comp_multilinear_map g (multilinear_map.dom_dom_congr σ f) := sorry end linear_map namespace multilinear_map /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ theorem map_piecewise_smul {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [comm_semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (c : ι → R) (m : (i : ι) → M₁ i) (s : finset ι) : coe_fn f (finset.piecewise s (fun (i : ι) => c i • m i) m) = (finset.prod s fun (i : ι) => c i) • coe_fn f m := sorry /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. -/ theorem map_smul_univ {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [comm_semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) [fintype ι] (c : ι → R) (m : (i : ι) → M₁ i) : (coe_fn f fun (i : ι) => c i • m i) = (finset.prod finset.univ fun (i : ι) => c i) • coe_fn f m := sorry protected instance has_scalar {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] {R' : Type u_1} {A : Type u_2} [monoid R'] [semiring A] [(i : ι) → semimodule A (M₁ i)] [distrib_mul_action R' M₂] [semimodule A M₂] [smul_comm_class A R' M₂] : has_scalar R' (multilinear_map A M₁ M₂) := has_scalar.mk fun (c : R') (f : multilinear_map A M₁ M₂) => mk (fun (m : (i : ι) → M₁ i) => c • coe_fn f m) sorry sorry @[simp] theorem smul_apply {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] {R' : Type u_1} {A : Type u_2} [monoid R'] [semiring A] [(i : ι) → semimodule A (M₁ i)] [distrib_mul_action R' M₂] [semimodule A M₂] [smul_comm_class A R' M₂] (f : multilinear_map A M₁ M₂) (c : R') (m : (i : ι) → M₁ i) : coe_fn (c • f) m = c • coe_fn f m := rfl protected instance distrib_mul_action {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] {R' : Type u_1} {A : Type u_2} [monoid R'] [semiring A] [(i : ι) → semimodule A (M₁ i)] [distrib_mul_action R' M₂] [semimodule A M₂] [smul_comm_class A R' M₂] : distrib_mul_action R' (multilinear_map A M₁ M₂) := distrib_mul_action.mk sorry sorry /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ protected instance semimodule {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] {R' : Type u_1} {A : Type u_2} [semiring R'] [semiring A] [(i : ι) → semimodule A (M₁ i)] [semimodule R' M₂] [semimodule A M₂] [smul_comm_class A R' M₂] : semimodule R' (multilinear_map A M₁ M₂) := semimodule.mk sorry sorry /-- Given two multilinear maps `(ι₁ → N) → N₁` and `(ι₂ → N) → N₂`, this produces the map `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂` by taking the coproduct of the domain and the tensor product of the codomain. This can be thought of as combining `equiv.sum_arrow_equiv_prod_arrow.symm` with `tensor_product.map`, noting that the two operations can't be separated as the intermediate result is not a `multilinear_map`. While this can be generalized to work for dependent `Π i : ι₁, N'₁ i` instead of `ι₁ → N`, doing so introduces `sum.elim N'₁ N'₂` types in the result which are difficult to work with and not defeq to the simple case defined here. See [this zulip thread]( https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there.20code.20for.20X.3F/topic/Instances.20on.20.60sum.2Eelim.20A.20B.20i.60/near/218484619). -/ def dom_coprod {R : Type u} [comm_semiring R] {ι₁ : Type u_1} {ι₂ : Type u_2} [DecidableEq ι₁] [DecidableEq ι₂] {N₁ : Type u_5} [add_comm_monoid N₁] [semimodule R N₁] {N₂ : Type u_6} [add_comm_monoid N₂] [semimodule R N₂] {N : Type u_7} [add_comm_monoid N] [semimodule R N] (a : multilinear_map R (fun (_x : ι₁) => N) N₁) (b : multilinear_map R (fun (_x : ι₂) => N) N₂) : multilinear_map R (fun (_x : ι₁ ⊕ ι₂) => N) (tensor_product R N₁ N₂) := mk (fun (v : ι₁ ⊕ ι₂ → N) => tensor_product.tmul R (coe_fn a fun (i : ι₁) => v (sum.inl i)) (coe_fn b fun (i : ι₂) => v (sum.inr i))) sorry sorry /-- A more bundled version of `multilinear_map.dom_coprod` that maps `((ι₁ → N) → N₁) ⊗ ((ι₂ → N) → N₂)` to `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂`. -/ def dom_coprod' {R : Type u} [comm_semiring R] {ι₁ : Type u_1} {ι₂ : Type u_2} [DecidableEq ι₁] [DecidableEq ι₂] {N₁ : Type u_5} [add_comm_monoid N₁] [semimodule R N₁] {N₂ : Type u_6} [add_comm_monoid N₂] [semimodule R N₂] {N : Type u_7} [add_comm_monoid N] [semimodule R N] : linear_map R (tensor_product R (multilinear_map R (fun (_x : ι₁) => N) N₁) (multilinear_map R (fun (_x : ι₂) => N) N₂)) (multilinear_map R (fun (_x : ι₁ ⊕ ι₂) => N) (tensor_product R N₁ N₂)) := tensor_product.lift (linear_map.mk₂ R dom_coprod sorry sorry sorry sorry) @[simp] theorem dom_coprod'_apply {R : Type u} [comm_semiring R] {ι₁ : Type u_1} {ι₂ : Type u_2} [DecidableEq ι₁] [DecidableEq ι₂] {N₁ : Type u_5} [add_comm_monoid N₁] [semimodule R N₁] {N₂ : Type u_6} [add_comm_monoid N₂] [semimodule R N₂] {N : Type u_7} [add_comm_monoid N] [semimodule R N] (a : multilinear_map R (fun (_x : ι₁) => N) N₁) (b : multilinear_map R (fun (_x : ι₂) => N) N₂) : coe_fn dom_coprod' (tensor_product.tmul R a b) = dom_coprod a b := rfl /-- When passed an `equiv.sum_congr`, `multilinear_map.dom_dom_congr` distributes over `multilinear_map.dom_coprod`. -/ theorem dom_coprod_dom_dom_congr_sum_congr {R : Type u} [comm_semiring R] {ι₁ : Type u_1} {ι₂ : Type u_2} {ι₃ : Type u_3} {ι₄ : Type u_4} [DecidableEq ι₁] [DecidableEq ι₂] [DecidableEq ι₃] [DecidableEq ι₄] {N₁ : Type u_5} [add_comm_monoid N₁] [semimodule R N₁] {N₂ : Type u_6} [add_comm_monoid N₂] [semimodule R N₂] {N : Type u_7} [add_comm_monoid N] [semimodule R N] (a : multilinear_map R (fun (_x : ι₁) => N) N₁) (b : multilinear_map R (fun (_x : ι₂) => N) N₂) (σa : ι₁ ≃ ι₃) (σb : ι₂ ≃ ι₄) : dom_dom_congr (equiv.sum_congr σa σb) (dom_coprod a b) = dom_coprod (dom_dom_congr σa a) (dom_dom_congr σb b) := rfl /-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ι` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative algebra `A` but requires `ι = fin n`. -/ protected def mk_pi_algebra (R : Type u) (ι : Type u') [DecidableEq ι] [comm_semiring R] (A : Type u_1) [comm_semiring A] [algebra R A] [fintype ι] : multilinear_map R (fun (i : ι) => A) A := mk (fun (m : ι → A) => finset.prod finset.univ fun (i : ι) => m i) sorry sorry @[simp] theorem mk_pi_algebra_apply {R : Type u} {ι : Type u'} [DecidableEq ι] [comm_semiring R] {A : Type u_1} [comm_semiring A] [algebra R A] [fintype ι] (m : ι → A) : coe_fn (multilinear_map.mk_pi_algebra R ι A) m = finset.prod finset.univ fun (i : ι) => m i := rfl /-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works for `A^ι` with any finite type `ι`. -/ protected def mk_pi_algebra_fin (R : Type u) (n : ℕ) [comm_semiring R] (A : Type u_1) [semiring A] [algebra R A] : multilinear_map R (fun (i : fin n) => A) A := mk (fun (m : fin n → A) => list.prod (list.of_fn m)) sorry sorry @[simp] theorem mk_pi_algebra_fin_apply {R : Type u} {n : ℕ} [comm_semiring R] {A : Type u_1} [semiring A] [algebra R A] (m : fin n → A) : coe_fn (multilinear_map.mk_pi_algebra_fin R n A) m = list.prod (list.of_fn m) := rfl theorem mk_pi_algebra_fin_apply_const {R : Type u} {n : ℕ} [comm_semiring R] {A : Type u_1} [semiring A] [algebra R A] (a : A) : (coe_fn (multilinear_map.mk_pi_algebra_fin R n A) fun (_x : fin n) => a) = a ^ n := sorry /-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map sending `m` to `f m • z`. -/ def smul_right {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [comm_semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ R) (z : M₂) : multilinear_map R M₁ M₂ := linear_map.comp_multilinear_map (linear_map.smul_right linear_map.id z) f @[simp] theorem smul_right_apply {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [comm_semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ R) (z : M₂) (m : (i : ι) → M₁ i) : coe_fn (smul_right f z) m = coe_fn f m • z := rfl /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module). See also `mk_pi_algebra` for a more general version. -/ protected def mk_pi_ring (R : Type u) (ι : Type u') {M₂ : Type v₂} [DecidableEq ι] [comm_semiring R] [add_comm_monoid M₂] [semimodule R M₂] [fintype ι] (z : M₂) : multilinear_map R (fun (i : ι) => R) M₂ := smul_right (multilinear_map.mk_pi_algebra R ι R) z @[simp] theorem mk_pi_ring_apply {R : Type u} {ι : Type u'} {M₂ : Type v₂} [DecidableEq ι] [comm_semiring R] [add_comm_monoid M₂] [semimodule R M₂] [fintype ι] (z : M₂) (m : ι → R) : coe_fn (multilinear_map.mk_pi_ring R ι z) m = (finset.prod finset.univ fun (i : ι) => m i) • z := rfl theorem mk_pi_ring_apply_one_eq_self {R : Type u} {ι : Type u'} {M₂ : Type v₂} [DecidableEq ι] [comm_semiring R] [add_comm_monoid M₂] [semimodule R M₂] [fintype ι] (f : multilinear_map R (fun (i : ι) => R) M₂) : multilinear_map.mk_pi_ring R ι (coe_fn f fun (i : ι) => 1) = f := sorry protected instance has_neg {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_group M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] : Neg (multilinear_map R M₁ M₂) := { neg := fun (f : multilinear_map R M₁ M₂) => mk (fun (m : (i : ι) → M₁ i) => -coe_fn f m) sorry sorry } @[simp] theorem neg_apply {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_group M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) : coe_fn (-f) m = -coe_fn f m := rfl protected instance has_sub {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_group M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] : Sub (multilinear_map R M₁ M₂) := { sub := fun (f g : multilinear_map R M₁ M₂) => mk (fun (m : (i : ι) → M₁ i) => coe_fn f m - coe_fn g m) sorry sorry } @[simp] theorem sub_apply {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_group M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) : coe_fn (f - g) m = coe_fn f m - coe_fn g m := rfl protected instance add_comm_group {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_group M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] : add_comm_group (multilinear_map R M₁ M₂) := add_comm_group.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry @[simp] theorem map_neg {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_group (M₁ i)] [add_comm_group M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) (i : ι) (x : M₁ i) : coe_fn f (function.update m i (-x)) = -coe_fn f (function.update m i x) := sorry @[simp] theorem map_sub {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [semiring R] [(i : ι) → add_comm_group (M₁ i)] [add_comm_group M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] (f : multilinear_map R M₁ M₂) (m : (i : ι) → M₁ i) (i : ι) (x : M₁ i) (y : M₁ i) : coe_fn f (function.update m i (x - y)) = coe_fn f (function.update m i x) - coe_fn f (function.update m i y) := sorry /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv {R : Type u} {ι : Type u'} {M₂ : Type v₂} [DecidableEq ι] [comm_semiring R] [add_comm_group M₂] [semimodule R M₂] [fintype ι] : linear_equiv R M₂ (multilinear_map R (fun (i : ι) => R) M₂) := linear_equiv.mk (fun (z : M₂) => multilinear_map.mk_pi_ring R ι z) sorry sorry (fun (f : multilinear_map R (fun (i : ι) => R) M₂) => coe_fn f fun (i : ι) => 1) sorry sorry end multilinear_map /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : linear_map R (M 0) (multilinear_map R (fun (i : fin n) => M (fin.succ i)) M₂)) : multilinear_map R M M₂ := multilinear_map.mk (fun (m : (i : fin (Nat.succ n)) → M i) => coe_fn (coe_fn f (m 0)) (fin.tail m)) sorry sorry @[simp] theorem linear_map.uncurry_left_apply {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : linear_map R (M 0) (multilinear_map R (fun (i : fin n) => M (fin.succ i)) M₂)) (m : (i : fin (Nat.succ n)) → M i) : coe_fn (linear_map.uncurry_left f) m = coe_fn (coe_fn f (m 0)) (fin.tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) : linear_map R (M 0) (multilinear_map R (fun (i : fin n) => M (fin.succ i)) M₂) := linear_map.mk (fun (x : M 0) => multilinear_map.mk (fun (m : (i : fin n) → M (fin.succ i)) => coe_fn f (fin.cons x m)) sorry sorry) sorry sorry @[simp] theorem multilinear_map.curry_left_apply {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) (x : M 0) (m : (i : fin n) → M (fin.succ i)) : coe_fn (coe_fn (multilinear_map.curry_left f) x) m = coe_fn f (fin.cons x m) := rfl @[simp] theorem linear_map.curry_uncurry_left {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : linear_map R (M 0) (multilinear_map R (fun (i : fin n) => M (fin.succ i)) M₂)) : multilinear_map.curry_left (linear_map.uncurry_left f) = f := sorry @[simp] theorem multilinear_map.uncurry_curry_left {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) : linear_map.uncurry_left (multilinear_map.curry_left f) = f := sorry /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv (R : Type u) {n : ℕ} (M : fin (Nat.succ n) → Type v) (M₂ : Type v₂) [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] : linear_equiv R (linear_map R (M 0) (multilinear_map R (fun (i : fin n) => M (fin.succ i)) M₂)) (multilinear_map R M M₂) := linear_equiv.mk linear_map.uncurry_left sorry sorry multilinear_map.curry_left linear_map.curry_uncurry_left sorry /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R (fun (i : fin n) => M (coe_fn fin.cast_succ i)) (linear_map R (M (fin.last n)) M₂)) : multilinear_map R M M₂ := multilinear_map.mk (fun (m : (i : fin (Nat.succ n)) → M i) => coe_fn (coe_fn f (fin.init m)) (m (fin.last n))) sorry sorry @[simp] theorem multilinear_map.uncurry_right_apply {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R (fun (i : fin n) => M (coe_fn fin.cast_succ i)) (linear_map R (M (fin.last n)) M₂)) (m : (i : fin (Nat.succ n)) → M i) : coe_fn (multilinear_map.uncurry_right f) m = coe_fn (coe_fn f (fin.init m)) (m (fin.last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) : multilinear_map R (fun (i : fin n) => M (coe_fn fin.cast_succ i)) (linear_map R (M (fin.last n)) M₂) := multilinear_map.mk (fun (m : (i : fin n) → M (coe_fn fin.cast_succ i)) => linear_map.mk (fun (x : M (fin.last n)) => coe_fn f (fin.snoc m x)) sorry sorry) sorry sorry @[simp] theorem multilinear_map.curry_right_apply {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) (m : (i : fin n) → M (coe_fn fin.cast_succ i)) (x : M (fin.last n)) : coe_fn (coe_fn (multilinear_map.curry_right f) m) x = coe_fn f (fin.snoc m x) := rfl @[simp] theorem multilinear_map.curry_uncurry_right {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R (fun (i : fin n) => M (coe_fn fin.cast_succ i)) (linear_map R (M (fin.last n)) M₂)) : multilinear_map.curry_right (multilinear_map.uncurry_right f) = f := sorry @[simp] theorem multilinear_map.uncurry_curry_right {R : Type u} {n : ℕ} {M : fin (Nat.succ n) → Type v} {M₂ : Type v₂} [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] (f : multilinear_map R M M₂) : multilinear_map.uncurry_right (multilinear_map.curry_right f) = f := sorry /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv (R : Type u) {n : ℕ} (M : fin (Nat.succ n) → Type v) (M₂ : Type v₂) [comm_semiring R] [(i : fin (Nat.succ n)) → add_comm_monoid (M i)] [add_comm_monoid M₂] [(i : fin (Nat.succ n)) → semimodule R (M i)] [semimodule R M₂] : linear_equiv R (multilinear_map R (fun (i : fin n) => M (coe_fn fin.cast_succ i)) (linear_map R (M (fin.last n)) M₂)) (multilinear_map R M M₂) := linear_equiv.mk multilinear_map.uncurry_right sorry sorry multilinear_map.curry_right multilinear_map.curry_uncurry_right sorry namespace multilinear_map /-- The pushforward of an indexed collection of submodule `p i ⊆ M₁ i` by `f : M₁ → M₂`. Note that this is not a submodule - it is not closed under addition. -/ def map {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [ring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] [Nonempty ι] (f : multilinear_map R M₁ M₂) (p : (i : ι) → submodule R (M₁ i)) : sub_mul_action R M₂ := sub_mul_action.mk (⇑f '' set_of fun (v : (i : ι) → M₁ i) => ∀ (i : ι), v i ∈ p i) sorry /-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/ theorem map_nonempty {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [ring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] [Nonempty ι] (f : multilinear_map R M₁ M₂) (p : (i : ι) → submodule R (M₁ i)) : set.nonempty ↑(map f p) := Exists.intro (coe_fn f 0) (Exists.intro 0 { left := fun (i : ι) => submodule.zero_mem (p i), right := rfl }) /-- The range of a multilinear map, closed under scalar multiplication. -/ def range {R : Type u} {ι : Type u'} {M₁ : ι → Type v₁} {M₂ : Type v₂} [DecidableEq ι] [ring R] [(i : ι) → add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [(i : ι) → semimodule R (M₁ i)] [semimodule R M₂] [Nonempty ι] (f : multilinear_map R M₁ M₂) : sub_mul_action R M₂ := map f fun (i : ι) => ⊤ end Mathlib
e0aee35034acd0f1f5b6eb2e2c4d1a4156e156b8
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/abelian/left_derived.lean
8600b4b02535af5fdf6bc44f97a72ac5eef86f94
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,180
lean
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca, Adam Topaz -/ import category_theory.abelian.homology import category_theory.functor.left_derived import category_theory.abelian.projective import category_theory.limits.constructions.epi_mono /-! # Zeroth left derived functors If `F : C ⥤ D` is an additive right exact functor between abelian categories, where `C` has enough projectives, we provide the natural isomorphism `F.left_derived 0 ≅ F`. ## Main definitions * `category_theory.abelian.functor.left_derived_zero_iso_self`: the natural isomorphism `(F.left_derived 0) ≅ F`. ## Main results * `preserves_exact_of_preserves_finite_colimits_of_epi`: if `preserves_finite_colimits F` and `epi g`, then `exact (F.map f) (F.map g)` if `exact f g`. -/ noncomputable theory universes w v u open category_theory.limits category_theory category_theory.functor variables {C : Type u} [category.{w} C] {D : Type u} [category.{w} D] variables (F : C ⥤ D) {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} namespace category_theory.abelian.functor open category_theory.preadditive variables [abelian C] [abelian D] [additive F] /-- If `preserves_finite_colimits F` and `epi g`, then `exact (F.map f) (F.map g)` if `exact f g`. -/ lemma preserves_exact_of_preserves_finite_colimits_of_epi [preserves_finite_colimits F] [epi g] (ex : exact f g) : exact (F.map f) (F.map g) := abelian.exact_of_is_cokernel _ _ (by simp [← functor.map_comp, ex.w]) $ limits.is_colimit_cofork_map_of_is_colimit' _ ex.w (abelian.is_colimit_of_exact_of_epi _ _ ex) lemma exact_of_map_projective_resolution (P: ProjectiveResolution X) [preserves_finite_colimits F] : exact (((F.map_homological_complex (complex_shape.down ℕ)).obj P.complex).d_to 0) (F.map (P.π.f 0)) := preadditive.exact_of_iso_of_exact' (F.map (P.complex.d 1 0)) (F.map (P.π.f 0)) _ _ (homological_complex.X_prev_iso ((F.map_homological_complex _).obj P.complex) rfl).symm (iso.refl _) (iso.refl _) (by simp) (by simp) (preserves_exact_of_preserves_finite_colimits_of_epi _ (P.exact₀)) /-- Given `P : ProjectiveResolution X`, a morphism `(F.left_derived 0).obj X ⟶ F.obj X`. -/ @[nolint unused_arguments] def left_derived_zero_to_self_app [enough_projectives C] {X : C} (P : ProjectiveResolution X) : (F.left_derived 0).obj X ⟶ F.obj X := (left_derived_obj_iso F 0 P).hom ≫ homology.desc' _ _ _ (kernel.ι _ ≫ (F.map (P.π.f 0))) begin rw [kernel.lift_ι_assoc, homological_complex.d_to_eq _ (by simp : (complex_shape.down ℕ).rel 1 0), map_homological_complex_obj_d, category.assoc, ← functor.map_comp], simp end /-- Given `P : ProjectiveResolution X`, a morphism `F.obj X ⟶ (F.left_derived 0).obj X` given `preserves_finite_colimits F`. -/ def left_derived_zero_to_self_app_inv [enough_projectives C] [preserves_finite_colimits F] {X : C} (P : ProjectiveResolution X) : F.obj X ⟶ (F.left_derived 0).obj X := begin refine ((as_iso (cokernel.desc _ _ (exact_of_map_projective_resolution F P).w)).inv) ≫ _ ≫ (homology_iso_cokernel_lift _ _ _).inv ≫ (left_derived_obj_iso F 0 P).inv, exact cokernel.map _ _ (𝟙 _) (kernel.lift _ (𝟙 _) (by simp)) (by { ext, simp }), end lemma left_derived_zero_to_self_app_comp_inv [enough_projectives C] [preserves_finite_colimits F] {X : C} (P : ProjectiveResolution X) : left_derived_zero_to_self_app F P ≫ left_derived_zero_to_self_app_inv F P = 𝟙 _ := begin dsimp [left_derived_zero_to_self_app, left_derived_zero_to_self_app_inv], rw [← category.assoc, ← category.assoc, ← category.assoc, iso.comp_inv_eq, category.id_comp, category.assoc, category.assoc, category.assoc], convert category.comp_id _, rw [← category.assoc, ← category.assoc, iso.comp_inv_eq, category.id_comp], ext, rw [← category.assoc, ← category.assoc, homology.π'_desc', category.assoc, category.assoc, ← category.assoc (F.map _), abelian.cokernel.desc.inv, cokernel.π_desc, homology.π', category.assoc, iso.inv_hom_id, category.comp_id, ← category.assoc], convert category.id_comp _ using 2, ext, rw [category.id_comp, category.assoc, equalizer_as_kernel, kernel.lift_ι, category.comp_id], end lemma left_derived_zero_to_self_app_inv_comp [enough_projectives C] [preserves_finite_colimits F] {X : C} (P : ProjectiveResolution X) : left_derived_zero_to_self_app_inv F P ≫ left_derived_zero_to_self_app F P = 𝟙 _ := begin dsimp [left_derived_zero_to_self_app, left_derived_zero_to_self_app_inv], rw [category.assoc, category.assoc, category.assoc, ← category.assoc (F.left_derived_obj_iso 0 P).inv, iso.inv_hom_id, category.id_comp, is_iso.inv_comp_eq, category.comp_id], ext, simp only [cokernel.π_desc_assoc, category.assoc, cokernel.π_desc, homology.desc'], rw [← category.assoc, ← category.assoc (homology_iso_cokernel_lift _ _ _).inv, iso.inv_hom_id, category.id_comp], simp only [category.assoc, cokernel.π_desc, kernel.lift_ι_assoc, category.id_comp], end /-- Given `P : ProjectiveResolution X`, the isomorphism `(F.left_derived 0).obj X ≅ F.obj X` if `preserves_finite_colimits F`. -/ def left_derived_zero_to_self_app_iso [enough_projectives C] [preserves_finite_colimits F] {X : C} (P : ProjectiveResolution X) : (F.left_derived 0).obj X ≅ F.obj X := { hom := left_derived_zero_to_self_app _ P, inv := left_derived_zero_to_self_app_inv _ P, hom_inv_id' := left_derived_zero_to_self_app_comp_inv _ P, inv_hom_id' := left_derived_zero_to_self_app_inv_comp _ P } /-- Given `P : ProjectiveResolution X` and `Q : ProjectiveResolution Y` and a morphism `f : X ⟶ Y`, naturality of the square given by `left_derived_zero_to_self_obj_hom. -/ lemma left_derived_zero_to_self_natural [enough_projectives C] {X : C} {Y : C} (f : X ⟶ Y) (P : ProjectiveResolution X) (Q : ProjectiveResolution Y) : (F.left_derived 0).map f ≫ left_derived_zero_to_self_app F Q = left_derived_zero_to_self_app F P ≫ F.map f := begin dsimp only [left_derived_zero_to_self_app], rw [functor.left_derived_map_eq F 0 f (ProjectiveResolution.lift f P Q) (by simp), category.assoc, category.assoc, ← category.assoc _ (F.left_derived_obj_iso 0 Q).hom, iso.inv_hom_id, category.id_comp, category.assoc, whisker_eq], dsimp only [homology_functor_map], ext, simp only [homological_complex.hom.sq_to_right, map_homological_complex_map_f, homology.π'_map_assoc, homology.π'_desc', kernel.lift_ι_assoc, category.assoc, homology.π'_desc'_assoc, ← map_comp, show (ProjectiveResolution.lift f P Q).f 0 ≫ _ = _ ≫ f, from homological_complex.congr_hom (ProjectiveResolution.lift_commutes f P Q) 0], end /-- Given `preserves_finite_colimits F`, the natural isomorphism `(F.left_derived 0) ≅ F`. -/ def left_derived_zero_iso_self [enough_projectives C] [preserves_finite_colimits F] : (F.left_derived 0) ≅ F := nat_iso.of_components (λ X, left_derived_zero_to_self_app_iso _ (ProjectiveResolution.of X)) (λ X Y f, left_derived_zero_to_self_natural _ _ _ _) end category_theory.abelian.functor
f8a06fc7be54e146d10c9cb799352ebc5f7b2640
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/tactic/omega/nat/main.lean
908c4b05b6fdc9cc6943ae9010132805c7e2b792
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
4,887
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Main procedure for linear natural number arithmetic. -/ import tactic.omega.prove_unsats import tactic.omega.nat.dnf import tactic.omega.nat.neg_elim import tactic.omega.nat.sub_elim open tactic namespace omega namespace nat open_locale omega.nat run_cmd mk_simp_attr `sugar_nat attribute [sugar_nat] ne not_le not_lt nat.lt_iff_add_one_le nat.succ_eq_add_one or_false false_or and_true true_and ge gt mul_add add_mul mul_comm one_mul mul_one classical.imp_iff_not_or classical.iff_iff_not_or_and_or_not meta def desugar := `[try {simp only with sugar_nat}] lemma univ_close_of_unsat_neg_elim_not (m) (p : form) : (neg_elim (¬* p)).unsat → univ_close p (λ _, 0) m := begin intro h1, apply univ_close_of_valid, apply valid_of_unsat_not, intro h2, apply h1, apply form.sat_of_implies_of_sat implies_neg_elim h2, end meta def preterm.prove_sub_free : preterm → tactic expr | (& m) := return `(trivial) | (m ** n) := return `(trivial) | (t +* s) := do x ← preterm.prove_sub_free t, y ← preterm.prove_sub_free s, return `(@and.intro (preterm.sub_free %%`(t)) (preterm.sub_free %%`(s)) %%x %%y) | (_ -* _) := failed meta def prove_neg_free : form → tactic expr | (t =* s) := return `(trivial) | (t ≤* s) := return `(trivial) | (p ∨* q) := do x ← prove_neg_free p, y ← prove_neg_free q, return `(@and.intro (form.neg_free %%`(p)) (form.neg_free %%`(q)) %%x %%y) | (p ∧* q) := do x ← prove_neg_free p, y ← prove_neg_free q, return `(@and.intro (form.neg_free %%`(p)) (form.neg_free %%`(q)) %%x %%y) | _ := failed meta def prove_sub_free : form → tactic expr | (t =* s) := do x ← preterm.prove_sub_free t, y ← preterm.prove_sub_free s, return `(@and.intro (preterm.sub_free %%`(t)) (preterm.sub_free %%`(s)) %%x %%y) | (t ≤* s) := do x ← preterm.prove_sub_free t, y ← preterm.prove_sub_free s, return `(@and.intro (preterm.sub_free %%`(t)) (preterm.sub_free %%`(s)) %%x %%y) | (¬*p) := prove_sub_free p | (p ∨* q) := do x ← prove_sub_free p, y ← prove_sub_free q, return `(@and.intro (form.sub_free %%`(p)) (form.sub_free %%`(q)) %%x %%y) | (p ∧* q) := do x ← prove_sub_free p, y ← prove_sub_free q, return `(@and.intro (form.sub_free %%`(p)) (form.sub_free %%`(q)) %%x %%y) /- Given a p : form, return the expr of a term t : p.unsat, where p is subtraction- and negation-free. -/ meta def prove_unsat_sub_free (p : form) : tactic expr := do x ← prove_neg_free p, y ← prove_sub_free p, z ← prove_unsats (dnf p), return `(unsat_of_unsat_dnf %%`(p) %%x %%y %%z) /- Given a p : form, return the expr of a term t : p.unsat, where p is negation-free. -/ meta def prove_unsat_neg_free : form → tactic expr | p := match p.sub_terms with | none := prove_unsat_sub_free p | (some (t,s)) := do x ← prove_unsat_neg_free (sub_elim t s p), return `(unsat_of_unsat_sub_elim %%`(t) %%`(s) %%`(p) %%x) end /- Given a (m : nat) and (p : form), return the expr of (t : univ_close m p) -/ meta def prove_univ_close (m : nat) (p : form) : tactic expr := do x ← prove_unsat_neg_free (neg_elim (¬*p)), to_expr ``(univ_close_of_unsat_neg_elim_not %%`(m) %%`(p) %%x) meta def to_preterm : expr → tactic preterm | (expr.var k) := return (preterm.var 1 k) | `(%%(expr.var k) * %%mx) := do m ← eval_expr nat mx, return (preterm.var m k) | `(%%t1x + %%t2x) := do t1 ← to_preterm t1x, t2 ← to_preterm t2x, return (preterm.add t1 t2) | `(%%t1x - %%t2x) := do t1 ← to_preterm t1x, t2 ← to_preterm t2x, return (preterm.sub t1 t2) | mx := do m ← eval_expr nat mx, return (preterm.cst m) meta def to_form_core : expr → tactic form | `(%%tx1 = %%tx2) := do t1 ← to_preterm tx1, t2 ← to_preterm tx2, return (t1 =* t2) | `(%%tx1 ≤ %%tx2) := do t1 ← to_preterm tx1, t2 ← to_preterm tx2, return (t1 ≤* t2) | `(¬ %%px) := do p ← to_form_core px, return (¬* p) | `(%%px ∨ %%qx) := do p ← to_form_core px, q ← to_form_core qx, return (p ∨* q) | `(%%px ∧ %%qx) := do p ← to_form_core px, q ← to_form_core qx, return (p ∧* q) | `(_ → %%px) := to_form_core px | x := trace "Cannot reify expr : " >> trace x >> failed meta def to_form : nat → expr → tactic (form × nat) | m `(_ → %%px) := to_form (m+1) px | m x := do p ← to_form_core x, return (p,m) meta def prove_lna : tactic expr := do (p,m) ← target >>= to_form 0, prove_univ_close m p end nat end omega open omega.nat meta def omega_nat : tactic unit := desugar >> (done <|> (prove_lna >>= apply >> skip))
abe78a401c0d3ecea09b5a6e23c680eaabab3784
63abd62053d479eae5abf4951554e1064a4c45b4
/src/logic/function/basic.lean
ee2b3d0520c5f0492562bb6289d3b202255c40bf
[ "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
20,739
lean
/- Copyright (c) 2016 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import logic.basic import data.option.defs /-! # Miscellaneous function constructions and lemmas -/ universes u v w namespace function section variables {α β γ : Sort*} {f : α → β} /-- Evaluate a function at an argument. Useful if you want to talk about the partially applied `function.eval x : (Π x, β x) → β x`. -/ @[reducible] def eval {β : α → Sort*} (x : α) (f : Π x, β x) : β x := f x @[simp] lemma eval_apply {β : α → Sort*} (x : α) (f : Π x, β x) : eval x f = f x := rfl lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl lemma const_def {y : β} : (λ x : α, y) = const α y := rfl @[simp] lemma const_apply {y : β} {x : α} : const α y x = y := rfl @[simp] lemma const_comp {f : α → β} {c : γ} : const β c ∘ f = const α c := rfl @[simp] lemma comp_const {f : β → γ} {b : β} : f ∘ const α b = const α (f b) := rfl lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a} (hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' := begin subst hα, have : ∀a, f a == f' a, { intro a, exact h a a (heq.refl a) }, have : β = β', { funext a, exact type_eq_of_heq (this a) }, subst this, apply heq_of_eq, funext a, exact eq_of_heq (this a) end lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := iff.intro (assume h a, h ▸ rfl) funext @[simp] theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ theorem injective.eq_iff' (I : injective f) {a b : α} {c : β} (h : f b = c) : f a = c ↔ a = b := h ▸ I.eq_iff lemma injective.ne (hf : injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ := mt (assume h, hf h) lemma injective.ne_iff (hf : injective f) {x y : α} : f x ≠ f y ↔ x ≠ y := ⟨mt $ congr_arg f, hf.ne⟩ lemma injective.ne_iff' (hf : injective f) {x y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y := h ▸ hf.ne_iff /-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then the domain `α` also has decidable equality. -/ def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α := λ a b, decidable_of_iff _ I.eq_iff lemma injective.of_comp {g : γ → α} (I : injective (f ∘ g)) : injective g := λ x y h, I $ show f (g x) = f (g y), from congr_arg f h lemma surjective.of_comp {g : γ → α} (S : surjective (f ∘ g)) : surjective f := λ y, let ⟨x, h⟩ := S y in ⟨g x, h⟩ instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*) [Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp) | f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm theorem surjective.forall {f : α → β} (hf : surjective f) {p : β → Prop} : (∀ y, p y) ↔ ∀ x, p (f x) := ⟨λ h x, h (f x), λ h y, let ⟨x, hx⟩ := hf y in hx ▸ h x⟩ theorem surjective.forall₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∀ y₁ y₂, p y₁ y₂) ↔ ∀ x₁ x₂, p (f x₁) (f x₂) := hf.forall.trans $ forall_congr $ λ x, hf.forall theorem surjective.forall₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∀ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∀ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.forall.trans $ forall_congr $ λ x, hf.forall₂ theorem surjective.exists {f : α → β} (hf : surjective f) {p : β → Prop} : (∃ y, p y) ↔ ∃ x, p (f x) := ⟨λ ⟨y, hy⟩, let ⟨x, hx⟩ := hf y in ⟨x, hx.symm ▸ hy⟩, λ ⟨x, hx⟩, ⟨f x, hx⟩⟩ theorem surjective.exists₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∃ y₁ y₂, p y₁ y₂) ↔ ∃ x₁ x₂, p (f x₁) (f x₂) := hf.exists.trans $ exists_congr $ λ x, hf.exists theorem surjective.exists₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∃ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∃ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.exists.trans $ exists_congr $ λ x, hf.exists₂ /-- Cantor's diagonal argument implies that there are no surjective functions from `α` to `set α`. -/ theorem cantor_surjective {α} (f : α → set α) : ¬ function.surjective f | h := let ⟨D, e⟩ := h (λ a, ¬ f a a) in (iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D) /-- Cantor's diagonal argument implies that there are no injective functions from `set α` to `α`. -/ theorem cantor_injective {α : Type*} (f : (set α) → α) : ¬ function.injective f | i := cantor_surjective (λ a b, ∀ U, a = f U → U b) $ right_inverse.surjective (λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩) /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem left_inverse_iff_comp {f : α → β} {g : β → α} : left_inverse f g ↔ f ∘ g = id := ⟨left_inverse.comp_eq_id, congr_fun⟩ theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem right_inverse_iff_comp {f : α → β} {g : β → α} : right_inverse f g ↔ g ∘ f = id := ⟨right_inverse.comp_eq_id, congr_fun⟩ theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf theorem left_inverse.right_inverse {f : α → β} {g : β → α} (h : left_inverse g f) : right_inverse f g := h theorem right_inverse.left_inverse {f : α → β} {g : β → α} (h : right_inverse g f) : left_inverse f g := h theorem left_inverse.surjective {f : α → β} {g : β → α} (h : left_inverse f g) : surjective f := h.right_inverse.surjective theorem right_inverse.injective {f : α → β} {g : β → α} (h : right_inverse f g) : injective f := h.left_inverse.injective theorem left_inverse.eq_right_inverse {f : α → β} {g₁ g₂ : β → α} (h₁ : left_inverse g₁ f) (h₂ : right_inverse g₂ f) : g₁ = g₂ := calc g₁ = g₁ ∘ f ∘ g₂ : by rw [h₂.comp_eq_id, comp.right_id] ... = g₂ : by rw [← comp.assoc, h₁.comp_eq_id, comp.left_id] local attribute [instance, priority 10] classical.prop_decidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a b := ⟨λ h, if h' : ∃ a, f a = b then begin rw [partial_inv, dif_pos h'] at h, injection h with h, subst h, apply classical.some_spec h' end else by rw [partial_inv, dif_neg h'] at h; contradiction, λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variables {α : Type u} [n : nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β} include n local attribute [instance, priority 10] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice n theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀ (x ∈ s) (y ∈ s), f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice n := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = classical.choice n := by refine inv_fun_on_neg (mt _ h); exact assume ⟨a, _, ha⟩, ⟨a, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := (left_inverse_inv_fun hf).surjective lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf end inv_fun section inv_fun variables {α : Type u} [i : nonempty α] {β : Sort v} {f : α → β} include i lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, has_left_inverse.injective⟩ end inv_fun section surj_inv variables {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, has_right_inverse.surjective⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩, ⟨gl.injective, gr.surjective⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := (right_inverse_surj_inv h).injective end surj_inv section update variables {α : Sort u} {β : α → Sort v} {α' : Sort w} [decidable_eq α] [decidable_eq α'] /-- Replacing the value of a function at a given point by a given value. -/ def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then eq.rec v h.symm else f a @[simp] lemma update_same (a : α) (v : β a) (f : Πa, β a) : update f a v a = v := dif_pos rfl lemma update_injective (f : Πa, β a) (a' : α) : injective (update f a') := λ v v' h, have _ := congr_fun h a', by rwa [update_same, update_same] at this @[simp] lemma update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : Πa, β a) : update f a' v a = f a := dif_neg h @[simp] lemma update_eq_self (a : α) (f : Πa, β a) : update f a (f a) = f := begin refine funext (λi, _), by_cases h : i = a, { rw h, simp }, { simp [h] } end lemma update_comp {β : Sort v} (f : α → β) {g : α' → α} (hg : injective g) (a : α') (v : β) : (update f (g a) v) ∘ g = update (f ∘ g) a v := begin refine funext (λi, _), by_cases h : i = a, { rw h, simp }, { simp [h, hg.ne] } end lemma apply_update {ι : Sort*} [decidable_eq ι] {α β : ι → Sort*} (f : Π i, α i → β i) (g : Π i, α i) (i : ι) (v : α i) (j : ι) : f j (update g i v j) = update (λ k, f k (g k)) i (f i v) j := begin by_cases h : j = i, { subst j, simp }, { simp [h] } end lemma comp_update {α' : Sort*} {β : Sort*} (f : α' → β) (g : α → α') (i : α) (v : α') : f ∘ (update g i v) = update (f ∘ g) i (f v) := funext $ apply_update _ _ _ _ theorem update_comm {α} [decidable_eq α] {β : α → Sort*} {a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : Πa, β a) : update (update f a v) b w = update (update f b w) a v := begin funext c, simp [update], by_cases h₁ : c = b; by_cases h₂ : c = a; try {simp [h₁, h₂]}, cases h (h₂.symm.trans h₁), end @[simp] theorem update_idem {α} [decidable_eq α] {β : α → Sort*} {a : α} (v w : β a) (f : Πa, β a) : update (update f a v) a w = update f a w := by {funext b, by_cases b = a; simp [update, h]} end update section extend noncomputable theory local attribute [instance, priority 10] classical.prop_decidable variables {α β γ : Type*} {f : α → β} /-- `extend f g e'` extends a function `g : α → γ` along a function `f : α → β` to a function `β → γ`, by using the values of `g` on the range of `f` and the values of an auxiliary function `e' : β → γ` elsewhere. Mostly useful when `f` is injective. -/ def extend (f : α → β) (g : α → γ) (e' : β → γ) : β → γ := λ b, if h : ∃ a, f a = b then g (classical.some h) else e' b lemma extend_def (f : α → β) (g : α → γ) (e' : β → γ) (b : β) : extend f g e' b = if h : ∃ a, f a = b then g (classical.some h) else e' b := rfl @[simp] lemma extend_apply (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := begin simp only [extend_def, dif_pos, exists_apply_eq_apply], exact congr_arg g (hf $ classical.some_spec (exists_apply_eq_apply f a)) end @[simp] lemma extend_comp (hf : injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g := funext $ λ a, extend_apply hf g e' a end extend lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) := rfl @[simp] lemma uncurry_apply_pair {α β γ} (f : α → β → γ) (x : α) (y : β) : uncurry f (x, y) = f x y := rfl @[simp] lemma curry_apply {α β γ} (f : α × β → γ) (x : α) (y : β) : curry f x y = f (x, y) := rfl section bicomp variables {α β γ δ ε : Type*} /-- Compose a binary function `f` with a pair of unary functions `g` and `h`. If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/ def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) := f (g a) (h b) /-- Compose an unary function `f` with a binary function `g`. -/ def bicompr (f : γ → δ) (g : α → β → γ) (a b) := f (g a b) -- Suggested local notation: local notation f `∘₂` g := bicompr f g lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) : uncurry (g ∘₂ f) = (g ∘ uncurry f) := rfl lemma uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = (uncurry f) ∘ (prod.map g h) := rfl end bicomp section uncurry variables {α β γ δ : Type*} /-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ class has_uncurry (α : Type*) (β : out_param Type*) (γ : out_param Type*) := (uncurry : α → (β → γ)) /-- Uncurrying operator. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps.-/ add_decl_doc has_uncurry.uncurry notation `↿`:max x:max := has_uncurry.uncurry x instance has_uncurry_base : has_uncurry (α → β) α β := ⟨id⟩ instance has_uncurry_induction [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ := ⟨λ f p, ↿(f p.1) p.2⟩ end uncurry /-- A function is involutive, if `f ∘ f = id`. -/ def involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x lemma involutive_iff_iter_2_eq_id {α} {f : α → α} : involutive f ↔ (f^[2] = id) := funext_iff.symm namespace involutive variables {α : Sort u} {f : α → α} (h : involutive f) include h @[simp] lemma comp_self : f ∘ f = id := funext h protected lemma left_inverse : left_inverse f f := h protected lemma right_inverse : right_inverse f f := h protected lemma injective : injective f := h.left_inverse.injective protected lemma surjective : surjective f := λ x, ⟨f x, h x⟩ protected lemma bijective : bijective f := ⟨h.injective, h.surjective⟩ /-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/ protected lemma ite_not (P : Prop) [decidable P] (x : α) : f (ite P x (f x)) = ite (¬ P) x (f x) := by rw [apply_ite f, h, ite_not] end involutive /-- The property of a binary function `f : α → β → γ` being injective. Mathematically this should be thought of as the corresponding function `α × β → γ` being injective. -/ @[reducible] def injective2 {α β γ} (f : α → β → γ) : Prop := ∀ ⦃a₁ a₂ b₁ b₂⦄, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂ namespace injective2 variables {α β γ : Type*} (f : α → β → γ) protected lemma left (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ := (hf h).1 protected lemma right (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ := (hf h).2 lemma eq_iff (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ h, hf h, λ⟨h1, h2⟩, congr_arg2 f h1 h2⟩ end injective2 section sometimes local attribute [instance, priority 10] classical.prop_decidable /-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially interesting in the case where `α` is a proposition, in which case `f` is necessarily a constant function, so that `sometimes f = f a` for all `a`. -/ noncomputable def sometimes {α β} [nonempty β] (f : α → β) : β := if h : nonempty α then f (classical.choice h) else classical.choice ‹_› theorem sometimes_eq {p : Prop} {α} [nonempty α] (f : p → α) (a : p) : sometimes f = f a := dif_pos ⟨a⟩ theorem sometimes_spec {p : Prop} {α} [nonempty α] (P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) := by rwa sometimes_eq end sometimes end function /-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/ def set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f g : Πi, β i) [∀j, decidable (j ∈ s)] : Πi, β i := λi, if i ∈ s then f i else g i
683eb30f3ffc30b3f56f47c961061a2e2b9004ea
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/cone/dual.lean
c8d05c0bce19a0a6bce732da4272803a329e7832
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,362
lean
/- Copyright (c) 2021 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import analysis.convex.cone.basic import analysis.inner_product_space.projection /-! # Convex cones in inner product spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define `set.inner_dual_cone` to be the cone consisting of all points `y` such that for all points `x` in a given set `0 ≤ ⟪ x, y ⟫`. ## Main statements We prove the following theorems: * `convex_cone.inner_dual_cone_of_inner_dual_cone_eq_self`: The `inner_dual_cone` of the `inner_dual_cone` of a nonempty, closed, convex cone is itself. -/ open set linear_map open_locale classical pointwise variables {𝕜 E F G : Type*} /-! ### The dual cone -/ section dual variables {H : Type*} [normed_add_comm_group H] [inner_product_space ℝ H] (s t : set H) open_locale real_inner_product_space /-- The dual cone is the cone consisting of all points `y` such that for all points `x` in a given set `0 ≤ ⟪ x, y ⟫`. -/ def set.inner_dual_cone (s : set H) : convex_cone ℝ H := { carrier := { y | ∀ x ∈ s, 0 ≤ ⟪ x, y ⟫ }, smul_mem' := λ c hc y hy x hx, begin rw real_inner_smul_right, exact mul_nonneg hc.le (hy x hx) end, add_mem' := λ u hu v hv x hx, begin rw inner_add_right, exact add_nonneg (hu x hx) (hv x hx) end } @[simp] lemma mem_inner_dual_cone (y : H) (s : set H) : y ∈ s.inner_dual_cone ↔ ∀ x ∈ s, 0 ≤ ⟪ x, y ⟫ := iff.rfl @[simp] lemma inner_dual_cone_empty : (∅ : set H).inner_dual_cone = ⊤ := eq_top_iff.mpr $ λ x hy y, false.elim /-- Dual cone of the convex cone {0} is the total space. -/ @[simp] lemma inner_dual_cone_zero : (0 : set H).inner_dual_cone = ⊤ := eq_top_iff.mpr $ λ x hy y (hy : y = 0), hy.symm ▸ (inner_zero_left _).ge /-- Dual cone of the total space is the convex cone {0}. -/ @[simp] lemma inner_dual_cone_univ : (univ : set H).inner_dual_cone = 0 := begin suffices : ∀ x : H, x ∈ (univ : set H).inner_dual_cone → x = 0, { apply set_like.coe_injective, exact eq_singleton_iff_unique_mem.mpr ⟨λ x hx, (inner_zero_right _).ge, this⟩ }, exact λ x hx, by simpa [←real_inner_self_nonpos] using hx (-x) (mem_univ _), end lemma inner_dual_cone_le_inner_dual_cone (h : t ⊆ s) : s.inner_dual_cone ≤ t.inner_dual_cone := λ y hy x hx, hy x (h hx) lemma pointed_inner_dual_cone : s.inner_dual_cone.pointed := λ x hx, by rw inner_zero_right /-- The inner dual cone of a singleton is given by the preimage of the positive cone under the linear map `λ y, ⟪x, y⟫`. -/ lemma inner_dual_cone_singleton (x : H) : ({x} : set H).inner_dual_cone = (convex_cone.positive ℝ ℝ).comap (innerₛₗ ℝ x) := convex_cone.ext $ λ i, forall_eq lemma inner_dual_cone_union (s t : set H) : (s ∪ t).inner_dual_cone = s.inner_dual_cone ⊓ t.inner_dual_cone := le_antisymm (le_inf (λ x hx y hy, hx _ $ or.inl hy) (λ x hx y hy, hx _ $ or.inr hy)) (λ x hx y, or.rec (hx.1 _) (hx.2 _)) lemma inner_dual_cone_insert (x : H) (s : set H) : (insert x s).inner_dual_cone = set.inner_dual_cone {x} ⊓ s.inner_dual_cone := by rw [insert_eq, inner_dual_cone_union] lemma inner_dual_cone_Union {ι : Sort*} (f : ι → set H) : (⋃ i, f i).inner_dual_cone = ⨅ i, (f i).inner_dual_cone := begin refine le_antisymm (le_infi $ λ i x hx y hy, hx _ $ mem_Union_of_mem _ hy) _, intros x hx y hy, rw [convex_cone.mem_infi] at hx, obtain ⟨j, hj⟩ := mem_Union.mp hy, exact hx _ _ hj, end lemma inner_dual_cone_sUnion (S : set (set H)) : (⋃₀ S).inner_dual_cone = Inf (set.inner_dual_cone '' S) := by simp_rw [Inf_image, sUnion_eq_bUnion, inner_dual_cone_Union] /-- The dual cone of `s` equals the intersection of dual cones of the points in `s`. -/ lemma inner_dual_cone_eq_Inter_inner_dual_cone_singleton : (s.inner_dual_cone : set H) = ⋂ i : s, (({i} : set H).inner_dual_cone : set H) := by rw [←convex_cone.coe_infi, ←inner_dual_cone_Union, Union_of_singleton_coe] lemma is_closed_inner_dual_cone : is_closed (s.inner_dual_cone : set H) := begin -- reduce the problem to showing that dual cone of a singleton `{x}` is closed rw inner_dual_cone_eq_Inter_inner_dual_cone_singleton, apply is_closed_Inter, intros x, -- the dual cone of a singleton `{x}` is the preimage of `[0, ∞)` under `inner x` have h : ↑({x} : set H).inner_dual_cone = (inner x : H → ℝ) ⁻¹' set.Ici 0, { rw [inner_dual_cone_singleton, convex_cone.coe_comap, convex_cone.coe_positive, innerₛₗ_apply_coe] }, -- the preimage is closed as `inner x` is continuous and `[0, ∞)` is closed rw h, exact is_closed_Ici.preimage (by continuity), end lemma convex_cone.pointed_of_nonempty_of_is_closed (K : convex_cone ℝ H) (ne : (K : set H).nonempty) (hc : is_closed (K : set H)) : K.pointed := begin obtain ⟨x, hx⟩ := ne, let f : ℝ → H := (• x), -- f (0, ∞) is a subset of K have fI : f '' set.Ioi 0 ⊆ (K : set H), { rintro _ ⟨_, h, rfl⟩, exact K.smul_mem (set.mem_Ioi.1 h) hx }, -- closure of f (0, ∞) is a subset of K have clf : closure (f '' set.Ioi 0) ⊆ (K : set H) := hc.closure_subset_iff.2 fI, -- f is continuous at 0 from the right have fc : continuous_within_at f (set.Ioi (0 : ℝ)) 0 := (continuous_id.smul continuous_const).continuous_within_at, -- 0 belongs to the closure of the f (0, ∞) have mem₀ := fc.mem_closure_image (by rw [closure_Ioi (0 : ℝ), mem_Ici]), -- as 0 ∈ closure f (0, ∞) and closure f (0, ∞) ⊆ K, 0 ∈ K. have f₀ : f 0 = 0 := zero_smul ℝ x, simpa only [f₀, convex_cone.pointed, ← set_like.mem_coe] using mem_of_subset_of_mem clf mem₀, end section complete_space variables [complete_space H] /-- This is a stronger version of the Hahn-Banach separation theorem for closed convex cones. This is also the geometric interpretation of Farkas' lemma. -/ theorem convex_cone.hyperplane_separation_of_nonempty_of_is_closed_of_nmem (K : convex_cone ℝ H) (ne : (K : set H).nonempty) (hc : is_closed (K : set H)) {b : H} (disj : b ∉ K) : ∃ (y : H), (∀ x : H, x ∈ K → 0 ≤ ⟪x, y⟫_ℝ) ∧ ⟪y, b⟫_ℝ < 0 := begin -- let `z` be the point in `K` closest to `b` obtain ⟨z, hzK, infi⟩ := exists_norm_eq_infi_of_complete_convex ne hc.is_complete K.convex b, -- for any `w` in `K`, we have `⟪b - z, w - z⟫_ℝ ≤ 0` have hinner := (norm_eq_infi_iff_real_inner_le_zero K.convex hzK).1 infi, -- set `y := z - b` use z - b, split, { -- the rest of the proof is a straightforward calculation rintros x hxK, specialize hinner _ (K.add_mem hxK hzK), rwa [add_sub_cancel, real_inner_comm, ← neg_nonneg, neg_eq_neg_one_mul, ← real_inner_smul_right, neg_smul, one_smul, neg_sub] at hinner }, { -- as `K` is closed and non-empty, it is pointed have hinner₀ := hinner 0 (K.pointed_of_nonempty_of_is_closed ne hc), -- the rest of the proof is a straightforward calculation rw [zero_sub, inner_neg_right, right.neg_nonpos_iff] at hinner₀, have hbz : b - z ≠ 0 := by { rw sub_ne_zero, contrapose! hzK, rwa ← hzK }, rw [← neg_zero, lt_neg, ← neg_one_mul, ← real_inner_smul_left, smul_sub, neg_smul, one_smul, neg_smul, neg_sub_neg, one_smul], calc 0 < ⟪b - z, b - z⟫_ℝ : lt_of_not_le ((iff.not real_inner_self_nonpos).2 hbz) ... = ⟪b - z, b - z⟫_ℝ + 0 : (add_zero _).symm ... ≤ ⟪b - z, b - z⟫_ℝ + ⟪b - z, z⟫_ℝ : add_le_add rfl.ge hinner₀ ... = ⟪b - z, b - z + z⟫_ℝ : (inner_add_right _ _ _).symm ... = ⟪b - z, b⟫_ℝ : by rw sub_add_cancel }, end /-- The inner dual of inner dual of a non-empty, closed convex cone is itself. -/ theorem convex_cone.inner_dual_cone_of_inner_dual_cone_eq_self (K : convex_cone ℝ H) (ne : (K : set H).nonempty) (hc : is_closed (K : set H)) : ((K : set H).inner_dual_cone : set H).inner_dual_cone = K := begin ext x, split, { rw [mem_inner_dual_cone, ← set_like.mem_coe], contrapose!, exact K.hyperplane_separation_of_nonempty_of_is_closed_of_nmem ne hc }, { rintro hxK y h, specialize h x hxK, rwa real_inner_comm }, end end complete_space end dual
ef7c3fbdf829cc017f0c998447e123b8e3d749e9
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/finMatch.lean
ea51a5ef04e2d1e977f991ae74015a31ec3b4555
[ "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
343
lean
variable (F : Fin 4 → Type) (a : F 0 → F 1) (b : F 1 → F 2) (c : F 2 → F 3) def map : (i j : Fin 4) → (hij : i ≤ j) → F i → F j | 0, 0, _ => id | 1, 1, _ => id | 2, 2, _ => id | 3, 3, _ => id | 0, 1, _ => a | 0, 2, _ => b ∘ a | 0, 3, _ => c ∘ b ∘ a | 1, 2, _ => b | 1, 3, _ => c ∘ b | 2, 3, _ => c
74ef7e2c49cdbae04ecbbc4461af0b8bdcb22a26
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/finset/sort.lean
9340250bcd86beace90c26ff3f2e7c33fd8e007c
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,910
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import data.multiset.sort import data.list.nodup_equiv_fin /-! # Construct a sorted list from a finset. -/ namespace finset open multiset nat variables {α β : Type*} /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ lemma sort_perm_to_list (s : finset α) : sort r s ~ s.to_list := by { rw ←multiset.coe_eq_coe, simp only [coe_to_list, sort_eq] } end sort section sort_linear_order variables [linear_order α] theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min'_aux (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le 0 h = s.min' H := begin let l := s.sort (≤), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h), exact s.min'_le _ this } end lemma sorted_zero_eq_min' {s : finset α} {h : 0 < (s.sort (≤)).length} : (s.sort (≤)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) := sorted_zero_eq_min'_aux _ _ _ lemma min'_eq_sorted_zero {s : finset α} {h : s.nonempty} : s.min' h = (s.sort (≤)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) := (sorted_zero_eq_min'_aux _ _ _).symm lemma sorted_last_eq_max'_aux (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H := begin let l := s.sort (≤), apply le_antisymm, { have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l _ h), exact s.le_max' _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.le_pred_of_lt i_lt) }, end lemma sorted_last_eq_max' {s : finset α} {h : (s.sort (≤)).length - 1 < (s.sort (≤)).length} : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) := sorted_last_eq_max'_aux _ _ _ lemma max'_eq_sorted_last {s : finset α} {h : s.nonempty} : s.max' h = (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) (by simpa using nat.sub_lt (card_pos.mpr h) zero_lt_one) := (sorted_last_eq_max'_aux _ _ _).symm /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_iso_of_fin s h` is the increasing bijection between `fin k` and `s` as an `order_iso`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an iso `fin s.card ≃o s` to avoid casting issues in further uses of this function. -/ def order_iso_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃o s := order_iso.trans (fin.cast ((length_sort (≤)).trans h).symm) $ (s.sort_sorted_lt.nth_le_iso _).trans $ order_iso.set_congr _ _ $ set.ext $ λ x, mem_sort _ /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_emb_of_fin s h` is the increasing bijection between `fin k` and `s` as an order embedding into `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an embedding `fin s.card ↪o α` to avoid casting issues in further uses of this function. -/ def order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ↪o α := (order_iso_of_fin s h).to_order_embedding.trans (order_embedding.subtype _) @[simp] lemma coe_order_iso_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : ↑(order_iso_of_fin s h i) = order_emb_of_fin s h i := rfl lemma order_iso_of_fin_symm_apply (s : finset α) {k : ℕ} (h : s.card = k) (x : s) : ↑((s.order_iso_of_fin h).symm x) = (s.sort (≤)).index_of x := rfl lemma order_emb_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i = (s.sort (≤)).nth_le i (by { rw [length_sort, h], exact i.2 }) := rfl @[simp] lemma order_emb_of_fin_mem (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i ∈ s := (s.order_iso_of_fin h i).2 @[simp] lemma range_order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : set.range (s.order_emb_of_fin h) = s := by simp [order_emb_of_fin, set.range_comp coe (s.order_iso_of_fin h)] /-- The bijection `order_emb_of_fin s h` sends `0` to the minimum of `s`. -/ lemma order_emb_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) := by simp only [order_emb_of_fin_apply, subtype.coe_mk, sorted_zero_eq_min'] /-- The bijection `order_emb_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma order_emb_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) := by simp [order_emb_of_fin_apply, max'_eq_sorted_last, h] /-- `order_emb_of_fin {a} h` sends any argument to `a`. -/ @[simp] lemma order_emb_of_fin_singleton (a : α) (i : fin 1) : order_emb_of_fin {a} (card_singleton a) i = a := by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, order_emb_of_fin_zero _ zero_lt_one, min'_singleton] /-- Any increasing map `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (hfs : ∀ x, f x ∈ s) (hmono : strict_mono f) : f = s.order_emb_of_fin h := begin apply fin.strict_mono_unique hmono (s.order_emb_of_fin h).strict_mono, rw [range_order_emb_of_fin, ← set.image_univ, ← coe_fin_range, ← coe_image, coe_inj], refine eq_of_subset_of_card_le (λ x hx, _) _, { rcases mem_image.1 hx with ⟨x, hx, rfl⟩, exact hfs x }, { rw [h, card_image_of_injective _ hmono.injective, fin_range_card] } end /-- An order embedding `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique' {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k ↪o α} (hfs : ∀ x, f x ∈ s) : f = s.order_emb_of_fin h := rel_embedding.ext $ function.funext_iff.1 $ order_emb_of_fin_unique h hfs f.strict_mono /-- Two parametrizations `order_emb_of_fin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/ @[simp] lemma order_emb_of_fin_eq_order_emb_of_fin_iff {k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} : s.order_emb_of_fin h i = s.order_emb_of_fin h' j ↔ (i : ℕ) = (j : ℕ) := begin substs k l, exact (s.order_emb_of_fin rfl).eq_iff_eq.trans (fin.ext_iff _ _) end lemma card_le_of_interleaved {s t : finset α} (h : ∀ x y ∈ s, x < y → ∃ z ∈ t, x < z ∧ z < y) : s.card ≤ t.card + 1 := begin have h1 : ∀ i : fin (s.card - 1), ↑i + 1 < (s.sort (≤)).length, { intro i, rw [finset.length_sort, ←lt_sub_iff_right], exact i.2 }, have h0 : ∀ i : fin (s.card - 1), ↑i < (s.sort (≤)).length := λ i, lt_of_le_of_lt (nat.le_succ i) (h1 i), have p := λ i : fin (s.card - 1), h ((s.sort (≤)).nth_le i (h0 i)) ((s.sort (≤)).nth_le (i + 1) (h1 i)) ((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h0 i))) ((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h1 i))) (s.sort_sorted_lt.rel_nth_le_of_lt (h0 i) (h1 i) (nat.lt_succ_self i)), let f : fin (s.card - 1) → t := λ i, ⟨classical.some (p i), (exists_prop.mp (classical.some_spec (p i))).1⟩, have hf : ∀ i j : fin (s.card - 1), i < j → f i < f j := λ i j hij, subtype.coe_lt_coe.mp ((exists_prop.mp (classical.some_spec (p i))).2.2.trans (lt_of_le_of_lt ((s.sort_sorted (≤)).rel_nth_le_of_le (h1 i) (h0 j) (nat.succ_le_iff.mpr hij)) (exists_prop.mp (classical.some_spec (p j))).2.1)), have key := fintype.card_le_of_embedding (function.embedding.mk f (λ i j hij, le_antisymm (not_lt.mp (mt (hf j i) (not_lt.mpr (le_of_eq hij)))) (not_lt.mp (mt (hf i j) (not_lt.mpr (ge_of_eq hij)))))), rwa [fintype.card_fin, fintype.card_coe, sub_le_iff_right] at key, end end sort_linear_order instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ end finset
1d5ce09cb802cfefabd87fc4e988edcca3f9d988
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebraic_geometry/sheafed_space.lean
8b6b807b50c3d3730f198fb1e5ffe420bd874f92
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
5,917
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 algebraic_geometry.presheafed_space.has_colimits import topology.sheaves.functors /-! # Sheafed spaces Introduces the category of topological spaces equipped with a sheaf (taking values in an arbitrary target category `C`.) We further describe how to apply functors and natural transformations to the values of the presheaves. -/ universes v u open category_theory open Top open topological_space open opposite open category_theory.limits open category_theory.category category_theory.functor variables (C : Type u) [category.{v} C] [has_products.{v} C] local attribute [tidy] tactic.op_induction' namespace algebraic_geometry /-- A `SheafedSpace C` is a topological space equipped with a sheaf of `C`s. -/ structure SheafedSpace extends PresheafedSpace.{v} C := (is_sheaf : presheaf.is_sheaf) variables {C} namespace SheafedSpace instance coe_carrier : has_coe (SheafedSpace C) Top := { coe := λ X, X.carrier } /-- Extract the `sheaf C (X : Top)` from a `SheafedSpace C`. -/ def sheaf (X : SheafedSpace C) : sheaf C (X : Top.{v}) := ⟨X.presheaf, X.is_sheaf⟩ @[simp] lemma as_coe (X : SheafedSpace.{v} C) : X.carrier = (X : Top.{v}) := rfl @[simp] lemma mk_coe (carrier) (presheaf) (h) : (({ carrier := carrier, presheaf := presheaf, is_sheaf := h } : SheafedSpace.{v} C) : Top.{v}) = carrier := rfl instance (X : SheafedSpace.{v} C) : topological_space X := X.carrier.str /-- The trivial `unit` valued sheaf on any topological space. -/ def unit (X : Top) : SheafedSpace (discrete unit) := { is_sheaf := presheaf.is_sheaf_unit _, ..@PresheafedSpace.const (discrete unit) _ X ⟨⟨⟩⟩ } instance : inhabited (SheafedSpace (discrete _root_.unit)) := ⟨unit (Top.of pempty)⟩ instance : category (SheafedSpace C) := show category (induced_category (PresheafedSpace.{v} C) SheafedSpace.to_PresheafedSpace), by apply_instance /-- Forgetting the sheaf condition is a functor from `SheafedSpace C` to `PresheafedSpace C`. -/ @[derive [full, faithful]] def forget_to_PresheafedSpace : (SheafedSpace.{v} C) ⥤ (PresheafedSpace.{v} C) := induced_functor _ instance is_PresheafedSpace_iso {X Y : SheafedSpace.{v} C} (f : X ⟶ Y) [is_iso f] : @is_iso (PresheafedSpace C) _ _ _ f := SheafedSpace.forget_to_PresheafedSpace.map_is_iso f variables {C} section local attribute [simp] id comp @[simp] lemma id_base (X : SheafedSpace C) : ((𝟙 X) : X ⟶ X).base = (𝟙 (X : Top.{v})) := rfl lemma id_c (X : SheafedSpace C) : ((𝟙 X) : X ⟶ X).c = eq_to_hom (presheaf.pushforward.id_eq X.presheaf).symm := rfl @[simp] lemma id_c_app (X : SheafedSpace C) (U) : ((𝟙 X) : X ⟶ X).c.app U = eq_to_hom (by { induction U using opposite.rec, cases U, refl }) := by { induction U using opposite.rec, cases U, simp only [id_c], dsimp, simp, } @[simp] lemma comp_base {X Y Z : SheafedSpace C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).base = f.base ≫ g.base := rfl @[simp] lemma comp_c_app {X Y Z : SheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (U) : (α ≫ β).c.app U = (β.c).app U ≫ (α.c).app (op ((opens.map (β.base)).obj (unop U))) := rfl lemma comp_c_app' {X Y Z : SheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (U) : (α ≫ β).c.app (op U) = (β.c).app (op U) ≫ (α.c).app (op ((opens.map (β.base)).obj U)) := rfl lemma congr_app {X Y : SheafedSpace C} {α β : X ⟶ Y} (h : α = β) (U) : α.c.app U = β.c.app U ≫ X.presheaf.map (eq_to_hom (by subst h)) := PresheafedSpace.congr_app h U variables (C) /-- The forgetful functor from `SheafedSpace` to `Top`. -/ def forget : SheafedSpace C ⥤ Top := { obj := λ X, (X : Top.{v}), map := λ X Y f, f.base } end open Top.presheaf /-- The restriction of a sheafed space along an open embedding into the space. -/ def restrict {U : Top} (X : SheafedSpace C) {f : U ⟶ (X : Top.{v})} (h : open_embedding f) : SheafedSpace C := { is_sheaf := λ ι 𝒰, ⟨is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv _ _).inv_fun (X.is_sheaf _).some) (sheaf_condition_equalizer_products.fork.iso_of_open_embedding h 𝒰).symm⟩, ..X.to_PresheafedSpace.restrict h } /-- The restriction of a sheafed space `X` to the top subspace is isomorphic to `X` itself. -/ def restrict_top_iso (X : SheafedSpace C) : X.restrict (opens.open_embedding ⊤) ≅ X := forget_to_PresheafedSpace.preimage_iso X.to_PresheafedSpace.restrict_top_iso /-- The global sections, notated Gamma. -/ def Γ : (SheafedSpace C)ᵒᵖ ⥤ C := forget_to_PresheafedSpace.op ⋙ PresheafedSpace.Γ lemma Γ_def : (Γ : _ ⥤ C) = forget_to_PresheafedSpace.op ⋙ PresheafedSpace.Γ := rfl @[simp] lemma Γ_obj (X : (SheafedSpace C)ᵒᵖ) : Γ.obj X = (unop X).presheaf.obj (op ⊤) := rfl lemma Γ_obj_op (X : SheafedSpace C) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl @[simp] lemma Γ_map {X Y : (SheafedSpace C)ᵒᵖ} (f : X ⟶ Y) : Γ.map f = f.unop.c.app (op ⊤) := rfl lemma Γ_map_op {X Y : SheafedSpace C} (f : X ⟶ Y) : Γ.map f.op = f.c.app (op ⊤) := rfl noncomputable instance [has_limits C] : creates_colimits (forget_to_PresheafedSpace : SheafedSpace C ⥤ _) := ⟨λ J hJ, by exactI ⟨λ K, creates_colimit_of_fully_faithful_of_iso ⟨(PresheafedSpace.colimit_cocone (K ⋙ forget_to_PresheafedSpace)).X, limit_is_sheaf _ (λ j, sheaf.pushforward_sheaf_of_sheaf _ (K.obj (unop j)).2)⟩ (colimit.iso_colimit_cocone ⟨_, PresheafedSpace.colimit_cocone_is_colimit _⟩).symm⟩⟩ instance [has_limits C] : has_colimits (SheafedSpace C) := has_colimits_of_has_colimits_creates_colimits forget_to_PresheafedSpace noncomputable instance [has_limits C] : preserves_colimits (forget C) := limits.comp_preserves_colimits forget_to_PresheafedSpace (PresheafedSpace.forget C) end SheafedSpace end algebraic_geometry
ebf52208ed9d3ac59fc52ee6508e96f23cd7719e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Eval.lean
5145a67df9b52b90f98bb24a8d7a7cbe0ddc23b1
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,440
lean
/- Copyright (c) 2022 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Meta.Check namespace Lean.Meta unsafe def evalExprCore (α) (value : Expr) (checkType : Expr → MetaM Unit) (safety := DefinitionSafety.safe) : MetaM α := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let value ← instantiateMVars value if value.hasMVar then throwError "failed to evaluate expression, it contains metavariables{indentExpr value}" let type ← inferType value checkType type let decl := Declaration.defnDecl { name, levelParams := [], type value, hints := ReducibilityHints.opaque, safety } addAndCompile decl evalConst α name unsafe def evalExpr' (α) (typeName : Name) (value : Expr) (safety := DefinitionSafety.safe) : MetaM α := evalExprCore (safety := safety) α value fun type => do let type ← whnfD type unless type.isConstOf typeName do throwError "unexpected type at evalExpr{indentExpr type}" unsafe def evalExpr (α) (expectedType : Expr) (value : Expr) (safety := DefinitionSafety.safe) : MetaM α := evalExprCore (safety := safety) α value fun type => do unless ← isDefEq type expectedType do throwError "unexpected type at `evalExpr` {← mkHasTypeButIsExpectedMsg type expectedType}" end Lean.Meta
d42e787ce40efb12a72438d6bcfc9f3624c6ea5c
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world8/level3.lean
94578f4bd07dc4c95b5e398a6220cbd289a8e009
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
639
lean
import mynat.definition -- hide import mynat.add -- hide import game.world8.level2 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 3: `succ_eq_succ_of_eq`. -/ /- We are going to prove something completely obvious: if $a=b$ then $succ(a)=succ(b)$. This is *not* `succ_inj`! This is trivial -- we can just rewrite our proof of `a=b`. But how do we get to that proof? Use the `intro` tactic. -/ /- Theorem For all naturals $a$ and $b$, $a=b\implies succ(a)=succ(b)$. -/ theorem succ_eq_succ_of_eq {a b : mynat} : a = b → succ(a) = succ(b) := begin [nat_num_game] intro h, rw h, refl, end end mynat -- hide
bc51f6fe1656e967ae341fae0b8c8bbaa80d3038
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/tactic/simps.lean
d9c02287ad89c78ca67f8aad458af7cc16d277a8
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,996
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import tactic.core import data.sum /-! # simps attribute This file defines the `@[simps]` attribute, to automatically generate simp-lemmas reducing a definition when projections are applied to it. ## Implementation Notes There are three attributes being defined here * `@[simps]` is the attribute for objects of a structure or instances of a class. It will automatically generate simplification lemmas for each projection of the object/instance that contains data. See the doc strings for `simps_attr` and `simps_cfg` for more details and configuration options. * `@[_simps_str]` is automatically added to structures that have been used in `@[simps]` at least once. This attribute contains the data of the projections used for this structure by all following invocations of `@[simps]`. * `@[notation_class]` should be added to all classes that define notation, like `has_mul` and `has_zero`. This specifies that the projections that `@[simps]` used are the projections from these notation classes instead of the projections of the superclasses. Example: if `has_mul` is tagged with `@[notation_class]` then the projection used for `semigroup` will be `λ α hα, @has_mul.mul α (@semigroup.to_has_mul α hα)` instead of `@semigroup.mul`. ## Tags structures, projections, simp, simplifier, generates declarations -/ open tactic expr option sum setup_tactic_parser declare_trace simps.verbose declare_trace simps.debug /-- The `@[_simps_str]` attribute specifies the preferred projections of the given structure, used by the `@[simps]` attribute. - This will usually be tagged by the `@[simps]` tactic. - You can also generate this with the command `initialize_simps_projections`. - To change the default value, see Note [custom simps projection]. - You are strongly discouraged to add this attribute manually. - The first argument is the list of names of the universe variables used in the structure - The second argument is a list that consists of - a custom name for each projection of the structure - an expressions for each projections of the structure (definitionally equal to the corresponding projection). These expressions can contain the universe parameters specified in the first argument). - a list of natural numbers, which is the projection number(s) that have to be applied to the expression. For example the list `[0, 1]` corresponds to applying the first projection of the structure, and then the second projection of the resulting structure (this assumes that the target of the first projection is a structure with at least two projections). The composition of these projections is required to be definitionally equal to the provided expression. - A boolean specifying whether simp-lemmas are generated for this projection by default. -/ @[user_attribute] meta def simps_str_attr : user_attribute unit (list name × list (name × expr × list ℕ × bool)) := { name := `_simps_str, descr := "An attribute specifying the projection of the given structure.", parser := do e ← texpr, eval_pexpr _ e } /-- The `@[notation_class]` attribute specifies that this is a notation class, and this notation should be used instead of projections by @[simps]. * The first argument `tt` for notation classes and `ff` for classes applied to the structure, like `has_coe_to_sort` and `has_coe_to_fun` * The second argument is the name of the projection (by default it is the first projection of the structure) -/ @[user_attribute] meta def notation_class_attr : user_attribute unit (bool × option name) := { name := `notation_class, descr := "An attribute specifying that this is a notation class. Used by @[simps].", parser := prod.mk <$> (option.is_none <$> (tk "*")?) <*> ident? } attribute [notation_class] has_zero has_one has_add has_mul has_inv has_neg has_sub has_div has_dvd has_mod has_le has_lt has_append has_andthen has_union has_inter has_sdiff has_equiv has_subset has_ssubset has_emptyc has_insert has_singleton has_sep has_mem has_pow attribute [notation_class* coe_sort] has_coe_to_sort attribute [notation_class* coe_fn] has_coe_to_fun /-- Returns the projection information of a structure. -/ meta def projections_info (l : list (name × expr × list ℕ × bool)) (pref : string) (str : name) : tactic format := do ⟨defaults, nondefaults⟩ ← return $ l.partition_map $ λ s, if s.2.2.2 then inl s else inr s, to_print ← defaults.mmap $ λ s, to_string <$> pformat!"Projection {s.1}: {s.2.1}", let print2 := string.join $ (nondefaults.map (λ nm : _ × _, to_string nm.1)).intersperse ", ", let to_print := to_print ++ if nondefaults = [] then [] else ["No lemmas are generated for the projections: " ++ print2 ++ "."], let to_print := string.join $ to_print.intersperse "\n > ", return format!"[simps] > {pref} {str}:\n > {to_print}" /-- Auxilliary function of `get_composite_of_projections`. -/ meta def get_composite_of_projections_aux : Π (str : name) (proj : string) (x : expr) (pos : list ℕ) (args : list expr), tactic (expr × list ℕ) | str proj x pos args := do e ← get_env, projs ← e.structure_fields str, let proj_info := projs.map_with_index $ λ n p, (λ x, (x, n, p)) <$> proj.get_rest ("_" ++ p.last), when (proj_info.filter_map id = []) $ fail!"Failed to find constructor {proj.popn 1} in structure {str}.", (proj_rest, index, proj_nm) ← return (proj_info.filter_map id).ilast, str_d ← e.get str, let proj_e : expr := const (str ++ proj_nm) str_d.univ_levels, proj_d ← e.get (str ++ proj_nm), type ← infer_type x, let params := get_app_args type, let univs := proj_d.univ_params.zip type.get_app_fn.univ_levels, let new_x := (proj_e.instantiate_univ_params univs).mk_app $ params ++ [x], let new_pos := pos ++ [index], if proj_rest.is_empty then return (new_x.lambdas args, new_pos) else do type ← infer_type new_x, (type_args, tgt) ← open_pis_whnf type, let new_str := tgt.get_app_fn.const_name, get_composite_of_projections_aux new_str proj_rest new_x new_pos (args ++ type_args) /-- Given a structure `str` and a projection `proj`, that could be multiple nested projections (separated by `_`), returns an expression that is the composition of these projections and a list of natural numbers, that are the projection numbers of the applied projections. -/ meta def get_composite_of_projections (str : name) (proj : string) : tactic (expr × list ℕ) := do e ← get_env, str_d ← e.get str, let str_e : expr := const str str_d.univ_levels, type ← infer_type str_e, (type_args, tgt) ← open_pis_whnf type, let str_ap := str_e.mk_app type_args, x ← mk_local' `x binder_info.default str_ap, get_composite_of_projections_aux str ("_" ++ proj) x [] $ type_args ++ [x] /-- Get the projections used by `simps` associated to a given structure `str`. The returned information is also stored in a parameter of the attribute `@[_simps_str]`, which is given to `str`. If `str` already has this attribute, the information is read from this attribute instead. See the documentation for this attribute for the data this tactic returns. The returned universe levels are the universe levels of the structure. For the projections there are three cases * If the declaration `{structure_name}.simps.{projection_name}` has been declared, then the value of this declaration is used (after checking that it is definitionally equal to the actual projection. If you rename the projection name, the declaration should have the *new* projection name. * You can also declare a custom projection that is a composite of multiple projections. * Otherwise, for every class with the `notation_class` attribute, and the structure has an instance of that notation class, then the projection of that notation class is used for the projection that is definitionally equal to it (if there is such a projection). This means in practice that coercions to function types and sorts will be used instead of a projection, if this coercion is definitionally equal to a projection. Furthermore, for notation classes like `has_mul` and `has_zero` those projections are used instead of the corresponding projection. Projections for coercions and notation classes are not automatically generated if they are composites of multiple projections (for example when you use `extend` without the `old_structure_cmd`). * Otherwise, the projection of the structure is chosen. For example: ``simps_get_raw_projections env `prod`` gives the default projections ``` ([u, v], [prod.fst.{u v}, prod.snd.{u v}]) ``` while ``simps_get_raw_projections env `equiv`` gives ``` ([u_1, u_2], [λ α β, coe_fn, λ {α β} (e : α ≃ β), ⇑(e.symm), left_inv, right_inv]) ``` after declaring the coercion from `equiv` to function and adding the declaration ``` def equiv.simps.inv_fun {α β} (e : α ≃ β) : β → α := e.symm ``` Optionally, this command accepts three optional arguments: * If `trace_if_exists` the command will always generate a trace message when the structure already has the attribute `@[_simps_str]`. * The `rules` argument accepts a list of pairs `sum.inl (old_name, new_name)`. This is used to change the projection name `old_name` to the custom projection name `new_name`. Example: for the structure `equiv` the projection `to_fun` could be renamed `apply`. This name will be used for parsing and generating projection names. This argument is ignored if the structure already has an existing attribute. If an element of `rules` is of the form `sum.inr name`, this means that the projection `name` will not be applied by default. * if `trc` is true, this tactic will trace information. -/ -- if performance becomes a problem, possible heuristic: use the names of the projections to -- skip all classes that don't have the corresponding field. meta def simps_get_raw_projections (e : environment) (str : name) (trace_if_exists : bool := ff) (rules : list (name × name ⊕ name) := []) (trc := ff) : tactic (list name × list (name × expr × list ℕ × bool)) := do let trc := trc || is_trace_enabled_for `simps.verbose, has_attr ← has_attribute' `_simps_str str, if has_attr then do data ← simps_str_attr.get_param str, -- We always print the projections when they already exists and are called by -- `initialize_simps_projections`. when (trace_if_exists || is_trace_enabled_for `simps.verbose) $ projections_info data.2 "Already found projection information for structure" str >>= trace, return data else do when trc trace!"[simps] > generating projection information for structure {str}.", when_tracing `simps.debug trace!"[simps] > Applying the rules {rules}.", d_str ← e.get str, let raw_univs := d_str.univ_params, let raw_levels := level.param <$> raw_univs, /- Figure out projections, including renamings. The information for a projection is (before we figure out the `expr` of the projection: `(original name, given name, is default)`. The first projections are always the actual projections of the structure, but `rules` could specify custom projections that are compositions of multiple projections. -/ projs ← e.structure_fields str, let projs := projs.map_with_index (λ n nm, (nm, nm, tt)), let projs : list (name × name × bool) := rules.foldl (λ projs rule, match rule with | (inl (old_nm, new_nm)) := if old_nm ∈ projs.map (λ x, x.2.1) then projs.map $ λ proj, if proj.2.1 = old_nm then (proj.1, new_nm, proj.2.2) else proj else projs ++ [(old_nm, new_nm, tt)] | (inr nm) := if nm ∈ projs.map (λ x, x.2.1) then projs.map $ λ proj, if proj.2.1 = nm then (proj.1, proj.2.1, ff) else proj else projs ++ [(nm, nm, ff)] end) projs, when_tracing `simps.debug trace!"[simps] > Projection info after applying the rules: {projs}.", /- Define the raw expressions for the projections, by default as the projections (as an expression), but this can be overriden by the user. -/ raw_exprs_and_nrs ← projs.mmap $ λ ⟨orig_nm, new_nm, _⟩, do { (raw_expr, nrs) ← get_composite_of_projections str orig_nm.last, custom_proj ← do { decl ← e.get (str ++ `simps ++ new_nm.last), let custom_proj := decl.value.instantiate_univ_params $ decl.univ_params.zip raw_levels, when trc trace! "[simps] > found custom projection for {new_nm}:\n > {custom_proj}", return custom_proj } <|> return raw_expr, is_def_eq custom_proj raw_expr <|> -- if the type of the expression is different, we show a different error message, because -- that is more likely going to be helpful. do { custom_proj_type ← infer_type custom_proj, raw_expr_type ← infer_type raw_expr, b ← succeeds (is_def_eq custom_proj_type raw_expr_type), if b then fail!"Invalid custom projection:\n {custom_proj} Expression is not definitionally equal to {raw_expr}." else fail!"Invalid custom projection:\n {custom_proj} Expression has different type than {str ++ orig_nm}. Given type:\n {custom_proj_type} Expected type:\n {raw_expr_type}" }, return (custom_proj, nrs) }, let raw_exprs := raw_exprs_and_nrs.map prod.fst, /- Check for other coercions and type-class arguments to use as projections instead. -/ (args, _) ← open_pis d_str.type, let e_str := (expr.const str raw_levels).mk_app args, automatic_projs ← attribute.get_instances `notation_class, raw_exprs ← automatic_projs.mfoldl (λ (raw_exprs : list expr) class_nm, do { (is_class, proj_nm) ← notation_class_attr.get_param class_nm, proj_nm ← proj_nm <|> (e.structure_fields_full class_nm).map list.head, /- For this class, find the projection. `raw_expr` is the projection found applied to `args`, and `lambda_raw_expr` has the arguments `args` abstracted. -/ (raw_expr, lambda_raw_expr) ← if is_class then (do guard $ args.length = 1, let e_inst_type := (const class_nm raw_levels).mk_app args, (hyp, e_inst) ← try_for 1000 (mk_conditional_instance e_str e_inst_type), raw_expr ← mk_mapp proj_nm [args.head, e_inst], clear hyp, -- Note: `expr.bind_lambda` doesn't give the correct type raw_expr_lambda ← lambdas [hyp] raw_expr, return (raw_expr, raw_expr_lambda.lambdas args)) else (do e_inst_type ← to_expr ((const class_nm []).app (pexpr.of_expr e_str)), e_inst ← try_for 1000 (mk_instance e_inst_type), raw_expr ← mk_mapp proj_nm [e_str, e_inst], return (raw_expr, raw_expr.lambdas args)), raw_expr_whnf ← whnf raw_expr, let relevant_proj := raw_expr_whnf.binding_body.get_app_fn.const_name, /- Use this as projection, if the function reduces to a projection, and this projection has not been overrriden by the user. -/ guard $ projs.any $ λ x, x.1 = relevant_proj.last ∧ ¬ e.contains (str ++ `simps ++ x.2.1.last), let pos := projs.find_index (λ x, x.1 = relevant_proj.last), when trc trace! " > using {proj_nm} instead of the default projection {relevant_proj.last}.", when_tracing `simps.debug trace!"[simps] > The raw projection is:\n {lambda_raw_expr}", return $ raw_exprs.update_nth pos lambda_raw_expr } <|> return raw_exprs) raw_exprs, let positions := raw_exprs_and_nrs.map prod.snd, let defaults := projs.map (λ x, x.2.2), let proj_names := projs.map (λ x, x.2.1), let projs := proj_names.zip $ raw_exprs.zip $ positions.zip defaults, /- make all proof non-default. -/ projs ← projs.mmap $ λ proj, is_proof proj.2.1 >>= λ b, return $ if b then (proj.1, proj.2.1, proj.2.2.1, ff) else proj, when trc $ projections_info projs "generated projections for" str >>= trace, simps_str_attr.set str (raw_univs, projs) tt, when_tracing `simps.debug trace! "[simps] > Generated raw projection data: \n{(raw_univs, projs)}", return (raw_univs, projs) /-- Parse a rule for `initialize_simps_projections`. It is either `<name>→<name>` or `-<name>`.-/ meta def simps_parse_rule : parser (name × name ⊕ name) := (λ x y, inl (x, y)) <$> ident <*> (tk "->" >> ident) <|> inr <$> (tk "-" >> ident) /-- You can specify custom projections for the `@[simps]` attribute. To do this for the projection `my_structure.original_projection` by adding a declaration `my_structure.simps.my_projection` that is definitionally equal to `my_structure.original_projection` but has the projection in the desired (simp-normal) form. Then you can call ``` initialize_simps_projections (original_projection → my_projection, ...) ``` to register this projection. Running `initialize_simps_projections` without arguments is not necessary, it has the same effect if you just add `@[simps]` to a declaration. If you do anything to change the default projections, make sure to call either `@[simps]` or `initialize_simps_projections` in the same file as the structure declaration. Otherwise, you might have a file that imports the structure, but not your custom projections. -/ library_note "custom simps projection" /-- Specify simps projections, see Note [custom simps projection]. * You can specify custom names by writing e.g. `initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`. * You can disable a projection by default by running `initialize_simps_projections equiv (-inv_fun)` This will ensure that no simp lemmas are generated for this projection, unless this projection is explicitly specified by the user. * Run `initialize_simps_projections?` (or set `trace.simps.verbose`) to see the generated projections. -/ @[user_command] meta def initialize_simps_projections_cmd (_ : parse $ tk "initialize_simps_projections") : parser unit := do env ← get_env, trc ← is_some <$> (tk "?")?, ns ← (prod.mk <$> ident <*> (tk "(" >> sep_by (tk ",") simps_parse_rule <* tk ")")?)*, ns.mmap' $ λ data, do nm ← resolve_constant data.1, simps_get_raw_projections env nm tt (data.2.get_or_else []) trc /-- Configuration options for the `@[simps]` attribute. * `attrs` specifies the list of attributes given to the generated lemmas. Default: ``[`simp]``. The attributes can be either basic attributes, or user attributes without parameters. There are two attributes which `simps` might add itself: * If ``[`simp]`` is in the list, then ``[`_refl_lemma]`` is added automatically if appropriate. * If the definition is marked with `@[to_additive ...]` then all generated lemmas are marked with `@[to_additive]` * `short_name` gives the generated lemmas a shorter name. This only has an effect when multiple projections are applied in a lemma. When this is `ff` (default) all projection names will be appended to the definition name to form the lemma name, and when this is `tt`, only the last projection name will be appended. * if `simp_rhs` is `tt` then the right-hand-side of the generated lemmas will be put in simp-normal form. More precisely: `dsimp, simp` will be called on all these expressions. See note [dsimp, simp]. * `type_md` specifies how aggressively definitions are unfolded in the type of expressions for the purposes of finding out whether the type is a function type. Default: `instances`. This will unfold coercion instances (so that a coercion to a function type is recognized as a function type), but not declarations like `set`. * `rhs_md` specifies how aggressively definition in the declaration are unfolded for the purposes of finding out whether it is a constructor. Default: `none` Exception: `@[simps]` will automatically add the options `{rhs_md := semireducible, simp_rhs := tt}` if the given definition is not a constructor with the given reducibility setting for `rhs_md`. * If `fully_applied` is `ff` then the generated simp-lemmas will be between non-fully applied terms, i.e. equalities between functions. This does not restrict the recursive behavior of `@[simps]`, so only the "final" projection will be non-fully applied. However, it can be used in combination with explicit field names, to get a partially applied intermediate projection. * The option `not_recursive` contains the list of names of types for which `@[simps]` doesn't recursively apply projections. For example, given an equivalence `α × β ≃ β × α` one usually wants to only apply the projections for `equiv`, and not also those for `×`. This option is only relevant if no explicit projection names are given as argument to `@[simps]`. * The option `trace` is set to `tt` when you write `@[simps?]`. In this case, the attribute will print all generated lemmas. It is almost the same as setting the option `trace.simps.verbose`, except that it doesn't print information about the found projections. -/ @[derive [has_reflect, inhabited]] structure simps_cfg := (attrs := [`simp]) (short_name := ff) (simp_rhs := ff) (type_md := transparency.instances) (rhs_md := transparency.none) (fully_applied := tt) (not_recursive := [`prod, `pprod]) (trace := ff) /-- A common configuration for `@[simps]`: generate equalities between functions instead equalities between fully applied expressions. -/ def as_fn : simps_cfg := {fully_applied := ff} /-- A common configuration for `@[simps]`: don't tag the generated lemmas with `@[simp]`. -/ def lemmas_only : simps_cfg := {attrs := []} /-- Get the projections of a structure used by `@[simps]` applied to the appropriate arguments. Returns a list of quintuples ``` (projection expression, given projection name, corresponding right-hand-side, projection numbers, used by default) ``` one for each projection. The given projection name is the name for the projection used by the user used to generate (and parse) projection names. For example, in the structure Example 1: ``simps_get_projection_exprs env `(α × β) `(⟨x, y⟩)`` will give the output ``` [(`(@prod.fst.{u v} α β), `fst, `(x), [0], tt), (`(@prod.snd.{u v} α β), `snd, `(y), [1], tt)] ``` Example 2: ``simps_get_projection_exprs env `(α ≃ α) `(⟨id, id, λ _, rfl, λ _, rfl⟩)`` will give the output ``` [(`(@equiv.to_fun.{u u} α α), `apply, `(id), [0], tt), (`(@equiv.inv_fun.{u u} α α), `symm_apply, `(id), [1], tt), ..., ...] ``` The last two fields of the list correspond to the propositional fields of the structure, and are rarely/never used. -/ -- This function does not use `tactic.mk_app` or `tactic.mk_mapp`, because the given arguments -- might not uniquely specify the universe levels yet. meta def simps_get_projection_exprs (e : environment) (tgt : expr) (rhs : expr) (cfg : simps_cfg) : tactic $ list $ expr × name × expr × list ℕ × bool := do let params := get_app_args tgt, -- the parameters of the structure (params.zip $ (get_app_args rhs).take params.length).mmap' (λ ⟨a, b⟩, is_def_eq a b) <|> fail "unreachable code (1)", let str := tgt.get_app_fn.const_name, let rhs_args := (get_app_args rhs).drop params.length, -- the fields of the object (raw_univs, proj_data) ← simps_get_raw_projections e str ff [] cfg.trace, let univs := raw_univs.zip tgt.get_app_fn.univ_levels, let projs := proj_data.map prod.fst, let raw_exprs := proj_data.map $ λ p, p.2.1, let nrs_and_default := proj_data.map $ λ p, p.2.2, let proj_exprs := raw_exprs.map $ λ raw_expr, (raw_expr.instantiate_univ_params univs).instantiate_lambdas_or_apps params, let rhs_exprs := nrs_and_default.map $ λ x, rhs_args.inth x.1.head, return $ proj_exprs.zip $ projs.zip $ rhs_exprs.zip $ nrs_and_default.map (λ x, (x.1.tail, x.2)) /-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`, `args` is the list of local constants occurring, and `univs` is the list of universe variables. If `add_simp` then we make the resulting lemma a simp-lemma. -/ meta def simps_add_projection (nm : name) (type lhs rhs : expr) (args : list expr) (univs : list name) (cfg : simps_cfg) : tactic unit := do when_tracing `simps.debug trace! "[simps] > Planning to add the equality\n > {lhs} = ({rhs} : {type})", -- simplify `rhs` if `cfg.simp_rhs` is true (rhs, prf) ← do { guard cfg.simp_rhs, rhs' ← rhs.dsimp {fail_if_unchanged := ff}, when_tracing `simps.debug $ when (rhs ≠ rhs') trace! "[simps] > `dsimp` simplified rhs to\n > {rhs'}", (rhsprf1, rhsprf2, ns) ← rhs'.simp {fail_if_unchanged := ff}, when_tracing `simps.debug $ when (rhs' ≠ rhsprf1) trace! "[simps] > `simp` simplified rhs to\n > {rhsprf1}", return (prod.mk rhsprf1 rhsprf2) } <|> prod.mk rhs <$> mk_app `eq.refl [type, lhs], eq_ap ← mk_mapp `eq $ [type, lhs, rhs].map some, decl_name ← get_unused_decl_name nm, let decl_type := eq_ap.pis args, let decl_value := prf.lambdas args, let decl := declaration.thm decl_name univs decl_type (pure decl_value), when cfg.trace trace! "[simps] > adding projection {decl_name}:\n > {decl_type}", decorate_error ("failed to add projection lemma " ++ decl_name.to_string ++ ". Nested error:") $ add_decl decl, b ← succeeds $ is_def_eq lhs rhs, when (b ∧ `simp ∈ cfg.attrs) (set_basic_attribute `_refl_lemma decl_name tt), cfg.attrs.mmap' $ λ nm, set_attribute nm decl_name tt /-- Derive lemmas specifying the projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. `to_apply` is non-empty after a custom projection that is a composition of multiple projections was just used. In that case we need to apply these projections before we continue changing lhs. -/ meta def simps_add_projections : Π (e : environment) (nm : name) (suffix : string) (type lhs rhs : expr) (args : list expr) (univs : list name) (must_be_str : bool) (cfg : simps_cfg) (todo : list string) (to_apply : list ℕ), tactic unit | e nm suffix type lhs rhs args univs must_be_str cfg todo to_apply := do -- we don't want to unfold non-reducible definitions (like `set`) to apply more arguments when_tracing `simps.debug trace! "[simps] > Trying to add simp-lemmas for\n > {lhs} [simps] > Type of the expression before normalizing: {type}", (type_args, tgt) ← open_pis_whnf type cfg.type_md, when_tracing `simps.debug trace!"[simps] > Type after removing pi's: {tgt}", tgt ← whnf tgt, when_tracing `simps.debug trace!"[simps] > Type after reduction: {tgt}", let new_args := args ++ type_args, let lhs_ap := lhs.mk_app type_args, let rhs_ap := rhs.instantiate_lambdas_or_apps type_args, let str := tgt.get_app_fn.const_name, let new_nm := nm.append_suffix suffix, /- We want to generate the current projection if it is in `todo` -/ let todo_next := todo.filter (≠ ""), /- Don't recursively continue if `str` is not a structure or if the structure is in `not_recursive`. -/ if e.is_structure str ∧ ¬(todo = [] ∧ str ∈ cfg.not_recursive ∧ ¬must_be_str) then do [intro] ← return $ e.constructors_of str | fail "unreachable code (3)", rhs_whnf ← whnf rhs_ap cfg.rhs_md, (rhs_ap, todo_now) ← -- `todo_now` means that we still have to generate the current simp lemma if h : ¬ is_constant_of rhs_ap.get_app_fn intro ∧ is_constant_of rhs_whnf.get_app_fn intro then /- If this was a desired projection, we want to apply it before taking the whnf. However, if the current field is an eta-expansion (see below), we first want to eta-reduce it and only then construct the projection. This makes the flow of this function messy. -/ when ("" ∈ todo ∧ to_apply = []) (if cfg.fully_applied then simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection new_nm type lhs rhs args univs cfg) >> return (rhs_whnf, ff) else return (rhs_ap, "" ∈ todo ∧ to_apply = []), if is_constant_of (get_app_fn rhs_ap) intro then do -- if the value is a constructor application tuples ← simps_get_projection_exprs e tgt rhs_ap cfg, when_tracing `simps.debug trace!"[simps] > Raw projection information:\n {tuples}", let projs := tuples.map $ λ x, x.2.1, eta ← rhs_ap.is_eta_expansion, -- check whether `rhs_ap` is an eta-expansion let rhs_ap := eta.lhoare rhs_ap, -- eta-reduce `rhs_ap` /- As a special case, we want to automatically generate the current projection if `rhs_ap` was an eta-expansion. Also, when this was a desired projection, we need to generate the current projection if we haven't done it above. -/ when (todo_now ∨ (todo = [] ∧ eta.is_some ∧ to_apply = [])) $ if cfg.fully_applied then simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection new_nm type lhs rhs args univs cfg, /- If we are in the middle of a composite projection. -/ when (to_apply ≠ []) $ do { (proj_expr, proj, new_rhs, proj_nrs, is_default) ← return $ tuples.inth to_apply.head, new_type ← infer_type new_rhs, simps_add_projections e nm suffix new_type lhs new_rhs new_args univs ff cfg todo to_apply.tail }, /- We stop if no further projection is specified or if we just reduced an eta-expansion and we automatically choose projections -/ when ¬(to_apply ≠ [] ∨ todo = [""] ∨ (eta.is_some ∧ todo = [])) $ do let todo := if to_apply = [] then todo_next else todo, -- check whether all elements in `todo` have a projection as prefix guard (todo.all $ λ x, projs.any $ λ proj, ("_" ++ proj.last).is_prefix_of x) <|> let x := (todo.find $ λ x, projs.all $ λ proj, ¬ ("_" ++ proj.last).is_prefix_of x).iget, simp_lemma := nm.append_suffix $ suffix ++ x, needed_proj := (x.split_on '_').tail.head in fail! "Invalid simp-lemma {simp_lemma}. Structure {str} does not have projection {needed_proj}. The known projections are: {projs} You can also see this information by running `initialize_simps_projections? {str}`. Note: these projection names might not correspond to the projection names of the structure.", tuples.mmap_with_index' $ λ proj_nr ⟨proj_expr, proj, new_rhs, proj_nrs, is_default⟩, do new_type ← infer_type new_rhs, let new_todo := todo.filter_map $ λ x, x.get_rest ("_" ++ proj.last), -- we only continue with this field if it is non-propositional or mentioned in todo when ((is_default ∧ todo = []) ∨ new_todo ≠ []) $ do let new_lhs := proj_expr.instantiate_lambdas_or_apps [lhs_ap], let new_suffix := if cfg.short_name then "_" ++ proj.last else suffix ++ "_" ++ proj.last, when_tracing `simps.debug trace!"[simps] > Recursively add projections for: {new_lhs}", simps_add_projections e nm new_suffix new_type new_lhs new_rhs new_args univs ff cfg new_todo proj_nrs -- if I'm about to run into an error, try to set the transparency for `rhs_md` higher. else if cfg.rhs_md = transparency.none ∧ (must_be_str ∨ todo_next ≠ [] ∨ to_apply ≠ []) then do when cfg.trace trace! "[simps] > The given definition is not a constructor application: > {rhs_ap} > Retrying with the options {{ rhs_md := semireducible, simp_rhs := tt}.", simps_add_projections e nm suffix type lhs rhs args univs must_be_str { rhs_md := semireducible, simp_rhs := tt, ..cfg} todo to_apply else do when (to_apply ≠ []) $ fail!"Invalid simp-lemma {nm}. The given definition is not a constructor application:\n {rhs_ap}", when must_be_str $ fail!"Invalid `simps` attribute. The body is not a constructor application:\n {rhs_ap}", when (todo_next ≠ []) $ fail!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo_next.head}. The given definition is not a constructor application:\n {rhs_ap}", if cfg.fully_applied then simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection new_nm type lhs rhs args univs cfg else do when must_be_str $ fail!"Invalid `simps` attribute. Target {str} is not a structure", when (todo_next ≠ [] ∧ str ∉ cfg.not_recursive) $ let first_todo := todo_next.head in fail!"Invalid simp-lemma {nm.append_suffix $ suffix ++ first_todo}. Projection {(first_todo.split_on '_').tail.head} doesn't exist, because target is not a structure.", if cfg.fully_applied then simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else simps_add_projection new_nm type lhs rhs args univs cfg /-- `simps_tac` derives simp-lemmas for all (nested) non-Prop projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. If `short_nm` is true, the generated names will only use the last projection name. If `trc` is true, trace as if `trace.simps.verbose` is true. -/ meta def simps_tac (nm : name) (cfg : simps_cfg := {}) (todo : list string := []) (trc := ff) : tactic unit := do e ← get_env, d ← e.get nm, let lhs : expr := const d.to_name (d.univ_params.map level.param), let todo := todo.erase_dup.map $ λ proj, "_" ++ proj, b ← has_attribute' `to_additive nm, let cfg := if b then { attrs := cfg.attrs ++ [`to_additive], ..cfg } else cfg, let cfg := { trace := cfg.trace || is_trace_enabled_for `simps.verbose || trc, ..cfg }, when (cfg.trace ∧ `to_additive ∈ cfg.attrs) trace!"[simps] > @[to_additive] will be added to all generated lemmas.", simps_add_projections e nm "" d.type lhs d.value [] d.univ_params tt cfg todo [] /-- The parser for the `@[simps]` attribute. -/ meta def simps_parser : parser (bool × list string × simps_cfg) := do /- note: we don't check whether the user has written a nonsense namespace in an argument. -/ prod.mk <$> is_some <$> (tk "?")? <*> (prod.mk <$> many (name.last <$> ident) <*> (do some e ← parser.pexpr? | return {}, eval_pexpr simps_cfg e)) /-- The `@[simps]` attribute automatically derives lemmas specifying the projections of this declaration. Example: ```lean @[simps] def foo : ℕ × ℤ := (1, 2) ``` derives two simp-lemmas: ```lean @[simp] lemma foo_fst : foo.fst = 1 @[simp] lemma foo_snd : foo.snd = 2 ``` * It does not derive simp-lemmas for the prop-valued projections. * It will automatically reduce newly created beta-redexes, but will not unfold any definitions. * If the structure has a coercion to either sorts or functions, and this is defined to be one of the projections, then this coercion will be used instead of the projection. * If the structure is a class that has an instance to a notation class, like `has_mul`, then this notation is used instead of the corresponding projection. * You can specify custom projections, by giving a declaration with name `{structure_name}.simps.{projection_name}`. See Note [custom simps projection]. Example: ```lean def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm @[simps] def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩ ``` generates ``` @[simp] lemma equiv.trans_to_fun : ∀ {α β γ} (e₁ e₂) (a : α), ⇑(e₁.trans e₂) a = (⇑e₂ ∘ ⇑e₁) a @[simp] lemma equiv.trans_inv_fun : ∀ {α β γ} (e₁ e₂) (a : γ), ⇑((e₁.trans e₂).symm) a = (⇑(e₁.symm) ∘ ⇑(e₂.symm)) a ``` * You can specify custom projection names, by specifying the new projection names using `initialize_simps_projections`. Example: `initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`. * If one of the fields itself is a structure, this command will recursively create simp-lemmas for all fields in that structure. * Exception: by default it will not recursively create simp-lemmas for fields in the structures `prod` and `pprod`. Give explicit projection names to override this behavior. Example: ```lean structure my_prod (α β : Type*) := (fst : α) (snd : β) @[simps] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ ``` generates ```lean @[simp] lemma foo_fst : foo.fst = (1, 2) @[simp] lemma foo_snd_fst : foo.snd.fst = 3 @[simp] lemma foo_snd_snd : foo.snd.snd = 4 ``` * You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified projections. * Recursive projection names can be specified using `proj1_proj2_proj3`. This will create a lemma of the form `foo.proj1.proj2.proj3 = ...`. Example: ```lean structure my_prod (α β : Type*) := (fst : α) (snd : β) @[simps fst fst_fst snd] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩ ``` generates ```lean @[simp] lemma foo_fst : foo.fst = (1, 2) @[simp] lemma foo_fst_fst : foo.fst.fst = 1 @[simp] lemma foo_snd : foo.snd = {fst := 3, snd := 4} ``` * If one of the values is an eta-expanded structure, we will eta-reduce this structure. Example: ```lean structure equiv_plus_data (α β) extends α ≃ β := (data : bool) @[simps] def bar {α} : equiv_plus_data α α := { data := tt, ..equiv.refl α } ``` generates the following, even though Lean inserts an eta-expanded version of `equiv.refl α` in the definition of `bar`: ```lean @[simp] lemma bar_to_equiv : ∀ {α : Sort u_1}, bar.to_equiv = equiv.refl α @[simp] lemma bar_data : ∀ {α : Sort u_1}, bar.data = tt ``` * For configuration options, see the doc string of `simps_cfg`. * The precise syntax is `('simps' ident* e)`, where `e` is an expression of type `simps_cfg`. * `@[simps]` reduces let-expressions where necessary. * If one of the fields is a partially applied constructor, we will eta-expand it (this likely never happens). * When option `trace.simps.verbose` is true, `simps` will print the projections it finds and the lemmas it generates. The same can be achieved by using `@[simps?]`, except that in this case it will not print projection information. * Use `@[to_additive, simps]` to apply both `to_additive` and `simps` to a definition, making sure that `simps` comes after `to_additive`. This will also generate the additive versions of all simp-lemmas. Note however, that the additive versions of the simp-lemmas always use the default name generated by `to_additive`, even if a custom name is given for the additive version of the definition. -/ @[user_attribute] meta def simps_attr : user_attribute unit (bool × list string × simps_cfg) := { name := `simps, descr := "Automatically derive lemmas specifying the projections of this declaration.", parser := simps_parser, after_set := some $ λ n _ persistent, do guard persistent <|> fail "`simps` currently cannot be used as a local attribute", (trc, todo, cfg) ← simps_attr.get_param n, simps_tac n cfg todo trc } add_tactic_doc { name := "simps", category := doc_category.attr, decl_names := [`simps_attr], tags := ["simplification"] }
923eba00ce0d635bc7369a35ea813820b375dd08
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/def15.lean
cbb00c9096ece164edbc93929049285733eb9d9d
[ "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
297
lean
def head {α} : (as : List α) → as ≠ [] → α | [], h => absurd rfl h | a::as, _ => a theorem head_cons {α} (a : α) (as : List α) : head (a::as) (fun h => List.noConfusion h) = a := rfl theorem head_cons' {α} (a : α) (as : List α) (h : a::as ≠ []) : head (a::as) h = a := rfl
3966bc86a9d41bb758b2c83a7d6128327617e01d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/filter/germ.lean
78cf1df6724925dbeb51b38fa22d322def0f9406
[ "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
21,604
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Abhimanyu Pallavi Sudhir -/ import order.filter.basic import algebra.module.pi /-! # Germ of a function at a filter The germ of a function `f : α → β` at a filter `l : filter α` is the equivalence class of `f` with respect to the equivalence relation `eventually_eq l`: `f ≈ g` means `∀ᶠ x in l, f x = g x`. ## Main definitions We define * `germ l β` to be the space of germs of functions `α → β` at a filter `l : filter α`; * coercion from `α → β` to `germ l β`: `(f : germ l β)` is the germ of `f : α → β` at `l : filter α`; this coercion is declared as `has_coe_t`, so it does not require an explicit up arrow `↑`; * coercion from `β` to `germ l β`: `(↑c : germ l β)` is the germ of the constant function `λ x:α, c` at a filter `l`; this coercion is declared as `has_lift_t`, so it requires an explicit up arrow `↑`, see [TPiL][TPiL_coe] for details. * `map (F : β → γ) (f : germ l β)` to be the composition of a function `F` and a germ `f`; * `map₂ (F : β → γ → δ) (f : germ l β) (g : germ l γ)` to be the germ of `λ x, F (f x) (g x)` at `l`; * `f.tendsto lb`: we say that a germ `f : germ l β` tends to a filter `lb` if its representatives tend to `lb` along `l`; * `f.comp_tendsto g hg` and `f.comp_tendsto' g hg`: given `f : germ l β` and a function `g : γ → α` (resp., a germ `g : germ lc α`), if `g` tends to `l` along `lc`, then the composition `f ∘ g` is a well-defined germ at `lc`; * `germ.lift_pred`, `germ.lift_rel`: lift a predicate or a relation to the space of germs: `(f : germ l β).lift_pred p` means `∀ᶠ x in l, p (f x)`, and similarly for a relation. [TPiL_coe]: https://leanprover.github.io/theorem_proving_in_lean/type_classes.html#coercions-using-type-classes We also define `map (F : β → γ) : germ l β → germ l γ` sending each germ `f` to `F ∘ f`. For each of the following structures we prove that if `β` has this structure, then so does `germ l β`: * one-operation algebraic structures up to `comm_group`; * `mul_zero_class`, `distrib`, `semiring`, `comm_semiring`, `ring`, `comm_ring`; * `mul_action`, `distrib_mul_action`, `module`; * `preorder`, `partial_order`, and `lattice` structures up to `bounded_lattice`; * `ordered_cancel_comm_monoid` and `ordered_cancel_add_comm_monoid`. ## Tags filter, germ -/ namespace filter variables {α β γ δ : Type*} {l : filter α} {f g h : α → β} lemma const_eventually_eq' [ne_bot l] {a b : β} : (∀ᶠ x in l, a = b) ↔ a = b := eventually_const lemma const_eventually_eq [ne_bot l] {a b : β} : ((λ _, a) =ᶠ[l] (λ _, b)) ↔ a = b := @const_eventually_eq' _ _ _ _ a b lemma eventually_eq.comp_tendsto {f' : α → β} (H : f =ᶠ[l] f') {g : γ → α} {lc : filter γ} (hg : tendsto g lc l) : f ∘ g =ᶠ[lc] f' ∘ g := hg.eventually H /-- Setoid used to define the space of germs. -/ def germ_setoid (l : filter α) (β : Type*) : setoid (α → β) := { r := eventually_eq l, iseqv := ⟨eventually_eq.refl _, λ _ _, eventually_eq.symm, λ _ _ _, eventually_eq.trans⟩ } /-- The space of germs of functions `α → β` at a filter `l`. -/ def germ (l : filter α) (β : Type*) : Type* := quotient (germ_setoid l β) namespace germ instance : has_coe_t (α → β) (germ l β) := ⟨quotient.mk'⟩ instance : has_lift_t β (germ l β) := ⟨λ c, ↑(λ (x : α), c)⟩ @[simp] lemma quot_mk_eq_coe (l : filter α) (f : α → β) : quot.mk _ f = (f : germ l β) := rfl @[simp] lemma mk'_eq_coe (l : filter α) (f : α → β) : quotient.mk' f = (f : germ l β) := rfl @[elab_as_eliminator] lemma induction_on (f : germ l β) {p : germ l β → Prop} (h : ∀ f : α → β, p f) : p f := quotient.induction_on' f h @[elab_as_eliminator] lemma induction_on₂ (f : germ l β) (g : germ l γ) {p : germ l β → germ l γ → Prop} (h : ∀ (f : α → β) (g : α → γ), p f g) : p f g := quotient.induction_on₂' f g h @[elab_as_eliminator] lemma induction_on₃ (f : germ l β) (g : germ l γ) (h : germ l δ) {p : germ l β → germ l γ → germ l δ → Prop} (H : ∀ (f : α → β) (g : α → γ) (h : α → δ), p f g h) : p f g h := quotient.induction_on₃' f g h H /-- Given a map `F : (α → β) → (γ → δ)` that sends functions eventually equal at `l` to functions eventually equal at `lc`, returns a map from `germ l β` to `germ lc δ`. -/ def map' {lc : filter γ} (F : (α → β) → (γ → δ)) (hF : (l.eventually_eq ⇒ lc.eventually_eq) F F) : germ l β → germ lc δ := quotient.map' F hF /-- Given a germ `f : germ l β` and a function `F : (α → β) → γ` sending eventually equal functions to the same value, returns the value `F` takes on functions having germ `f` at `l`. -/ def lift_on {γ : Sort*} (f : germ l β) (F : (α → β) → γ) (hF : (l.eventually_eq ⇒ (=)) F F) : γ := quotient.lift_on' f F hF @[simp] lemma map'_coe {lc : filter γ} (F : (α → β) → (γ → δ)) (hF : (l.eventually_eq ⇒ lc.eventually_eq) F F) (f : α → β) : map' F hF f = F f := rfl @[simp, norm_cast] lemma coe_eq : (f : germ l β) = g ↔ (f =ᶠ[l] g) := quotient.eq' alias coe_eq ↔ _ filter.eventually_eq.germ_eq /-- Lift a function `β → γ` to a function `germ l β → germ l γ`. -/ def map (op : β → γ) : germ l β → germ l γ := map' ((∘) op) $ λ f g H, H.mono $ λ x H, congr_arg op H @[simp] lemma map_coe (op : β → γ) (f : α → β) : map op (f : germ l β) = op ∘ f := rfl @[simp] lemma map_id : map id = (id : germ l β → germ l β) := by { ext ⟨f⟩, refl } lemma map_map (op₁ : γ → δ) (op₂ : β → γ) (f : germ l β) : map op₁ (map op₂ f) = map (op₁ ∘ op₂) f := induction_on f $ λ f, rfl /-- Lift a binary function `β → γ → δ` to a function `germ l β → germ l γ → germ l δ`. -/ def map₂ (op : β → γ → δ) : germ l β → germ l γ → germ l δ := quotient.map₂' (λ f g x, op (f x) (g x)) $ λ f f' Hf g g' Hg, Hg.mp $ Hf.mono $ λ x Hf Hg, by simp only [Hf, Hg] @[simp] lemma map₂_coe (op : β → γ → δ) (f : α → β) (g : α → γ) : map₂ op (f : germ l β) g = λ x, op (f x) (g x) := rfl /-- A germ at `l` of maps from `α` to `β` tends to `lb : filter β` if it is represented by a map which tends to `lb` along `l`. -/ protected def tendsto (f : germ l β) (lb : filter β) : Prop := lift_on f (λ f, tendsto f l lb) $ λ f g H, propext (tendsto_congr' H) @[simp, norm_cast] lemma coe_tendsto {f : α → β} {lb : filter β} : (f : germ l β).tendsto lb ↔ tendsto f l lb := iff.rfl alias coe_tendsto ↔ _ filter.tendsto.germ_tendsto /-- Given two germs `f : germ l β`, and `g : germ lc α`, where `l : filter α`, if `g` tends to `l`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto' (f : germ l β) {lc : filter γ} (g : germ lc α) (hg : g.tendsto l) : germ lc β := lift_on f (λ f, g.map f) $ λ f₁ f₂ hF, (induction_on g $ λ g hg, coe_eq.2 $ hg.eventually hF) hg @[simp] lemma coe_comp_tendsto' (f : α → β) {lc : filter γ} {g : germ lc α} (hg : g.tendsto l) : (f : germ l β).comp_tendsto' g hg = g.map f := rfl /-- Given a germ `f : germ l β` and a function `g : γ → α`, where `l : filter α`, if `g` tends to `l` along `lc : filter γ`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto (f : germ l β) {lc : filter γ} (g : γ → α) (hg : tendsto g lc l) : germ lc β := f.comp_tendsto' _ hg.germ_tendsto @[simp] lemma coe_comp_tendsto (f : α → β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : (f : germ l β).comp_tendsto g hg = f ∘ g := rfl @[simp] lemma comp_tendsto'_coe (f : germ l β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : f.comp_tendsto' _ hg.germ_tendsto = f.comp_tendsto g hg := rfl @[simp, norm_cast] lemma const_inj [ne_bot l] {a b : β} : (↑a : germ l β) = ↑b ↔ a = b := coe_eq.trans $ const_eventually_eq @[simp] lemma map_const (l : filter α) (a : β) (f : β → γ) : (↑a : germ l β).map f = ↑(f a) := rfl @[simp] lemma map₂_const (l : filter α) (b : β) (c : γ) (f : β → γ → δ) : map₂ f (↑b : germ l β) ↑c = ↑(f b c) := rfl @[simp] lemma const_comp_tendsto {l : filter α} (b : β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : (↑b : germ l β).comp_tendsto g hg = ↑b := rfl @[simp] lemma const_comp_tendsto' {l : filter α} (b : β) {lc : filter γ} {g : germ lc α} (hg : g.tendsto l) : (↑b : germ l β).comp_tendsto' g hg = ↑b := induction_on g (λ _ _, rfl) hg /-- Lift a predicate on `β` to `germ l β`. -/ def lift_pred (p : β → Prop) (f : germ l β) : Prop := lift_on f (λ f, ∀ᶠ x in l, p (f x)) $ λ f g H, propext $ eventually_congr $ H.mono $ λ x hx, hx ▸ iff.rfl @[simp] lemma lift_pred_coe {p : β → Prop} {f : α → β} : lift_pred p (f : germ l β) ↔ ∀ᶠ x in l, p (f x) := iff.rfl lemma lift_pred_const {p : β → Prop} {x : β} (hx : p x) : lift_pred p (↑x : germ l β) := eventually_of_forall $ λ y, hx @[simp] lemma lift_pred_const_iff [ne_bot l] {p : β → Prop} {x : β} : lift_pred p (↑x : germ l β) ↔ p x := @eventually_const _ _ _ (p x) /-- Lift a relation `r : β → γ → Prop` to `germ l β → germ l γ → Prop`. -/ def lift_rel (r : β → γ → Prop) (f : germ l β) (g : germ l γ) : Prop := quotient.lift_on₂' f g (λ f g, ∀ᶠ x in l, r (f x) (g x)) $ λ f g f' g' Hf Hg, propext $ eventually_congr $ Hg.mp $ Hf.mono $ λ x hf hg, hf ▸ hg ▸ iff.rfl @[simp] lemma lift_rel_coe {r : β → γ → Prop} {f : α → β} {g : α → γ} : lift_rel r (f : germ l β) g ↔ ∀ᶠ x in l, r (f x) (g x) := iff.rfl lemma lift_rel_const {r : β → γ → Prop} {x : β} {y : γ} (h : r x y) : lift_rel r (↑x : germ l β) ↑y := eventually_of_forall $ λ _, h @[simp] lemma lift_rel_const_iff [ne_bot l] {r : β → γ → Prop} {x : β} {y : γ} : lift_rel r (↑x : germ l β) ↑y ↔ r x y := @eventually_const _ _ _ (r x y) instance [inhabited β] : inhabited (germ l β) := ⟨↑(default β)⟩ section monoid variables {M : Type*} {G : Type*} @[to_additive] instance [has_mul M] : has_mul (germ l M) := ⟨map₂ (*)⟩ @[simp, to_additive] lemma coe_mul [has_mul M] (f g : α → M) : ↑(f * g) = (f * g : germ l M) := rfl attribute [norm_cast] coe_mul coe_add @[to_additive] instance [has_one M] : has_one (germ l M) := ⟨↑(1:M)⟩ @[simp, to_additive] lemma coe_one [has_one M] : ↑(1 : α → M) = (1 : germ l M) := rfl attribute [norm_cast] coe_one coe_zero @[to_additive] instance [semigroup M] : semigroup (germ l M) := { mul := (*), mul_assoc := by { rintros ⟨f⟩ ⟨g⟩ ⟨h⟩, simp only [mul_assoc, quot_mk_eq_coe, ← coe_mul] } } @[to_additive] instance [comm_semigroup M] : comm_semigroup (germ l M) := { mul := (*), mul_comm := by { rintros ⟨f⟩ ⟨g⟩, simp only [mul_comm, quot_mk_eq_coe, ← coe_mul] }, .. germ.semigroup } @[to_additive add_left_cancel_semigroup] instance [left_cancel_semigroup M] : left_cancel_semigroup (germ l M) := { mul := (*), mul_left_cancel := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃ H, coe_eq.2 ((coe_eq.1 H).mono $ λ x, mul_left_cancel), .. germ.semigroup } @[to_additive add_right_cancel_semigroup] instance [right_cancel_semigroup M] : right_cancel_semigroup (germ l M) := { mul := (*), mul_right_cancel := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃ H, coe_eq.2 $ (coe_eq.1 H).mono $ λ x, mul_right_cancel, .. germ.semigroup } @[to_additive] instance [monoid M] : monoid (germ l M) := { mul := (*), one := 1, one_mul := λ f, induction_on f $ λ f, by { norm_cast, rw [one_mul] }, mul_one := λ f, induction_on f $ λ f, by { norm_cast, rw [mul_one] }, .. germ.semigroup } /-- coercion from functions to germs as a monoid homomorphism. -/ @[to_additive] def coe_mul_hom [monoid M] (l : filter α) : (α → M) →* germ l M := ⟨coe, rfl, λ f g, rfl⟩ /-- coercion from functions to germs as an additive monoid homomorphism. -/ add_decl_doc coe_add_hom @[simp, to_additive] lemma coe_coe_mul_hom [monoid M] : (coe_mul_hom l : (α → M) → germ l M) = coe := rfl @[to_additive] instance [comm_monoid M] : comm_monoid (germ l M) := { mul := (*), one := 1, .. germ.comm_semigroup, .. germ.monoid } @[to_additive] instance [has_inv G] : has_inv (germ l G) := ⟨map has_inv.inv⟩ @[simp, to_additive] lemma coe_inv [has_inv G] (f : α → G) : ↑f⁻¹ = (f⁻¹ : germ l G) := rfl attribute [norm_cast] coe_inv coe_neg @[to_additive] instance [has_div M] : has_div (germ l M) := ⟨map₂ (/)⟩ @[simp, norm_cast, to_additive] lemma coe_div [has_div M] (f g : α → M) : ↑(f / g) = (f / g : germ l M) := rfl @[to_additive] instance [div_inv_monoid G] : div_inv_monoid (germ l G) := { inv := has_inv.inv, div := has_div.div, div_eq_mul_inv := by { rintros ⟨f⟩ ⟨g⟩, exact congr_arg (quot.mk _) (div_eq_mul_inv f g) }, .. germ.monoid } @[to_additive] instance [group G] : group (germ l G) := { mul := (*), one := 1, mul_left_inv := by { rintros ⟨f⟩, exact congr_arg (quot.mk _) (mul_left_inv f) }, .. germ.div_inv_monoid } @[to_additive] instance [comm_group G] : comm_group (germ l G) := { mul := (*), one := 1, inv := has_inv.inv, .. germ.group, .. germ.comm_monoid } end monoid section ring variables {R : Type*} instance nontrivial [nontrivial R] [ne_bot l] : nontrivial (germ l R) := let ⟨x, y, h⟩ := exists_pair_ne R in ⟨⟨↑x, ↑y, mt const_inj.1 h⟩⟩ instance [mul_zero_class R] : mul_zero_class (germ l R) := { zero := 0, mul := (*), mul_zero := λ f, induction_on f $ λ f, by { norm_cast, rw [mul_zero] }, zero_mul := λ f, induction_on f $ λ f, by { norm_cast, rw [zero_mul] } } instance [distrib R] : distrib (germ l R) := { mul := (*), add := (+), left_distrib := λ f g h, induction_on₃ f g h $ λ f g h, by { norm_cast, rw [left_distrib] }, right_distrib := λ f g h, induction_on₃ f g h $ λ f g h, by { norm_cast, rw [right_distrib] } } instance [semiring R] : semiring (germ l R) := { .. germ.add_comm_monoid, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } /-- Coercion `(α → R) → germ l R` as a `ring_hom`. -/ def coe_ring_hom [semiring R] (l : filter α) : (α → R) →+* germ l R := { to_fun := coe, .. (coe_mul_hom l : _ →* germ l R), .. (coe_add_hom l : _ →+ germ l R) } @[simp] lemma coe_coe_ring_hom [semiring R] : (coe_ring_hom l : (α → R) → germ l R) = coe := rfl instance [ring R] : ring (germ l R) := { .. germ.add_comm_group, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } instance [comm_semiring R] : comm_semiring (germ l R) := { .. germ.semiring, .. germ.comm_monoid } instance [comm_ring R] : comm_ring (germ l R) := { .. germ.ring, .. germ.comm_monoid } end ring section module variables {M N R : Type*} instance [has_scalar M β] : has_scalar M (germ l β) := ⟨λ c, map ((•) c)⟩ instance has_scalar' [has_scalar M β] : has_scalar (germ l M) (germ l β) := ⟨map₂ (•)⟩ @[simp, norm_cast] lemma coe_smul [has_scalar M β] (c : M) (f : α → β) : ↑(c • f) = (c • f : germ l β) := rfl @[simp, norm_cast] lemma coe_smul' [has_scalar M β] (c : α → M) (f : α → β) : ↑(c • f) = (c : germ l M) • (f : germ l β) := rfl instance [monoid M] [mul_action M β] : mul_action M (germ l β) := { one_smul := λ f, induction_on f $ λ f, by { norm_cast, simp only [one_smul] }, mul_smul := λ c₁ c₂ f, induction_on f $ λ f, by { norm_cast, simp only [mul_smul] } } instance mul_action' [monoid M] [mul_action M β] : mul_action (germ l M) (germ l β) := { one_smul := λ f, induction_on f $ λ f, by simp only [← coe_one, ← coe_smul', one_smul], mul_smul := λ c₁ c₂ f, induction_on₃ c₁ c₂ f $ λ c₁ c₂ f, by { norm_cast, simp only [mul_smul] } } instance [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action M (germ l N) := { smul_add := λ c f g, induction_on₂ f g $ λ f g, by { norm_cast, simp only [smul_add] }, smul_zero := λ c, by simp only [← coe_zero, ← coe_smul, smul_zero] } instance distrib_mul_action' [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action (germ l M) (germ l N) := { smul_add := λ c f g, induction_on₃ c f g $ λ c f g, by { norm_cast, simp only [smul_add] }, smul_zero := λ c, induction_on c $ λ c, by simp only [← coe_zero, ← coe_smul', smul_zero] } instance [semiring R] [add_comm_monoid M] [module R M] : module R (germ l M) := { add_smul := λ c₁ c₂ f, induction_on f $ λ f, by { norm_cast, simp only [add_smul] }, zero_smul := λ f, induction_on f $ λ f, by { norm_cast, simp only [zero_smul, coe_zero] } } instance module' [semiring R] [add_comm_monoid M] [module R M] : module (germ l R) (germ l M) := { add_smul := λ c₁ c₂ f, induction_on₃ c₁ c₂ f $ λ c₁ c₂ f, by { norm_cast, simp only [add_smul] }, zero_smul := λ f, induction_on f $ λ f, by simp only [← coe_zero, ← coe_smul', zero_smul] } end module instance [has_le β] : has_le (germ l β) := ⟨lift_rel (≤)⟩ @[simp] lemma coe_le [has_le β] : (f : germ l β) ≤ g ↔ (f ≤ᶠ[l] g) := iff.rfl lemma le_def [has_le β] : ((≤) : germ l β → germ l β → Prop) = lift_rel (≤) := rfl lemma const_le [has_le β] {x y : β} (h : x ≤ y) : (↑x : germ l β) ≤ ↑y := lift_rel_const h @[simp, norm_cast] lemma const_le_iff [has_le β] [ne_bot l] {x y : β} : (↑x : germ l β) ≤ ↑y ↔ x ≤ y := lift_rel_const_iff instance [preorder β] : preorder (germ l β) := { le := (≤), le_refl := λ f, induction_on f $ eventually_le.refl l, le_trans := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃, eventually_le.trans } instance [partial_order β] : partial_order (germ l β) := { le := (≤), le_antisymm := λ f g, induction_on₂ f g $ λ f g h₁ h₂, (eventually_le.antisymm h₁ h₂).germ_eq, .. germ.preorder } instance [has_bot β] : has_bot (germ l β) := ⟨↑(⊥:β)⟩ @[simp, norm_cast] lemma const_bot [has_bot β] : (↑(⊥:β) : germ l β) = ⊥ := rfl instance [order_bot β] : order_bot (germ l β) := { bot := ⊥, le := (≤), bot_le := λ f, induction_on f $ λ f, eventually_of_forall $ λ x, bot_le, .. germ.partial_order } instance [has_top β] : has_top (germ l β) := ⟨↑(⊤:β)⟩ @[simp, norm_cast] lemma const_top [has_top β] : (↑(⊤:β) : germ l β) = ⊤ := rfl instance [order_top β] : order_top (germ l β) := { top := ⊤, le := (≤), le_top := λ f, induction_on f $ λ f, eventually_of_forall $ λ x, le_top, .. germ.partial_order } instance [has_sup β] : has_sup (germ l β) := ⟨map₂ (⊔)⟩ @[simp, norm_cast] lemma const_sup [has_sup β] (a b : β) : ↑(a ⊔ b) = (↑a ⊔ ↑b : germ l β) := rfl instance [has_inf β] : has_inf (germ l β) := ⟨map₂ (⊓)⟩ @[simp, norm_cast] lemma const_inf [has_inf β] (a b : β) : ↑(a ⊓ b) = (↑a ⊓ ↑b : germ l β) := rfl instance [semilattice_sup β] : semilattice_sup (germ l β) := { sup := (⊔), le_sup_left := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, le_sup_left, le_sup_right := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, le_sup_right, sup_le := λ f₁ f₂ g, induction_on₃ f₁ f₂ g $ λ f₁ f₂ g h₁ h₂, h₂.mp $ h₁.mono $ λ x, sup_le, .. germ.partial_order } instance [semilattice_inf β] : semilattice_inf (germ l β) := { inf := (⊓), inf_le_left := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, inf_le_left, inf_le_right := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, inf_le_right, le_inf := λ f₁ f₂ g, induction_on₃ f₁ f₂ g $ λ f₁ f₂ g h₁ h₂, h₂.mp $ h₁.mono $ λ x, le_inf, .. germ.partial_order } instance [semilattice_inf_bot β] : semilattice_inf_bot (germ l β) := { .. germ.semilattice_inf, .. germ.order_bot } instance [semilattice_sup_bot β] : semilattice_sup_bot (germ l β) := { .. germ.semilattice_sup, .. germ.order_bot } instance [semilattice_inf_top β] : semilattice_inf_top (germ l β) := { .. germ.semilattice_inf, .. germ.order_top } instance [semilattice_sup_top β] : semilattice_sup_top (germ l β) := { .. germ.semilattice_sup, .. germ.order_top } instance [lattice β] : lattice (germ l β) := { .. germ.semilattice_sup, .. germ.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (germ l β) := { .. germ.lattice, .. germ.order_bot, .. germ.order_top } @[to_additive] instance [ordered_cancel_comm_monoid β] : ordered_cancel_comm_monoid (germ l β) := { mul_le_mul_left := λ f g, induction_on₂ f g $ λ f g H h, induction_on h $ λ h, H.mono $ λ x H, mul_le_mul_left' H _, le_of_mul_le_mul_left := λ f g h, induction_on₃ f g h $ λ f g h H, H.mono $ λ x, le_of_mul_le_mul_left', .. germ.partial_order, .. germ.comm_monoid, .. germ.left_cancel_semigroup } @[to_additive] instance ordered_comm_group [ordered_comm_group β] : ordered_comm_group (germ l β) := { mul_le_mul_left := λ f g, induction_on₂ f g $ λ f g H h, induction_on h $ λ h, H.mono $ λ x H, mul_le_mul_left' H _, .. germ.partial_order, .. germ.comm_group } end germ end filter
0de52c1a29314fe194ca86f13ed834d7e6da1152
4727251e0cd73359b15b664c3170e5d754078599
/test/squeeze.lean
a6ce4fb3529764cd8baa9f74efa88dce2db9a0cb
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,201
lean
import data.nat.basic import data.pnat.basic import tactic.squeeze namespace tactic namespace interactive setup_tactic_parser /-- version of squeeze_simp that tests whether the output matches the expected output -/ meta def squeeze_simp_test (key : parse cur_pos) (slow_and_accurate : parse (tk "?")?) (use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : parse struct_inst?) (_ : parse (tk "=")) (l : parse simp_arg_list) : tactic unit := do (cfg',c) ← parse_config cfg, squeeze_simp_core slow_and_accurate.is_some no_dflt hs (λ l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg') (λ a, guard (a.map to_string = l.map to_string) <|> fail!"{a.map to_string} expected.") end interactive end tactic -- Test that squeeze_simp succeeds when it closes the goal. example : 1 = 1 := by { squeeze_simp_test = [eq_self_iff_true] } -- Test that `squeeze_simp` succeeds when given arguments. example {a b : ℕ} (h : a + a = b) : b + 0 = 2 * a := by { squeeze_simp_test [←h, two_mul] = [←h, two_mul, add_zero] } -- Test that the order of the given hypotheses do not matter. example {a b : ℕ} (h : a + a = b) : b + 0 = 2 * a := by { squeeze_simp_test [←h, two_mul] = [←h, two_mul, add_zero] } section namespacing1 @[simp] lemma asda {a : ℕ} : 0 ≤ a := nat.zero_le _ @[simp] lemma pnat.asda {a : ℕ+} : 1 ≤ a := pnat.one_le _ open pnat -- Test that adding two clashing decls to a namespace doesn't break `squeeze_simp`. example {a : ℕ} {b : ℕ+} : 0 ≤ a ∧ 1 ≤ b := by { squeeze_simp_test = [_root_.asda, pnat.asda, and_self] } end namespacing1 section namespacing2 open nat local attribute [simp] nat.mul_succ -- Test that we strip superflous prefixes from `squeeze_simp` output, if needed. example (n m : ℕ) : n * m.succ = n*m + n := by { squeeze_simp_test = [mul_succ] } end namespacing2 def a := 0 def b := 0 def c := 0 def f : ℕ → ℕ := default @[simp] lemma k (x) : f x = b := rfl @[simp] lemma l : f b = c := rfl -- Test the fix for #3097 example : f (f a) = c := by { squeeze_simp_test = [k, l] }
71f653ff274fe36ad244fc2cd1c979631629d0f8
c5b07d17b3c9fb19e4b302465d237fd1d988c14f
/src/isos/bool.lean
b4aa315fb722831b920b4f20939bee559c7e0141
[ "MIT" ]
permissive
skaslev/papers
acaec61602b28c33d6115e53913b2002136aa29b
f15b379f3c43bbd0a37ac7bb75f4278f7e901389
refs/heads/master
1,665,505,770,318
1,660,378,602,000
1,660,378,602,000
14,101,547
0
1
MIT
1,595,414,522,000
1,383,542,702,000
Lean
UTF-8
Lean
false
false
715
lean
import functors.generating namespace bool def def_iso : bool ≃ 1 ⊕ 1 := ⟨λ x, bool.rec (sum.inl ()) (sum.inr ()) x, λ x, sum.rec (λ x, ff) (λ x, tt) x, λ x, begin induction x, repeat {simp} end, λ x, begin induction x, repeat {induction x, simp} end⟩ def cf : ℕ → ℕ | 0 := 2 | _ := 0 def ogf_iso : bool ≃ ogf cf 1 := begin apply (def_iso ⋆ _), apply (_ ⋆ ax₁.inv), apply (_ ⋆ iso.add_left (iso.mul_one_right ⋆ iso.mul_right fseq.one_iso.inv)), apply iso.add_zero_right_subst fin.two_iso.inv _, apply iso.sigma_subst_zero (λ n, _), apply (iso.mul_left fin.zero_iso ⋆ _), apply iso.mul_zero_left.inv end instance : has_ogf₁ bool := ⟨cf, ogf_iso⟩ end bool
52401d11d70aeb42f37e368ac50033752684b69c
e750538628490a3f5600df1edf4885819c33a4f3
/Chain-BIRDS/Patient/D13_update.sql.lean
b1462a062e9b93d29834dcf1fed1a3f3c5423b60
[ "Apache-2.0" ]
permissive
cmli93/Chain-Dejima
0c054cc8d2d28ebcd6b2f84f8b7ba45e0d88b5cf
008d2748f0602b7d65bba8a9a86530e0899496ec
refs/heads/master
1,634,811,960,801
1,551,677,784,000
1,551,677,784,000
173,666,288
0
0
null
null
null
null
UTF-8
Lean
false
false
2,295
lean
import logic.basic import tactic.basic import tactic.finish import tactic.interactive import bx import super import smt2 universe u open int open auto local attribute [instance] classical.prop_decidable -- make all prop decidable theorem disjoint_deltas {d13_patianddoct: ℤ → string → string → string → Prop} {d1_patient: ℤ → string → string → string → string → Prop}: true → (∃ COL0 COL1 COL2 COL3 COL4, ((d13_patianddoct COL0 COL1 COL2 COL4 ∧ (∃ MEDICATIONNAME CLINICALDATA DOSAGE, d1_patient COL0 MEDICATIONNAME CLINICALDATA COL3 DOSAGE)) ∧ ¬(∃ ADDRESS, d1_patient COL0 COL1 COL2 ADDRESS COL4)) ∧ d1_patient COL0 COL1 COL2 COL3 COL4 ∧ ¬d13_patianddoct COL0 COL1 COL2 COL4) → false:= begin intro h, try{rw[imp_false] at *}, try{simp at *}, revert h, z3_smt, end theorem getput {d1_patient: ℤ → string → string → string → string → Prop}: true → (∃ COL0 COL1 COL2 COL3 COL4, d1_patient COL0 COL1 COL2 COL3 COL4 ∧ ¬(∃ ADDRESS, d1_patient COL0 COL1 COL2 ADDRESS COL4)) ∨ (∃ COL0 COL1 COL2 COL3 COL4, ((∃ ADDRESS, d1_patient COL0 COL1 COL2 ADDRESS COL4) ∧ (∃ MEDICATIONNAME CLINICALDATA DOSAGE, d1_patient COL0 MEDICATIONNAME CLINICALDATA COL3 DOSAGE)) ∧ ¬(∃ ADDRESS, d1_patient COL0 COL1 COL2 ADDRESS COL4)) → false:= begin intro h, try{rw[imp_false] at *}, try{simp at *}, revert h, z3_smt, end theorem putget {d13_patianddoct: ℤ → string → string → string → Prop} {d1_patient: ℤ → string → string → string → string → Prop}: true → (∀ CLINICALDATA DOSAGE MEDICATIONNAME PATIENTID, (∃ COL3', d1_patient PATIENTID MEDICATIONNAME CLINICALDATA COL3' DOSAGE ∧ ¬(d1_patient PATIENTID MEDICATIONNAME CLINICALDATA COL3' DOSAGE ∧ ¬d13_patianddoct PATIENTID MEDICATIONNAME CLINICALDATA DOSAGE) ∨ (d13_patianddoct PATIENTID MEDICATIONNAME CLINICALDATA DOSAGE ∧ (∃ MEDICATIONNAME CLINICALDATA DOSAGE, d1_patient PATIENTID MEDICATIONNAME CLINICALDATA COL3' DOSAGE)) ∧ ¬(∃ ADDRESS, d1_patient PATIENTID MEDICATIONNAME CLINICALDATA ADDRESS DOSAGE)) ↔ d13_patianddoct PATIENTID MEDICATIONNAME CLINICALDATA DOSAGE):= begin intro h, try{rw[imp_false] at *}, try{simp at *}, revert h, z3_smt, end
1ba123aba7447d08631380539e94791dad69d2b0
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.50.lean
0d6f1990921fb06f22e7404fe349837a6a99423c
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
188
lean
/- page 94 -/ import standard open nat print definition nat.rec_on definition rec_on {C : nat → Type} (n : nat) (fz : C zero) (fs : Π a, C a → C (succ a)) : C n := nat.rec fz fs n
6b5869e7f75d0b42044ff74684931cc3cfcada33
05b503addd423dd68145d68b8cde5cd595d74365
/src/data/fin_enum.lean
c1385fdee88680c50b711f9bdda3b425293eaf68
[ "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
9,013
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import category.monad.basic import data.list.basic import data.equiv.basic import data.finset import data.fintype.basic /-! Type class for finitely enumerable types. The property is stronger than `fintype` in that it assigns each element a rank in a finite enumeration. -/ open finset (hiding singleton) /-- `fin_enum α` means that `α` is finite and can be enumerated in some order, i.e. `α` has an explicit bijection with `fin n` for some n. -/ class fin_enum (α : Sort*) := (card : ℕ) (equiv : α ≃ fin card) [dec_eq : decidable_eq α] attribute [instance, priority 100] fin_enum.dec_eq namespace fin_enum variables {α : Type*} /-- transport a `fin_enum` instance across an equivalence -/ def of_equiv (α) {β} [fin_enum α] (h : β ≃ α) : fin_enum β := { card := card α, equiv := h.trans (equiv α), dec_eq := equiv.decidable_eq_of_equiv (h.trans (equiv _)) } /-- create a `fin_enum` instance from an exhaustive list without duplicates -/ def of_nodup_list [decidable_eq α] (xs : list α) (h : ∀ x : α, x ∈ xs) (h' : list.nodup xs) : fin_enum α := { card := xs.length, equiv := ⟨λ x, ⟨xs.index_of x,by rw [list.index_of_lt_length]; apply h⟩, λ ⟨i,h⟩, xs.nth_le _ h, λ x, by simp [of_nodup_list._match_1], λ ⟨i,h⟩, by simp [of_nodup_list._match_1,*]; rw list.nth_le_index_of; apply list.nodup_erase_dup ⟩ } /-- create a `fin_enum` instance from an exhaustive list; duplicates are removed -/ def of_list [decidable_eq α] (xs : list α) (h : ∀ x : α, x ∈ xs) : fin_enum α := of_nodup_list xs.erase_dup (by simp *) (list.nodup_erase_dup _) /-- create an exhaustive list of the values of a given type -/ def to_list (α) [fin_enum α] : list α := (list.fin_range (card α)).map (equiv α).symm open function @[simp] lemma mem_to_list [fin_enum α] (x : α) : x ∈ to_list α := by simp [to_list]; existsi equiv α x; simp @[simp] lemma nodup_to_list [fin_enum α] : list.nodup (to_list α) := by simp [to_list]; apply list.nodup_map; [apply equiv.injective, apply list.nodup_fin_range] /-- create a `fin_enum` instance using a surjection -/ def of_surjective {β} (f : β → α) [decidable_eq α] [fin_enum β] (h : surjective f) : fin_enum α := of_list ((to_list β).map f) (by intro; simp; exact h _) /-- create a `fin_enum` instance using an injection -/ noncomputable def of_injective {α β} (f : α → β) [decidable_eq α] [fin_enum β] (h : injective f) : fin_enum α := of_list ((to_list β).filter_map (partial_inv f)) begin intro x, simp only [mem_to_list, true_and, list.mem_filter_map], use f x, simp only [h, function.partial_inv_left], end instance pempty : fin_enum pempty := of_list [] (λ x, pempty.elim x) instance empty : fin_enum empty := of_list [] (λ x, empty.elim x) instance punit : fin_enum punit := of_list [punit.star] (λ x, by cases x; simp) instance prod {β} [fin_enum α] [fin_enum β] : fin_enum (α × β) := of_list ( (to_list α).product (to_list β) ) (λ x, by cases x; simp) instance sum {β} [fin_enum α] [fin_enum β] : fin_enum (α ⊕ β) := of_list ( (to_list α).map sum.inl ++ (to_list β).map sum.inr ) (λ x, by cases x; simp) instance fin {n} : fin_enum (fin n) := of_list (list.fin_range _) (by simp) instance quotient.enum [fin_enum α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fin_enum (quotient s) := fin_enum.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) /-- enumerate all finite sets of a given type -/ def finset.enum [decidable_eq α] : list α → list (finset α) | [] := [∅] | (x :: xs) := do r ← finset.enum xs, [r,{x} ∪ r] @[simp] lemma finset.mem_enum [decidable_eq α] (s : finset α) (xs : list α) : s ∈ finset.enum xs ↔ ∀ x ∈ s, x ∈ xs := begin induction xs generalizing s; simp [*,finset.enum], { simp [finset.eq_empty_iff_forall_not_mem,(∉)], refl }, { split, rintro ⟨a,h,h'⟩ x hx, cases h', { right, apply h, subst a, exact hx, }, { simp only [h', mem_union, mem_singleton] at hx ⊢, cases hx, { exact or.inl hx }, { exact or.inr (h _ hx) } }, intro h, existsi s \ ({xs_hd} : finset α), simp only [and_imp, union_comm, mem_sdiff, insert_empty_eq_singleton, mem_singleton], simp only [or_iff_not_imp_left] at h, existsi h, by_cases xs_hd ∈ s, { have : finset.singleton xs_hd ⊆ s, simp only [has_subset.subset, *, forall_eq, mem_singleton], simp only [union_sdiff_of_subset this, or_true, finset.union_sdiff_of_subset, eq_self_iff_true], }, { left, symmetry, simp only [sdiff_eq_self], intro a, simp only [and_imp, mem_inter, mem_singleton, not_mem_empty], intros h₀ h₁, subst a, apply h h₀, } } end instance finset.fin_enum [fin_enum α] : fin_enum (finset α) := of_list (finset.enum (to_list α)) (by intro; simp) instance subtype.fin_enum [fin_enum α] (p : α → Prop) [decidable_pred p] : fin_enum {x // p x} := of_list ((to_list α).filter_map $ λ x, if h : p x then some ⟨_,h⟩ else none) (by rintro ⟨x,h⟩; simp; existsi x; simp *) instance (β : α → Type*) [fin_enum α] [∀ a, fin_enum (β a)] : fin_enum (sigma β) := of_list ((to_list α).bind $ λ a, (to_list (β a)).map $ sigma.mk a) (by intro x; cases x; simp) instance psigma.fin_enum {β : α → Type*} [fin_enum α] [∀ a, fin_enum (β a)] : fin_enum (Σ' a, β a) := fin_enum.of_equiv _ (equiv.psigma_equiv_sigma _) instance psigma.fin_enum_prop_left {α : Prop} {β : α → Type*} [∀ a, fin_enum (β a)] [decidable α] : fin_enum (Σ' a, β a) := if h : α then of_list ((to_list (β h)).map $ psigma.mk h) (λ ⟨a,Ba⟩, by simp) else of_list [] (λ ⟨a,Ba⟩, (h a).elim) instance psigma.fin_enum_prop_right {β : α → Prop} [fin_enum α] [∀ a, decidable (β a)] : fin_enum (Σ' a, β a) := fin_enum.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fin_enum_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fin_enum (Σ' a, β a) := if h : ∃ a, β a then of_list [⟨h.fst,h.snd⟩] (by rintro ⟨⟩; simp) else of_list [] (λ a, (h ⟨a.fst,a.snd⟩).elim) @[priority 100] instance [fin_enum α] : fintype α := { elems := univ.map (equiv α).symm.to_embedding, complete := by intros; simp; existsi (equiv α x); simp } /-- For `pi.cons x xs y f` create a function where every `i ∈ xs` is mapped to `f i` and `x` is mapped to `y` -/ def pi.cons {β : α → Type*} [decidable_eq α] (x : α) (xs : list α) (y : β x) (f : Π a, a ∈ xs → β a) : Π a, a ∈ (x :: xs : list α) → β a | b h := if h' : b = x then cast (by rw h') y else f b (list.mem_of_ne_of_mem h' h) /-- Given `f` a function whose domain is `x :: xs`, produce a function whose domain is restricted to `xs`. -/ def pi.tail {α : Type*} {β : α → Type*} {x : α} {xs : list α} (f : Π a, a ∈ (x :: xs : list α) → β a) : Π a, a ∈ xs → β a | a h := f a (list.mem_cons_of_mem _ h) /-- `pi xs f` creates the list of functions `g` such that, for `x ∈ xs`, `g x ∈ f x` -/ def pi {α : Type*} {β : α → Type*} [decidable_eq α] : Π xs : list α, (Π a, list (β a)) → list (Π a, a ∈ xs → β a) | [] fs := [λ x h, h.elim] | (x :: xs) fs := fin_enum.pi.cons x xs <$> fs x <*> pi xs fs lemma mem_pi {α : Type*} {β : α → Type*} [fin_enum α] [∀a, fin_enum (β a)] (xs : list α) (f : Π a, a ∈ xs → β a) : f ∈ pi xs (λ x, to_list (β x)) := begin induction xs; simp [pi,-list.map_eq_map] with monad_norm functor_norm, { ext a ⟨ ⟩ }, { existsi pi.cons xs_hd xs_tl (f _ (list.mem_cons_self _ _)), split, exact ⟨_,rfl⟩, existsi pi.tail f, split, { apply xs_ih, }, { ext x h, simp [pi.cons], split_ifs, subst x, refl, refl }, } end /-- enumerate all functions whose domain and range are finitely enumerable -/ def pi.enum {α : Type*} (β : α → Type*) [fin_enum α] [∀a, fin_enum (β a)] : list (Π a, β a) := (pi (to_list α) (λ x, to_list (β x))).map (λ f x, f x (mem_to_list _)) lemma pi.mem_enum {α : Type*} {β : α → Type*} [fin_enum α] [∀a, fin_enum (β a)] (f : Π a, β a) : f ∈ pi.enum β := by simp [pi.enum]; refine ⟨λ a h, f a, mem_pi _ _, rfl⟩ instance pi.fin_enum {α : Type*} {β : α → Type*} [fin_enum α] [∀a, fin_enum (β a)] : fin_enum (Πa, β a) := of_list (pi.enum _) (λ x, pi.mem_enum _) instance pfun_fin_enum (p : Prop) [decidable p] (α : p → Type*) [Π hp, fin_enum (α hp)] : fin_enum (Π hp : p, α hp) := if hp : p then of_list ( (to_list (α hp)).map $ λ x hp', x ) (by intro; simp; exact ⟨x hp,rfl⟩) else of_list [λ hp', (hp hp').elim] (by intro; simp; ext hp'; cases hp hp') end fin_enum
829656c35f8b26eee41ec9ed0350a3befa90946f
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/ring_theory/ideal/basic.lean
f820428343cab73bc01e1c1670a97490e95ce7af
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,457
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.zorn import order.atoms /-! # Ideals over a ring This file defines `ideal R`, the type of ideals over a commutative ring `R`. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `•` is interpreted as `*`. ## TODO Support one-sided ideals, and ideals over non-commutative rings. See `algebra.ring_quot` for quotients of non-commutative rings. -/ universes u v w variables {α : Type u} {β : Type v} open set function open_locale classical big_operators /-- An ideal in a commutative semiring `R` is an additive submonoid `s` such that `a * b ∈ s` whenever `b ∈ s`. If `R` is a ring, then `s` is an additive subgroup. -/ @[reducible] def ideal (R : Type u) [comm_semiring R] := submodule R R namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem variables (a) lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem a variables {a} variables (b) lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left b h variables {b} end ideal variables {a b : α} -- A separate namespace definition is needed because the variables were historically in a different order namespace ideal variables [comm_ring α] (I : ideal α) @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left _ hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := is_unit_iff_exists_inv'.1 h in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one lemma exists_mem_ne_zero_iff_ne_bot : (∃ p ∈ I, p ≠ (0 : α)) ↔ I ≠ ⊥ := begin refine ⟨λ h, let ⟨p, hp, hp0⟩ := h in λ h, absurd (h ▸ hp : p ∈ (⊥ : ideal α)) hp0, λ h, _⟩, contrapose! h, exact eq_bot_iff.2 (λ x hx, (h x hx).symm ▸ (ideal.zero_mem ⊥)), end lemma exists_mem_ne_zero_of_ne_bot (hI : I ≠ ⊥) : ∃ p ∈ I, p ≠ (0 : α) := (exists_mem_ne_zero_iff_ne_bot I).mpr hI @[simp] theorem unit_mul_mem_iff_mem {x y : α} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, λ h, I.mul_mem_left y h⟩, obtain ⟨y', hy'⟩ := is_unit_iff_exists_inv.1 hy, have := I.mul_mem_left y' h, rwa [← mul_assoc, mul_comm y' y, hy', one_mul] at this, end @[simp] theorem mul_unit_mem_iff_mem {x y : α} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x ▸ unit_mul_mem_iff_mem I hy /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span (1 : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {α : Type u} [integral_domain α] {x y : α} : span ({x} : set α) = span ({y} : set α) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot @[simp] lemma span_zero : span (0 : set α) = ⊥ := by rw [←set.singleton_zero, span_singleton_eq_bot] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, singleton_one, span_singleton_one, eq_top_iff] lemma span_singleton_mul_right_unit {a : α} (h2 : is_unit a) (x : α) : span ({x * a} : set α) = span {x} := begin apply le_antisymm, { rw span_singleton_le_span_singleton, use a}, { rw span_singleton_le_span_singleton, rw is_unit.mul_right_dvd h2} end lemma span_singleton_mul_left_unit {a : α} (h2 : is_unit a) (x : α) : span ({a * x} : set α) = span {x} := by rw [mul_comm, span_singleton_mul_right_unit h2] /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : α → α → Prop) : ideal α := submodule.span α { x | ∃ (a b) (h : r a b), x = a - b } /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ @[class] def is_prime (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.2 (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { exact (mt (eq_top_iff_one _).2 hI.1).elim H }, exact or.cases_on (hI.mem_or_mem H) id ih end lemma not_is_prime_iff {I : ideal α} : ¬ I.is_prime ↔ I = ⊤ ∨ ∃ (x ∉ I) (y ∉ I), x * y ∈ I := begin simp_rw [ideal.is_prime, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, λ ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime, prime, span_singleton_eq_top, hp, mem_span_singleton] lemma bot_prime {R : Type*} [integral_domain R] : (⊥ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), λ x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ @[class] def is_maximal (I : ideal α) : Prop := is_coatom I theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.2 _ h)⟩ theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, y * x - 1 ∈ I := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert'.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, hy⟩, rw [span_eq, ← neg_mem_iff, add_comm, neg_add', neg_mul_eq_neg_mul] at hy, exact ⟨-y, hy⟩ end theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin cases H.exists_inv hx with z hz, have := I.mul_mem_left _ hz, rw [mul_sub, mul_one, mul_comm, mul_assoc, sub_eq_add_neg] at this, exact I.neg_mem_iff.1 ((I.add_mem_iff_right $ I.mul_mem_left _ hxy).1 this) end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime /-- Krull's theorem: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := begin rcases zorn.zorn_partial_order₀ { J : ideal α | J ≠ ⊤ } _ I hI with ⟨M, M0, IM, h⟩, { refine ⟨M, ⟨M0, λ J hJ, by_contradiction $ λ J0, _⟩, IM⟩, cases h J J0 (le_of_lt hJ), exact lt_irrefl _ hJ }, { intros S SC cC I IS, refine ⟨Sup S, λ H, _, λ _, le_Sup⟩, obtain ⟨J, JS, J0⟩ : ∃ J ∈ S, (1 : α) ∈ J, from (submodule.mem_Sup_of_directed ⟨I, IS⟩ cC.directed_on).1 ((eq_top_iff_one _).1 H), exact SC JS ((eq_top_iff_one _).2 J0) } end /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial α] : ∃ M : ideal α, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (⊥ : ideal α) submodule.bot_ne_top in ⟨I, hI⟩ /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [comm_ring R] {P : ideal R} (hmax : ∀ m : ideal R, P < m → ¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊤ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [integral_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : span ({b₁ * b₂} : set β) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] /-- The quotient `R/I` of a ring `R` by an ideal `I`. -/ def quotient (I : ideal α) := I.quotient namespace quotient variables {I} {x y : α} instance (I : ideal α) : has_one I.quotient := ⟨submodule.quotient.mk 1⟩ instance (I : ideal α) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, submodule.quotient.mk (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, begin apply @quot.sound _ I.quotient_rel.r, calc a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ : _ ... ∈ I : I.add_mem (I.mul_mem_left _ h₁) (I.mul_mem_right _ h₂), rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] end⟩ instance (I : ideal α) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg submodule.quotient.mk (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (right_distrib a b c), ..submodule.quotient.add_comm_group I } /-- The ring homomorphism from a ring `R` to a quotient ring `R/I`. -/ def mk (I : ideal α) : α →+* I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ instance : inhabited (quotient I) := ⟨mk I 37⟩ protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I @[simp] theorem mk_eq_mk (x : α) : (submodule.quotient.mk x : quotient I) = mk I x := rfl lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected theorem nontrivial {I : ideal α} (hI : I ≠ ⊤) : nontrivial I.quotient := ⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩ lemma mk_surjective : function.surjective (mk I) := λ y, quotient.induction_on' y (λ x, exists.intro x rfl) instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), .. quotient.comm_ring I, .. quotient.nontrivial hI.1 } lemma is_integral_domain_iff_prime (I : ideal α) : is_integral_domain I.quotient ↔ I.is_prime := ⟨ λ ⟨h1, h2, h3⟩, ⟨zero_ne_one_iff.1 $ @zero_ne_one _ _ ⟨h1⟩, λ x y h, by { simp only [←eq_zero_iff_mem, (mk I).map_mul] at ⊢ h, exact h3 _ _ h}⟩, λ h, by exactI integral_domain.to_is_integral_domain I.quotient⟩ lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, cases hI.exists_inv (mt eq_zero_iff_mem.2 h) with b hb, rw [mul_comm] at hb, exact ⟨mk _ b, quot.sound hb⟩ end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, ..quotient.integral_domain I } /-- If the quotient by an ideal is a field, then the ideal is maximal. -/ theorem maximal_of_is_field (I : ideal α) (hqf : is_field I.quotient) : I.is_maximal := begin apply ideal.is_maximal_iff.2, split, { intro h, rcases hqf.exists_pair_ne with ⟨⟨x⟩, ⟨y⟩, hxy⟩, exact hxy (ideal.quotient.eq.2 (mul_one (x - y) ▸ I.mul_mem_left _ h)) }, { intros J x hIJ hxnI hxJ, rcases hqf.mul_inv_cancel (mt ideal.quotient.eq_zero_iff_mem.1 hxnI) with ⟨⟨y⟩, hy⟩, rw [← zero_add (1 : α), ← sub_self (x * y), sub_add], refine J.sub_mem (J.mul_mem_right _ hxJ) (hIJ (ideal.quotient.eq.1 hy)) } end /-- The quotient of a ring by an ideal is a field iff the ideal is maximal. -/ theorem maximal_ideal_iff_is_field_quotient (I : ideal α) : I.is_maximal ↔ is_field I.quotient := ⟨λ h, @field.to_is_field I.quotient (@ideal.quotient.field _ _ I h), λ h, maximal_of_is_field I h⟩ variable [comm_ring β] /-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero, lift it to the quotient by this ideal. -/ def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S →+* β := { to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h], map_one' := f.map_one, map_zero' := f.map_zero, map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add, map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul } @[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : lift S f H (mk S a) = f a := rfl @[simp] lemma lift_comp_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : (lift S f H).comp (mk S) = f := ring_hom.ext (λ _, rfl) lemma lift_surjective (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) (hf : function.surjective f) : function.surjective (lift S f H) := λ x, let ⟨y, hy⟩ := hf x in ⟨(quotient.mk S) y, by simpa⟩ end quotient section lattice variables {R : Type u} [comm_ring R] lemma mem_sup_left {S T : ideal R} : ∀ {x : R}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : ideal R} : ∀ {x : R}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Type*} {S : ι → ideal R} (i : ι) : ∀ {x : R}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : ∀ {x : R}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ι : Type*} {I : ι → ideal R} {x : R} : x ∈ infi I ↔ ∀ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (⊥ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice /-- All ideals in a field are trivial. -/ lemma eq_bot_or_top {K : Type u} [field K] (I : ideal K) : I = ⊥ ∨ I = ⊤ := begin rw or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using I.mul_mem_left r⁻¹ hr, end lemma eq_bot_of_prime {K : Type u} [field K] (I : ideal K) [h : I.is_prime] : I = ⊥ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal {K : Type u} [field K] : is_maximal (⊥ : ideal K) := ⟨λ h, absurd ((eq_top_iff_one (⊤ : ideal K)).mp rfl) (by rw ← h; simp), λ I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩ section pi variables (ι : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ι → α) := { carrier := { x | ∀ i, x i ∈ I }, zero_mem' := λ i, I.zero_mem, add_mem' := λ a b ha hb i, I.add_mem (ha i) (hb i), smul_mem' := λ a b hb i, I.mul_mem_left (a i) (hb i) } lemma mem_pi (x : ι → α) : x ∈ I.pi ι ↔ ∀ i, x i ∈ I := iff.rfl /-- `R^n/I^n` is a `R/I`-module. -/ instance module_pi : module (I.quotient) (I.pi ι).quotient := begin refine { smul := λ c m, quotient.lift_on₂' c m (λ r m, submodule.quotient.mk $ r • m) _, .. }, { intros c₁ m₁ c₂ m₂ hc hm, change c₁ - c₂ ∈ I at hc, change m₁ - m₂ ∈ (I.pi ι) at hm, apply ideal.quotient.eq.2, have : c₁ • (m₂ - m₁) ∈ I.pi ι, { rw ideal.mem_pi, intro i, simp only [smul_eq_mul, pi.smul_apply, pi.sub_apply], apply ideal.mul_mem_left, rw ←ideal.neg_mem_iff, simpa only [neg_sub] using hm i }, rw [←ideal.add_mem_iff_left (I.pi ι) this, sub_eq_add_neg, add_comm, ←add_assoc, ←smul_add, sub_add_cancel, ←sub_eq_add_neg, ←sub_smul, ideal.mem_pi], exact λ i, I.mul_mem_right _ hc }, all_goals { rintro ⟨a⟩ ⟨b⟩ ⟨c⟩ <|> rintro ⟨a⟩, simp only [(•), submodule.quotient.quot_mk_eq_mk, ideal.quotient.mk_eq_mk], change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, simp [mul_assoc, mul_add, add_mul] } end /-- `R^n/I^n` is isomorphic to `(R/I)^n` as an `R/I`-module. -/ noncomputable def pi_quot_equiv : (I.pi ι).quotient ≃ₗ[I.quotient] (ι → I.quotient) := { to_fun := λ x, quotient.lift_on' x (λ f i, ideal.quotient.mk I (f i)) $ λ a b hab, funext (λ i, ideal.quotient.eq.2 (hab i)), map_add' := by { rintros ⟨_⟩ ⟨_⟩, refl }, map_smul' := by { rintros ⟨_⟩ ⟨_⟩, refl }, inv_fun := λ x, ideal.quotient.mk (I.pi ι) $ λ i, quotient.out' (x i), left_inv := begin rintro ⟨x⟩, exact ideal.quotient.eq.2 (λ i, ideal.quotient.eq.1 (quotient.out_eq' _)) end, right_inv := begin intro x, ext i, obtain ⟨r, hr⟩ := @quot.exists_rep _ _ (x i), simp_rw ←hr, convert quotient.out_eq' _ end } /-- If `f : R^n → R^m` is an `R`-linear map and `I ⊆ R` is an ideal, then the image of `I^n` is contained in `I^m`. -/ lemma map_pi {ι} [fintype ι] {ι' : Type w} (x : ι → α) (hi : ∀ i, x i ∈ I) (f : (ι → α) →ₗ[α] (ι' → α)) (i : ι') : f x i ∈ I := begin rw pi_eq_sum_univ x, simp only [finset.sum_apply, smul_eq_mul, linear_map.map_sum, pi.smul_apply, linear_map.map_smul], exact I.sum_mem (λ j hj, I.mul_mem_right _ (hi j)) end end pi end ideal namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : ¬ is_field R := λ ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : ¬ is_field R) : ∃ x ≠ (0 : R), ¬ is_unit x := begin have : ¬ _ := λ h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊢ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : ¬ is_field R ↔ ∃ I : ideal R, ⊥ < I ∧ I < ⊤ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := submodule.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (I.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : ¬ is_field R ↔ ∃ p : ideal R, p ≠ ⊥ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, λ ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ /-- When a ring is not a field, the maximal ideals are nontrivial. -/ lemma ne_bot_of_is_maximal_of_not_is_field [nontrivial R] {M : ideal R} (max : M.is_maximal) (not_field : ¬ is_field R) : M ≠ ⊥ := begin rintros h, rw h at max, cases max with h1 h2, obtain ⟨I, hIbot, hItop⟩ := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.mp not_field, exact ne_of_lt hItop (h2 I hIbot), end end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : ¬ is_field R) : ⊥ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, finish, intro mle, apply @irrefl _ (<) _ (⊤ : ideal R), have : M = ⊥ := eq_bot_iff.mpr mle, rw this at *, rwa hm.2 I Ibot at Itop, end end ideal /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [comm_monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [comm_ring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_ring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end /-- A commutative ring is local if it has a unique maximal ideal. Note that `local_ring` is a predicate. -/ class local_ring (α : Type u) [comm_ring α] extends nontrivial α : Prop := (is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a))) namespace local_ring variables [comm_ring α] [local_ring α] lemma is_unit_or_is_unit_one_sub_self (a : α) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) : x + y ∈ nonunits α := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : α) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : α) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : α) * z) hu.symm, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (α) /-- The ideal of elements that are not units. -/ def maximal_ideal : ideal α := { carrier := nonunits α, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance maximal_ideal.is_maximal : (maximal_ideal α).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.mul_mem_left ↑u⁻¹ H } end lemma maximal_ideal_unique : ∃! I : ideal α, I.is_maximal := ⟨maximal_ideal α, maximal_ideal.is_maximal α, λ I hI, hI.eq_of_le (maximal_ideal.is_maximal α).1 $ λ x hx, hI.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {α} lemma eq_maximal_ideal {I : ideal α} (hI : I.is_maximal) : I = maximal_ideal α := unique_of_exists_unique (maximal_ideal_unique α) hI $ maximal_ideal.is_maximal α lemma le_maximal_ideal {J : ideal α} (hJ : J ≠ ⊤) : J ≤ maximal_ideal α := begin rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩, rwa ←eq_maximal_ideal hM1 end @[simp] lemma mem_maximal_ideal (x) : x ∈ maximal_ideal α ↔ x ∈ nonunits α := iff.rfl end local_ring lemma local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α := { exists_pair_ne := ⟨0, 1, hnze⟩, is_local := λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ _ hx H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end } lemma local_of_unique_max_ideal [comm_ring α] (h : ∃! I : ideal α, I.is_maximal) : local_ring α := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H lemma local_of_unique_nonzero_prime (R : Type u) [comm_ring R] (h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R := local_of_unique_max_ideal begin rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩, refine ⟨P, ⟨hPnot_top, _⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩, { refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _), exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm }, { rintro rfl, exact hPnot_top (hM.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) }, end lemma local_of_surjective {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] [nontrivial B] (f : A →+* B) (hf : function.surjective f) : local_ring B := { is_local := begin intros b, obtain ⟨a, rfl⟩ := hf b, apply (local_ring.is_unit_or_is_unit_one_sub_self a).imp f.is_unit_map _, rw [← f.map_one, ← f.map_sub], apply f.is_unit_map, end, .. ‹nontrivial B› } /-- A local ring homomorphism is a homomorphism between local rings such that the image of the maximal ideal of the source is contained within the maximal ideal of the target. -/ class is_local_ring_hom [semiring α] [semiring β] (f : α →+* β) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) instance is_local_ring_hom_id (A : Type*) [semiring A] : is_local_ring_hom (ring_hom.id A) := { map_nonunit := λ a, id } @[simp] lemma is_unit_map_iff {A B : Type*} [semiring A] [semiring B] (f : A →+* B) [is_local_ring_hom f] (a) : is_unit (f a) ↔ is_unit a := ⟨is_local_ring_hom.map_nonunit a, f.is_unit_map⟩ instance is_local_ring_hom_comp {A B C : Type*} [semiring A] [semiring B] [semiring C] (g : B →+* C) (f : A →+* B) [is_local_ring_hom g] [is_local_ring_hom f] : is_local_ring_hom (g.comp f) := { map_nonunit := λ a, is_local_ring_hom.map_nonunit a ∘ is_local_ring_hom.map_nonunit (f a) } @[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h theorem of_irreducible_map [semiring α] [semiring β] (f : α →+* β) [h : is_local_ring_hom f] {x : α} (hfx : irreducible (f x)) : irreducible x := ⟨λ h, hfx.1 $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in or.imp (H p) (H q) $ hfx.2 _ _ $ f.map_mul p q ▸ congr_arg f hx⟩ section open local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variables (f : α →+* β) [is_local_ring_hom f] lemma map_nonunit (a) (h : a ∈ maximal_ideal α) : f a ∈ maximal_ideal β := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variable (α) /-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/ def residue_field := (maximal_ideal α).quotient noncomputable instance residue_field.field : field (residue_field α) := ideal.quotient.field (maximal_ideal α) noncomputable instance : inhabited (residue_field α) := ⟨37⟩ /-- The quotient map from a local ring to its residue field. -/ def residue : α →+* (residue_field α) := ideal.quotient.mk _ namespace residue_field variables {α β} /-- The map on residue fields induced by a local homomorphism between local rings -/ noncomputable def map (f : α →+* β) [is_local_ring_hom f] : residue_field α →+* residue_field β := ideal.quotient.lift (maximal_ideal α) ((ideal.quotient.mk _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field end local_ring namespace field variables [field α] @[priority 100] -- see Note [lower instance priority] instance : local_ring α := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit_of_mul_eq_one a a⁻¹ $ div_self h } end field
9382f0393dd14ef02b7886fbf9e530cde5d4e0de
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/miu_language/decision_suf.lean
ce9f364ae1a2ebac705253c2617711e13cf0a326
[ "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,382
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 .decision_nec import tactic.linarith /-! # Decision procedure - sufficient condition and decidability We give a sufficient condition for a string to be derivable in the MIU language. Together with the necessary condition, we use this to prove that `derivable` is an instance of `decicdable_pred`. Let `count I st` and `count U st` denote the number of `I`s (respectively `U`s) in `st : miustr`. We'll show that `st` is derivable if it has the form `M::x` where `x` is a string of `I`s and `U`s for which `count I x` is congruent to 1 or 2 modulo 3. To prove this, it suffices to show `derivable M::y` where `y` is any `miustr` consisting only of `I`s such that the number of `I`s in `y` is `a+3b`, where `a = count I x` and `b = count U x`. This suffices because Rule 3 permits us to change any string of three consecutive `I`s into a `U`. As `count I y = (count I x) + 3*(count U x) ≡ (count I x) [MOD 3]`, it suffices to show `derivable M::z` where `z` is an `miustr` of `I`s such that `count I z` is congruent to 1 or 2 modulo 3. Let `z` be such an `miustr` and let `c` denote `count I z`, so `c ≡ 1 or 2 [MOD 3]`. To derive such an `miustr`, it suffices to derive an `miustr` `M::w`, where again w is an `miustr` of only `I`s with the additional conditions that `count I w` is a power of 2, that `count I w ≥ c` and that `count I w ≡ c [MOD 3]`. To see that this suffices, note that we can remove triples of `I`s from the end of `M::w`, creating `U`s as we go along. Once the number of `I`s equals `m`, we remove `U`s two at a time until we have no `U`s. The only issue is that we may begin the removal process with an odd number of `U`s. Writing `d = count I w`, we see that this happens if and only if `(d-c)/3` is odd. In this case, we must apply Rule 1 to `z`, prior to removing triples of `I`s. We thereby introduce an additional `U` and ensure that the final number of `U`s will be even. ## Tags miu, decision procedure, decidability, decidable_pred, decidable -/ namespace miu open miu_atom list nat /-- We start by showing that an `miustr` `M::w` can be derived, where `w` consists only of `I`s and where `count I w` is a power of 2. -/ private lemma der_cons_repeat (n : ℕ) : derivable (M::(repeat I (2^n))) := begin induction n with k hk, { constructor, }, -- base case { rw [succ_eq_add_one, pow_add, pow_one 2, mul_two,repeat_add], -- inductive step exact derivable.r2 hk, }, end /-! ## Converting `I`s to `U`s For any given natural number `c ≡ 1 or 2 [MOD 3]`, we need to show that can derive an `miustr` `M::w` where `w` consists only of `I`s, where `d = count I w` is a power of 2, where `d ≥ c` and where `d ≡ c [MOD 3]`. Given the above lemmas, the desired result reduces to an arithmetic result, given in the file `arithmetic.lean`. We'll use this result to show we can derive an `miustr` of the form `M::z` where `z` is an string consisting only of `I`s such that `count I z ≡ 1 or 2 [MOD 3]`. As an intermediate step, we show that derive `z` from `zt`, where `t` is aN `miustr` consisting of an even number of `U`s and `z` is any `miustr`. -/ /-- Any number of successive occurrences of `"UU"` can be removed from the end of a `derivable` `miustr` to produce another `derivable` `miustr`. -/ lemma der_of_der_append_repeat_U_even {z : miustr} {m : ℕ} (h : derivable (z ++ repeat U (m*2))) : derivable z := begin induction m with k hk, { revert h, simp only [list.repeat, zero_mul, append_nil, imp_self], }, { apply hk, simp only [succ_mul, repeat_add] at h, change repeat U 2 with [U,U] at h, rw ←(append_nil (z ++ repeat U (k*2) )), apply derivable.r4, simp only [append_nil, append_assoc,h], }, end /-! In fine-tuning my application of `simp`, I issued the following commend to determine which lemmas `simp` uses. `set_option trace.simplify.rewrite true` -/ /-- We may replace several consecutive occurrences of `"III"` with the same number of `"U"`s. In application of the following lemma, `xs` will either be `[]` or `[U]`. -/ lemma der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append (c k : ℕ) (hc : c % 3 = 1 ∨ c % 3 = 2) (xs : miustr) (hder : derivable (M ::(repeat I (c+3*k)) ++ xs)) : derivable (M::(repeat I c ++ repeat U k) ++ xs) := begin revert xs, induction k with a ha, { simp only [list.repeat, mul_zero, add_zero, append_nil, forall_true_iff, imp_self],}, { intro xs, specialize ha (U::xs), intro h₂, simp only [succ_eq_add_one, repeat_add], -- We massage the goal rw [←append_assoc, ←cons_append], -- into a form amenable change repeat U 1 with [U], -- to the application of rw [append_assoc, singleton_append], -- ha. apply ha, apply derivable.r3, change [I,I,I] with repeat I 3, simp only [cons_append, ←repeat_add], convert h₂, }, end /-! ### Arithmetic We collect purely arithmetic lemmas: `add_mod2` is used to ensure we have an even number of `U`s while `le_pow2_and_pow2_eq_mod3` treats the congruence condition modulo 3. -/ section arithmetic /-- For every `a`, the number `a + a % 2` is even. -/ lemma add_mod2 (a : ℕ) : ∃ t, a + a % 2 = t*2 := begin simp only [mul_comm _ 2], -- write `t*2` as `2*t` apply dvd_of_mod_eq_zero, -- it suffices to prove `(a + a % 2) % 2 = 0` rw [add_mod, mod_mod, ←two_mul, mul_mod_right], end private lemma le_pow2_and_pow2_eq_mod3' (c : ℕ) (x : ℕ) (h : c = 1 ∨ c = 2) : ∃ m : ℕ, c + 3*x ≤ 2^m ∧ 2^m % 3 = c % 3 := begin induction x with k hk, { use (c+1), cases h with hc hc; { rw hc, norm_num }, }, { rcases hk with ⟨g, hkg, hgmod⟩, by_cases hp : (c + 3*(k+1) ≤ 2 ^g), { use g, exact ⟨hp,hgmod⟩ }, use (g+2), { split, { rw [mul_succ, ←add_assoc, pow_add], change 2^2 with (1+3), rw [mul_add (2^g) 1 3, mul_one], linarith [hkg, one_le_two_pow g], }, { rw [pow_add,←mul_one c], exact modeq.modeq_mul hgmod rfl, }, }, }, end /-- If `a` is 1 or 2 modulo 3, then exists `k` a power of 2 for which `a ≤ k` and `a ≡ k [MOD 3]`. -/ lemma le_pow2_and_pow2_eq_mod3 (a : ℕ) (h : a % 3 = 1 ∨ a % 3 = 2) : ∃ m : ℕ, a ≤ 2^m ∧ 2^m % 3 = a % 3:= begin cases le_pow2_and_pow2_eq_mod3' (a%3) (a/3) h with m hm, use m, split, { convert hm.1, exact (mod_add_div a 3).symm, }, { rw [hm.2, mod_mod _ 3], }, end end arithmetic lemma repeat_pow_minus_append {m : ℕ} : M :: repeat I (2^m - 1) ++ [I] = M::(repeat I (2^m)) := begin change [I] with repeat I 1, rw [cons_append, ←repeat_add, nat.sub_add_cancel (one_le_pow' m 1)], end /-- `der_repeat_I_of_mod3` states that `M::y` is `derivable` if `y` is any `miustr` consisiting just of `I`s, where `count I y` is 1 or 2 modulo 3. -/ lemma der_repeat_I_of_mod3 (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2): derivable (M::(repeat I c)) := begin -- From `der_cons_repeat`, we can derive the `miustr` `M::w` described in the introduction. cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w` have hw₂ : derivable (M::(repeat I (2^m)) ++ repeat U ((2^m -c)/3 % 2)), { cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one, { simp only [der_cons_repeat m, append_nil,list.repeat, h_zero], }, -- `(2^m - c)/3 ≡ 0 [MOD 2]` { rw [h_one, ←repeat_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]` apply derivable.r1, rw repeat_pow_minus_append, exact (der_cons_repeat m), }, }, have hw₃ : derivable (M::(repeat I c) ++ repeat U ((2^m-c)/3) ++ repeat U ((2^m-c)/3 % 2)), { apply der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append c ((2^m-c)/3) h, convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m` rw nat.mul_div_cancel', { exact add_sub_of_le hm.1, }, { exact (modeq.modeq_iff_dvd' hm.1).mp hm.2.symm, }, }, rw [append_assoc, ←repeat_add _ _] at hw₃, cases add_mod2 ((2^m-c)/3) with t ht, rw ht at hw₃, exact der_of_der_append_repeat_U_even hw₃, end example (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2): derivable (M::(repeat I c)) := begin -- From `der_cons_repeat`, we can derive the `miustr` `M::w` described in the introduction. cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w` have hw₂ : derivable (M::(repeat I (2^m)) ++ repeat U ((2^m -c)/3 % 2)), { cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one, { simp only [der_cons_repeat m, append_nil, list.repeat,h_zero], }, -- `(2^m - c)/3 ≡ 0 [MOD 2]` { rw [h_one, ←repeat_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]` apply derivable.r1, rw repeat_pow_minus_append, exact (der_cons_repeat m), }, }, have hw₃ : derivable (M::(repeat I c) ++ repeat U ((2^m-c)/3) ++ repeat U ((2^m-c)/3 % 2)), { apply der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append c ((2^m-c)/3) h, convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m` rw nat.mul_div_cancel', { exact add_sub_of_le hm.1, }, { exact (modeq.modeq_iff_dvd' hm.1).mp hm.2.symm, }, }, rw [append_assoc, ←repeat_add _ _] at hw₃, cases add_mod2 ((2^m-c)/3) with t ht, rw ht at hw₃, exact der_of_der_append_repeat_U_even hw₃, end /-! ### `decstr` is a sufficient condition The remainder of this file sets up the proof that `dectstr en` is sufficent to ensure `derivable en`. Decidability of `derivable en` is an easy consequence. The proof proceeds by induction on the `count U` of `en`. We tackle first the base case of the induction. This requires auxiliary results giving conditions under which `count I ys = length ys`. -/ /-- If an `miustr` has a zero `count U` and contains no `M`, then its `count I` is its length. -/ lemma count_I_eq_length_of_count_U_zero_and_neg_mem {ys : miustr} (hu : count U ys = 0) (hm : M ∉ ys) : count I ys = length ys := begin induction ys with x xs hxs, { refl, }, { cases x, { exfalso, exact hm (mem_cons_self M xs), }, -- case `x = M` gives a contradiction. { rw [count_cons, if_pos (rfl), length, succ_eq_add_one, succ_inj'], -- case `x = I` apply hxs, { simpa only [count], }, { simp only [mem_cons_iff,false_or] at hm, exact hm, }, }, { exfalso, simp only [count, countp_cons_of_pos] at hu, -- case `x = U` gives a contradiction. exact succ_ne_zero _ hu, }, }, end /-- `base_case_suf` is the base case of the sufficiency result. -/ lemma base_case_suf (en : miustr) (h : decstr en) (hu : count U en = 0) : derivable en := begin rcases h with ⟨⟨mhead, nmtail⟩, hi ⟩, have : en ≠ nil, { intro k, simp only [k, count, countp, if_false, zero_mod, zero_ne_one, false_or] at hi, contradiction, }, rcases (exists_cons_of_ne_nil this) with ⟨y,ys,rfl⟩, rw head at mhead, rw mhead at *, suffices : ∃ c, repeat I c = ys ∧ (c % 3 = 1 ∨ c % 3 = 2), { rcases this with ⟨c, hysr, hc⟩, rw ←hysr, exact der_repeat_I_of_mod3 c hc, }, { simp only [count] at *, use (count I ys), refine and.intro _ hi, apply repeat_count_eq_of_count_eq_length, exact count_I_eq_length_of_count_U_zero_and_neg_mem hu nmtail, }, end /-! Before continuing to the proof of the induction step, we need other auxiliary results that relate to `count U`. -/ lemma mem_of_count_U_eq_succ {xs : miustr} {k : ℕ} (h : count U xs = succ k) : U ∈ xs := begin induction xs with z zs hzs, { exfalso, rw count at h, contradiction, }, { simp only [mem_cons_iff], cases z, repeat -- cases `z = M` and `z=I` { right, apply hzs, simp only [count, countp, if_false] at h, rw ←h, refl, }, { left, refl, }, }, -- case `z = U` end lemma eq_append_cons_U_of_count_U_pos {k : ℕ} {zs : miustr} (h : count U zs = succ k) : ∃ (as bs : miustr), (zs = as ++ U :: bs) := mem_split (mem_of_count_U_eq_succ h) /-- `ind_hyp_suf` is the inductive step of the sufficiency result. -/ lemma ind_hyp_suf (k : ℕ) (ys : miustr) (hu : count U ys = succ k) (hdec : decstr ys) : ∃ (as bs : miustr), (ys = M::as ++ U:: bs) ∧ (count U (M::as ++ [I,I,I] ++ bs) = k) ∧ decstr (M::as ++ [I,I,I] ++ bs) := begin rcases hdec with ⟨⟨mhead,nmtail⟩, hic⟩, have : ys ≠ nil, { intro k, simp only [k ,count, countp, zero_mod, false_or, zero_ne_one] at hic, contradiction, }, rcases (exists_cons_of_ne_nil this) with ⟨z,zs,rfl⟩, rw head at mhead, rw mhead at *, simp only [count, countp, cons_append, if_false, countp_append] at *, rcases (eq_append_cons_U_of_count_U_pos hu) with ⟨as,bs,hab⟩, rw hab at *, simp only [countp, cons_append, if_pos, if_false, countp_append] at *, use [as,bs], apply and.intro rfl (and.intro (succ.inj hu) _), split, { apply and.intro rfl, simp only [tail, mem_append, mem_cons_iff, false_or, not_mem_nil, or_false] at *, exact nmtail, }, { simp only [count, countp, cons_append, if_false, countp_append, if_pos], rw [add_right_comm, add_mod_right], exact hic, }, end /-- `der_of_decstr` states that `derivable en` follows from `decstr en`. -/ theorem der_of_decstr {en : miustr} (h : decstr en) : derivable en := begin /- The next three lines have the effect of introducing `count U en` as a variable that can be used for induction -/ have hu : ∃ n, count U en = n := exists_eq', cases hu with n hu, revert en, /- Crucially, we need the induction hypothesis to quantify over `en` -/ induction n with k hk, { exact base_case_suf, }, { intros ys hdec hus, rcases ind_hyp_suf k ys hus hdec with ⟨as, bs, hyab, habuc, hdecab⟩, have h₂ : derivable (M::as ++ [I,I,I] ++ bs) := hk hdecab habuc, rw hyab, exact derivable.r3 h₂, }, end /-! ### Decidability of `derivable` -/ /-- Finally, we have the main result, namely that `derivable` is a decidable predicate. -/ instance : decidable_pred derivable := λ en, decidable_of_iff _ ⟨der_of_decstr, decstr_of_der⟩ /-! By decidability, we can automatically determine whether any given `miustr` is `derivable`. -/ example : ¬(derivable "MU") := dec_trivial example : derivable "MUIUIUIIIIIUUUIUII" := dec_trivial end miu
2044edc7772638ed81095f0c1815c164e908a959
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/set/pairwise/lattice.lean
1b27355c2f03793b96f4269259ab695fa083fc56
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
4,467
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.set.lattice import data.set.pairwise.basic /-! # Relations holding pairwise > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove many facts about `pairwise` and the set lattice. -/ open set function variables {α β γ ι ι' : Type*} {r p q : α → α → Prop} section pairwise variables {f g : ι → α} {s t u : set α} {a b : α} namespace set lemma pairwise_Union {f : ι → set α} (h : directed (⊆) f) : (⋃ n, f n).pairwise r ↔ ∀ n, (f n).pairwise r := begin split, { assume H n, exact pairwise.mono (subset_Union _ _) H }, { assume H i hi j hj hij, rcases mem_Union.1 hi with ⟨m, hm⟩, rcases mem_Union.1 hj with ⟨n, hn⟩, rcases h m n with ⟨p, mp, np⟩, exact H p (mp hm) (np hn) hij } end lemma pairwise_sUnion {r : α → α → Prop} {s : set (set α)} (h : directed_on (⊆) s) : (⋃₀ s).pairwise r ↔ (∀ a ∈ s, set.pairwise a r) := by { rw [sUnion_eq_Union, pairwise_Union (h.directed_coe), set_coe.forall], refl } end set end pairwise namespace set section partial_order_bot variables [partial_order α] [order_bot α] {s t : set ι} {f g : ι → α} lemma pairwise_disjoint_Union {g : ι' → set ι} (h : directed (⊆) g) : (⋃ n, g n).pairwise_disjoint f ↔ ∀ ⦃n⦄, (g n).pairwise_disjoint f := pairwise_Union h lemma pairwise_disjoint_sUnion {s : set (set ι)} (h : directed_on (⊆) s) : (⋃₀ s).pairwise_disjoint f ↔ ∀ ⦃a⦄, a ∈ s → set.pairwise_disjoint a f := pairwise_sUnion h end partial_order_bot section complete_lattice variables [complete_lattice α] /-- Bind operation for `set.pairwise_disjoint`. If you want to only consider finsets of indices, you can use `set.pairwise_disjoint.bUnion_finset`. -/ lemma pairwise_disjoint.bUnion {s : set ι'} {g : ι' → set ι} {f : ι → α} (hs : s.pairwise_disjoint (λ i' : ι', ⨆ i ∈ g i', f i)) (hg : ∀ i ∈ s, (g i).pairwise_disjoint f) : (⋃ i ∈ s, g i).pairwise_disjoint f := begin rintro a ha b hb hab, simp_rw set.mem_Union at ha hb, obtain ⟨c, hc, ha⟩ := ha, obtain ⟨d, hd, hb⟩ := hb, obtain hcd | hcd := eq_or_ne (g c) (g d), { exact hg d hd (hcd.subst ha) hb hab }, { exact (hs hc hd $ ne_of_apply_ne _ hcd).mono (le_supr₂ a ha) (le_supr₂ b hb) } end end complete_lattice lemma bUnion_diff_bUnion_eq {s t : set ι} {f : ι → set α} (h : (s ∪ t).pairwise_disjoint f) : (⋃ i ∈ s, f i) \ (⋃ i ∈ t, f i) = (⋃ i ∈ s \ t, f i) := begin refine (bUnion_diff_bUnion_subset f s t).antisymm (Union₂_subset $ λ i hi a ha, (mem_diff _).2 ⟨mem_bUnion hi.1 ha, _⟩), rw mem_Union₂, rintro ⟨j, hj, haj⟩, exact (h (or.inl hi.1) (or.inr hj) (ne_of_mem_of_not_mem hj hi.2).symm).le_bot ⟨ha, haj⟩, end /-- Equivalence between a disjoint bounded union and a dependent sum. -/ noncomputable def bUnion_eq_sigma_of_disjoint {s : set ι} {f : ι → set α} (h : s.pairwise_disjoint f) : (⋃ i ∈ s, f i) ≃ (Σ i : s, f i) := (equiv.set_congr (bUnion_eq_Union _ _)).trans $ Union_eq_sigma_of_disjoint $ λ ⟨i, hi⟩ ⟨j, hj⟩ ne, h hi hj $ λ eq, ne $ subtype.eq eq end set section variables {f : ι → set α} {s t : set ι} lemma set.pairwise_disjoint.subset_of_bUnion_subset_bUnion (h₀ : (s ∪ t).pairwise_disjoint f) (h₁ : ∀ i ∈ s, (f i).nonempty) (h : (⋃ i ∈ s, f i) ⊆ ⋃ i ∈ t, f i) : s ⊆ t := begin rintro i hi, obtain ⟨a, hai⟩ := h₁ i hi, obtain ⟨j, hj, haj⟩ := mem_Union₂.1 (h $ mem_Union₂_of_mem hi hai), rwa h₀.eq (subset_union_left _ _ hi) (subset_union_right _ _ hj) (not_disjoint_iff.2 ⟨a, hai, haj⟩), end lemma pairwise.subset_of_bUnion_subset_bUnion (h₀ : pairwise (disjoint on f)) (h₁ : ∀ i ∈ s, (f i).nonempty) (h : (⋃ i ∈ s, f i) ⊆ ⋃ i ∈ t, f i) : s ⊆ t := set.pairwise_disjoint.subset_of_bUnion_subset_bUnion (h₀.set_pairwise _) h₁ h lemma pairwise.bUnion_injective (h₀ : pairwise (disjoint on f)) (h₁ : ∀ i, (f i).nonempty) : injective (λ s : set ι, ⋃ i ∈ s, f i) := λ s t h, (h₀.subset_of_bUnion_subset_bUnion (λ _ _, h₁ _) $ h.subset).antisymm $ h₀.subset_of_bUnion_subset_bUnion (λ _ _, h₁ _) $ h.superset end
d43c78d631a94beb2b898a81b5daca77e7fe669b
5a6ff5f8d173cbfe51967eb4c96837e3a791fe3d
/mm0-lean/x86/mmc.lean
6c4a1263b3350faaeab726edffc6ce20203ae261
[ "CC0-1.0" ]
permissive
digama0/mm0
491ac09146708aa1bb775007bf3dbe339ffc0096
98496badaf6464e56ed7b4204e7d54b85667cb01
refs/heads/master
1,692,321,030,902
1,686,254,458,000
1,686,254,458,000
172,456,790
273
38
CC0-1.0
1,689,939,563,000
1,551,080,059,000
Rust
UTF-8
Lean
false
false
21,149
lean
import algebra.group_power data.list.alist namespace alist def map {α} {β γ : α → Type*} (f : ∀ a, β a → γ a) (l : alist β) : alist γ := ⟨l.entries.map (λ a, ⟨a.1, f a.1 a.2⟩), show (list.map _ _).nodup, by rw list.map_map; exact l.2⟩ end alist noncomputable theory local attribute [instance] classical.prop_decidable namespace mmc inductive wsize | S8 | S16 | S32 | S64 | Sinf def wsize.nat_ok : wsize → nat → Prop | wsize.S8 n := n < 2^8 | wsize.S16 n := n < 2^16 | wsize.S32 n := n < 2^32 | wsize.S64 n := n < 2^64 | wsize.Sinf n := true def wsize.int_ok : wsize → int → Prop | wsize.S8 n := -2^7 ≤ n ∧ n < 2^7 | wsize.S16 n := -2^15 ≤ n ∧ n < 2^16 | wsize.S32 n := -2^31 ≤ n ∧ n < 2^32 | wsize.S64 n := -2^64 ≤ n ∧ n < 2^64 | wsize.Sinf n := true inductive unop | neg | not | bnot (sz : wsize) inductive binop | and | or | band | bor | lt | le | eq def user_type : Type := sorry def func : Type := sorry def pure_proof : Type := sorry def var : Type := nat def tvar : Type := nat inductive label : Type | self : label | reg : nat → label mutual inductive arg, ty, prop, pexp with arg : Type | mk : var → bool → ty → arg with ty : Type | var : tvar → ty -- a type variable α | core_var : tvar → ty -- the core of a variable, |α| | void | unit | bool -- basic types | nat (_:wsize) | int (_:wsize) -- integral types | inter : ty → ty → ty -- intersection type | union : ty → ty → ty -- union type | pair : ty → ty → ty -- tuple type | sigma : arg → ty → ty -- dependent tuple type | prop : prop → ty -- propositions as types | user : user_type → ty → pexp → ty -- a user-defined type with prop : Type -- basic FOL operations | true | false | all : var → ty → prop → prop | ex : var → ty → prop → prop | imp : prop → prop → prop | not : prop → prop | and : prop → prop → prop | or : prop → prop → prop | emp : prop -- the empty heap | sep : prop → prop → prop -- separating conjunction | wand : prop → prop → prop -- separating implication | pexp : pexp → prop -- a boolean proposition as a predicate | eq : pexp → pexp → prop -- equality of general types | heap : pexp → pexp → prop -- the points-to assertion x |-> v | has_ty : pexp → ty → prop -- the [x : ty] typing assertion with pexp : Type | var : var → pexp -- a variable reference | star | tt | ff -- unit and bool constants | const : ℤ → pexp -- integer constants | unop : unop → pexp → pexp -- unary operations | binop : binop → pexp → pexp → pexp -- binary operations | if_ : option var → pexp → pexp → pexp → pexp -- a conditional expression (possibly dependent) | pair : pexp → pexp → pexp -- a pair (or dependent pair) ⟨x, y⟩ | call : func → pexp → pexp -- a function call f(x) def arg.ty : arg → ty | (arg.mk _ _ τ) := τ def arg.var : arg → var | (arg.mk x _ _) := x inductive place | var : var → place inductive tuple_pat | blank : tuple_pat | var : var → bool → tuple_pat | typed : tuple_pat → ty → tuple_pat | pair : tuple_pat → tuple_pat → tuple_pat inductive exp | var : var → exp -- a variable reference | star | tt | ff -- unit and bool constants | const : ℤ → exp -- integer constants | unop : unop → exp → exp -- unary operations | binop : binop → exp → exp → exp -- binary operations | if_ : option var → exp → exp → exp → exp -- a conditional expression (possibly dependent) | pair : exp → exp → exp -- a pair (or dependent pair) ⟨x, y⟩ | call : func → exp → exp -- a function or procedure call -- a variable declaration let h := t := e in e' | let_ : option var → tuple_pat → exp → exp → exp -- a mutation let h := η ← e in e' | mut : option var → place → exp → exp → exp -- an unreachable statement | unreachable : exp → exp -- declaring jump labels | label : list (label × arg × exp) → exp → exp -- jump to a label or return | goto : label → exp → exp -- proof of an entailment: proves Q from P where P -* Q is pure | entail : exp → pure_proof → exp -- Evaluate a boolean to produce a proof | assert : exp → exp -- Extract the type of a variable | typeof : exp → exp def user_core : user_type → ty → pexp → ty := sorry def pure_proof.ok : pure_proof → prop → prop → Prop := sorry def pexp.to_exp : pexp → exp | (pexp.var i) := exp.var i | pexp.star := exp.star | pexp.tt := exp.tt | pexp.ff := exp.ff | (pexp.const n) := exp.const n | (pexp.unop o e) := exp.unop o e.to_exp | (pexp.binop o e₁ e₂) := exp.binop o e₁.to_exp e₂.to_exp | (pexp.if_ b c e₁ e₂) := exp.if_ b c.to_exp e₁.to_exp e₂.to_exp | (pexp.pair e₁ e₂) := exp.pair e₁.to_exp e₂.to_exp | (pexp.call f e) := exp.call f e.to_exp def exp.pure (e : exp) : Prop := ∃ pe, pexp.to_exp pe = e noncomputable mutual def arg.core, ty.core, prop.core with arg.core : arg → arg | (arg.mk x ghost t) := arg.mk x ghost t.core with ty.core : ty → ty | (ty.var α) := ty.core_var α | (ty.core_var α) := ty.core_var α | ty.void := ty.void | ty.unit := ty.unit | ty.bool := ty.bool | (ty.nat s) := ty.nat s | (ty.int s) := ty.int s | (ty.inter a b) := ty.inter a.core b.core | (ty.union a b) := ty.union a.core b.core | (ty.pair a b) := ty.pair a.core b.core | (ty.sigma a b) := ty.sigma a.core b.core | (ty.user T t e) := ty.user T t.core e | (ty.prop A) := ty.prop A.core with prop.core : prop → prop | prop.true := prop.true | prop.false := prop.false | (prop.all x t A) := if t = t.core then prop.all x t A.core else prop.emp | (prop.ex x t A) := if t = t.core then prop.ex x t A.core else prop.emp | (prop.imp A B) := if A = A.core then prop.imp A B.core else prop.emp | (prop.not A) := if A = A.core then prop.not A.core else prop.emp | (prop.and A B) := prop.and A.core B.core | (prop.or A B) := prop.or A.core B.core | prop.emp := prop.emp | (prop.sep A B) := prop.sep A.core B.core | (prop.wand A B) := if A = A.core then prop.wand A B.core else prop.emp | (prop.pexp e) := prop.pexp e | (prop.eq e₁ e₂) := prop.eq e₁ e₂ | (prop.heap _ _) := prop.emp | (prop.has_ty e t) := prop.has_ty e t.core def tuple_pat.size : tuple_pat → ℕ | (tuple_pat.blank) := 0 | (tuple_pat.var x γ) := 1 | (tuple_pat.typed t _) := t.size | (tuple_pat.pair t t') := t.size + t'.size -- substitute e for x def ty.subst (x : var) (e : pexp) : ty → ty := sorry def prop.subst (x : var) (e : pexp) : prop → prop := sorry inductive tuple_pat.to_pexp : tuple_pat → pexp → Prop | var {x γ} : tuple_pat.to_pexp (tuple_pat.var x γ) (pexp.var x) | typed {t τ e} : tuple_pat.to_pexp t e → tuple_pat.to_pexp (tuple_pat.typed t τ) e | pair {t t' e e'} : tuple_pat.to_pexp t e → tuple_pat.to_pexp t' e' → tuple_pat.to_pexp (tuple_pat.pair t t') (pexp.pair e e') structure ctx := (args : list arg) def ctx.app : ctx → list arg → ctx | ⟨R⟩ S := ⟨S.reverse ++ R⟩ def ctx.get : ctx → var → bool → ty → Prop | ⟨R⟩ x γ τ := arg.mk x γ τ ∈ R def ctx.modify (f : arg → arg) (idx : ℕ) : ctx → ctx | ⟨R⟩ := ⟨list.modify_nth f idx R⟩ inductive tuple_pat.ok : ctx → tuple_pat → ty → list arg → Prop | blank {Γ τ} : tuple_pat.ok Γ tuple_pat.blank τ [] | var {Γ x γ τ} : tuple_pat.ok Γ (tuple_pat.var x γ) τ [arg.mk x γ τ] | typed {Γ t τ R} : tuple_pat.ok Γ t τ R → tuple_pat.ok Γ (tuple_pat.typed t τ) τ R | sum {Γ x t τ S te t' τ' S' γ} : tuple_pat.ok Γ t τ S → tuple_pat.to_pexp t te → tuple_pat.ok (Γ.app S) t' (ty.subst x te τ') S' → tuple_pat.ok Γ (tuple_pat.pair t t') (ty.sigma (arg.mk x γ τ) τ') (S ++ S') | ex {Γ x t τ S te t' A S'} : tuple_pat.ok Γ t τ S → tuple_pat.to_pexp t te → tuple_pat.ok (Γ.app S) t' (ty.prop (prop.subst x te A)) S' → tuple_pat.ok Γ (tuple_pat.pair t t') (ty.prop (prop.ex x τ A)) (S ++ S') | list {Γ t τ S t' τ' S'} : tuple_pat.ok Γ t τ S → tuple_pat.ok Γ t' τ' S' → tuple_pat.ok Γ (tuple_pat.pair t t') (ty.pair τ τ') (S ++ S') | sep {Γ t A S t' B S'} : tuple_pat.ok Γ t (ty.prop A) S → tuple_pat.ok Γ t' (ty.prop B) S' → tuple_pat.ok Γ (tuple_pat.pair t t') (ty.prop (prop.sep A B)) (S ++ S') | and {Γ t A S t' B S'} : tuple_pat.ok Γ t (ty.prop A) S → tuple_pat.ok Γ t' (ty.prop $ prop.core B) S' → tuple_pat.ok Γ (tuple_pat.pair t t') (ty.prop (prop.and A B)) (S ++ S') -- substitute for the type variables in an expression def ty.tsubst : tvar → ty → ty → ty := sorry def pexp.tsubst : tvar → ty → pexp → pexp := sorry -- Typing for primitive operations (assumes exactly one type variable) def user.type : user_type → tvar → ty → Prop := sorry def func.type : func → arg → ty → Prop := sorry def proc.type : func → arg → ty → Prop := sorry def ty.ptr := ty.nat wsize.S64 inductive unop.ok : unop → ty → ty → Prop | neg : unop.ok unop.neg (ty.int wsize.Sinf) (ty.int wsize.Sinf) | not : unop.ok unop.not ty.bool ty.bool | bnot {s τ} : τ = ty.nat s ∨ (∃ s', τ = ty.int s' ∧ s = wsize.Sinf) → unop.ok (unop.bnot s) τ τ def ty.numeric : ty → Prop | (ty.nat _) := true | (ty.int _) := true | _ := false mutual inductive ty.uninhabited, prop.uninhabited, pexp.uninhabited with ty.uninhabited : ty → Prop | void : ty.uninhabited ty.void | prop {p} : prop.uninhabited p → ty.uninhabited (ty.prop p) with prop.uninhabited : prop → Prop | false : prop.uninhabited prop.false | anl {p q} : prop.uninhabited p → prop.uninhabited (prop.and p q) | anr {p q} : prop.uninhabited q → prop.uninhabited (prop.and p q) | or {p q} : prop.uninhabited p → prop.uninhabited q → prop.uninhabited (prop.or p q) | sepl {p q} : prop.uninhabited p → prop.uninhabited (prop.sep p q) | sepr {p q} : prop.uninhabited q → prop.uninhabited (prop.sep p q) | exl {x t A} : ty.uninhabited t → prop.uninhabited (prop.ex x t A) | exr {x t A} : prop.uninhabited A → prop.uninhabited (prop.ex x t A) | pexp {e} : pexp.uninhabited e → prop.uninhabited (prop.pexp e) with pexp.uninhabited : pexp → Prop | ff : pexp.uninhabited pexp.ff | anl {p q} : pexp.uninhabited p → pexp.uninhabited (pexp.binop binop.and p q) | anr {p q} : pexp.uninhabited q → pexp.uninhabited (pexp.binop binop.and p q) | or {p q} : pexp.uninhabited p → pexp.uninhabited q → pexp.uninhabited (pexp.binop binop.or p q) | if_ {h c p q} : pexp.uninhabited p → pexp.uninhabited q → pexp.uninhabited (pexp.if_ h c p q) inductive binop.ok : binop → ty → ty → ty → Prop | and : binop.ok binop.and ty.bool ty.bool ty.bool | or : binop.ok binop.or ty.bool ty.bool ty.bool | band {τ} : ty.numeric τ → binop.ok binop.band τ τ τ | bor {τ} : ty.numeric τ → binop.ok binop.bor τ τ τ | lt {τ₁ τ₂} : ty.numeric τ₁ → ty.numeric τ₂ → binop.ok binop.lt τ₁ τ₂ ty.bool | le {τ₁ τ₂} : ty.numeric τ₁ → ty.numeric τ₂ → binop.ok binop.le τ₁ τ₂ ty.bool | eq {τ₁ τ₂} : ty.numeric τ₁ → ty.numeric τ₂ → binop.ok binop.eq τ₁ τ₂ ty.bool mutual inductive arg.ok, ty.ok, prop.ok, pexp.ok with arg.ok : ctx → arg → Prop | var {Γ x γ τ} : ty.ok Γ τ → arg.ok Γ (arg.mk x γ τ) with ty.ok : ctx → ty → Prop | void {Γ} : ty.ok Γ ty.void | unit {Γ} : ty.ok Γ ty.unit | bool {Γ} : ty.ok Γ ty.bool | nat {Γ s} : ty.ok Γ (ty.nat s) | int {Γ s} : ty.ok Γ (ty.int s) | union {Γ A B} : ty.ok Γ A → ty.ok Γ B → ty.ok Γ (ty.union A B) | inter {Γ A B} : ty.ok Γ A → ty.ok Γ B → ty.ok Γ (ty.inter A B) | pair {Γ A B} : ty.ok Γ A → ty.ok Γ B → ty.ok Γ (ty.pair A B) | sigma {Γ A B} : arg.ok Γ A → ty.ok (Γ.app [A]) B → ty.ok Γ (ty.sigma A B) | user {Γ U ℓ α τ e} : user.type U α ℓ → ty.ok Γ τ → pexp.ok Γ e (ty.tsubst α τ ℓ) → ty.ok Γ (ty.user U τ e) | prop {Γ A} : prop.ok Γ A → ty.ok Γ (ty.prop A) with prop.ok : ctx → prop → Prop | true {Γ} : prop.ok Γ prop.true | false {Γ} : prop.ok Γ prop.false | all {Γ:ctx} {τ:ty} {x A} : prop.ok (Γ.app [arg.mk x ff τ.core]) A → prop.ok Γ (prop.all x τ A) | ex {Γ:ctx} {τ:ty} {x A} : prop.ok (Γ.app [arg.mk x ff τ.core]) A → prop.ok Γ (prop.ex x τ A) | imp {Γ A B} : prop.ok Γ A → prop.ok Γ B → prop.ok Γ (prop.imp A B) | not {Γ A} : prop.ok Γ A → prop.ok Γ (prop.not A) | and {Γ A B} : prop.ok Γ A → prop.ok Γ B → prop.ok Γ (prop.and A B) | or {Γ A B} : prop.ok Γ A → prop.ok Γ B → prop.ok Γ (prop.or A B) | emp {Γ} : prop.ok Γ prop.emp | sep {Γ A B} : prop.ok Γ A → prop.ok Γ B → prop.ok Γ (prop.sep A B) | wand {Γ A B} : prop.ok Γ A → prop.ok Γ B → prop.ok Γ (prop.wand A B) | pexp {Γ e} : pexp.ok Γ e ty.bool → prop.ok Γ (prop.pexp e) | eq {Γ e₁ e₂ τ} : pexp.ok Γ e₁ τ → pexp.ok Γ e₂ τ → prop.ok Γ (prop.eq e₁ e₂) | heap {Γ l v τ} : pexp.ok Γ l ty.ptr → ty.ok Γ τ → pexp.ok Γ v (ty.core τ) → prop.ok Γ (prop.heap l v) | has_ty {Γ e τ} : ty.ok Γ τ → pexp.ok Γ e (ty.core τ) → prop.ok Γ (prop.has_ty e τ) with pexp.ok : ctx → pexp → ty → Prop | var {Γ:ctx} {x γ τ} : Γ.get x γ τ → pexp.ok Γ (pexp.var x) τ.core | star {Γ} : pexp.ok Γ pexp.star ty.unit | tt {Γ} : pexp.ok Γ pexp.tt ty.bool | ff {Γ} : pexp.ok Γ pexp.ff ty.bool | nat {Γ s n} : wsize.nat_ok s n → pexp.ok Γ (pexp.const (n:ℕ)) (ty.nat s) | int {Γ s n} : wsize.int_ok s n → pexp.ok Γ (pexp.const n) (ty.int s) | neg {Γ e} : pexp.ok Γ e (ty.int wsize.Sinf) → pexp.ok Γ (pexp.unop unop.neg e) (ty.int wsize.Sinf) | unop {Γ o e τ τ'} : unop.ok o τ τ' → pexp.ok Γ e τ → pexp.ok Γ (pexp.unop o e) τ' | binop {Γ o e₁ e₂ τ₁ τ₂ τ'} : binop.ok o τ₁ τ₂ τ' → pexp.ok Γ e₁ τ₁ → pexp.ok Γ e₂ τ₂ → pexp.ok Γ (pexp.binop o e₁ e₂) τ' | if_ {Γ c e₁ e₂ τ} : pexp.ok Γ c ty.bool → pexp.ok Γ e₁ τ → pexp.ok Γ e₂ τ → pexp.ok Γ (pexp.if_ none c e₁ e₂) τ | dif {Γ h c e₁ e₂ τ} : pexp.ok Γ c ty.bool → pexp.ok (Γ.app [arg.mk h ff (ty.prop (prop.pexp c))]) e₁ τ → pexp.ok (Γ.app [arg.mk h ff (ty.prop (prop.not (prop.pexp c)))]) e₂ τ → pexp.ok Γ (pexp.if_ (some h) c e₁ e₂) τ | pair {Γ e₁ e₂ τ₁ τ₂} : pexp.ok Γ e₁ τ₁ → pexp.ok Γ e₂ τ₂ → pexp.ok Γ (pexp.pair e₁ e₂) (ty.pair τ₁ τ₂) | dpair {Γ:ctx} {e₁ e₂ x γ τ B} : ty.ok (Γ.app [arg.mk x γ τ]) B → pexp.ok Γ e₁ τ → pexp.ok Γ e₂ (B.subst x e₁) → pexp.ok Γ (pexp.pair e₁ e₂) (ty.sigma (arg.mk x γ τ) B) | call {Γ:ctx} {f x γ τ τ' e} : func.type f (arg.mk x γ τ) τ' → pexp.ok Γ e τ → pexp.ok Γ (pexp.call f e) (τ'.subst x e) inductive ctx.ok : ctx → Prop | nil : ctx.ok ⟨[]⟩ | cons {Γ R} : ctx.ok Γ → arg.ok Γ R → ctx.ok (Γ.app [R]) structure mctx := (ctx : ctx) (labels : alist (λ _:label, arg)) (muts : alist (λ _:var, pexp × ty)) instance : has_coe mctx ctx := ⟨mctx.ctx⟩ def mctx.ok : mctx → Prop | ⟨Γ, labs, muts⟩ := Γ.ok ∧ (∀ k x γ τ, labs.lookup k = some (arg.mk x γ τ) → ty.ok Γ τ) ∧ (∀ x e τ, muts.lookup x = some (e, τ) → pexp.ok Γ e τ) def mctx.app : mctx → list arg → mctx | ⟨Γ, labs, muts⟩ R := ⟨Γ.app R, labs, muts⟩ def mctx.appl : mctx → alist (λ _:label, arg) → mctx | ⟨Γ, labs, muts⟩ ks := ⟨Γ, labs.union ks, muts⟩ def mctx.mut : mctx → var → pexp → ty → mctx | ⟨Γ, labs, muts⟩ x e τ := ⟨Γ, labs, muts.insert x (e, τ)⟩ def mctx.modify (f : arg → arg) (idx : ℕ) : mctx → mctx | ⟨Γ, labs, muts⟩ := ⟨Γ.modify f idx, labs, muts⟩ def mctx.move : ℕ → mctx → mctx := mctx.modify arg.core def mctx.move_all : mctx → mctx | ⟨⟨Γ⟩, labs, muts⟩ := ⟨⟨Γ.map arg.core⟩, labs, muts⟩ def ty.sigmas : list arg → ty | [] := ty.unit | (A::R) := ty.sigma A (ty.sigmas R) def pexp.pairs : list pexp → pexp | [] := pexp.star | (e::es) := pexp.pair e (pexp.pairs es) inductive mctx.merge : mctx → mctx → Prop | refl {Γ} : mctx.merge Γ Γ | trans {Γ₁ Γ₂ Γ₃} : mctx.merge Γ₁ Γ₂ → mctx.merge Γ₂ Γ₃ → mctx.merge Γ₁ Γ₃ | drop {Γ : mctx} {R} : (∀ i e τ, Γ.muts.lookup i = some (e, τ) → pexp.ok Γ e τ) → mctx.merge (Γ.app R) Γ | drop_label {Γ : mctx} {ks} : mctx.merge (Γ.appl ks) Γ | move {Γ i} : mctx.merge Γ (Γ.move i) | mut {Γ : mctx} {R : list arg} {es} : R.map arg.core <+ Γ.ctx.1.map arg.core → R.mmap (λ R:arg, Γ.muts.lookup R.var) = some es → pexp.ok Γ (pexp.pairs (es.map prod.fst)) (ty.sigmas R) → mctx.merge Γ ⟨Γ.ctx, Γ.labels, list.foldr alist.erase Γ.muts (R.map arg.var)⟩ mutual inductive exp.ok_merge, exp.ok with exp.ok_merge : mctx → exp → ty → mctx → Prop | mk {Γ e τ Γ' Γ''} : exp.ok Γ e τ Γ' → mctx.merge Γ' Γ'' → exp.ok_merge Γ e τ Γ'' with exp.ok : mctx → exp → ty → mctx → Prop | var {Γ:mctx} {x γ τ} : Γ.1.get x γ τ → exp.ok Γ (exp.var x) τ.core Γ | star {Γ} : exp.ok Γ exp.star ty.unit Γ | tt {Γ} : exp.ok Γ exp.tt ty.bool Γ | ff {Γ} : exp.ok Γ exp.ff ty.bool Γ | nat {Γ s n} : wsize.nat_ok s n → exp.ok Γ (exp.const (n:ℕ)) (ty.nat s) Γ | int {Γ s n} : wsize.int_ok s n → exp.ok Γ (exp.const n) (ty.int s) Γ | neg {Γ Γ' e} : exp.ok Γ e (ty.int wsize.Sinf) Γ' → exp.ok Γ (exp.unop unop.neg e) (ty.int wsize.Sinf) Γ' | unop {Γ o e τ τ' Γ'} : unop.ok o τ τ' → exp.ok Γ e τ Γ' → exp.ok Γ (exp.unop o e) τ' Γ' | binop {Γ Γ₁ Γ₂ o e₁ e₂ τ₁ τ₂ τ'} : binop.ok o τ₁ τ₂ τ' → exp.ok Γ e₁ τ₁ Γ₁ → exp.ok Γ₁ e₂ τ₂ Γ₂ → exp.ok Γ₂ (exp.binop o e₁ e₂) τ' Γ₂ | if_ {Γ Γ' Γ'' c e₁ e₂ τ} : exp.ok Γ c ty.bool Γ' → exp.ok_merge Γ' e₁ τ Γ'' → exp.ok Γ' e₂ τ Γ'' → exp.ok Γ (exp.if_ none c e₁ e₂) τ Γ'' | dif {Γ Γ' : mctx} {h c e₁ e₂ τ} : pexp.ok Γ c ty.bool → let A := arg.mk h ff (ty.prop (prop.pexp c)), B := arg.mk h ff (ty.prop (prop.not (prop.pexp c))) in exp.ok_merge (Γ.app [A]) e₁ τ (Γ'.app [A]) → exp.ok_merge (Γ.app [B]) e₂ τ (Γ'.app [B]) → exp.ok Γ (exp.if_ (some h) (pexp.to_exp c) e₁ e₂) τ Γ' | pair {Γ Γ₁ Γ₂ e₁ e₂ τ₁ τ₂} : exp.ok Γ e₁ τ₁ Γ₁ → exp.ok Γ₁ e₂ τ₂ Γ₂ → exp.ok Γ (exp.pair e₁ e₂) (ty.pair τ₁ τ₂) Γ₂ | dpair {Γ Γ₁ Γ₂ : mctx} {e₁ e₂ x γ τ B} : ty.ok (Γ.app [arg.mk x γ τ]) B → exp.ok Γ (pexp.to_exp e₁) τ Γ₁ → exp.ok Γ₁ e₂ (B.subst x e₁) Γ₂ → exp.ok Γ (exp.pair (pexp.to_exp e₁) e₂) (ty.sigma (arg.mk x γ τ) B) Γ₂ | func {Γ Γ' f x γ τ τ' e} : func.type f (arg.mk x γ τ) τ' → exp.ok Γ (pexp.to_exp e) τ Γ' → exp.ok Γ (exp.call f (pexp.to_exp e)) (τ'.subst x e) Γ' | proc {Γ Γ' : mctx} {f x γ τ τ' e} : proc.type f (arg.mk x γ τ) τ' → (∀ e, τ'.subst x e = τ') → exp.ok Γ e τ Γ' → exp.ok Γ (exp.call f e) τ' Γ' | let_ {Γ Γ' Γ'' : mctx} {R t e₁ e₂ τ τ'} : exp.ok Γ e₁ τ Γ' → tuple_pat.ok Γ' t τ R → ty.ok ↑Γ'' τ' → exp.ok_merge (Γ'.app R) e₂ τ' (Γ''.app R) → exp.ok Γ (exp.let_ none t e₁ e₂) τ' Γ'' | let_hyp {Γ Γ' : mctx} {R h t te e₁ e₂ τ τ'} : pexp.ok ↑Γ e₁ τ → tuple_pat.ok ↑Γ t τ R → tuple_pat.to_pexp t te → ty.ok ↑Γ' τ' → let R' := R ++ [arg.mk h ff (ty.prop (prop.eq te e₁))] in exp.ok_merge (Γ.app R') e₂ τ' (Γ'.app R') → exp.ok Γ (exp.let_ (some h) t (pexp.to_exp e₁) e₂) τ' Γ' | mut {Γ Γ' Γ'' : mctx} {x γ e₁ e₂ τ τ' τ''} : exp.ok Γ (pexp.to_exp e₁) τ Γ' → Γ'.1.get x γ τ'' → ty.ok ↑Γ'' τ' → exp.ok (Γ'.mut x e₁ τ) e₂ τ' Γ'' → exp.ok Γ (exp.mut none (place.var x) (pexp.to_exp e₁) e₂) τ' Γ'' | unreachable {Γ Γ' e τ τ'} : ty.uninhabited τ → exp.ok Γ e τ Γ' → ty.ok Γ τ' → exp.ok Γ (exp.unreachable e) τ' Γ | label {Γ Γ' : mctx} {ls : list (label × arg × exp)} {ks : alist (λ _:label,arg)} {e τ} : ks.entries = ls.map (λ p, ⟨p.1, p.2.1⟩) → (∀ k R e, (k,R,e) ∈ ls → let Γ₁ := (Γ.move_all.appl ks).app [R] in exp.ok_merge Γ₁ e ty.void Γ₁.move_all) → exp.ok (Γ.appl ks) e τ Γ' → exp.ok Γ (exp.label ls e) τ Γ' | goto {Γ Γ' : mctx} {k e τ τ' x γ} : Γ.labels.lookup k = some (arg.mk x γ τ) → exp.ok_merge Γ e τ Γ' → ty.ok Γ τ' → exp.ok Γ (exp.goto k e) τ' Γ | entail {Γ Γ' p q A B} : exp.ok Γ p (ty.prop A) Γ' → pure_proof.ok q A B → exp.ok Γ (exp.entail p q) (ty.prop B) Γ' | assert {Γ Γ' e} : exp.ok Γ (pexp.to_exp e) ty.bool Γ' → exp.ok Γ (exp.assert (pexp.to_exp e)) (ty.prop (prop.pexp e)) Γ' | typeof {Γ e τ Γ'} : exp.ok Γ (pexp.to_exp e) τ Γ' → exp.ok Γ (exp.typeof (pexp.to_exp e)) (ty.prop (prop.has_ty e τ)) Γ' end mmc
132c9ab388588b335143f936c99705954a9ed0a4
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/unboundImplicitLocals.lean
07e6448eafefe6a3c016b58bb0fd2ed532fdb054
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,164
lean
def myid (a : α) := a -- works #check myid 10 #check myid true theorem ex1 (a : α) : myid a = a := rfl def cnst (b : β) : α → β := fun _ => b -- works theorem ex2 (b : β) (a : α) : cnst b a = b := rfl def Vec (α : Type) (n : Nat) := { a : Array α // a.size = n } def mkVec : Vec α 0 := ⟨ #[], rfl ⟩ def Vec.map (xs : Vec α n) (f : α → β) : Vec β n := ⟨ xs.val.map f, sorry ⟩ /- unbound implicit locals must be greek or lower case letters -/ def Vec.map2 (xs : Vec α size /- error: unknown identifier size -/) (f : α → β) : Vec β n := ⟨ xs.val.map f, sorry ⟩ set_option unboundImplicitLocal false in def Vec.map3 (xs : Vec α n) (f : α → β) : Vec β n := -- Errors, unknown identifiers 'α', 'n', 'β' ⟨ xs.val.map f, sorry ⟩ def double [Add α] (a : α) := a + a variables (xs : Vec α n) -- works def f := xs #check @f #check f mkVec #check f (α := Nat) mkVec def g (a : α) := xs.val.push a theorem ex3 : g ⟨#[0], rfl⟩ 1 = #[0, 1] := rfl inductive Tree (α β : Type) := | leaf1 : α → Tree α β | leaf2 : β → Tree α β | node : Tree α β → Tree α β → Tree α β inductive TreeElem1 : α → Tree α β → Prop | leaf1 : (a : α) → TreeElem1 a (Tree.leaf1 (β := β) a) | nodeLeft : (a : α) → (left : Tree α β) → (right : Tree α β) → TreeElem1 a left → TreeElem1 a (Tree.node left right) | nodeRight : (a : α) → (left : Tree α β) → (right : Tree α β) → TreeElem1 a right → TreeElem1 a (Tree.node left right) inductive TreeElem2 : β → Tree α β → Prop | leaf2 : (b : β) → TreeElem2 b (Tree.leaf2 (α := α) b) | nodeLeft : (b : β) → (left : Tree α β) → (right : Tree α β) → TreeElem2 b left → TreeElem2 b (Tree.node left right) | nodeRight : (b : β) → (left : Tree α β) → (right : Tree α β) → TreeElem2 b right → TreeElem2 b (Tree.node left right) namespace Ex1 def findSomeRevM? [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := pure none def findSomeRev? (as : Array α) (f : α → Option β) : Option β := Id.run <| findSomeRevM? as f end Ex1
2f17628120ecaa9c77cf5b7a801128a7e5f573bb
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/set/basic.lean
4e3af611b712cc6a51248a5e478899e55cc064bc
[ "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
121,914
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import order.symm_diff /-! # Basic properties of sets Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements have type `X` are thus defined as `set X := X → Prop`. Note that this function need not be decidable. The definition is in the core library. This file provides some basic definitions related to sets and functions not present in the core library, as well as extra lemmas for functions in the core library (empty set, univ, union, intersection, insert, singleton, set-theoretic difference, complement, and powerset). Note that a set is a term, not a type. There is a coercion from `set α` to `Type*` sending `s` to the corresponding subtype `↥s`. See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean. ## Main definitions Notation used here: - `f : α → β` is a function, - `s : set α` and `s₁ s₂ : set α` are subsets of `α` - `t : set β` is a subset of `β`. Definitions in the file: * `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the fact that `s` has an element (see the Implementation Notes). * `preimage f t : set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β. * `subsingleton s : Prop` : the predicate saying that `s` has at most one element. * `nontrivial s : Prop` : the predicate saying that `s` has at least two distinct elements. * `range f : set β` : the image of `univ` under `f`. Also works for `{p : Prop} (f : p → α)` (unlike `image`) * `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`. ## Notation * `f ⁻¹' t` for `preimage f t` * `f '' s` for `image f s` * `sᶜ` for the complement of `s` ## Implementation notes * `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that the `s.nonempty` dot notation can be used. * For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`. ## Tags set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert, singleton, complement, powerset -/ /-! ### Set coercion to a type -/ open function universes u v w x namespace set variables {α : Type*} {s t : set α} instance : has_le (set α) := ⟨λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t⟩ instance : has_subset (set α) := ⟨(≤)⟩ instance {α : Type*} : boolean_algebra (set α) := { sup := λ s t, {x | x ∈ s ∨ x ∈ t}, le := (≤), lt := λ s t, s ⊆ t ∧ ¬t ⊆ s, inf := λ s t, {x | x ∈ s ∧ x ∈ t}, bot := ∅, compl := λ s, {x | x ∉ s}, top := univ, sdiff := λ s t, {x | x ∈ s ∧ x ∉ t}, .. (infer_instance : boolean_algebra (α → Prop)) } instance : has_ssubset (set α) := ⟨(<)⟩ instance : has_union (set α) := ⟨(⊔)⟩ instance : has_inter (set α) := ⟨(⊓)⟩ @[simp] lemma top_eq_univ : (⊤ : set α) = univ := rfl @[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl @[simp] lemma sup_eq_union : ((⊔) : set α → set α → set α) = (∪) := rfl @[simp] lemma inf_eq_inter : ((⊓) : set α → set α → set α) = (∩) := rfl @[simp] lemma le_eq_subset : ((≤) : set α → set α → Prop) = (⊆) := rfl @[simp] lemma lt_eq_ssubset : ((<) : set α → set α → Prop) = (⊂) := rfl lemma le_iff_subset : s ≤ t ↔ s ⊆ t := iff.rfl lemma lt_iff_ssubset : s ≤ t ↔ s ⊆ t := iff.rfl alias le_iff_subset ↔ _root_.has_le.le.subset _root_.has_subset.subset.le alias lt_iff_ssubset ↔ _root_.has_lt.lt.ssubset _root_.has_ssubset.ssubset.lt /-- Coercion from a set to the corresponding subtype. -/ instance {α : Type u} : has_coe_to_sort (set α) (Type u) := ⟨λ s, {x // x ∈ s}⟩ instance pi_set_coe.can_lift (ι : Type u) (α : Π i : ι, Type v) [ne : Π i, nonempty (α i)] (s : set ι) : can_lift (Π i : s, α i) (Π i, α i) := { coe := λ f i, f i, .. pi_subtype.can_lift ι α s } instance pi_set_coe.can_lift' (ι : Type u) (α : Type v) [ne : nonempty α] (s : set ι) : can_lift (s → α) (ι → α) := pi_set_coe.can_lift ι (λ _, α) s end set section set_coe variables {α : Type u} theorem set.coe_eq_subtype (s : set α) : ↥s = {x // x ∈ s} := rfl @[simp] theorem set.coe_set_of (p : α → Prop) : ↥{x | p x} = {x // p x} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} : (∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x x.2) := (@set_coe.exists _ _ $ λ x, p x.1 x.2).symm theorem set_coe.forall' {s : set α} {p : Π x, x ∈ s → Prop} : (∀ x (h : x ∈ s), p x h) ↔ (∀ x : s, p x x.2) := (@set_coe.forall _ _ $ λ x, p x.1 x.2).symm @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : ↥s = ↥t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe /-- See also `subtype.prop` -/ lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop /-- Duplicate of `eq.subset'`, which currently has elaboration problems. -/ lemma eq.subset {α} {s t : set α} : s = t → s ⊆ t := eq.subset' namespace set variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a b : α} {s t u : set α} instance : inhabited (set α) := ⟨∅⟩ @[ext] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx lemma forall_in_swap {p : α → β → Prop} : (∀ (a ∈ s) b, p a b) ↔ ∀ b (a ∈ s), p a b := by tauto /-! ### Lemmas about `mem` and `set_of` -/ lemma mem_set_of {a : α} {p : α → Prop} : a ∈ {x | p x} ↔ p a := iff.rfl /-- If `h : a ∈ {x | p x}` then `h.out : p x`. These are definitionally equal, but this can nevertheless be useful for various reasons, e.g. to apply further projection notation or in an argument to `simp`. -/ lemma _root_.has_mem.mem.out {p : α → Prop} {a : α} (h : a ∈ {x | p x}) : p a := h theorem nmem_set_of_eq {a : α} {p : α → Prop} : a ∉ {x | p x} = ¬ p a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem set_of_set {s : set α} : set_of s = s := rfl lemma set_of_app_iff {p : α → Prop} {x : α} : {x | p x} x ↔ p x := iff.rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl lemma set_of_bijective : bijective (set_of : (α → Prop) → set α) := bijective_id @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl lemma set_of_and {p q : α → Prop} : {a | p a ∧ q a} = {a | p a} ∩ {a | q a} := rfl lemma set_of_or {p q : α → Prop} : {a | p a ∨ q a} = {a | p a} ∪ {a | q a} := rfl /-! ### Subset and strict subset relations -/ instance : is_refl (set α) (⊆) := has_le.le.is_refl instance : is_trans (set α) (⊆) := has_le.le.is_trans instance : is_antisymm (set α) (⊆) := has_le.le.is_antisymm instance : is_irrefl (set α) (⊂) := has_lt.lt.is_irrefl instance : is_trans (set α) (⊂) := has_lt.lt.is_trans instance : is_asymm (set α) (⊂) := has_lt.lt.is_asymm instance : is_nonstrict_strict_order (set α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? lemma subset_def : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl lemma ssubset_def : s ⊂ t = (s ⊆ t ∧ ¬ t ⊆ s) := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := λ x h, bc $ ab h @[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := set.ext $ λ x, ⟨@h₁ _, @h₂ _⟩ theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, ⟨e.subset, e.symm.subset⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alternative name theorem eq_of_subset_of_subset {a b : set α} : a ⊆ b → b ⊆ a → a = b := subset.antisymm theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ := @h _ theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s := mt $ mem_of_subset_of_mem h theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp only [subset_def, not_forall] /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ protected theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := eq_or_lt_of_le h lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := not_subset.1 h.2 protected lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne (set α) _ s t lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s := ⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩ protected lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂.1 hs₂s₃, λ hs₃s₁, hs₁s₂.2 (subset.trans hs₂s₃ hs₃s₁)⟩ protected lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂ hs₂s₃.1, λ hs₃s₁, hs₂s₃.2 (subset.trans hs₃s₁ hs₁s₂)⟩ theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := id @[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := not_not /-! ### Non-empty sets -/ /-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s @[simp] lemma nonempty_coe_sort {s : set α} : nonempty ↥s ↔ s.nonempty := nonempty_subtype lemma nonempty_def : s.nonempty ↔ ∃ x, x ∈ s := iff.rfl lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩ theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅) | ⟨x, hx⟩ hs := hs hx theorem nonempty.ne_empty : ∀ {s : set α}, s.nonempty → s ≠ ∅ | _ ⟨x, hx⟩ rfl := hx @[simp] theorem not_nonempty_empty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl /-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/ protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht lemma nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).nonempty := let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩ lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := nonempty_of_not_subset ht.2 lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr @[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right lemma inter_nonempty : (s ∩ t).nonempty ↔ ∃ x, x ∈ s ∧ x ∈ t := iff.rfl lemma inter_nonempty_iff_exists_left : (s ∩ t).nonempty ↔ ∃ x ∈ s, x ∈ t := by simp_rw [inter_nonempty, exists_prop] lemma inter_nonempty_iff_exists_right : (s ∩ t).nonempty ↔ ∃ x ∈ t, x ∈ s := by simp_rw [inter_nonempty, exists_prop, and_comm] lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty := ⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩ @[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty | ⟨x⟩ := ⟨x, trivial⟩ lemma nonempty.to_subtype (h : s.nonempty) : nonempty s := nonempty_subtype.2 h instance [nonempty α] : nonempty (set.univ : set α) := set.univ_nonempty.to_subtype lemma nonempty_of_nonempty_subtype [nonempty s] : s.nonempty := nonempty_subtype.mp ‹_› /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s. theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := (subset.antisymm_iff.trans $ and_iff_left (empty_subset _)).symm theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := subset_empty_iff.symm lemma eq_empty_of_forall_not_mem (h : ∀ x, x ∉ s) : s = ∅ := subset_empty_iff.1 h theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem eq_empty_of_is_empty [is_empty α] (s : set α) : s = ∅ := eq_empty_of_subset_empty $ λ x hx, is_empty_elim x /-- There is exactly one set of a type that is empty. -/ instance unique_empty [is_empty α] : unique (set α) := { default := ∅, uniq := eq_empty_of_is_empty } lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ := by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists] lemma empty_not_nonempty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := not_iff_comm.1 not_nonempty_iff_eq_empty @[simp] lemma is_empty_coe_sort {s : set α} : is_empty ↥s ↔ s = ∅ := not_iff_not.1 $ by simpa using ne_empty_iff_nonempty.symm lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty := or_iff_not_imp_left.2 ne_empty_iff_nonempty.1 theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := iff_true_intro $ λ x, false.elim instance (α : Type u) : is_empty.{u+1} (∅ : set α) := ⟨λ x, x.2⟩ @[simp] lemma empty_ssubset : ∅ ⊂ s ↔ s.nonempty := (@bot_lt_iff_ne_bot (set α) _ _ _).trans ne_empty_iff_nonempty /-! ### Universal set. In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ @[simp] theorem set_of_true : {x : α | true} = univ := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial @[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ is_empty α := eq_empty_iff_forall_not_mem.trans ⟨λ H, ⟨λ x, H x trivial⟩, λ H x _, @is_empty.false α H x⟩ theorem empty_ne_univ [nonempty α] : (∅ : set α) ≠ univ := λ e, not_is_empty_of_nonempty α $ univ_eq_empty_iff.1 e.symm @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := (subset.antisymm_iff.trans $ and_iff_right (subset_univ _)).symm theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := univ_subset_iff.symm.trans $ forall_congr $ λ x, imp_iff_right ⟨⟩ theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ := eq_univ_of_univ_subset $ hs ▸ h lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ lemma ne_univ_iff_exists_not_mem {α : Type*} (s : set α) : s ≠ univ ↔ ∃ a, a ∉ s := by rw [←not_forall, ←eq_univ_iff_forall] lemma not_subset_iff_exists_mem_not_mem {α : Type*} {s t : set α} : ¬ s ⊆ t ↔ ∃ x, x ∈ s ∧ x ∉ t := by simp [subset_def] lemma univ_unique [unique α] : @set.univ α = {default} := set.ext $ λ x, iff_of_true trivial $ subsingleton.elim x default instance nontrivial_of_nonempty [nonempty α] : nontrivial (set α) := ⟨⟨∅, univ, empty_ne_univ⟩⟩ /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext $ λ x, or_self _ @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext $ λ x, or_false _ @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext $ λ x, false_or _ theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext $ λ x, or.comm theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext $ λ x, or.assoc instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ x, or.left_comm theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, or.right_comm @[simp] theorem union_eq_left_iff_subset {s t : set α} : s ∪ t = s ↔ t ⊆ s := sup_eq_left @[simp] theorem union_eq_right_iff_subset {s t : set α} : s ∪ t = t ↔ s ⊆ t := sup_eq_right theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := union_eq_right_iff_subset.mpr h theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := union_eq_left_iff_subset.mpr h @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x, or.rec (@sr _) (@tr _) @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (forall_congr (by exact λ x, or_imp_distrib)).trans forall_and_distrib theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := λ x, or.imp (@h₁ _) (@h₂ _) theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h subset.rfl theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union subset.rfl h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) lemma union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ⊔ u := sup_congr_left ht hu lemma union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u := sup_congr_right hs ht lemma union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t := sup_eq_sup_iff_left lemma union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u := sup_eq_sup_iff_right @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := by simp only [← subset_empty_iff]; exact union_subset_iff @[simp] lemma union_univ {s : set α} : s ∪ univ = univ := sup_top_eq @[simp] lemma univ_union {s : set α} : univ ∪ s = univ := top_sup_eq /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext $ λ x, and_self _ @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext $ λ x, and_false _ @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext $ λ x, false_and _ theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext $ λ x, and.comm theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext $ λ x, and.assoc instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ x, and.left_comm theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ x, and.right_comm @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x, and.left @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x, and.right theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x h, ⟨rs h, rt h⟩ @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := (forall_congr (by exact λ x, imp_and_distrib)).trans forall_and_distrib @[simp] theorem inter_eq_left_iff_subset {s t : set α} : s ∩ t = s ↔ s ⊆ t := inf_eq_left @[simp] theorem inter_eq_right_iff_subset {s t : set α} : s ∩ t = t ↔ t ⊆ s := inf_eq_right theorem inter_eq_self_of_subset_left {s t : set α} : s ⊆ t → s ∩ t = s := inter_eq_left_iff_subset.mpr theorem inter_eq_self_of_subset_right {s t : set α} : t ⊆ s → s ∩ t = t := inter_eq_right_iff_subset.mpr lemma inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u := inf_congr_left ht hu lemma inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u := inf_congr_right hs ht lemma inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u := inf_eq_inf_iff_left lemma inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t := inf_eq_inf_iff_right @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := inf_top_eq @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := top_inf_eq theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := λ x, and.imp (@h₁ _) (@h₂ _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter H subset.rfl theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := inter_subset_inter subset.rfl H theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := inter_eq_self_of_subset_right $ subset_union_left _ _ theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := inter_eq_self_of_subset_right $ subset_union_right _ _ /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_union_distrib_left (s t u : set α) : s ∪ (t ∪ u) = (s ∪ t) ∪ (s ∪ u) := sup_sup_distrib_left _ _ _ lemma union_union_distrib_right (s t u : set α) : (s ∪ t) ∪ u = (s ∪ u) ∪ (t ∪ u) := sup_sup_distrib_right _ _ _ lemma inter_inter_distrib_left (s t u : set α) : s ∩ (t ∩ u) = (s ∩ t) ∩ (s ∩ u) := inf_inf_distrib_left _ _ _ lemma inter_inter_distrib_right (s t u : set α) : (s ∩ t) ∩ u = (s ∩ u) ∩ (t ∩ u) := inf_inf_distrib_right _ _ _ lemma union_union_union_comm (s t u v : set α) : (s ∪ t) ∪ (u ∪ v) = (s ∪ u) ∪ (t ∪ v) := sup_sup_sup_comm _ _ _ _ lemma inter_inter_inter_comm (s t u v : set α) : (s ∩ t) ∩ (u ∩ v) = (s ∩ u) ∩ (t ∩ v) := inf_inf_inf_comm _ _ _ _ /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := λ y, or.inr theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id lemma mem_of_mem_insert_of_ne : b ∈ insert a s → b ≠ a → b ∈ s := or.resolve_left lemma eq_of_not_mem_of_mem_insert : b ∈ insert a s → b ∉ s → b = a := or.resolve_right @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ x = a ∨ x ∈ s := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := ext $ λ x, or_iff_right_of_imp $ λ e, e.symm ▸ h lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} : a ∉ s → s ≠ insert a t := mt $ λ e, e.symm ▸ mem_insert _ _ @[simp] lemma insert_eq_self : insert a s = s ↔ a ∈ s := ⟨λ h, h ▸ mem_insert _ _, insert_eq_of_mem⟩ lemma insert_ne_self : insert a s ≠ s ↔ a ∉ s := insert_eq_self.not theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp only [subset_def, or_imp_distrib, forall_and_distrib, forall_eq, mem_insert_iff] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := λ x, or.imp_right (@h _) theorem insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t := begin refine ⟨λ h x hx, _, insert_subset_insert⟩, rcases h (subset_insert _ _ hx) with (rfl|hxt), exacts [(ha hx).elim, hxt] end theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := begin simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset], simp only [exists_prop, and_comm] end theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff_insert.2 ⟨a, h, subset.rfl⟩ theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, or.left_comm @[simp] lemma insert_idem (a : α) (s : set α) : insert a (insert a s) = insert a s := insert_eq_of_mem $ mem_insert _ _ theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ λ x, or.assoc @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ λ x, or.left_comm @[simp] theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ instance (a : α) (s : set α) : nonempty (insert a s : set α) := (insert_nonempty a s).to_subtype lemma insert_inter_distrib (a : α) (s t : set α) : insert a (s ∩ t) = insert a s ∩ insert a t := ext $ λ y, or_and_distrib_left lemma insert_union_distrib (a : α) (s t : set α) : insert a (s ∪ t) = insert a s ∪ insert a t := ext $ λ _, or_or_distrib_left _ _ _ lemma insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b := ⟨λ h, eq_of_not_mem_of_mem_insert (h.subst $ mem_insert a s) ha, congr_arg _⟩ -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ insert a s → P x) (x) (h : x ∈ s) : P x := H _ (or.inr h) theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ s → P x) (ha : P a) (x) (h : x ∈ insert a s) : P x := h.elim (λ e, e.symm ▸ ha) (H _) theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} : (∃ x ∈ insert a s, P x) ↔ P a ∨ (∃ x ∈ s, P x) := bex_or_left_distrib.trans $ or_congr_left' bex_eq_left theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := ball_or_left_distrib.trans $ and_congr_left' forall_eq /-! ### Lemmas about singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := (insert_emptyc_eq _).symm @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := iff.rfl @[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := rfl @[simp] lemma set_of_eq_eq_singleton' {a : α} : {x | a = x} = {a} := ext $ λ x, eq_comm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := @rfl _ _ theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := h @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := ext_iff.trans eq_iff_eq_cancel_left lemma singleton_injective : injective (singleton : α → set α) := λ _ _, singleton_eq_singleton_iff.mp theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := H theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := rfl @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := union_self _ theorem pair_comm (a b : α) : ({a, b} : set α) = {b, a} := union_comm _ _ @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := ⟨a, rfl⟩ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := forall_eq theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := rfl @[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl @[simp] theorem union_singleton : s ∪ {a} = insert a s := union_comm _ _ @[simp] theorem singleton_inter_nonempty : ({a} ∩ s).nonempty ↔ a ∈ s := by simp only [set.nonempty, mem_inter_eq, mem_singleton_iff, exists_eq_left] @[simp] theorem inter_singleton_nonempty : (s ∩ {a}).nonempty ↔ a ∈ s := by rw [inter_comm, singleton_inter_nonempty] @[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := not_nonempty_iff_eq_empty.symm.trans singleton_inter_nonempty.not @[simp] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty := ne_empty_iff_nonempty instance unique_singleton (a : α) : unique ↥({a} : set α) := ⟨⟨⟨a, mem_singleton a⟩⟩, λ ⟨x, h⟩, subtype.eq h⟩ lemma eq_singleton_iff_unique_mem : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := subset.antisymm_iff.trans $ and.comm.trans $ and_congr_left' singleton_subset_iff lemma eq_singleton_iff_nonempty_unique_mem : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := eq_singleton_iff_unique_mem.trans $ and_congr_left $ λ H, ⟨λ h', ⟨_, h'⟩, λ ⟨x, h⟩, H x h ▸ h⟩ -- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS. @[simp] lemma default_coe_singleton (x : α) : (default : ({x} : set α)) = ⟨x, rfl⟩ := rfl /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem sep_mem_eq {s t : set α} : {x ∈ s | x ∈ t} = s ∩ t := rfl @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (h : s ⊆ t) : s = {x ∈ t | x ∈ s} := (inter_eq_self_of_subset_right h).symm @[simp] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := λ x, and.left @[simp] lemma sep_empty (p : α → Prop) : {x ∈ (∅ : set α) | p x} = ∅ := by { ext, exact false_and _ } theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (H : {x ∈ s | p x} = ∅) (x) : x ∈ s → ¬ p x := not_and.1 (eq_empty_iff_forall_not_mem.1 H x : _) @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := univ_inter _ @[simp] lemma sep_true : {a ∈ s | true} = s := by { ext, simp } @[simp] lemma sep_false : {a ∈ s | false} = ∅ := by { ext, simp } lemma sep_inter_sep {p q : α → Prop} : {x ∈ s | p x} ∩ {x ∈ s | q x} = {x ∈ s | p x ∧ q x} := begin ext, simp_rw [mem_inter_iff, mem_sep_iff], rw [and_and_and_comm, and_self], end @[simp] lemma subset_singleton_iff {α : Type*} {s : set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x := iff.rfl lemma subset_singleton_iff_eq {s : set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} := begin obtain (rfl | hs) := s.eq_empty_or_nonempty, use ⟨λ _, or.inl rfl, λ _, empty_subset _⟩, simp [eq_singleton_iff_nonempty_unique_mem, hs, ne_empty_iff_nonempty.2 hs], end lemma nonempty.subset_singleton_iff (h : s.nonempty) : s ⊆ {a} ↔ s = {a} := subset_singleton_iff_eq.trans $ or_iff_right h.ne_empty lemma ssubset_singleton_iff {s : set α} {x : α} : s ⊂ {x} ↔ s = ∅ := begin rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_distrib_right, and_not_self, or_false, and_iff_left_iff_imp], rintro rfl, refine ne_comm.1 (ne_empty_iff_nonempty.2 (singleton_nonempty _)), end lemma eq_empty_of_ssubset_singleton {s : set α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### Disjointness -/ lemma _root_.disjoint.inter_eq : disjoint s t → s ∩ t = ∅ := disjoint.eq_bot lemma disjoint_left : disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t := forall_congr $ λ _, not_and lemma disjoint_right : disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] /-! ### Lemmas about complement -/ lemma compl_def (s : set α) : sᶜ = {x | x ∉ s} := rfl theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h lemma compl_set_of {α} (p : α → Prop) : {a | p a}ᶜ = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ sᶜ = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ sᶜ ↔ x ∉ s := iff.rfl lemma not_mem_compl_iff {x : α} : x ∉ sᶜ ↔ x ∈ s := not_not @[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ := compl_inf_eq_bot @[simp] theorem compl_empty : (∅ : set α)ᶜ = univ := compl_bot @[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ := compl_top @[simp] lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ := compl_eq_bot @[simp] lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ := compl_eq_top lemma compl_ne_univ : sᶜ ≠ univ ↔ s.nonempty := compl_univ_iff.not.trans ne_empty_iff_nonempty lemma nonempty_compl {s : set α} : sᶜ.nonempty ↔ s ≠ univ := ne_empty_iff_nonempty.symm.trans compl_empty_iff.not lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a := mem_singleton_iff.not lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} := ext $ λ x, mem_compl_singleton_iff @[simp] lemma compl_ne_eq_singleton (a : α) : ({x | x ≠ a} : set α)ᶜ = {a} := by { ext, simp, } theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ := ext $ λ x, or_iff_not_and_not theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ := ext $ λ x, and_iff_not_or_not @[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ := eq_univ_iff_forall.2 $ λ x, em _ @[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self] lemma compl_subset_comm : sᶜ ⊆ t ↔ tᶜ ⊆ s := @compl_le_iff_compl_le _ s _ _ lemma subset_compl_comm : s ⊆ tᶜ ↔ t ⊆ sᶜ := @le_compl_iff_le_compl _ _ _ t @[simp] lemma compl_subset_compl : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le (set α) _ _ _ lemma subset_compl_iff_disjoint_left : s ⊆ tᶜ ↔ disjoint t s := @le_compl_iff_disjoint_left (set α) _ _ _ lemma subset_compl_iff_disjoint_right : s ⊆ tᶜ ↔ disjoint s t := @le_compl_iff_disjoint_right (set α) _ _ _ lemma disjoint_compl_left_iff_subset : disjoint sᶜ t ↔ t ⊆ s := disjoint_compl_left_iff lemma disjoint_compl_right_iff_subset : disjoint s tᶜ ↔ s ⊆ t := disjoint_compl_right_iff alias subset_compl_iff_disjoint_right ↔ _ _root_.disjoint.subset_compl_right alias subset_compl_iff_disjoint_left ↔ _ _root_.disjoint.subset_compl_left alias disjoint_compl_left_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_left alias disjoint_compl_right_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_right theorem subset_union_compl_iff_inter_subset {s t u : set α} : s ⊆ t ∪ uᶜ ↔ s ∩ u ⊆ t := (@is_compl_compl _ u _).le_sup_right_iff_inf_left_le theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, or_iff_not_imp_left @[simp] lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s := subset_compl_comm.trans singleton_subset_iff theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c := forall_congr $ λ x, and_imp.trans $ imp_congr_right $ λ _, imp_iff_not_or lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t := (not_subset.trans $ exists_congr $ by exact λ x, by simp [mem_compl]).symm /-! ### Lemmas about set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ tᶜ := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem diff_eq_compl_inter {s t : set α} : s \ t = tᶜ ∩ s := by rw [diff_eq, inter_comm] theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := inter_compl_nonempty_iff theorem diff_subset (s t : set α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le theorem union_diff_cancel' {s t u : set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ (u \ s) = u := sup_sdiff_cancel' h₁ h₂ theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := sup_sdiff_cancel_right h theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := disjoint.sup_sdiff_cancel_left h theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := disjoint.sup_sdiff_cancel_right h @[simp] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := sup_sdiff_left_self @[simp] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := sup_sdiff_right_self theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := sup_sdiff theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inf_sdiff_assoc @[simp] theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := inf_sdiff_self_right @[simp] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := sup_inf_sdiff s t @[simp] lemma diff_union_inter (s t : set α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] theorem inter_union_compl (s t : set α) : (s ∩ t) ∪ (s ∩ tᶜ) = s := inter_union_diff _ _ theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂, from sdiff_le_sdiff theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := sdiff_le_sdiff_right ‹s₁ ≤ s₂› theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := sdiff_le_sdiff_left ‹t ≤ u› theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s := top_sdiff.symm @[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ := bot_sdiff theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := sdiff_bot @[simp] lemma diff_univ (s : set α) : s \ univ = ∅ := diff_eq_empty.2 (subset_univ s) theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := sdiff_sdiff_left -- the following statement contains parentheses to help the reader lemma diff_diff_comm {s t u : set α} : (s \ t) \ u = (s \ u) \ t := sdiff_sdiff_comm lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := show s \ t ≤ u ↔ s ≤ t ∪ u, from sdiff_le_iff lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t := show s ≤ (s \ t) ∪ t, from le_sdiff_sup lemma diff_union_of_subset {s t : set α} (h : t ⊆ s) : (s \ t) ∪ t = s := subset.antisymm (union_subset (diff_subset _ _) h) (subset_diff_union _ _) @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} := subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := show s \ t ≤ u ↔ s \ u ≤ t, from sdiff_le_comm lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := sdiff_inf lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) := sdiff_sup.symm lemma diff_compl : s \ tᶜ = s ∩ t := sdiff_compl lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) := sdiff_sdiff_right' @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := by { ext, split; simp [or_imp_distrib, h] {contextual := tt} } theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := begin classical, ext x, by_cases h' : x ∈ t, { have : x ≠ a, { assume H, rw H at h', exact h h' }, simp [h, h', this] }, { simp [h, h'] } end lemma insert_diff_self_of_not_mem {a : α} {s : set α} (h : a ∉ s) : insert a s \ {a} = s := by { ext, simp [and_iff_left_of_imp (λ hx : x ∈ s, show x ≠ a, from λ hxa, h $ hxa ▸ hx)] } @[simp] lemma insert_diff_eq_singleton {a : α} {s : set α} (h : a ∉ s) : insert a s \ s = {a} := begin ext, rw [set.mem_diff, set.mem_insert_iff, set.mem_singleton_iff, or_and_distrib_right, and_not_self, or_false, and_iff_left_iff_imp], rintro rfl, exact h, end lemma inter_insert_of_mem (h : a ∈ s) : s ∩ insert a t = insert a (s ∩ t) := by rw [insert_inter_distrib, insert_eq_of_mem h] lemma insert_inter_of_mem (h : a ∈ t) : insert a s ∩ t = insert a (s ∩ t) := by rw [insert_inter_distrib, insert_eq_of_mem h] lemma inter_insert_of_not_mem (h : a ∉ s) : s ∩ insert a t = s ∩ t := ext $ λ x, and_congr_right $ λ hx, or_iff_right $ ne_of_mem_of_not_mem hx h lemma insert_inter_of_not_mem (h : a ∉ t) : insert a s ∩ t = s ∩ t := ext $ λ x, and_congr_left $ λ hx, or_iff_right $ ne_of_mem_of_not_mem hx h @[simp] lemma union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := sup_sdiff_self _ _ @[simp] lemma diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := sdiff_sup_self _ _ @[simp] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := inf_sdiff_self_left @[simp] theorem diff_inter_self_eq_diff {s t : set α} : s \ (t ∩ s) = s \ t := sdiff_inf_self_right _ _ @[simp] theorem diff_self_inter {s t : set α} : s \ (s ∩ t) = s \ t := sdiff_inf_self_left _ _ @[simp] theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := show s \ t = s ↔ t ⊓ s ≤ ⊥, from sdiff_eq_self_iff_disjoint @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := sdiff_self lemma diff_diff_right_self (s t : set α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s := sdiff_sdiff_eq_self h lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) := iff.rfl lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} : s ∈ t \ {∅} ↔ (s ∈ t ∧ s.nonempty) := mem_diff_singleton.trans $ iff.rfl.and ne_empty_iff_nonempty lemma union_eq_diff_union_diff_union_inter (s t : set α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf /-! ### Symmetric difference -/ lemma mem_symm_diff : a ∈ s ∆ t ↔ a ∈ s ∧ a ∉ t ∨ a ∈ t ∧ a ∉ s := iff.rfl lemma symm_diff_subset_union : s ∆ t ⊆ s ∪ t := @symm_diff_le_sup (set α) _ _ _ lemma inter_symm_diff_distrib_left (s t u : set α) : s ∩ t ∆ u = (s ∩ t) ∆ (s ∩ u) := inf_symm_diff_distrib_left _ _ _ lemma inter_symm_diff_distrib_right (s t u : set α) : s ∆ t ∩ u = (s ∩ u) ∆ (t ∩ u) := inf_symm_diff_distrib_right _ _ _ /-! ### Powerset -/ /-- `𝒫 s = set.powerset s` is the set of all subsets of `s`. -/ def powerset (s : set α) : set (set α) := {t | t ⊆ s} prefix `𝒫`:100 := powerset theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ 𝒫 s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ 𝒫 s) : x ⊆ s := h @[simp] theorem mem_powerset_iff (x s : set α) : x ∈ 𝒫 s ↔ x ⊆ s := iff.rfl theorem powerset_inter (s t : set α) : 𝒫 (s ∩ t) = 𝒫 s ∩ 𝒫 t := ext $ λ u, subset_inter_iff @[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t := ⟨λ h, h (subset.refl s), λ h u hu, subset.trans hu h⟩ theorem monotone_powerset : monotone (powerset : set α → set (set α)) := λ s t, powerset_mono.2 @[simp] theorem powerset_nonempty : (𝒫 s).nonempty := ⟨∅, empty_subset s⟩ @[simp] theorem powerset_empty : 𝒫 (∅ : set α) = {∅} := ext $ λ s, subset_empty_iff @[simp] theorem powerset_univ : 𝒫 (univ : set α) = univ := eq_univ_of_forall subset_univ /-! ### If-then-else for sets -/ /-- `ite` for sets: `set.ite t s s' ∩ t = s ∩ t`, `set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`. Defined as `s ∩ t ∪ s' \ t`. -/ protected def ite (t s s' : set α) : set α := s ∩ t ∪ s' \ t @[simp] lemma ite_inter_self (t s s' : set α) : t.ite s s' ∩ t = s ∩ t := by rw [set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty] @[simp] lemma ite_compl (t s s' : set α) : tᶜ.ite s s' = t.ite s' s := by rw [set.ite, set.ite, diff_compl, union_comm, diff_eq] @[simp] lemma ite_inter_compl_self (t s s' : set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ := by rw [← ite_compl, ite_inter_self] @[simp] lemma ite_diff_self (t s s' : set α) : t.ite s s' \ t = s' \ t := ite_inter_compl_self t s s' @[simp] lemma ite_same (t s : set α) : t.ite s s = s := inter_union_diff _ _ @[simp] lemma ite_left (s t : set α) : s.ite s t = s ∪ t := by simp [set.ite] @[simp] lemma ite_right (s t : set α) : s.ite t s = t ∩ s := by simp [set.ite] @[simp] lemma ite_empty (s s' : set α) : set.ite ∅ s s' = s' := by simp [set.ite] @[simp] lemma ite_univ (s s' : set α) : set.ite univ s s' = s := by simp [set.ite] @[simp] lemma ite_empty_left (t s : set α) : t.ite ∅ s = s \ t := by simp [set.ite] @[simp] lemma ite_empty_right (t s : set α) : t.ite s ∅ = s ∩ t := by simp [set.ite] lemma ite_mono (t : set α) {s₁ s₁' s₂ s₂' : set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') : t.ite s₁ s₁' ⊆ t.ite s₂ s₂' := union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h') lemma ite_subset_union (t s s' : set α) : t.ite s s' ⊆ s ∪ s' := union_subset_union (inter_subset_left _ _) (diff_subset _ _) lemma inter_subset_ite (t s s' : set α) : s ∩ s' ⊆ t.ite s s' := ite_same t (s ∩ s') ▸ ite_mono _ (inter_subset_left _ _) (inter_subset_right _ _) lemma ite_inter_inter (t s₁ s₂ s₁' s₂' : set α) : t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' := by { ext x, simp only [set.ite, set.mem_inter_eq, set.mem_diff, set.mem_union_eq], itauto } lemma ite_inter (t s₁ s₂ s : set α) : t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s := by rw [ite_inter_inter, ite_same] lemma ite_inter_of_inter_eq (t : set α) {s₁ s₂ s : set α} (h : s₁ ∩ s = s₂ ∩ s) : t.ite s₁ s₂ ∩ s = s₁ ∩ s := by rw [← ite_inter, ← h, ite_same] lemma subset_ite {t s s' u : set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' := begin simp only [subset_def, ← forall_and_distrib], refine forall_congr (λ x, _), by_cases hx : x ∈ t; simp [*, set.ite] end /-! ### Inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl lemma preimage_congr {f g : α → β} {s : set β} (h : ∀ (x : α), f x = g x) : f ⁻¹' s = g ⁻¹' s := by { congr' with x, apply_assumption } theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _ @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' sᶜ = (f ⁻¹' s)ᶜ := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_ite (f : α → β) (s t₁ t₂ : set β) : f ⁻¹' (s.ite t₁ t₂) = (f ⁻¹' s).ite (f ⁻¹' t₁) (f ⁻¹' t₂) := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl @[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl @[simp] theorem preimage_id' {s : set α} : (λ x, x) ⁻¹' s = s := rfl @[simp] theorem preimage_const_of_mem {b : β} {s : set β} (h : b ∈ s) : (λ (x : α), b) ⁻¹' s = univ := eq_univ_of_forall $ λ x, h @[simp] theorem preimage_const_of_not_mem {b : β} {s : set β} (h : b ∉ s) : (λ (x : α), b) ⁻¹' s = ∅ := eq_empty_of_subset_empty $ λ x hx, h hx theorem preimage_const (b : β) (s : set β) [decidable (b ∈ s)] : (λ (x : α), b) ⁻¹' s = if b ∈ s then univ else ∅ := by { split_ifs with hb hb, exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] } theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl lemma preimage_preimage {g : β → γ} {f : α → β} {s : set γ} : f ⁻¹' (g ⁻¹' s) = (λ x, g (f x)) ⁻¹' s := preimage_comp.symm theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by { rw [s_eq], simp }, assume h, ext $ λ ⟨x, hx⟩, by simp [h]⟩ lemma nonempty_of_nonempty_preimage {s : set β} {f : α → β} (hf : (f ⁻¹' s).nonempty) : s.nonempty := let ⟨x, hx⟩ := hf in ⟨f x, hx⟩ end preimage /-! ### Image of a set under a function -/ section image /-- The image of `s : set α` by `f : α → β`, written `f '' s`, is the set of `y : β` such that `f x = y` for some `x ∈ s`. -/ def image (f : α → β) (s : set α) : set β := {y | ∃ x, x ∈ s ∧ f x = y} infix ` '' `:80 := image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl lemma image_eta (f : α → β) : f '' s = (λ x, f x) '' s := rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem _root_.function.injective.mem_set_image {f : α → β} (hf : injective f) {s : set α} {a : α} : f a ∈ f '' s ↔ a ∈ s := ⟨λ ⟨b, hb, eq⟩, (hf eq) ▸ hb, mem_image_of_mem f⟩ theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := by simp theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := ball_image_iff.2 h theorem bex_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∃ y ∈ f '' s, p y) ↔ (∃ x ∈ s, p (f x)) := by simp theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /-- A common special case of `image_congr` -/ lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s := image_congr (λx _, h x) theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s := (image_comp g f s).symm lemma image_comm {β'} {f : β → γ} {g : α → β} {f' : α → β'} {g' : β' → γ} (h_comm : ∀ a, f (g a) = g' (f' a)) : (s.image g).image f = (s.image f').image g' := by simp_rw [image_image, h_comm] lemma _root_.function.semiconj.set_image {f : α → β} {ga : α → α} {gb : β → β} (h : function.semiconj f ga gb) : function.semiconj (image f) (image ga) (image gb) := λ s, image_comm h lemma _root_.function.commute.set_image {f g : α → α} (h : function.commute f g) : function.commute (image f) (image g) := h.set_image /-- Image is monotone with respect to `⊆`. See `set.monotone_image` for the statement in terms of `≤`. -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by { simp only [subset_def, mem_image_eq], exact λ x, λ ⟨w, h1, h2⟩, ⟨w, h h1, h2⟩ } theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := ext $ λ x, ⟨by rintro ⟨a, h|h, rfl⟩; [left, right]; exact ⟨_, h, rfl⟩, by rintro (⟨a, h, rfl⟩ | ⟨a, h, rfl⟩); refine ⟨_, _, rfl⟩; [left, right]; exact h⟩ @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := by { ext, simp } lemma image_inter_subset (f : α → β) (s t : set α) : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := subset_inter (image_subset _ $ inter_subset_left _ _) (image_subset _ $ inter_subset_right _ _) theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (image_inter_subset _ _ _) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by { simpa [image] } @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := by { ext, simp [image, eq_comm] } @[simp] theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} := ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _, λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩ @[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ := by { simp only [eq_empty_iff_forall_not_mem], exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ } lemma preimage_compl_eq_image_compl [boolean_algebra α] (S : set α) : compl ⁻¹' S = compl '' S := set.ext (λ x, ⟨λ h, ⟨xᶜ,h, compl_compl x⟩, λ h, exists.elim h (λ y hy, (compl_eq_comm.mp hy.2).symm.subst hy.1)⟩) theorem mem_compl_image [boolean_algebra α] (t : α) (S : set α) : t ∈ compl '' S ↔ tᶜ ∈ S := by simp [←preimage_compl_eq_image_compl] /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := by { ext, simp } theorem image_id (s : set α) : id '' s = s := by simp theorem compl_compl_image [boolean_algebra α] (S : set α) : compl '' (compl '' S) = S := by rw [←image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := by { ext, simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] } theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} := by simp only [image_insert_eq, image_singleton] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' sᶜ ⊆ (f '' s)ᶜ := disjoint.subset_compl_left $ by simp [disjoint, image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : (f '' s)ᶜ ⊆ f '' sᶜ := compl_subset_iff_union.2 $ by { rw ← image_union, simp [image_univ_of_surjective H] } theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' sᶜ = (f '' s)ᶜ := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) theorem subset_image_diff (f : α → β) (s t : set α) : f '' s \ f '' t ⊆ f '' (s \ t) := begin rw [diff_subset_iff, ← image_union, union_diff_self], exact image_subset f (subset_union_right t s) end theorem image_diff {f : α → β} (hf : injective f) (s t : set α) : f '' (s \ t) = f '' s \ f '' t := subset.antisymm (subset.trans (image_inter_subset _ _ _) $ inter_subset_inter_right _ $ image_compl_subset hf) (subset_image_diff f s t) lemma nonempty.image (f : α → β) {s : set α} : s.nonempty → (f '' s).nonempty | ⟨x, hx⟩ := ⟨f x, mem_image_of_mem f hx⟩ lemma nonempty.of_image {f : α → β} {s : set α} : (f '' s).nonempty → s.nonempty | ⟨y, x, hx, _⟩ := ⟨x, hx⟩ @[simp] lemma nonempty_image_iff {f : α → β} {s : set α} : (f '' s).nonempty ↔ s.nonempty := ⟨nonempty.of_image, λ h, h.image f⟩ lemma nonempty.preimage {s : set β} (hs : s.nonempty) {f : α → β} (hf : surjective f) : (f ⁻¹' s).nonempty := let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf y in ⟨x, mem_preimage.2 $ hx.symm ▸ hy⟩ instance (f : α → β) (s : set α) [nonempty s] : nonempty (f '' s) := (set.nonempty.image f nonempty_of_nonempty_subtype).to_subtype /-- image and preimage are a Galois connection -/ @[simp] theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 subset.rfl theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} (s : set β) (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := iff.intro (assume eq, by rw [← image_preimage_eq s hf, ← image_preimage_eq t hf, eq]) (assume eq, eq ▸ rfl) lemma image_inter_preimage (f : α → β) (s : set α) (t : set β) : f '' (s ∩ f ⁻¹' t) = f '' s ∩ t := begin apply subset.antisymm, { calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ (f '' (f⁻¹' t)) : image_inter_subset _ _ _ ... ⊆ f '' s ∩ t : inter_subset_inter_right _ (image_preimage_subset f t) }, { rintros _ ⟨⟨x, h', rfl⟩, h⟩, exact ⟨x, ⟨h', h⟩, rfl⟩ } end lemma image_preimage_inter (f : α → β) (s : set α) (t : set β) : f '' (f ⁻¹' t ∩ s) = t ∩ f '' s := by simp only [inter_comm, image_inter_preimage] @[simp] lemma image_inter_nonempty_iff {f : α → β} {s : set α} {t : set β} : (f '' s ∩ t).nonempty ↔ (s ∩ f ⁻¹' t).nonempty := by rw [←image_inter_preimage, nonempty_image_iff] lemma image_diff_preimage {f : α → β} {s : set α} {t : set β} : f '' (s \ f ⁻¹' t) = f '' s \ t := by simp_rw [diff_eq, ← preimage_compl, image_inter_preimage] theorem compl_image : image (compl : set α → set α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {p : set α → Prop} : compl '' {s | p s} = {s | p sᶜ} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) lemma exists_image_iff (f : α → β) (x : set α) (P : β → Prop) : (∃ (a : f '' x), P a) ↔ ∃ (a : x), P (f a) := ⟨λ ⟨a, h⟩, ⟨⟨_, a.prop.some_spec.1⟩, a.prop.some_spec.2.symm ▸ h⟩, λ ⟨a, h⟩, ⟨⟨_, _, a.prop, rfl⟩, h⟩⟩ /-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/ def image_factorization (f : α → β) (s : set α) : s → f '' s := λ p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : α → β} {s : set α} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ λ p, rfl lemma surjective_onto_image {f : α → β} {s : set α} : surjective (image_factorization f s) := λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ /-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect. -/ lemma image_perm {s : set α} {σ : equiv.perm α} (hs : {a : α | σ a ≠ a} ⊆ s) : σ '' s = s := begin ext i, obtain hi | hi := eq_or_ne (σ i) i, { refine ⟨_, λ h, ⟨i, h, hi⟩⟩, rintro ⟨j, hj, h⟩, rwa σ.injective (hi.trans h.symm) }, { refine iff_of_true ⟨σ.symm i, hs $ λ h, hi _, σ.apply_symm_apply _⟩ (hs hi), convert congr_arg σ h; exact (σ.apply_symm_apply _).symm } end end image /-! ### Subsingleton -/ /-- A set `s` is a `subsingleton` if it has at most one element. -/ protected def subsingleton (s : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y lemma subsingleton.anti (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton := λ x hx y hy, ht (hst hx) (hst hy) lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) : s = {x} := ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩ @[simp] lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim @[simp] lemma subsingleton_singleton {a} : ({a} : set α).subsingleton := λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl lemma subsingleton_of_subset_singleton (h : s ⊆ {a}) : s.subsingleton := subsingleton_singleton.anti h lemma subsingleton_of_forall_eq (a : α) (h : ∀ b ∈ s, b = a) : s.subsingleton := λ b hb c hc, (h _ hb).trans (h _ hc).symm lemma subsingleton_iff_singleton {x} (hx : x ∈ s) : s.subsingleton ↔ s = {x} := ⟨λ h, h.eq_singleton_of_mem hx, λ h,h.symm ▸ subsingleton_singleton⟩ lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) : s = ∅ ∨ ∃ x, s = {x} := s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩) lemma subsingleton.induction_on {p : set α → Prop} (hs : s.subsingleton) (he : p ∅) (h₁ : ∀ x, p {x}) : p s := by { rcases hs.eq_empty_or_singleton with rfl|⟨x, rfl⟩, exacts [he, h₁ _] } lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton := λ x hx y hy, subsingleton.elim x y lemma subsingleton_of_univ_subsingleton (h : (univ : set α).subsingleton) : subsingleton α := ⟨λ a b, h (mem_univ a) (mem_univ b)⟩ @[simp] lemma subsingleton_univ_iff : (univ : set α).subsingleton ↔ subsingleton α := ⟨subsingleton_of_univ_subsingleton, λ h, @subsingleton_univ _ h⟩ lemma subsingleton_of_subsingleton [subsingleton α] {s : set α} : set.subsingleton s := subsingleton_univ.anti (subset_univ s) lemma subsingleton_is_top (α : Type*) [partial_order α] : set.subsingleton {x : α | is_top x} := λ x hx y hy, hx.is_max.eq_of_le (hy x) lemma subsingleton_is_bot (α : Type*) [partial_order α] : set.subsingleton {x : α | is_bot x} := λ x hx y hy, hx.is_min.eq_of_ge (hy x) lemma exists_eq_singleton_iff_nonempty_subsingleton : (∃ a : α, s = {a}) ↔ s.nonempty ∧ s.subsingleton := begin refine ⟨_, λ h, _⟩, { rintros ⟨a, rfl⟩, exact ⟨singleton_nonempty a, subsingleton_singleton⟩ }, { exact h.2.eq_empty_or_singleton.resolve_left h.1.ne_empty }, end /-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/ @[simp, norm_cast] lemma subsingleton_coe (s : set α) : subsingleton s ↔ s.subsingleton := begin split, { refine λ h, (λ a ha b hb, _), exact set_coe.ext_iff.2 (@subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) }, { exact λ h, subsingleton.intro (λ a b, set_coe.ext (h a.property b.property)) } end /-- The `coe_sort` of a set `s` in a subsingleton type is a subsingleton. For the corresponding result for `subtype`, see `subtype.subsingleton`. -/ instance subsingleton_coe_of_subsingleton [subsingleton α] {s : set α} : subsingleton s := by { rw [s.subsingleton_coe], exact subsingleton_of_subsingleton } /-- The image of a subsingleton is a subsingleton. -/ lemma subsingleton.image (hs : s.subsingleton) (f : α → β) : (f '' s).subsingleton := λ _ ⟨x, hx, Hx⟩ _ ⟨y, hy, Hy⟩, Hx ▸ Hy ▸ congr_arg f (hs hx hy) /-- The preimage of a subsingleton under an injective map is a subsingleton. -/ theorem subsingleton.preimage {s : set β} (hs : s.subsingleton) {f : α → β} (hf : function.injective f) : (f ⁻¹' s).subsingleton := λ a ha b hb, hf $ hs ha hb /-- If the image of a set under an injective map is a subsingleton, the set is a subsingleton. -/ theorem subsingleton_of_image {α β : Type*} {f : α → β} (hf : function.injective f) (s : set α) (hs : (f '' s).subsingleton) : s.subsingleton := (hs.preimage hf).anti $ subset_preimage_image _ _ /-- If the preimage of a set under an surjective map is a subsingleton, the set is a subsingleton. -/ theorem subsingleton_of_preimage {α β : Type*} {f : α → β} (hf : function.surjective f) (s : set β) (hs : (f ⁻¹' s).subsingleton) : s.subsingleton := λ fx hx fy hy, by { rcases ⟨hf fx, hf fy⟩ with ⟨⟨x, rfl⟩, ⟨y, rfl⟩⟩, exact congr_arg f (hs hx hy) } /-! ### Nontrivial -/ /-- A set `s` is `nontrivial` if it has at least two distinct elements. -/ protected def nontrivial (s : set α) : Prop := ∃ x y ∈ s, x ≠ y lemma nontrivial_of_mem_mem_ne {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : s.nontrivial := ⟨x, hx, y, hy, hxy⟩ /-- Extract witnesses from s.nontrivial. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the classical.choice axiom. -/ protected noncomputable def nontrivial.some (hs : s.nontrivial) : α × α := (hs.some, hs.some_spec.some_spec.some) protected lemma nontrivial.some_fst_mem (hs : s.nontrivial) : hs.some.fst ∈ s := hs.some_spec.some protected lemma nontrivial.some_snd_mem (hs : s.nontrivial) : hs.some.snd ∈ s := hs.some_spec.some_spec.some_spec.some protected lemma nontrivial.some_fst_ne_some_snd (hs : s.nontrivial) : hs.some.fst ≠ hs.some.snd := hs.some_spec.some_spec.some_spec.some_spec lemma nontrivial.mono (hs : s.nontrivial) (hst : s ⊆ t) : t.nontrivial := let ⟨x, hx, y, hy, hxy⟩ := hs in ⟨x, hst hx, y, hst hy, hxy⟩ lemma nontrivial_pair {x y} (hxy : x ≠ y) : ({x, y} : set α).nontrivial := ⟨x, mem_insert _ _, y, mem_insert_of_mem _ (mem_singleton _), hxy⟩ lemma nontrivial_of_pair_subset {x y} (hxy : x ≠ y) (h : {x, y} ⊆ s) : s.nontrivial := (nontrivial_pair hxy).mono h lemma nontrivial.pair_subset (hs : s.nontrivial) : ∃ x y (hab : x ≠ y), {x, y} ⊆ s := let ⟨x, hx, y, hy, hxy⟩ := hs in ⟨x, y, hxy, insert_subset.2 ⟨hx, (singleton_subset_iff.2 hy)⟩⟩ lemma nontrivial_iff_pair_subset : s.nontrivial ↔ ∃ x y (hxy : x ≠ y), {x, y} ⊆ s := ⟨nontrivial.pair_subset, λ H, let ⟨x, y, hxy, h⟩ := H in nontrivial_of_pair_subset hxy h⟩ lemma nontrivial_of_exists_ne {x} (hx : x ∈ s) (h : ∃ y ∈ s, y ≠ x) : s.nontrivial := let ⟨y, hy, hyx⟩ := h in ⟨y, hy, x, hx, hyx⟩ lemma nontrivial.exists_ne {z} (hs : s.nontrivial) : ∃ x ∈ s, x ≠ z := begin by_contra H, push_neg at H, rcases hs with ⟨x, hx, y, hy, hxy⟩, rw [H x hx, H y hy] at hxy, exact hxy rfl end lemma nontrivial_iff_exists_ne {x} (hx : x ∈ s) : s.nontrivial ↔ ∃ y ∈ s, y ≠ x := ⟨λ H, H.exists_ne, nontrivial_of_exists_ne hx⟩ lemma nontrivial_of_lt [preorder α] {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x < y) : s.nontrivial := ⟨x, hx, y, hy, ne_of_lt hxy⟩ lemma nontrivial_of_exists_lt [preorder α] (H : ∃ x y ∈ s, x < y) : s.nontrivial := let ⟨x, hx, y, hy, hxy⟩ := H in nontrivial_of_lt hx hy hxy lemma nontrivial.exists_lt [linear_order α] (hs : s.nontrivial) : ∃ x y ∈ s, x < y := let ⟨x, hx, y, hy, hxy⟩ := hs in or.elim (lt_or_gt_of_ne hxy) (λ H, ⟨x, hx, y, hy, H⟩) (λ H, ⟨y, hy, x, hx, H⟩) lemma nontrivial.iff_exists_lt [linear_order α] : s.nontrivial ↔ ∃ x y ∈ s, x < y := ⟨nontrivial.exists_lt, nontrivial_of_exists_lt⟩ lemma nontrivial.nonempty (hs : s.nontrivial) : s.nonempty := let ⟨x, hx, _⟩ := hs in ⟨x, hx⟩ lemma nontrivial.ne_empty (hs : s.nontrivial) : s ≠ ∅ := hs.nonempty.ne_empty lemma nontrivial.not_subset_empty (hs : s.nontrivial) : ¬ s ⊆ ∅ := hs.nonempty.not_subset_empty @[simp] lemma not_nontrivial_empty : ¬ (∅ : set α).nontrivial := λ h, h.ne_empty rfl @[simp] lemma not_nontrivial_singleton {x} : ¬ ({x} : set α).nontrivial := λ H, begin rw nontrivial_iff_exists_ne (mem_singleton x) at H, exact let ⟨y, hy, hya⟩ := H in hya (mem_singleton_iff.1 hy) end lemma nontrivial.ne_singleton {x} (hs : s.nontrivial) : s ≠ {x} := λ H, by { rw H at hs, exact not_nontrivial_singleton hs } lemma nontrivial.not_subset_singleton {x} (hs : s.nontrivial) : ¬ s ⊆ {x} := (not_congr subset_singleton_iff_eq).2 (not_or hs.ne_empty hs.ne_singleton) lemma nontrivial_univ [nontrivial α] : (univ : set α).nontrivial := let ⟨x, y, hxy⟩ := exists_pair_ne α in ⟨x, mem_univ _, y, mem_univ _, hxy⟩ lemma nontrivial_of_univ_nontrivial (h : (univ : set α).nontrivial) : nontrivial α := let ⟨x, _, y, _, hxy⟩ := h in ⟨⟨x, y, hxy⟩⟩ @[simp] lemma nontrivial_univ_iff : (univ : set α).nontrivial ↔ nontrivial α := ⟨nontrivial_of_univ_nontrivial, λ h, @nontrivial_univ _ h⟩ lemma nontrivial_of_nontrivial (hs : s.nontrivial) : nontrivial α := let ⟨x, _, y, _, hxy⟩ := hs in ⟨⟨x, y, hxy⟩⟩ /-- `s`, coerced to a type, is a nontrivial type if and only if `s` is a nontrivial set. -/ @[simp, norm_cast] lemma nontrivial_coe (s : set α) : nontrivial s ↔ s.nontrivial := by simp_rw [← nontrivial_univ_iff, set.nontrivial, mem_univ, exists_true_left, set_coe.exists, subtype.mk_eq_mk] /-- A type with a set `s` whose `coe_sort` is a nontrivial type is nontrivial. For the corresponding result for `subtype`, see `subtype.nontrivial_iff_exists_ne`. -/ lemma nontrivial_of_nontrivial_coe (hs : nontrivial s) : nontrivial α := by { rw [s.nontrivial_coe] at hs, exact nontrivial_of_nontrivial hs } theorem nontrivial_mono {α : Type*} {s t : set α} (hst : s ⊆ t) (hs : nontrivial s) : nontrivial t := (nontrivial_coe _).2 $ (s.nontrivial_coe.1 hs).mono hst /-- The preimage of a nontrivial set under a surjective map is nontrivial. -/ theorem nontrivial.preimage {s : set β} (hs : s.nontrivial) {f : α → β} (hf : function.surjective f) : (f ⁻¹' s).nontrivial := begin rcases hs with ⟨fx, hx, fy, hy, hxy⟩, rcases ⟨hf fx, hf fy⟩ with ⟨⟨x, rfl⟩, ⟨y, rfl⟩⟩, exact ⟨x, hx, y, hy, mt (congr_arg f) hxy⟩ end /-- The image of a nontrivial set under an injective map is nontrivial. -/ theorem nontrivial.image (hs : s.nontrivial) {f : α → β} (hf : function.injective f) : (f '' s).nontrivial := let ⟨x, hx, y, hy, hxy⟩ := hs in ⟨f x, mem_image_of_mem f hx, f y, mem_image_of_mem f hy, hf.ne hxy⟩ /-- If the image of a set is nontrivial, the set is nontrivial. -/ lemma nontrivial_of_image (f : α → β) (s : set α) (hs : (f '' s).nontrivial) : s.nontrivial := let ⟨_, ⟨x, hx, rfl⟩, _, ⟨y, hy, rfl⟩, hxy⟩ := hs in ⟨x, hx, y, hy, mt (congr_arg f) hxy⟩ /-- If the preimage of a set under an injective map is nontrivial, the set is nontrivial. -/ lemma nontrivial_of_preimage {f : α → β} (hf : function.injective f) (s : set β) (hs : (f ⁻¹' s).nontrivial) : s.nontrivial := (hs.image hf).mono $ image_preimage_subset _ _ @[simp] lemma not_subsingleton_iff : ¬ s.subsingleton ↔ s.nontrivial := by simp_rw [set.subsingleton, set.nontrivial, not_forall] @[simp] lemma not_nontrivial_iff : ¬ s.nontrivial ↔ s.subsingleton := iff.not_left not_subsingleton_iff.symm theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section preorder variables [preorder α] [preorder β] (f : α → β) /-! ### Monotonicity on singletons -/ protected lemma subsingleton.monotone_on (h : s.subsingleton) : monotone_on f s := λ a ha b hb _, (congr_arg _ (h ha hb)).le protected lemma subsingleton.antitone_on (h : s.subsingleton) : antitone_on f s := λ a ha b hb _, (congr_arg _ (h hb ha)).le protected lemma subsingleton.strict_mono_on (h : s.subsingleton) : strict_mono_on f s := λ a ha b hb hlt, (hlt.ne (h ha hb)).elim protected lemma subsingleton.strict_anti_on (h : s.subsingleton) : strict_anti_on f s := λ a ha b hb hlt, (hlt.ne (h ha hb)).elim @[simp] lemma monotone_on_singleton : monotone_on f {a} := subsingleton_singleton.monotone_on f @[simp] lemma antitone_on_singleton : antitone_on f {a} := subsingleton_singleton.antitone_on f @[simp] lemma strict_mono_on_singleton : strict_mono_on f {a} := subsingleton_singleton.strict_mono_on f @[simp] lemma strict_anti_on_singleton : strict_anti_on f {a} := subsingleton_singleton.strict_anti_on f end preorder /-! ### Lemmas about range of a function. -/ section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl @[simp] theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := by simp theorem forall_subtype_range_iff {p : range f → Prop} : (∀ a : range f, p a) ↔ ∀ i, p ⟨f i, mem_range_self _⟩ := ⟨λ H i, H _, λ H ⟨y, i, hi⟩, by { subst hi, apply H }⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := by simp lemma exists_range_iff' {p : α → Prop} : (∃ a, a ∈ range f ∧ p a) ↔ ∃ i, p (f i) := by simpa only [exists_prop] using exists_range_iff lemma exists_subtype_range_iff {p : range f → Prop} : (∃ a : range f, p a) ↔ ∃ i, p ⟨f i, mem_range_self _⟩ := ⟨λ ⟨⟨a, i, hi⟩, ha⟩, by { subst a, exact ⟨i, ha⟩}, λ ⟨i, hi⟩, ⟨_, hi⟩⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall alias range_iff_surjective ↔ _ _root_.function.surjective.range_eq @[simp] theorem image_univ {f : α → β} : f '' univ = range f := by { ext, simp [image, range] } theorem image_subset_range (f : α → β) (s) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem mem_range_of_mem_image (f : α → β) (s) {x : β} (h : x ∈ f '' s) : x ∈ range f := image_subset_range f s h lemma nonempty.preimage' {s : set β} (hs : s.nonempty) {f : α → β} (hf : s ⊆ set.range f) : (f ⁻¹' s).nonempty := let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf hy in ⟨x, set.mem_preimage.2 $ hx.symm ▸ hy⟩ theorem range_comp (g : α → β) (f : ι → α) : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff theorem range_eq_iff (f : α → β) (s : set β) : range f = s ↔ (∀ a, f a ∈ s) ∧ ∀ b ∈ s, ∃ a, f a = b := by { rw ←range_subset_iff, exact le_antisymm_iff } lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g := by rw range_comp; apply image_subset_range lemma range_nonempty_iff_nonempty : (range f).nonempty ↔ nonempty ι := ⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩ lemma range_nonempty [h : nonempty ι] (f : ι → α) : (range f).nonempty := range_nonempty_iff_nonempty.2 h @[simp] lemma range_eq_empty_iff {f : ι → α} : range f = ∅ ↔ is_empty ι := by rw [← not_nonempty_iff, ← range_nonempty_iff_nonempty, not_nonempty_iff_eq_empty] lemma range_eq_empty [is_empty ι] (f : ι → α) : range f = ∅ := range_eq_empty_iff.2 ‹_› instance [nonempty ι] (f : ι → α) : nonempty (range f) := (range_nonempty f).to_subtype @[simp] lemma image_union_image_compl_eq_range (f : α → β) : (f '' s) ∪ (f '' sᶜ) = range f := by rw [← image_union, ← image_univ, ← union_compl_self] lemma insert_image_compl_eq_range (f : α → β) (x : α) : insert (f x) (f '' {x}ᶜ) = range f := begin ext y, rw [mem_range, mem_insert_iff, mem_image], split, { rintro (h | ⟨x', hx', h⟩), { exact ⟨x, h.symm⟩ }, { exact ⟨x', h⟩ } }, { rintro ⟨x', h⟩, by_cases hx : x' = x, { left, rw [← h, hx] }, { right, refine ⟨_, _, h⟩, rw mem_compl_singleton_iff, exact hx } } end theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] lemma image_preimage_eq_iff {f : α → β} {s : set β} : f '' (f ⁻¹' s) = s ↔ s ⊆ range f := ⟨by { intro h, rw [← h], apply image_subset_range }, image_preimage_eq_of_subset⟩ lemma subset_range_iff_exists_image_eq {f : α → β} {s : set β} : s ⊆ range f ↔ ∃ t, f '' t = s := ⟨λ h, ⟨_, image_preimage_eq_iff.2 h⟩, λ ⟨t, ht⟩, ht ▸ image_subset_range _ _⟩ lemma range_image (f : α → β) : range (image f) = 𝒫 (range f) := ext $ λ s, subset_range_iff_exists_image_eq.symm lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end @[simp] theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ @[simp] theorem preimage_range_inter {f : α → β} {s : set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s := by rw [inter_comm, preimage_inter_range] theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem range_id' : range (λ (x : α), x) = univ := range_id @[simp] theorem _root_.prod.range_fst [nonempty β] : range (prod.fst : α × β → α) = univ := prod.fst_surjective.range_eq @[simp] theorem _root_.prod.range_snd [nonempty α] : range (prod.snd : α × β → β) = univ := prod.snd_surjective.range_eq @[simp] theorem range_eval {ι : Type*} {α : ι → Sort*} [Π i, nonempty (α i)] (i : ι) : range (eval i : (Π i, α i) → α i) = univ := (surjective_eval i).range_eq theorem is_compl_range_inl_range_inr : is_compl (range $ @sum.inl α β) (range sum.inr) := ⟨by { rintro y ⟨⟨x₁, rfl⟩, ⟨x₂, _⟩⟩, cc }, by { rintro (x|y) -; [left, right]; exact mem_range_self _ }⟩ @[simp] theorem range_inl_union_range_inr : range (sum.inl : α → α ⊕ β) ∪ range sum.inr = univ := is_compl_range_inl_range_inr.sup_eq_top @[simp] theorem range_inl_inter_range_inr : range (sum.inl : α → α ⊕ β) ∩ range sum.inr = ∅ := is_compl_range_inl_range_inr.inf_eq_bot @[simp] theorem range_inr_union_range_inl : range (sum.inr : β → α ⊕ β) ∪ range sum.inl = univ := is_compl_range_inl_range_inr.symm.sup_eq_top @[simp] theorem range_inr_inter_range_inl : range (sum.inr : β → α ⊕ β) ∩ range sum.inl = ∅ := is_compl_range_inl_range_inr.symm.inf_eq_bot @[simp] theorem preimage_inl_image_inr (s : set β) : sum.inl ⁻¹' (@sum.inr α β '' s) = ∅ := by { ext, simp } @[simp] theorem preimage_inr_image_inl (s : set α) : sum.inr ⁻¹' (@sum.inl α β '' s) = ∅ := by { ext, simp } @[simp] theorem preimage_inl_range_inr : sum.inl ⁻¹' range (sum.inr : β → α ⊕ β) = ∅ := by rw [← image_univ, preimage_inl_image_inr] @[simp] theorem preimage_inr_range_inl : sum.inr ⁻¹' range (sum.inl : α → α ⊕ β) = ∅ := by rw [← image_univ, preimage_inr_image_inl] @[simp] lemma compl_range_inl : (range (sum.inl : α → α ⊕ β))ᶜ = range (sum.inr : β → α ⊕ β) := is_compl.compl_eq is_compl_range_inl_range_inr @[simp] lemma compl_range_inr : (range (sum.inr : β → α ⊕ β))ᶜ = range (sum.inl : α → α ⊕ β) := is_compl.compl_eq is_compl_range_inl_range_inr.symm @[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ := (surjective_quot_mk r).range_eq instance can_lift [can_lift α β] : can_lift (set α) (set β) := { coe := λ s, can_lift.coe '' s, cond := λ s, ∀ x ∈ s, can_lift.cond β x, prf := λ s hs, subset_range_iff_exists_image_eq.mp (λ x hx, can_lift.prf _ (hs x hx)) } @[simp] theorem range_quotient_mk [setoid α] : range (λx : α, ⟦x⟧) = univ := range_quot_mk _ lemma range_const_subset {c : α} : range (λ x : ι, c) ⊆ {c} := range_subset_iff.2 $ λ x, rfl @[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c} | ⟨x⟩ c := subset.antisymm range_const_subset $ assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x lemma range_subtype_map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀ x, p x → q (f x)) : range (subtype.map f h) = coe ⁻¹' (f '' {x | p x}) := begin ext ⟨x, hx⟩, simp_rw [mem_preimage, mem_range, mem_image, subtype.exists, subtype.map, subtype.coe_mk, mem_set_of, exists_prop] end lemma image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem preimage_singleton_nonempty {f : α → β} {y : β} : (f ⁻¹' {y}).nonempty ↔ y ∈ range f := iff.rfl theorem preimage_singleton_eq_empty {f : α → β} {y : β} : f ⁻¹' {y} = ∅ ↔ y ∉ range f := not_nonempty_iff_eq_empty.symm.trans preimage_singleton_nonempty.not lemma range_subset_singleton {f : ι → α} {x : α} : range f ⊆ {x} ↔ f = const ι x := by simp [range_subset_iff, funext_iff, mem_singleton] lemma image_compl_preimage {f : α → β} {s : set β} : f '' ((f ⁻¹' s)ᶜ) = range f \ s := by rw [compl_eq_univ_diff, image_diff_preimage, image_univ] /-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/ def range_factorization (f : ι → β) : ι → range f := λ i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ι → β} : subtype.val ∘ range_factorization f = f := funext $ λ i, rfl @[simp] lemma range_factorization_coe (f : ι → β) (a : ι) : (range_factorization f a : β) = f a := rfl @[simp] lemma coe_comp_range_factorization (f : ι → β) : coe ∘ range_factorization f = f := rfl lemma surjective_onto_range : surjective (range_factorization f) := λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } @[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) : range (sum.elim f g) = range f ∪ range g := by simp [set.ext_iff, mem_range] lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} : range (if p then f else g) ⊆ range f ∪ range g := begin by_cases h : p, {rw if_pos h, exact subset_union_left _ _}, {rw if_neg h, exact subset_union_right _ _} end lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} : range (λ x, if p x then f x else g x) ⊆ range f ∪ range g := begin rw range_subset_iff, intro x, by_cases h : p x, simp [if_pos h, mem_union, mem_range_self], simp [if_neg h, mem_union, mem_range_self] end @[simp] lemma preimage_range (f : α → β) : f ⁻¹' (range f) = univ := eq_univ_of_forall mem_range_self /-- The range of a function from a `unique` type contains just the function applied to its single value. -/ lemma range_unique [h : unique ι] : range f = {f default} := begin ext x, rw mem_range, split, { rintros ⟨i, hi⟩, rw h.uniq i at hi, exact hi ▸ mem_singleton _ }, { exact λ h, ⟨default, h.symm⟩ } end lemma range_diff_image_subset (f : α → β) (s : set α) : range f \ f '' s ⊆ f '' sᶜ := λ y ⟨⟨x, h₁⟩, h₂⟩, ⟨x, λ h, h₂ ⟨x, h, h₁⟩, h₁⟩ lemma range_diff_image {f : α → β} (H : injective f) (s : set α) : range f \ f '' s = f '' sᶜ := subset.antisymm (range_diff_image_subset f s) $ λ y ⟨x, hx, hy⟩, hy ▸ ⟨mem_range_self _, λ ⟨x', hx', eq⟩, hx $ H eq ▸ hx'⟩ /-- We can use the axiom of choice to pick a preimage for every element of `range f`. -/ noncomputable def range_splitting (f : α → β) : range f → α := λ x, x.2.some -- This can not be a `@[simp]` lemma because the head of the left hand side is a variable. lemma apply_range_splitting (f : α → β) (x : range f) : f (range_splitting f x) = x := x.2.some_spec attribute [irreducible] range_splitting @[simp] lemma comp_range_splitting (f : α → β) : f ∘ range_splitting f = coe := by { ext, simp only [function.comp_app], apply apply_range_splitting, } -- When `f` is injective, see also `equiv.of_injective`. lemma left_inverse_range_splitting (f : α → β) : left_inverse (range_factorization f) (range_splitting f) := λ x, by { ext, simp only [range_factorization_coe], apply apply_range_splitting, } lemma range_splitting_injective (f : α → β) : injective (range_splitting f) := (left_inverse_range_splitting f).injective lemma right_inverse_range_splitting {f : α → β} (h : injective f) : right_inverse (range_factorization f) (range_splitting f) := (left_inverse_range_splitting f).right_inverse_of_injective $ λ x y hxy, h $ subtype.ext_iff.1 hxy lemma preimage_range_splitting {f : α → β} (hf : injective f) : preimage (range_splitting f) = image (range_factorization f) := (image_eq_preimage_of_inverse (right_inverse_range_splitting hf) (left_inverse_range_splitting f)).symm lemma is_compl_range_some_none (α : Type*) : is_compl (range (some : α → option α)) {none} := ⟨λ x ⟨⟨a, ha⟩, (hn : x = none)⟩, option.some_ne_none _ (ha.trans hn), λ x hx, option.cases_on x (or.inr rfl) (λ x, or.inl $ mem_range_self _)⟩ @[simp] lemma compl_range_some (α : Type*) : (range (some : α → option α))ᶜ = {none} := (is_compl_range_some_none α).compl_eq @[simp] lemma range_some_inter_none (α : Type*) : range (some : α → option α) ∩ {none} = ∅ := (is_compl_range_some_none α).inf_eq_bot @[simp] lemma range_some_union_none (α : Type*) : range (some : α → option α) ∪ {none} = univ := (is_compl_range_some_none α).sup_eq_top @[simp] lemma insert_none_range_some (α : Type*) : insert none (range (some : α → option α)) = univ := (is_compl_range_some_none α).symm.sup_eq_top end range end set open set namespace function variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β} lemma surjective.preimage_injective (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 lemma injective.preimage_image (hf : injective f) (s : set α) : f ⁻¹' (f '' s) = s := preimage_image_eq s hf lemma injective.preimage_surjective (hf : injective f) : surjective (preimage f) := by { intro s, use f '' s, rw hf.preimage_image } lemma injective.subsingleton_image_iff (hf : injective f) {s : set α} : (f '' s).subsingleton ↔ s.subsingleton := ⟨subsingleton_of_image hf s, λ h, h.image f⟩ lemma surjective.image_preimage (hf : surjective f) (s : set β) : f '' (f ⁻¹' s) = s := image_preimage_eq s hf lemma surjective.image_surjective (hf : surjective f) : surjective (image f) := by { intro s, use f ⁻¹' s, rw hf.image_preimage } lemma surjective.nonempty_preimage (hf : surjective f) {s : set β} : (f ⁻¹' s).nonempty ↔ s.nonempty := by rw [← nonempty_image_iff, hf.image_preimage] lemma injective.image_injective (hf : injective f) : injective (image f) := by { intros s t h, rw [←preimage_image_eq s hf, ←preimage_image_eq t hf, h] } lemma surjective.preimage_subset_preimage_iff {s t : set β} (hf : surjective f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := by { apply preimage_subset_preimage_iff, rw [hf.range_eq], apply subset_univ } lemma surjective.range_comp {ι' : Sort*} {f : ι → ι'} (hf : surjective f) (g : ι' → α) : range (g ∘ f) = range g := ext $ λ y, (@surjective.exists _ _ _ hf (λ x, g x = y)).symm lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f) (h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty := by rw [← ne_empty_iff_nonempty, ← h2, ← ne_empty_iff_nonempty, hf.ne_iff] lemma injective.mem_range_iff_exists_unique (hf : injective f) {b : β} : b ∈ range f ↔ ∃! a, f a = b := ⟨λ ⟨a, h⟩, ⟨a, h, λ a' ha, hf (ha.trans h.symm)⟩, exists_unique.exists⟩ lemma injective.exists_unique_of_mem_range (hf : injective f) {b : β} (hb : b ∈ range f) : ∃! a, f a = b := hf.mem_range_iff_exists_unique.mp hb theorem injective.compl_image_eq (hf : injective f) (s : set α) : (f '' s)ᶜ = f '' sᶜ ∪ (range f)ᶜ := begin ext y, rcases em (y ∈ range f) with ⟨x, rfl⟩|hx, { simp [hf.eq_iff] }, { rw [mem_range, not_exists] at hx, simp [hx] } end lemma left_inverse.image_image {g : β → α} (h : left_inverse g f) (s : set α) : g '' (f '' s) = s := by rw [← image_comp, h.comp_eq_id, image_id] lemma left_inverse.preimage_preimage {g : β → α} (h : left_inverse g f) (s : set α) : f ⁻¹' (g ⁻¹' s) = s := by rw [← preimage_comp, h.comp_eq_id, preimage_id] end function open function lemma option.injective_iff {α β} {f : option α → β} : injective f ↔ injective (f ∘ some) ∧ f none ∉ range (f ∘ some) := begin simp only [mem_range, not_exists, (∘)], refine ⟨λ hf, ⟨hf.comp (option.some_injective _), λ x, hf.ne $ option.some_ne_none _⟩, _⟩, rintro ⟨h_some, h_none⟩ (_|a) (_|b) hab, exacts [rfl, (h_none _ hab.symm).elim, (h_none _ hab).elim, congr_arg some (h_some hab)] end /-! ### Image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma coe_image {p : α → Prop} {s : set (subtype p)} : coe '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ @[simp] lemma coe_image_of_subset {s t : set α} (h : t ⊆ s) : coe '' {x : ↥s | ↑x ∈ t} = t := begin ext x, rw set.mem_image, exact ⟨λ ⟨x', hx', hx⟩, hx ▸ hx', λ hx, ⟨⟨x, h hx⟩, hx, rfl⟩⟩, end lemma range_coe {s : set α} : range (coe : s → α) = s := by { rw ← set.image_univ, simp [-set.image_univ, coe_image] } /-- A variant of `range_coe`. Try to use `range_coe` if possible. This version is useful when defining a new type that is defined as the subtype of something. In that case, the coercion doesn't fire anymore. -/ lemma range_val {s : set α} : range (subtype.val : s → α) = s := range_coe /-- We make this the simp lemma instead of `range_coe`. The reason is that if we write for `s : set α` the function `coe : s → α`, then the inferred implicit arguments of `coe` are `coe α (λ x, x ∈ s)`. -/ @[simp] lemma range_coe_subtype {p : α → Prop} : range (coe : subtype p → α) = {x | p x} := range_coe @[simp] lemma coe_preimage_self (s : set α) : (coe : s → α) ⁻¹' s = univ := by rw [← preimage_range (coe : s → α), range_coe] lemma range_val_subtype {p : α → Prop} : range (subtype.val : subtype p → α) = {x | p x} := range_coe theorem coe_image_subset (s : set α) (t : set s) : coe '' t ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem coe_image_univ (s : set α) : (coe : s → α) '' set.univ = s := image_univ.trans range_coe @[simp] theorem image_preimage_coe (s t : set α) : (coe : s → α) '' (coe ⁻¹' t) = t ∩ s := image_preimage_eq_inter_range.trans $ congr_arg _ range_coe theorem image_preimage_val (s t : set α) : (subtype.val : s → α) '' (subtype.val ⁻¹' t) = t ∩ s := image_preimage_coe s t theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} : ((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s := by rw [← image_preimage_coe, ← image_preimage_coe, coe_injective.image_injective.eq_iff] @[simp] theorem preimage_coe_inter_self (s t : set α) : (coe : s → α) ⁻¹' (t ∩ s) = coe ⁻¹' t := by rw [preimage_coe_eq_preimage_coe_iff, inter_assoc, inter_self] theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((subtype.val : s → α) ⁻¹' t = subtype.val ⁻¹' u) ↔ (t ∩ s = u ∩ s) := preimage_coe_eq_preimage_coe_iff lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (coe '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨coe '' s, _, hs⟩, convert image_subset_range _ _, rw [range_coe] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨coe ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_coe], exact hs₁ end lemma preimage_coe_nonempty {s t : set α} : ((coe : s → α) ⁻¹' t).nonempty ↔ (s ∩ t).nonempty := by rw [inter_comm, ← image_preimage_coe, nonempty_image_iff] lemma preimage_coe_eq_empty {s t : set α} : (coe : s → α) ⁻¹' t = ∅ ↔ s ∩ t = ∅ := by simp only [← not_nonempty_iff_eq_empty, preimage_coe_nonempty] @[simp] lemma preimage_coe_compl (s : set α) : (coe : s → α) ⁻¹' sᶜ = ∅ := preimage_coe_eq_empty.2 (inter_compl_self s) @[simp] lemma preimage_coe_compl' (s : set α) : (coe : sᶜ → α) ⁻¹' s = ∅ := preimage_coe_eq_empty.2 (compl_inter_self s) end subtype namespace set /-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/ section inclusion variables {α : Type*} {s t u : set α} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self (x : s) : inclusion subset.rfl x = x := by { cases x, refl } lemma inclusion_eq_id (h : s ⊆ s) : inclusion h = id := funext inclusion_self @[simp] lemma inclusion_mk {h : s ⊆ t} (a : α) (ha : a ∈ s) : inclusion h ⟨a, ha⟩ = ⟨a, h ha⟩ := rfl lemma inclusion_right (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) : inclusion h ⟨x, m⟩ = x := by { cases x, refl } @[simp] lemma inclusion_inclusion (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (hst.trans htu) x := by { cases x, refl } @[simp] lemma inclusion_comp_inclusion {α} {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) : inclusion htu ∘ inclusion hst = inclusion (hst.trans htu) := funext (inclusion_inclusion hst htu) @[simp] lemma coe_inclusion (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) := rfl lemma inclusion_injective (h : s ⊆ t) : injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1 @[simp] lemma range_inclusion (h : s ⊆ t) : range (inclusion h) = {x : t | (x:α) ∈ s} := by { ext ⟨x, hx⟩, simp [inclusion] } lemma eq_of_inclusion_surjective {s t : set α} {h : s ⊆ t} (h_surj : function.surjective (inclusion h)) : s = t := begin rw [← range_iff_surjective, range_inclusion, eq_univ_iff_forall] at h_surj, exact set.subset.antisymm h (λ x hx, h_surj ⟨x, hx⟩) end end inclusion /-! ### Injectivity and surjectivity lemmas for image and preimage -/ section image_preimage variables {α : Type u} {β : Type v} {f : α → β} @[simp] lemma preimage_injective : injective (preimage f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.preimage_injective⟩, obtain ⟨x, hx⟩ : (f ⁻¹' {y}).nonempty, { rw [h.nonempty_apply_iff preimage_empty], apply singleton_nonempty }, exact ⟨x, hx⟩ end @[simp] lemma preimage_surjective : surjective (preimage f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.preimage_surjective⟩, cases h {x} with s hs, have := mem_singleton x, rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this end @[simp] lemma image_surjective : surjective (image f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.image_surjective⟩, cases h {y} with s hs, have := mem_singleton y, rw [← hs] at this, rcases this with ⟨x, h1x, h2x⟩, exact ⟨x, h2x⟩ end @[simp] lemma image_injective : injective (image f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.image_injective⟩, rw [← singleton_eq_singleton_iff], apply h, rw [image_singleton, image_singleton, hx] end lemma preimage_eq_iff_eq_image {f : α → β} (hf : bijective f) {s t} : f ⁻¹' s = t ↔ s = f '' t := by rw [← image_eq_image hf.1, hf.2.image_preimage] lemma eq_preimage_iff_image_eq {f : α → β} (hf : bijective f) {s t} : s = f ⁻¹' t ↔ f '' s = t := by rw [← image_eq_image hf.1, hf.2.image_preimage] end image_preimage /-! ### Images of binary and ternary functions This section is very similar to `order.filter.n_ary`. Please keep them in sync. -/ section n_ary_image variables {α α' β β' γ γ' δ δ' ε ε' : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ} variables {s s' : set α} {t t' : set β} {u u' : set γ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ} /-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ := {c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c } lemma mem_image2_eq : c ∈ image2 f s t = ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := rfl @[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl lemma mem_image2_of_mem (h1 : a ∈ s) (h2 : b ∈ t) : f a b ∈ image2 f s t := ⟨a, b, h1, h2, rfl⟩ lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t := ⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ }, λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩ /-- image2 is monotone with respect to `⊆`. -/ lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' := by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) } lemma image2_subset_left (ht : t ⊆ t') : image2 f s t ⊆ image2 f s t' := image2_subset subset.rfl ht lemma image2_subset_right (hs : s ⊆ s') : image2 f s t ⊆ image2 f s' t := image2_subset hs subset.rfl lemma image_subset_image2_left (hb : b ∈ t) : (λ a, f a b) '' s ⊆ image2 f s t := ball_image_of_ball $ λ a ha, mem_image2_of_mem ha hb lemma image_subset_image2_right (ha : a ∈ s) : f a '' t ⊆ image2 f s t := ball_image_of_ball $ λ b, mem_image2_of_mem ha lemma forall_image2_iff {p : γ → Prop} : (∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) := ⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩ @[simp] lemma image2_subset_iff {u : set γ} : image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u := forall_image2_iff lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t := begin ext c, split, { rintros ⟨a, b, h1a|h2a, hb, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩; simp [mem_union, *] } end lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' := begin ext c, split, { rintros ⟨a, b, ha, h1b|h2b, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, ‹_›, _, rfl⟩; simp [mem_union, *] } end @[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp @[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp lemma nonempty.image2 : s.nonempty → t.nonempty → (image2 f s t).nonempty := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨_, mem_image2_of_mem ha hb⟩ @[simp] lemma image2_nonempty_iff : (image2 f s t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ ⟨_, a, b, ha, hb, _⟩, ⟨⟨a, ha⟩, b, hb⟩, λ h, h.1.image2 h.2⟩ lemma nonempty.of_image2_left (h : (image2 f s t).nonempty) : s.nonempty := (image2_nonempty_iff.1 h).1 lemma nonempty.of_image2_right (h : (image2 f s t).nonempty) : t.nonempty := (image2_nonempty_iff.1 h).2 @[simp] lemma image2_eq_empty_iff : image2 f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp_rw [←not_nonempty_iff_eq_empty, image2_nonempty_iff, not_and_distrib] lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t := by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' := by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } @[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t := ext $ λ x, by simp @[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s := ext $ λ x, by simp lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp @[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) : image2 f s t = image2 f' s t := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ } /-- A common special case of `image2_congr` -/ lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t := image2_congr (λ a _ b _, h a b) /-- The image of a ternary function `f : α → β → γ → δ` as a function `set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the corresponding function `α × β × γ → δ`. -/ def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ := {d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d } @[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d := iff.rfl lemma image3_mono (hs : s ⊆ s') (ht : t ⊆ t') (hu : u ⊆ u') : image3 g s t u ⊆ image3 g s' t' u' := λ x, Exists₃.imp $ λ a b c ⟨ha, hb, hc, hx⟩, ⟨hs ha, ht hb, hu hc, hx⟩ @[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) : image3 g s t u = image3 g' s t u := by { ext x, split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; exact ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ } /-- A common special case of `image3_congr` -/ lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u := image3_congr (λ a _ b _ c _, h a b c) lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) : image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u := begin ext, split, { rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ } end lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) : image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u := begin ext, split, { rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ } end lemma image_image2 (f : α → β → γ) (g : γ → δ) : g '' image2 f s t = image2 (λ a b, g (f a b)) s t := begin ext, split, { rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ } end lemma image2_image_left (f : γ → β → δ) (g : α → γ) : image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t := begin ext, split, { rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ } end lemma image2_image_right (f : α → γ → δ) (g : β → γ) : image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t := begin ext, split, { rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ } end lemma image2_swap (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = image2 (λ a b, f b a) t s := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ } @[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s := by simp [nonempty_def.mp h, ext_iff] @[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t := by simp [nonempty_def.mp h, ext_iff] lemma image2_assoc {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image2 f (image2 g s t) u = image2 f' s (image2 g' t u) := by simp only [image2_image2_left, image2_image2_right, h_assoc] lemma image2_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image2 f s t = image2 g t s := (image2_swap _ _ _).trans $ by simp_rw h_comm lemma image2_left_comm {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : image2 f s (image2 g t u) = image2 g' t (image2 f' s u) := by { rw [image2_swap f', image2_swap f], exact image2_assoc (λ _ _ _, h_left_comm _ _ _) } lemma image2_right_comm {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : image2 f (image2 g s t) u = image2 g' (image2 f' s u) t := by { rw [image2_swap g, image2_swap g'], exact image2_assoc (λ _ _ _, h_right_comm _ _ _) } lemma image_image2_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (image2 f s t).image g = image2 f' (s.image g₁) (t.image g₂) := by simp_rw [image_image2, image2_image_left, image2_image_right, h_distrib] /-- Symmetric of `set.image2_image_left_comm`. -/ lemma image_image2_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (image2 f s t).image g = image2 f' (s.image g') t := (image_image2_distrib h_distrib).trans $ by rw image_id' /-- Symmetric of `set.image_image2_right_comm`. -/ lemma image_image2_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (image2 f s t).image g = image2 f' s (t.image g') := (image_image2_distrib h_distrib).trans $ by rw image_id' /-- Symmetric of `set.image_image2_distrib_left`. -/ lemma image2_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : image2 f (s.image g) t = (image2 f' s t).image g' := (image_image2_distrib_left $ λ a b, (h_left_comm a b).symm).symm /-- Symmetric of `set.image_image2_distrib_right`. -/ lemma image_image2_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : image2 f s (t.image g) = (image2 f' s t).image g' := (image_image2_distrib_right $ λ a b, (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/ lemma image2_distrib_subset_left {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) : image2 f s (image2 g t u) ⊆ image2 g' (image2 f₁ s t) (image2 f₂ s u) := begin rintro _ ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, rw h_distrib, exact mem_image2_of_mem (mem_image2_of_mem ha hb) (mem_image2_of_mem ha hc), end /-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/ lemma image2_distrib_subset_right {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) : image2 f (image2 g s t) u ⊆ image2 g' (image2 f₁ s u) (image2 f₂ t u) := begin rintro _ ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, rw h_distrib, exact mem_image2_of_mem (mem_image2_of_mem ha hc) (mem_image2_of_mem hb hc), end lemma image_image2_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (image2 f s t).image g = image2 f' (t.image g₁) (s.image g₂) := by { rw image2_swap f, exact image_image2_distrib (λ _ _, h_antidistrib _ _) } /-- Symmetric of `set.image2_image_left_anticomm`. -/ lemma image_image2_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (image2 f s t).image g = image2 f' (t.image g') s := (image_image2_antidistrib h_antidistrib).trans $ by rw image_id' /-- Symmetric of `set.image_image2_right_anticomm`. -/ lemma image_image2_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (image2 f s t).image g = image2 f' t (s.image g') := (image_image2_antidistrib h_antidistrib).trans $ by rw image_id' /-- Symmetric of `set.image_image2_antidistrib_left`. -/ lemma image2_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : image2 f (s.image g) t = (image2 f' t s).image g' := (image_image2_antidistrib_left $ λ a b, (h_left_anticomm b a).symm).symm /-- Symmetric of `set.image_image2_antidistrib_right`. -/ lemma image_image2_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : image2 f s (t.image g) = (image2 f' t s).image g' := (image_image2_antidistrib_right $ λ a b, (h_right_anticomm b a).symm).symm end n_ary_image end set namespace subsingleton variables {α : Type*} [subsingleton α] lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ := λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx @[elab_as_eliminator] lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1 lemma mem_iff_nonempty {α : Type*} [subsingleton α] {s : set α} {x : α} : x ∈ s ↔ s.nonempty := ⟨λ hx, ⟨x, hx⟩, λ ⟨y, hy⟩, subsingleton.elim y x ▸ hy⟩ end subsingleton /-! ### Decidability instances for sets -/ namespace set variables {α : Type u} (s t : set α) (a : α) instance decidable_sdiff [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s \ t) := (by apply_instance : decidable (a ∈ s ∧ a ∉ t)) instance decidable_inter [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∩ t) := (by apply_instance : decidable (a ∈ s ∧ a ∈ t)) instance decidable_union [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∪ t) := (by apply_instance : decidable (a ∈ s ∨ a ∈ t)) instance decidable_compl [decidable (a ∈ s)] : decidable (a ∈ sᶜ) := (by apply_instance : decidable (a ∉ s)) instance decidable_emptyset : decidable_pred (∈ (∅ : set α)) := λ _, decidable.is_false (by simp) instance decidable_univ : decidable_pred (∈ (set.univ : set α)) := λ _, decidable.is_true (by simp) instance decidable_set_of (p : α → Prop) [decidable (p a)] : decidable (a ∈ {a | p a}) := by assumption end set
f349506a0ad6a4d952184aa1b1050753c2f15152
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/analysis/normed_space/multilinear.lean
8d0070c41fec64ec446ba39c3d6bda880a48535a
[ "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
56,454
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.operator_norm topology.algebra.multilinear import data.fintype.card /-! # Operator norm on the space of continuous multilinear maps When `f` is a continuous multilinear map in finitely many variables, we define its norm `∥f∥` as the smallest number such that `∥f m∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥)` for all `m`. We show that it is indeed a norm, and prove its basic properties. ## Main results Let `f` be a multilinear map in finitely many variables. * `exists_bound_of_continuous` asserts that, if `f` is continuous, then there exists `C > 0` with `∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)` for all `m`. * `continuous_of_bound`, conversely, asserts that this bound implies continuity. * `mk_continuous` constructs the associated continuous multilinear map. Let `f` be a continuous multilinear map in finitely many variables. * `∥f∥` is its norm, i.e., the smallest number such that `∥f m∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥)` for all `m`. * `le_op_norm f m` asserts the fundamental inequality `∥f m∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥)`. * `norm_image_sub_le_of_bound f m₁ m₂` gives a control of the difference `f m₁ - f m₂` in terms of `∥f∥` and `∥m₁ - m₂∥`. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a continuous multilinear function `f` in `n+1` variables into a continuous linear function taking values in continuous multilinear functions in `n` variables, and also into a continuous multilinear function in `n` variables taking values in continuous linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). They induce continuous linear equivalences between spaces of continuous multilinear functions in `n+1` variables and spaces of continuous linear functions into continuous multilinear functions in `n` variables (resp. continuous multilinear functions in `n` variables taking values in continuous linear functions), called respectively `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. ## Implementation notes We mostly follow the API (and the proofs) of `operator_norm.lean`, with the additional complexity that we should deal with multilinear maps in several variables. The currying/uncurrying constructions are based on those in `multilinear.lean`. From the mathematical point of view, all the results follow from the results on operator norm in one variable, by applying them to one variable after the other through currying. However, this is only well defined when there is an order on the variables (for instance on `fin n`) although the final result is independent of the order. While everything could be done following this approach, it turns out that direct proofs are easier and more efficient. -/ noncomputable theory open_locale classical open finset set_option class.instance_max_depth 45 universes u v w w₁ w₂ wG variables {𝕜 : Type u} {ι : Type v} {n : ℕ} {G : Type wG} {E : fin n.succ → Type w} {E₁ : ι → Type w₁} {E₂ : Type w₂} [decidable_eq ι] [fintype ι] [nondiscrete_normed_field 𝕜] [normed_group G] [∀i, normed_group (E i)] [∀i, normed_group (E₁ i)] [normed_group E₂] [normed_space 𝕜 G] [∀i, normed_space 𝕜 (E i)] [∀i, normed_space 𝕜 (E₁ i)] [normed_space 𝕜 E₂] /-! ### Continuity properties of multilinear maps We relate continuity of multilinear maps to the inequality `∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)`, in both directions. Along the way, we prove useful bounds on the difference `∥f m₁ - f m₂∥`. -/ namespace multilinear_map variable (f : multilinear_map 𝕜 E₁ E₂) /-- If a multilinear map in finitely many variables on normed spaces is continuous, then it satisfies the inequality `∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)`, for some `C` which can be chosen to be positive. -/ theorem exists_bound_of_continuous (hf : continuous f) : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) := begin /- The proof only uses the continuity at `0`. Then, given a general point `m`, rescale each of its coordinates to bring them to a shell of fixed width around `0`, on which one knows that `f` is bounded, and then use the multiplicativity of `f` along each coordinate to deduce the desired bound.-/ obtain ⟨ε, ε_pos, hε⟩ : ∃ ε > 0, ∀{m}, dist m 0 < ε → dist (f m) (f 0) < 1 := metric.tendsto_nhds_nhds.1 hf.continuous_at 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos ε_pos, /- On points of size at most `δ`, `f` is bounded (by `1 + ∥f 0∥`). -/ have H : ∀{a}, ∥a∥ ≤ δ → ∥f a∥ ≤ 1 + ∥f 0∥, { assume a ha, have : dist (f a) (f 0) ≤ 1, { apply le_of_lt (hε _), rw [dist_eq_norm, sub_zero], exact lt_of_le_of_lt ha (half_lt_self ε_pos) }, calc ∥f a∥ = dist (f a) 0 : (dist_zero_right _).symm ... ≤ dist (f a) (f 0) + dist (f 0) 0 : dist_triangle _ _ _ ... ≤ 1 + ∥f 0∥ : by { rw dist_zero_right, exact add_le_add_right this _ } }, obtain ⟨c, hc⟩ : ∃c : 𝕜, 1 < ∥c∥ := normed_field.exists_one_lt_norm 𝕜, set C := (1 + ∥f 0∥) * univ.prod (λ(i : ι), δ⁻¹ * ∥c∥), have C_pos : 0 < C := mul_pos (lt_of_lt_of_le zero_lt_one (by simp)) (prod_pos (λi hi, mul_pos (inv_pos.2 δ_pos) (lt_of_le_of_lt zero_le_one hc))), refine ⟨C, C_pos, λm, _⟩, /- Given a general point `m`, rescale each coordinate to bring it to `[δ/∥c∥, δ]` by multiplication by a power of a scalar `c` with norm `∥c∥ > 1`.-/ by_cases h : ∃i, m i = 0, { rcases h with ⟨i, hi⟩, rw [f.map_coord_zero i hi, _root_.norm_zero], exact mul_nonneg' (le_of_lt C_pos) (prod_nonneg (λi hi, norm_nonneg _)) }, { push_neg at h, have : ∀i, ∃d:𝕜, d ≠ 0 ∧ ∥d • m i∥ ≤ δ ∧ (δ/∥c∥ ≤ ∥d • m i∥) ∧ (∥d∥⁻¹ ≤ δ⁻¹ * ∥c∥ * ∥m i∥) := λi, rescale_to_shell hc δ_pos (h i), choose d hd using this, have A : 0 ≤ 1 + ∥f 0∥ := add_nonneg zero_le_one (norm_nonneg _), have B : ∀ (i : ι), i ∈ univ → 0 ≤ ∥d i∥⁻¹ := λi hi, by simp, -- use the bound on `f` on the ball of size `δ` to conclude. calc ∥f m∥ = ∥f (λi, (d i)⁻¹ • (d i • m i))∥ : by { unfold_coes, congr, ext i, rw [← mul_smul, inv_mul_cancel (hd i).1, one_smul] } ... = ∥univ.prod (λi, (d i)⁻¹) • f (λi, d i • m i)∥ : by rw f.map_smul_univ ... = univ.prod (λi, ∥d i∥⁻¹) * ∥f (λi, d i • m i)∥ : by { rw [norm_smul, normed_field.norm_prod], congr, ext i, rw normed_field.norm_inv } ... ≤ univ.prod (λi, ∥d i∥⁻¹) * (1 + ∥f 0∥) : mul_le_mul_of_nonneg_left (H ((pi_norm_le_iff (le_of_lt δ_pos)).2 (λi, (hd i).2.1))) (prod_nonneg B) ... ≤ univ.prod (λi, δ⁻¹ * ∥c∥ * ∥m i∥) * (1 + ∥f 0∥) : mul_le_mul_of_nonneg_right (prod_le_prod B (λi hi, (hd i).2.2.2)) A ... = univ.prod (λ(i : ι), δ⁻¹ * ∥c∥) * univ.prod (λi, ∥m i∥) * (1 + ∥f 0∥) : by rw prod_mul_distrib ... = C * univ.prod (λ (i : ι), ∥m i∥) : by rw [mul_comm, ← mul_assoc] } end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a precise but hard to use version. See `norm_image_sub_le_of_bound` for a less precise but more usable version. The bound reads `∥f m - f m'∥ ≤ C * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`. -/ lemma norm_image_sub_le_of_bound' {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ C * univ.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) := begin have A : ∀(s : finset ι), ∥f m₁ - f (s.piecewise m₂ m₁)∥ ≤ C * s.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)), { refine finset.induction (by simp) _, assume i s his Hrec, have I : ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ ≤ C * univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥), { have A : ((insert i s).piecewise m₂ m₁) = function.update (s.piecewise m₂ m₁) i (m₂ i) := s.piecewise_insert _ _ _, have B : s.piecewise m₂ m₁ = function.update (s.piecewise m₂ m₁) i (m₁ i), { ext j, by_cases h : j = i, { rw h, simp [his] }, { simp [h] } }, rw [B, A, ← f.map_sub], apply le_trans (H _) (mul_le_mul_of_nonneg_left _ hC), refine prod_le_prod (λj hj, norm_nonneg _) (λj hj, _), by_cases h : j = i, { rw h, simp }, { by_cases h' : j ∈ s; simp [h', h, le_refl] } }, calc ∥f m₁ - f ((insert i s).piecewise m₂ m₁)∥ ≤ ∥f m₁ - f (s.piecewise m₂ m₁)∥ + ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ : by { rw [← dist_eq_norm, ← dist_eq_norm, ← dist_eq_norm], exact dist_triangle _ _ _ } ... ≤ C * s.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) + C * univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) : add_le_add Hrec I ... = C * (insert i s).sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) : by simp [his, add_comm, left_distrib] }, convert A univ, simp end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a usable but not very precise version. See `norm_image_sub_le_of_bound'` for a more precise but less usable version. The bound is `∥f m - f m'∥ ≤ C * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`. -/ lemma norm_image_sub_le_of_bound {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := begin have A : ∀ (i : ι), univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1), { assume i, calc univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ (univ : finset ι).prod (function.update (λ j, max ∥m₁∥ ∥m₂∥) i (∥m₁ - m₂∥)) : begin apply prod_le_prod, { assume j hj, by_cases h : j = i; simp [h, norm_nonneg] }, { assume j hj, by_cases h : j = i, { rw h, simp, exact norm_le_pi_norm (m₁ - m₂) i }, { simp [h, max_le_max, norm_le_pi_norm] } } end ... = ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : by { rw prod_update_of_mem (finset.mem_univ _), simp [card_univ_diff] } }, calc ∥f m₁ - f m₂∥ ≤ C * univ.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) : f.norm_image_sub_le_of_bound' hC H m₁ m₂ ... ≤ C * univ.sum (λ (i : ι), ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1)) : mul_le_mul_of_nonneg_left (sum_le_sum (λi hi, A i)) hC ... = C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ : by { rw [sum_const, card_univ, add_monoid.smul_eq_mul], ring } end /-- If a multilinear map satisfies an inequality `∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)`, then it is continuous. -/ theorem continuous_of_bound (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) : continuous f := begin let D := max C 1, have D_pos : 0 ≤ D := le_trans zero_le_one (le_max_right _ _), replace H : ∀ m, ∥f m∥ ≤ D * univ.prod (λi, ∥m i∥), { assume m, apply le_trans (H m) (mul_le_mul_of_nonneg_right (le_max_left _ _) _), exact prod_nonneg (λ(i : ι) hi, norm_nonneg (m i)) }, refine continuous_iff_continuous_at.2 (λm, _), refine continuous_at_of_locally_lipschitz zero_lt_one (D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1)) (λm' h', _), rw [dist_eq_norm, dist_eq_norm], have : 0 ≤ (max ∥m'∥ ∥m∥), by simp, have : (max ∥m'∥ ∥m∥) ≤ ∥m∥ + 1, by simp [zero_le_one, norm_le_of_mem_closed_ball (le_of_lt h'), -add_comm], calc ∥f m' - f m∥ ≤ D * (fintype.card ι) * (max ∥m'∥ ∥m∥) ^ (fintype.card ι - 1) * ∥m' - m∥ : f.norm_image_sub_le_of_bound D_pos H m' m ... ≤ D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1) * ∥m' - m∥ : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul_of_nonneg_left, mul_nonneg', norm_nonneg, nat.cast_nonneg, pow_le_pow_of_le_left] end /-- Constructing a continuous multilinear map from a multilinear map satisfying a boundedness condition. -/ def mk_continuous (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) : continuous_multilinear_map 𝕜 E₁ E₂ := { cont := f.continuous_of_bound C H, ..f } /-- Given a multilinear map in `n` variables, if one restricts it to `k` variables putting `z` on the other coordinates, then the resulting restricted function satisfies an inequality `∥f.restr v∥ ≤ C * ∥z∥^(n-k) * Π ∥v i∥` if the original function satisfies `∥f v∥ ≤ C * Π ∥v i∥`. -/ lemma restr_norm_le {k n : ℕ} (f : (multilinear_map 𝕜 (λ i : fin n, G) E₂ : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) {C : ℝ} (H : ∀ m, ∥f m∥ ≤ C * finset.univ.prod (λi, ∥m i∥)) (v : fin k → G) : ∥f.restr s hk z v∥ ≤ C * ∥z∥ ^ (n - k) * finset.univ.prod (λi, ∥v i∥) := calc ∥f.restr s hk z v∥ ≤ C * finset.univ.prod (λ (j : fin n), ∥(if h : j ∈ s then v ((s.mono_equiv_of_fin hk).symm ⟨j, h⟩) else z)∥) : H _ ... = C * ((finset.univ \ s).prod (λ (j : fin n), ∥(if h : j ∈ s then v ((s.mono_equiv_of_fin hk).symm ⟨j, h⟩) else z)∥) * s.prod (λ (j : fin n), ∥(if h : j ∈ s then v ((s.mono_equiv_of_fin hk).symm ⟨j, h⟩) else z)∥)) : by rw ← finset.prod_sdiff (finset.subset_univ _) ... = C * (∥z∥ ^ (n - k) * finset.univ.prod (λi, ∥v i∥)) : begin congr' 2, { have : ∥z∥ ^ (n - k) = (finset.univ \ s).prod (λ (j : fin n), ∥z∥), by simp [finset.card_sdiff (finset.subset_univ _), hk], rw this, exact finset.prod_congr rfl (λ i hi, by rw dif_neg (finset.mem_sdiff.1 hi).2) }, { apply finset.prod_bij (λ (i : fin n) (hi : i ∈ s), (s.mono_equiv_of_fin hk).symm ⟨i, hi⟩), { exact λ _ _, finset.mem_univ _ }, { exact λ i hi, by simp [hi] }, { exact λ i j hi hi hij, subtype.mk.inj ((s.mono_equiv_of_fin hk).symm.injective hij) }, { assume i hi, rcases (s.mono_equiv_of_fin hk).symm.surjective i with ⟨j, hj⟩, refine ⟨j.1, j.2, _⟩, unfold_coes, convert hj.symm, rw subtype.ext } } end ... = C * ∥z∥ ^ (n - k) * finset.univ.prod (λi, ∥v i∥) : by rw mul_assoc end multilinear_map /-! ### Continuous multilinear maps We define the norm `∥f∥` of a continuous multilinear map `f` in finitely many variables as the smallest number such that `∥f m∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥)` for all `m`. We show that this defines a normed space structure on `continuous_multilinear_map 𝕜 E₁ E₂`. -/ namespace continuous_multilinear_map variables (c : 𝕜) (f g : continuous_multilinear_map 𝕜 E₁ E₂) (m : Πi, E₁ i) theorem bound : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) := f.to_multilinear_map.exists_bound_of_continuous f.2 open real /-- The operator norm of a continuous multilinear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * finset.univ.prod (λi, ∥m i∥)} instance has_op_norm : has_norm (continuous_multilinear_map 𝕜 E₁ E₂) := ⟨op_norm⟩ -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : continuous_multilinear_map 𝕜 E₁ E₂} : ∃ c, c ∈ {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * finset.univ.prod (λi, ∥m i∥)} := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : continuous_multilinear_map 𝕜 E₁ E₂} : bdd_below {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * finset.univ.prod (λi, ∥m i∥)} := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm of a continuous multilinear map: `∥f m∥` is bounded by `∥f∥` times the product of the `∥m i∥`. -/ theorem le_op_norm : ∥f m∥ ≤ ∥f∥ * finset.univ.prod (λi, ∥m i∥) := begin have A : 0 ≤ finset.univ.prod (λi, ∥m i∥) := prod_nonneg (λj hj, norm_nonneg _), by_cases h : finset.univ.prod (λi, ∥m i∥) = 0, { rcases prod_eq_zero_iff.1 h with ⟨i, _, hi⟩, rw norm_eq_zero at hi, have : f m = 0 := f.map_coord_zero i hi, rw [this, norm_zero], exact mul_nonneg' (op_norm_nonneg f) A }, { have hlt : 0 < finset.univ.prod (λi, ∥m i∥) := lt_of_le_of_ne A (ne.symm h), exact le_mul_of_div_le hlt ((le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, div_le_of_le_mul hlt (begin rw mul_comm, apply hc, end))) } end lemma ratio_le_op_norm : ∥f m∥ / finset.univ.prod (λi, ∥m i∥) ≤ ∥f∥ := begin have : 0 ≤ finset.univ.prod (λi, ∥m i∥) := prod_nonneg (λj hj, norm_nonneg _), cases eq_or_lt_of_le this with h h, { simp [h.symm, op_norm_nonneg f] }, { rw div_le_iff h, exact le_op_norm f m } end /-- The image of the unit ball under a continuous multilinear map is bounded. -/ lemma unit_le_op_norm (h : ∥m∥ ≤ 1) : ∥f m∥ ≤ ∥f∥ := calc ∥f m∥ ≤ ∥f∥ * finset.univ.prod (λi, ∥m i∥) : f.le_op_norm m ... ≤ ∥f∥ * finset.univ.prod (λ (i : ι), 1) : mul_le_mul_of_nonneg_left (prod_le_prod (λi hi, norm_nonneg _) (λi hi, le_trans (norm_le_pi_norm _ _) h)) (op_norm_nonneg f) ... = ∥f∥ : by simp /-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ m, ∥f m∥ ≤ M * finset.univ.prod (λi, ∥m i∥)) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := Inf_le _ bounds_bdd_below ⟨add_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw add_mul, exact norm_add_le_of_le (le_op_norm _ _) (le_op_norm _ _) }⟩ /-- A continuous linear map is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := begin split, { assume h, ext m, simpa [h, norm_le_zero_iff.symm] using f.le_op_norm m }, { assume h, apply le_antisymm (op_norm_le_bound f (le_refl _) (λm, _)) (op_norm_nonneg _), rw h, simp } end @[simp] lemma norm_zero : ∥(0 : continuous_multilinear_map 𝕜 E₁ E₂)∥ = 0 := by rw op_norm_zero_iff /-- The operator norm is homogeneous. -/ lemma op_norm_smul : ∥c • f∥ = ∥c∥ * ∥f∥ := le_antisymm (Inf_le _ bounds_bdd_below ⟨mul_nonneg (norm_nonneg _) (op_norm_nonneg _), λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end⟩) (lb_le_Inf _ bounds_nonempty (λ _ ⟨hn, hc⟩, (or.elim (lt_or_eq_of_le (norm_nonneg c)) (λ hlt, begin rw mul_comm, exact mul_le_of_le_div hlt (Inf_le _ bounds_bdd_below ⟨div_nonneg hn hlt, λ _, (by { rw div_mul_eq_mul_div, exact le_div_of_mul_le hlt (by { rw [ mul_comm, ←norm_smul ], exact hc _ }) })⟩) end) (λ heq, by { rw [←heq, zero_mul], exact hn })))) lemma op_norm_neg : ∥-f∥ = ∥f∥ := calc ∥-f∥ = ∥(-1:𝕜) • f∥ : by rw neg_one_smul ... = ∥(-1:𝕜)∥ * ∥f∥ : by rw op_norm_smul ... = ∥f∥ : by simp /-- Continuous multilinear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (continuous_multilinear_map 𝕜 E₁ E₂) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (continuous_multilinear_map 𝕜 E₁ E₂) := ⟨op_norm_smul⟩ /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, precise version. For a less precise but more usable version, see `norm_image_sub_le_of_bound`. The bound reads `∥f m - f m'∥ ≤ ∥f∥ * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`.-/ lemma norm_image_sub_le_of_bound' (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * univ.sum (λi, univ.prod (λj, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥)) := f.to_multilinear_map.norm_image_sub_le_of_bound' (norm_nonneg _) f.le_op_norm _ _ /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, less precise version. For a more precise but less usable version, see `norm_image_sub_le_of_bound'`. The bound is `∥f m - f m'∥ ≤ ∥f∥ * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`.-/ lemma norm_image_sub_le_of_bound (m₁ m₂ : Πi, E₁ i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := f.to_multilinear_map.norm_image_sub_le_of_bound (norm_nonneg _) f.le_op_norm _ _ /-- Applying a multilinear map to a vector is continuous in both coordinates. -/ lemma continuous_eval : continuous (λ (p : (continuous_multilinear_map 𝕜 E₁ E₂ × (Πi, E₁ i))), p.1 p.2) := begin apply continuous_iff_continuous_at.2 (λp, _), apply continuous_at_of_locally_lipschitz zero_lt_one ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + univ.prod (λi, ∥p.2 i∥)) (λq hq, _), have : 0 ≤ (max ∥q.2∥ ∥p.2∥), by simp, have : 0 ≤ ∥p∥ + 1, by simp [le_trans zero_le_one], have A : ∥q∥ ≤ ∥p∥ + 1 := norm_le_of_mem_closed_ball (le_of_lt hq), have : (max ∥q.2∥ ∥p.2∥) ≤ ∥p∥ + 1 := le_trans (max_le_max (norm_snd_le q) (norm_snd_le p)) (by simp [A, -add_comm, zero_le_one]), have : ∀ (i : ι), i ∈ univ → 0 ≤ ∥p.2 i∥ := λ i hi, norm_nonneg _, calc dist (q.1 q.2) (p.1 p.2) ≤ dist (q.1 q.2) (q.1 p.2) + dist (q.1 p.2) (p.1 p.2) : dist_triangle _ _ _ ... = ∥q.1 q.2 - q.1 p.2∥ + ∥q.1 p.2 - p.1 p.2∥ : by rw [dist_eq_norm, dist_eq_norm] ... ≤ ∥q.1∥ * (fintype.card ι) * (max ∥q.2∥ ∥p.2∥) ^ (fintype.card ι - 1) * ∥q.2 - p.2∥ + ∥q.1 - p.1∥ * univ.prod (λi, ∥p.2 i∥) : add_le_add (norm_image_sub_le_of_bound _ _ _) ((q.1 - p.1).le_op_norm p.2) ... ≤ (∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) * ∥q - p∥ + ∥q - p∥ * univ.prod (λi, ∥p.2 i∥) : by apply_rules [add_le_add, mul_le_mul, le_refl, le_trans (norm_fst_le q) A, nat.cast_nonneg, mul_nonneg', pow_le_pow_of_le_left, pow_nonneg, norm_snd_le (q - p), norm_nonneg, norm_fst_le (q - p), norm_nonneg, prod_nonneg] ... = ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + univ.prod (λi, ∥p.2 i∥)) * dist q p : by { rw dist_eq_norm, ring } end lemma continuous_eval_left (m : Π i, E₁ i) : continuous (λ (p : (continuous_multilinear_map 𝕜 E₁ E₂)), (p : (Π i, E₁ i) → E₂) m) := continuous_eval.comp (continuous.prod_mk continuous_id continuous_const) lemma has_sum_eval {α : Type*} {p : α → continuous_multilinear_map 𝕜 E₁ E₂} {q : continuous_multilinear_map 𝕜 E₁ E₂} (h : has_sum p q) (m : Π i, E₁ i) : has_sum (λ a, p a m) (q m) := begin dsimp [has_sum] at h ⊢, convert ((continuous_eval_left m).tendsto _).comp h, ext s, simp end open_locale topological_space open filter /-- If the target space is complete, the space of continuous multilinear maps with its norm is also complete. The proof is essentially the same as for the space of continuous linear maps (modulo the addition of `finset.prod` where needed. The duplication could be avoided by deducing the linear case from the multilinear case via a currying isomorphism. However, this would mess up imports, and it is more satisfactory to have the simplest case as a standalone proof. -/ instance [complete_space E₂] : complete_space (continuous_multilinear_map 𝕜 E₁ E₂) := begin have nonneg : ∀ (v : Π i, E₁ i), 0 ≤ finset.univ.prod (λ i, ∥v i∥) := λ v, finset.prod_nonneg (λ i hi, norm_nonneg _), -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, -- and establish that the evaluation at any point `v : Π i, E₁ i` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * finset.univ.prod (λ i, ∥v i∥), λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (nonneg v) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `E₂` is complete) -- into a function which we call `F`. choose F hF using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `F` is multilinear, let Fmult : multilinear_map 𝕜 E₁ E₂ := { to_fun := F, add := λ v i x y, begin have A := hF (function.update v i (x + y)), have B := (hF (function.update v i x)).add (hF (function.update v i y)), simp at A B, exact tendsto_nhds_unique filter.at_top_ne_bot A B end, smul := λ v i c x, begin have A := hF (function.update v i (c • x)), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hF (function.update v i x)), simp at A B, exact tendsto_nhds_unique filter.at_top_ne_bot A B end }, -- and that `F` has norm at most `(b 0 + ∥f 0∥)`. have Fnorm : ∀ v, ∥F v∥ ≤ (b 0 + ∥f 0∥) * finset.univ.prod (λ i, ∥v i∥), { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * finset.univ.prod (λ i, ∥v i∥), { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto at_top_ne_bot (hF v).norm (eventually_of_forall _ A) }, -- Thus `F` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Fcont := Fmult.mk_continuous _ Fnorm, use Fcont, -- Our last task is to establish convergence to `F` in norm. have : ∀ n, ∥f n - Fcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * finset.prod univ (λ (i : ι), ∥v i∥), { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Fcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hF v)), exact le_of_tendsto at_top_ne_bot B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end continuous_multilinear_map /-- If a continuous multilinear map is constructed from a multilinear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma multilinear_map.mk_continuous_norm_le (f : multilinear_map 𝕜 E₁ E₂) {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * univ.prod (λi, ∥m i∥)) : ∥f.mk_continuous C H∥ ≤ C := continuous_multilinear_map.op_norm_le_bound _ hC (λm, H m) namespace continuous_multilinear_map /- The next two instances are not found automatically. Register them explicitly. TODO: understand why, and fix. -/ instance : normed_group (continuous_multilinear_map 𝕜 (λ (i : ι), 𝕜) E₂) := @continuous_multilinear_map.to_normed_group 𝕜 ι (λ (i : ι), 𝕜) E₂ _ _ _ _ _ _ _ instance : normed_space 𝕜 (continuous_multilinear_map 𝕜 (λ (i : ι), 𝕜) E₂) := @continuous_multilinear_map.to_normed_space 𝕜 ι (λ (i : ι), 𝕜) E₂ _ _ _ _ _ _ _ /-- Given a continuous multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new continuous multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : (G [×n]→L[𝕜] E₂ : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) : G [×k]→L[𝕜] E₂ := (f.to_multilinear_map.restr s hk z).mk_continuous (∥f∥ * ∥z∥^(n-k)) $ λ v, multilinear_map.restr_norm_le _ _ _ _ f.le_op_norm _ lemma norm_restr {k n : ℕ} (f : G [×n]→L[𝕜] E₂) (s : finset (fin n)) (hk : s.card = k) (z : G) : ∥f.restr s hk z∥ ≤ ∥f∥ * ∥z∥ ^ (n - k) := begin apply multilinear_map.mk_continuous_norm_le, exact mul_nonneg (norm_nonneg _) (pow_nonneg (norm_nonneg _) _) end variables (𝕜 ι) /-- The canonical continuous multilinear map on `𝕜^ι`, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_field (z : E₂) : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂ := @multilinear_map.mk_continuous 𝕜 ι (λ(i : ι), 𝕜) E₂ _ _ _ _ _ _ _ (multilinear_map.mk_pi_ring 𝕜 ι z) (∥z∥) (λ m, by simp only [multilinear_map.mk_pi_ring_apply, norm_smul, normed_field.norm_prod, mul_comm]) variables {𝕜 ι} @[simp] lemma mk_pi_field_apply (z : E₂) (m : ι → 𝕜) : (continuous_multilinear_map.mk_pi_field 𝕜 ι z : (ι → 𝕜) → E₂) m = finset.univ.prod m • z := rfl lemma mk_pi_ring_apply_one_eq_self (f : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) : continuous_multilinear_map.mk_pi_field 𝕜 ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end variables (𝕜 ι E₂) /-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `continuous_multilinear_map.pi_field_equiv_aux`. The continuous linear equivalence is `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv_aux : E₂ ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) := { to_fun := λ z, continuous_multilinear_map.mk_pi_field 𝕜 ι z, inv_fun := λ f, f (λi, 1), add := λ z z', by { ext m, simp [smul_add] }, smul := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } /-- Continuous multilinear maps on `𝕜^n` with values in `E₂` are in bijection with `E₂`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a continuous linear equivalence in `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv : E₂ ≃L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) E₂) := { continuous_to_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λz, _), rw one_mul, change ∥continuous_multilinear_map.mk_pi_field 𝕜 ι z∥ ≤ ∥z∥, exact multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end, continuous_inv_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, _), rw one_mul, change ∥f (λi, 1)∥ ≤ ∥f∥, apply @continuous_multilinear_map.unit_le_op_norm 𝕜 ι (λ (i : ι), 𝕜) E₂ _ _ _ _ _ _ _ f, simp [pi_norm_le_iff zero_le_one, le_refl] end, .. continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι E₂ } end continuous_multilinear_map section currying /-! ### Currying We associate to a continuous multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a continuous linear map on `E 0` taking values in continuous multilinear maps in `n` variables) and `f.curry_right` (which is a continuous multilinear map in `n` variables taking values in continuous linear maps on `E (last n)`). The inverse operations are called `uncurry_left` and `uncurry_right`. We also register continuous linear equiv versions of these correspondences, in `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. -/ set_option class.instance_max_depth 360 open fin function lemma continuous_linear_map.norm_map_tail_le (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (m : Πi, E i) : ∥f (m 0) (tail m)∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥) := calc ∥f (m 0) (tail m)∥ ≤ ∥f (m 0)∥ * univ.prod (λi, ∥(tail m) i∥) : (f (m 0)).le_op_norm _ ... ≤ (∥f∥ * ∥m 0∥) * univ.prod (λi, ∥(tail m) i∥) : mul_le_mul_of_nonneg_right (f.le_op_norm _) (prod_nonneg (λi hi, norm_nonneg _)) ... = ∥f∥ * (∥m 0∥ * univ.prod (λi, ∥(tail m) i∥)) : by ring ... = ∥f∥ * univ.prod (λi, ∥m i∥) : by { rw prod_univ_succ, refl } lemma continuous_multilinear_map.norm_map_init_le (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) (m : Πi, E i) : ∥f (init m) (m (last n))∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥) := calc ∥f (init m) (m (last n))∥ ≤ ∥f (init m)∥ * ∥m (last n)∥ : (f (init m)).le_op_norm _ ... ≤ (∥f∥ * univ.prod (λi, ∥(init m) i∥)) * ∥m (last n)∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (norm_nonneg _) ... = ∥f∥ * (univ.prod (λi, ∥(init m) i∥) * ∥m (last n)∥) : mul_assoc _ _ _ ... = ∥f∥ * univ.prod (λi, ∥m i∥) : by { rw prod_univ_cast_succ, refl } lemma continuous_multilinear_map.norm_map_cons_le (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : Π(i : fin n), E i.succ) : ∥f (cons x m)∥ ≤ ∥f∥ * ∥x∥ * univ.prod (λi, ∥m i∥) := calc ∥f (cons x m)∥ ≤ ∥f∥ * univ.prod (λ(i : fin n.succ), ∥cons x m i∥) : f.le_op_norm _ ... = (∥f∥ * ∥x∥) * univ.prod (λi, ∥m i∥) : by { rw prod_univ_succ, simp [mul_assoc] } lemma continuous_multilinear_map.norm_map_snoc_le (f : continuous_multilinear_map 𝕜 E E₂) (m : Π(i : fin n), E i.cast_succ) (x : E (last n)) : ∥f (snoc m x)∥ ≤ ∥f∥ * univ.prod (λi, ∥m i∥) * ∥x∥ := calc ∥f (snoc m x)∥ ≤ ∥f∥ * univ.prod (λ(i : fin n.succ), ∥snoc m x i∥) : f.le_op_norm _ ... = ∥f∥ * univ.prod (λi, ∥m i∥) * ∥x∥ : by { rw prod_univ_cast_succ, simp [mul_assoc] } /-! #### Left currying -/ /-- Given a continuous linear map `f` from `E 0` to continuous multilinear maps on `n` variables, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def continuous_linear_map.uncurry_left (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : continuous_multilinear_map 𝕜 E E₂ := (@linear_map.uncurry_left 𝕜 n E E₂ _ _ _ _ _ (continuous_multilinear_map.to_multilinear_map_linear.comp f.to_linear_map)).mk_continuous (∥f∥) (λm, continuous_linear_map.norm_map_tail_le f m) @[simp] lemma continuous_linear_map.uncurry_left_apply (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (m : Πi, E i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the first variable to obtain a continuous linear map into continuous multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def continuous_multilinear_map.curry_left (f : continuous_multilinear_map 𝕜 E E₂) : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂) := linear_map.mk_continuous { -- define a linear map into `n` continuous multilinear maps from an `n+1` continuous multilinear map to_fun := λx, (f.to_multilinear_map.curry_left x).mk_continuous (∥f∥ * ∥x∥) (f.norm_map_cons_le x), add := λx y, by { ext m, exact f.cons_add m x y }, smul := λc x, by { ext m, exact f.cons_smul m c x } } -- then register its continuity thanks to its boundedness properties. (∥f∥) (λx, multilinear_map.mk_continuous_norm_le _ (mul_nonneg' (norm_nonneg _) (norm_nonneg _)) _) @[simp] lemma continuous_multilinear_map.curry_left_apply (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (m : Π(i : fin n), E i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma continuous_linear_map.curry_uncurry_left (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, continuous_linear_map.uncurry_left_apply, continuous_multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma continuous_multilinear_map.uncurry_curry_left (f : continuous_multilinear_map 𝕜 E E₂) : f.curry_left.uncurry_left = f := by { ext m, simp } @[simp] lemma continuous_multilinear_map.curry_left_norm (f : continuous_multilinear_map 𝕜 E E₂) : ∥f.curry_left∥ = ∥f∥ := begin apply le_antisymm (linear_map.mk_continuous_norm_le _ (norm_nonneg _) _), have : ∥f.curry_left.uncurry_left∥ ≤ ∥f.curry_left∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end @[simp] lemma continuous_linear_map.uncurry_left_norm (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) : ∥f.uncurry_left∥ = ∥f∥ := begin apply le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _), have : ∥f.uncurry_left.curry_left∥ ≤ ∥f.uncurry_left∥ := linear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end variables (𝕜 E E₂) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂`. The algebraic version (without continuity assumption on the maps) is `multilinear_curry_left_equiv 𝕜 E E₂`, and the topological isomorphism (registering additionally that the isomorphism is continuous) is `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_left_equiv_aux : (E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { to_fun := continuous_linear_map.uncurry_left, add := λf₁ f₂, by { ext m, refl }, smul := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_left, left_inv := continuous_linear_map.curry_uncurry_left, right_inv := continuous_multilinear_map.uncurry_curry_left } /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism in `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_left_equiv : (E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) ≃L[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { continuous_to_fun := begin refine (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.uncurry_left_norm end, continuous_inv_fun := begin refine (continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.curry_left_norm end, .. continuous_multilinear_curry_left_equiv_aux 𝕜 E E₂ } variables {𝕜 E E₂} @[simp] lemma continuous_multilinear_curry_left_equiv_apply (f : E 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.succ) E₂)) (v : Π i, E i) : continuous_multilinear_curry_left_equiv 𝕜 E E₂ f v = f (v 0) (tail v) := rfl @[simp] lemma continuous_multilinear_curry_left_equiv_symm_apply (f : continuous_multilinear_map 𝕜 E E₂) (x : E 0) (v : Π (i : fin n), E i.succ) : (continuous_multilinear_curry_left_equiv 𝕜 E E₂).symm f x v = f (cons x v) := rfl /-! #### Right currying -/ /-- Given a continuous linear map `f` from continuous multilinear maps on `n` variables to continuous linear maps on `E 0`, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`. -/ def continuous_multilinear_map.uncurry_right (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : continuous_multilinear_map 𝕜 E E₂ := let f' : multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →ₗ[𝕜] E₂) := { to_fun := λ m, (f m).to_linear_map, add := λ m i x y, by { simp, refl }, smul := λ m i c x, by { simp, refl } } in (@multilinear_map.uncurry_right 𝕜 n E E₂ _ _ _ _ _ f').mk_continuous (∥f∥) (λm, f.norm_map_init_le m) @[simp] lemma continuous_multilinear_map.uncurry_right_apply (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) (m : Πi, E i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the last variable to obtain a continuous multilinear map in `n` variables into continuous linear maps, given by `m ↦ (x ↦ f (snoc m x))`. -/ def continuous_multilinear_map.curry_right (f : continuous_multilinear_map 𝕜 E E₂) : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂) := let f' : multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂) := { to_fun := λm, (f.to_multilinear_map.curry_right m).mk_continuous (∥f∥ * univ.prod (λ(i : fin n), ∥m i∥)) $ λx, f.norm_map_snoc_le m x, add := λ m i x y, by { simp, refl }, smul := λ m i c x, by { simp, refl } } in f'.mk_continuous (∥f∥) (λm, linear_map.mk_continuous_norm_le _ (mul_nonneg' (norm_nonneg _) (prod_nonneg (λj hj, norm_nonneg _))) _) @[simp] lemma continuous_multilinear_map.curry_right_apply (f : continuous_multilinear_map 𝕜 E E₂) (m : Π(i : fin n), E i.cast_succ) (x : E (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma continuous_multilinear_map.curry_uncurry_right (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, continuous_multilinear_map.curry_right_apply, continuous_multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma continuous_multilinear_map.uncurry_curry_right (f : continuous_multilinear_map 𝕜 E E₂) : f.curry_right.uncurry_right = f := by { ext m, simp } @[simp] lemma continuous_multilinear_map.curry_right_norm (f : continuous_multilinear_map 𝕜 E E₂) : ∥f.curry_right∥ = ∥f∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, have : ∥f.curry_right.uncurry_right∥ ≤ ∥f.curry_right∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end @[simp] lemma continuous_multilinear_map.uncurry_right_norm (f : continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) : ∥f.uncurry_right∥ = ∥f∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, have : ∥f.uncurry_right.curry_right∥ ≤ ∥f.uncurry_right∥ := multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _, simpa end variables (𝕜 E E₂) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space of continuous linear maps on `E (last n)`, by separating the last variable. We register this isomorphism as a linear equiv in `continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂`. The algebraic version (without continuity assumption on the maps) is `multilinear_curry_right_equiv 𝕜 E E₂`, and the topological isomorphism (registering additionally that the isomorphism is continuous) is `continuous_multilinear_curry_right_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_right_equiv_aux : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { to_fun := continuous_multilinear_map.uncurry_right, add := λf₁ f₂, by { ext m, refl }, smul := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_right, left_inv := continuous_multilinear_map.curry_uncurry_right, right_inv := continuous_multilinear_map.uncurry_curry_right } /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), E i.cast_succ` with values in the space of continuous linear maps on `E (last n)`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_right_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_right_equiv : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂)) ≃L[𝕜] (continuous_multilinear_map 𝕜 E E₂) := { continuous_to_fun := begin refine (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂).to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.uncurry_right_norm end, continuous_inv_fun := begin refine (continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact f.curry_right_norm end, .. continuous_multilinear_curry_right_equiv_aux 𝕜 E E₂ } variables {𝕜 G E E₂} @[simp] lemma continuous_multilinear_curry_right_equiv_apply (f : (continuous_multilinear_map 𝕜 (λ(i : fin n), E i.cast_succ) (E (last n) →L[𝕜] E₂))) (v : Π i, E i) : (continuous_multilinear_curry_right_equiv 𝕜 E E₂) f v = f (init v) (v (last n)) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply (f : continuous_multilinear_map 𝕜 E E₂) (v : Π (i : fin n), E i.cast_succ) (x : E (last n)) : (continuous_multilinear_curry_right_equiv 𝕜 E E₂).symm f v x = f (snoc v x) := rfl /-! #### Currying with `0` variables The space of multilinear maps with `0` variables is trivial: such a multilinear map is just an arbitrary constant (note that multilinear maps in `0` variables need not map `0` to `0`!). Therefore, the space of continuous multilinear maps on `(fin 0) → G` with values in `E₂` is isomorphic (and even isometric) to `E₂`. As this is the zeroth step in the construction of iterated derivatives, we register this isomorphism. -/ variables {𝕜 G E₂} /-- Associating to a continuous multilinear map in `0` variables the unique value it takes. -/ def continuous_multilinear_map.uncurry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : E₂ := f 0 variables (𝕜 G) /-- Associating to an element `x` of a vector space `E₂` the continuous multilinear map in `0` variables taking the (unique) value `x` -/ def continuous_multilinear_map.curry0 (x : E₂) : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂ := { to_fun := λm, x, add := λ m i, fin.elim0 i, smul := λ m i, fin.elim0 i, cont := continuous_const } variable {G} @[simp] lemma continuous_multilinear_map.curry0_apply (x : E₂) (m : (fin 0) → G) : (continuous_multilinear_map.curry0 𝕜 G x : ((fin 0) → G) → E₂) m = x := rfl variable {𝕜} @[simp] lemma continuous_multilinear_map.uncurry0_apply (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : f.uncurry0 = f 0 := rfl @[simp] lemma continuous_multilinear_map.apply_zero_curry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) {x : fin 0 → G} : continuous_multilinear_map.curry0 𝕜 G (f x) = f := by { ext m, simp [(subsingleton.elim _ _ : x = m)] } lemma continuous_multilinear_map.uncurry0_curry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : continuous_multilinear_map.curry0 𝕜 G (f.uncurry0) = f := by simp variables (𝕜 G) @[simp] lemma continuous_multilinear_map.curry0_uncurry0 (x : E₂) : (continuous_multilinear_map.curry0 𝕜 G x).uncurry0 = x := rfl @[simp] lemma continuous_multilinear_map.uncurry0_norm (x : E₂) : ∥continuous_multilinear_map.curry0 𝕜 G x∥ = ∥x∥ := begin apply le_antisymm, { exact continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp) }, { simpa using (continuous_multilinear_map.curry0 𝕜 G x).le_op_norm 0 } end variables {𝕜 G} @[simp] lemma continuous_multilinear_map.fin0_apply_norm (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) {x : fin 0 → G} : ∥f x∥ = ∥f∥ := begin have : x = 0 := subsingleton.elim _ _, subst this, refine le_antisymm (by simpa using f.le_op_norm 0) _, have : ∥continuous_multilinear_map.curry0 𝕜 G (f.uncurry0)∥ ≤ ∥f.uncurry0∥ := continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp), simpa end lemma continuous_multilinear_map.curry0_norm (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) : ∥f.uncurry0∥ = ∥f∥ := by simp variables (𝕜 G E₂) /-- The linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The continuous version is given in `continuous_multilinear_curry_fin0`. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of linear equivs. -/ def continuous_multilinear_curry_fin0_aux : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) ≃ₗ[𝕜] E₂ := { to_fun := λf, continuous_multilinear_map.uncurry0 f, inv_fun := λf, continuous_multilinear_map.curry0 𝕜 G f, add := λf g, rfl, smul := λc f, rfl, left_inv := continuous_multilinear_map.uncurry0_curry0, right_inv := continuous_multilinear_map.curry0_uncurry0 𝕜 G } /-- The continuous linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of continuous linear equivs. -/ def continuous_multilinear_curry_fin0 : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂) ≃L[𝕜] E₂ := { continuous_to_fun := begin change continuous (λ (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂), (f : ((fin 0) → G) → E₂) 0), exact continuous_multilinear_map.continuous_eval.comp (continuous_id.prod_mk continuous_const) end, continuous_inv_fun := begin refine (continuous_multilinear_curry_fin0_aux 𝕜 G E₂).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, le_of_eq _), rw one_mul, exact continuous_multilinear_map.uncurry0_norm _ _ _ end, .. continuous_multilinear_curry_fin0_aux 𝕜 G E₂ } variables {𝕜 G E₂} @[simp] lemma continuous_multilinear_curry_fin0_apply (f : (continuous_multilinear_map 𝕜 (λ (i : fin 0), G) E₂)) : continuous_multilinear_curry_fin0 𝕜 G E₂ f = f 0 := rfl @[simp] lemma continuous_multilinear_curry_fin0_symm_apply (x : E₂) (v : (fin 0) → G) : (continuous_multilinear_curry_fin0 𝕜 G E₂).symm x v = x := rfl /-! #### With 1 variable -/ variables (𝕜 G E₂) /-- Continuous multilinear maps from `G^1` to `E₂` are isomorphic with continuous linear maps from `G` to `E₂`. -/ def continuous_multilinear_curry_fin1 : (continuous_multilinear_map 𝕜 (λ (i : fin 1), G) E₂) ≃L[𝕜] (G →L[𝕜] E₂) := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin 1), G) E₂).symm.trans (continuous_multilinear_curry_fin0 𝕜 G (G →L[𝕜] E₂)) variables {𝕜 G E₂} @[simp] lemma continuous_multilinear_curry_fin1_apply (f : (continuous_multilinear_map 𝕜 (λ (i : fin 1), G) E₂)) (x : G) : continuous_multilinear_curry_fin1 𝕜 G E₂ f x = f (fin.snoc 0 x) := rfl @[simp] lemma continuous_multilinear_curry_fin1_symm_apply (f : G →L[𝕜] E₂) (v : (fin 1) → G) : (continuous_multilinear_curry_fin1 𝕜 G E₂).symm f v = f (v 0) := rfl end currying
829752d2358bbcd3664cedca67cf918e7e796d5b
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/override/measurementSystemOverride.lean
408a6bf4c53aab4b61dded3119eb83c71f5603aa
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
370
lean
import ..imperative_DSL.environment import ..eval.measurementEval open lang.measurementSystem def assignMeasurementSystem : environment.env → measureVar → measureExpr → environment.env | i v e := { ms := ⟨(λ r, if (measureVarEq v r) then (measurementSystemEval e i) else (i.ms.ms r))⟩ ..i }
36422ff91547b756a77bb0c41d39ea628b89ac34
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/tactic/elementwise.lean
e78d75c364a33055b757bc3fafc0a03d73b3c443
[ "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
8,794
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 tactic.fresh_names import category_theory.concrete_category /-! # Tools to reformulate category-theoretic lemmas in concrete categories ## The `elementwise` attribute The `elementwise` attribute can be applied to a lemma ```lean @[elementwise] lemma some_lemma {C : Type*} [category C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : X ⟶ Z) (w : ...) : f ≫ g = h := ... ``` and will produce ```lean lemma some_lemma_apply {C : Type*} [category C] [concrete_category C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : X ⟶ Z) (w : ...) (x : X) : g (f x) = h x := ... ``` Here `X` is being coerced to a type via `concrete_category.has_coe_to_sort` and `f`, `g`, and `h` are being coerced to functions via `concrete_category.has_coe_to_fun`. Further, we simplify the type using `concrete_category.coe_id : ((𝟙 X) : X → X) x = x` and `concrete_category.coe_comp : (f ≫ g) x = g (f x)`, replacing morphism composition with function composition. The name of the produced lemma can be specified with `@[elementwise other_lemma_name]`. If `simp` is added first, the generated lemma will also have the `simp` attribute. ## Implementation This closely follows the implementation of the `@[reassoc]` attribute, due to Simon Hudon. Thanks to Gabriel Ebner for help diagnosing universe issues. -/ namespace tactic open interactive lean.parser category_theory /-- From an expression `f = g`, where `f g : X ⟶ Y` for some objects `X Y : V` with `[S : category V]`, extract the expression for `S`. -/ meta def extract_category : expr → tactic expr | `(@eq (@has_hom.hom ._ (@category_struct.to_has_hom _ (@category.to_category_struct _ %%S)) _ _) _ _) := pure S | _ := failed /-- (internals for `@[elementwise]`) Given a lemma of the form `f = g`, where `f g : X ⟶ Y` and `X Y : V`, proves a new lemma of the form `∀ (x : X), f x = g x` if we are already in a concrete category, or `∀ [concrete_category.{w} V] (x : X), f x = g x` otherwise. Returns the type and proof of this lemma, and the universe parameter `w` for the `concrete_category` instance, if it was not synthesized. -/ -- This is closely modelled on `reassoc_axiom`. meta def prove_elementwise (h : expr) : tactic (expr × expr × option name) := do (vs,t) ← infer_type h >>= open_pis, (f, g) ← match_eq t, S ← extract_category t <|> fail "no morphism equation found in statement", `(@has_hom.hom _ %%H %%X %%Y) ← infer_type f, C ← infer_type X, CC_type ← to_expr ``(@concrete_category %%C %%S), (CC, CC_found) ← (do CC ← mk_instance CC_type, pure (CC, tt)) <|> (do CC ← mk_local' `I binder_info.inst_implicit CC_type, pure (CC, ff)), -- This is need to fill in universe levels fixed by `mk_instance`: CC_type ← instantiate_mvars CC_type, x_type ← to_expr ``(@coe_sort %%C (@category_theory.concrete_category.has_coe_to_sort %%C %%S %%CC) %%X), x ← mk_local_def `x x_type, t' ← to_expr ``(@coe_fn (@category_theory.has_hom.hom %%C %%H %%X %%Y) (@category_theory.concrete_category.has_coe_to_fun %%C %%S %%CC %%X %%Y) %%f %%x = @coe_fn (@category_theory.has_hom.hom %%C %%H %%X %%Y) (@category_theory.concrete_category.has_coe_to_fun %%C %%S %%CC %%X %%Y) %%g %%x), let c' := h.mk_app vs, (_,pr) ← solve_aux t' (rewrite_target c'; reflexivity), -- The codomain of forget lives in a new universe, which may be now a universe metavariable -- if we didn't synthesize an instance: [w, _, _] ← pure CC_type.get_app_fn.univ_levels, -- We unify that with a fresh universe parameter. n ← match w with | level.mvar _ := (do n ← get_unused_name_reserved [`w] mk_name_set, unify (expr.sort (level.param n)) (expr.sort w), pure (option.some n)) | _ := pure option.none end, t' ← instantiate_mvars t', CC ← instantiate_mvars CC, x ← instantiate_mvars x, -- Now the key step: replace morphism composition with function composition, -- and identity morphisms with nothing. let s := simp_lemmas.mk, s ← s.add_simp ``coe_id, s ← s.add_simp ``coe_comp, (t'', pr', _) ← simplify s [] t', pr' ← mk_eq_mp pr' pr, t'' ← pis (vs ++ (if CC_found then [x] else [CC, x])) t'', pr' ← lambdas (vs ++ (if CC_found then [x] else [CC, x])) pr', pure (t'', pr', n) /-- (implementation for `@[elementwise]`) Given a declaration named `n` of the form `∀ ..., f = g`, proves a new lemma named `n'` of the form `∀ ... [concrete_category V] (x : X), f x = g x`. -/ meta def elementwise_lemma (n : name) (n' : name := n.append_suffix "_apply") : tactic unit := do d ← get_decl n, let c := @expr.const tt n d.univ_levels, (t'',pr',l') ← prove_elementwise c, let params := l'.to_list ++ d.univ_params, add_decl $ declaration.thm n' params t'' (pure pr'), copy_attribute `simp n n' /-- The `elementwise` attribute can be applied to a lemma ```lean @[elementwise] lemma some_lemma {C : Type*} [category C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : X ⟶ Z) (w : ...) : f ≫ g = h := ... ``` and will produce ```lean lemma some_lemma_apply {C : Type*} [category C] [concrete_category C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : X ⟶ Z) (w : ...) (x : X) : g (f x) = h x := ... ``` Here `X` is being coerced to a type via `concrete_category.has_coe_to_sort` and `f`, `g`, and `h` are being coerced to functions via `concrete_category.has_coe_to_fun`. Further, we simplify the type using `concrete_category.coe_id : ((𝟙 X) : X → X) x = x` and `concrete_category.coe_comp : (f ≫ g) x = g (f x)`, replacing morphism composition with function composition. The `[concrete_category C]` argument will be omitted if it is possible to synthesize an instance. The name of the produced lemma can be specified with `@[elementwise other_lemma_name]`. If `simp` is added first, the generated lemma will also have the `simp` attribute. -/ @[user_attribute] meta def elementwise_attr : user_attribute unit (option name) := { name := `elementwise, descr := "create a companion lemma for a morphism equation applied to an element", parser := optional ident, after_set := some (λ n _ _, do some n' ← elementwise_attr.get_param n | elementwise_lemma n (n.append_suffix "_apply"), elementwise_lemma n $ n.get_prefix ++ n' ) } add_tactic_doc { name := "elementwise", category := doc_category.attr, decl_names := [`tactic.elementwise_attr], tags := ["category theory"] } namespace interactive setup_tactic_parser /-- `elementwise h`, for assumption `w : ∀ ..., f ≫ g = h`, creates a new assumption `w : ∀ ... (x : X), g (f x) = h x`. `elementwise! h`, does the same but deletes the initial `h` assumption. (You can also add the attribute `@[elementwise]` to lemmas to generate new declarations generalized in this way.) -/ meta def elementwise (del : parse (tk "!")?) (ns : parse ident*) : tactic unit := do ns.mmap' (λ n, do h ← get_local n, (t,pr,u) ← prove_elementwise h, assertv n t pr, when del.is_some (tactic.clear h) ) end interactive /-- Auxiliary definition for `category_theory.elementwise_of`. -/ meta def derive_elementwise_proof : tactic unit := do `(calculated_Prop %%v %%h) ← target, (t,pr,n) ← prove_elementwise h, unify v t, exact pr end tactic /-- With `w : ∀ ..., f ≫ g = h` (with universal quantifiers tolerated), `elementwise_of w : ∀ ... (x : X), g (f x) = h x`. The type and proof of `elementwise_of h` is generated by `tactic.derive_elementwise_proof` which makes `elementwise_of` meta-programming adjacent. It is not called as a tactic but as an expression. The goal is to avoid creating assumptions that are dismissed after one use: ```lean example (M N K : Mon.{u}) (f : M ⟶ N) (g : N ⟶ K) (h : M ⟶ K) (w : f ≫ g = h) (m : M) : g (f m) = h m := begin rw elementwise_of w, end ``` -/ theorem category_theory.elementwise_of {α} (hh : α) {β} (x : tactic.calculated_Prop β hh . tactic.derive_elementwise_proof) : β := x /-- With `w : ∀ ..., f ≫ g = h` (with universal quantifiers tolerated), `elementwise_of w : ∀ ... (x : X), g (f x) = h x`. Although `elementwise_of` is not a tactic or a meta program, its type is generated through meta-programming to make it usable inside normal expressions. -/ add_tactic_doc { name := "category_theory.elementwise_of", category := doc_category.tactic, decl_names := [`category_theory.elementwise_of], tags := ["category theory"] }
509e3cb6e6ce171a9b48cdbf0f1d881e0b9499a9
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/elements.lean
91489d5da2e6a1d68c502a22a5524e24b14c9338
[ "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
4,895
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.comma import category_theory.groupoid import category_theory.punit /-! # The category of elements This file defines the category of elements, also known as (a special case of) the Grothendieck construction. Given a functor `F : C ⥤ Type`, an object of `F.elements` is a pair `(X : C, x : F.obj X)`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. ## Implementation notes This construction is equivalent to a special case of a comma construction, so this is mostly just a more convenient API. We prove the equivalence in `category_theory.category_of_elements.comma_equivalence`. ## References * [Emily Riehl, *Category Theory in Context*, Section 2.4][riehl2017] * <https://en.wikipedia.org/wiki/Category_of_elements> * <https://ncatlab.org/nlab/show/category+of+elements> ## Tags category of elements, Grothendieck construction, comma category -/ namespace category_theory universes w v u variables {C : Type u} [category.{v} C] /-- The type of objects for the category of elements of a functor `F : C ⥤ Type` is a pair `(X : C, x : F.obj X)`. -/ @[nolint has_inhabited_instance] def functor.elements (F : C ⥤ Type w) := (Σ c : C, F.obj c) /-- The category structure on `F.elements`, for `F : C ⥤ Type`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. -/ instance category_of_elements (F : C ⥤ Type w) : category.{v} F.elements := { hom := λ p q, { f : p.1 ⟶ q.1 // (F.map f) p.2 = q.2 }, id := λ p, ⟨𝟙 p.1, by obviously⟩, comp := λ p q r f g, ⟨f.val ≫ g.val, by obviously⟩ } namespace category_of_elements @[ext] lemma ext (F : C ⥤ Type w) {x y : F.elements} (f g : x ⟶ y) (w : f.val = g.val) : f = g := subtype.ext_val w @[simp] lemma comp_val {F : C ⥤ Type w} {p q r : F.elements} {f : p ⟶ q} {g : q ⟶ r} : (f ≫ g).val = f.val ≫ g.val := rfl @[simp] lemma id_val {F : C ⥤ Type w} {p : F.elements} : (𝟙 p : p ⟶ p).val = 𝟙 p.1 := rfl end category_of_elements instance groupoid_of_elements {G : Type u} [groupoid.{v} G] (F : G ⥤ Type w) : groupoid F.elements := { inv := λ p q f, ⟨inv f.val, calc F.map (inv f.val) q.2 = F.map (inv f.val) (F.map f.val p.2) : by rw f.2 ... = (F.map f.val ≫ F.map (inv f.val)) p.2 : by simp ... = p.2 : by {rw ←functor.map_comp, simp}⟩, } namespace category_of_elements variable (F : C ⥤ Type w) /-- The functor out of the category of elements which forgets the element. -/ @[simps] def π : F.elements ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.val } /-- A natural transformation between functors induces a functor between the categories of elements. -/ @[simps] def map {F₁ F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : F₁.elements ⥤ F₂.elements := { obj := λ t, ⟨t.1, α.app t.1 t.2⟩, map := λ t₁ t₂ k, ⟨k.1, by simpa [←k.2] using (functor_to_types.naturality _ _ α k.1 t₁.2).symm⟩ } @[simp] lemma map_π {F₁ F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : map α ⋙ π F₂ = π F₁ := rfl /-- The forward direction of the equivalence `F.elements ≅ (*, F)`. -/ def to_comma : F.elements ⥤ comma (functor.from_punit punit) F := { obj := λ X, { left := punit.star, right := X.1, hom := λ _, X.2 }, map := λ X Y f, { right := f.val } } @[simp] lemma to_comma_obj (X) : (to_comma F).obj X = { left := punit.star, right := X.1, hom := λ _, X.2 } := rfl @[simp] lemma to_comma_map {X Y} (f : X ⟶ Y) : (to_comma F).map f = { right := f.val } := rfl /-- The reverse direction of the equivalence `F.elements ≅ (*, F)`. -/ def from_comma : comma (functor.from_punit punit) F ⥤ F.elements := { obj := λ X, ⟨X.right, X.hom (punit.star)⟩, map := λ X Y f, ⟨f.right, congr_fun f.w'.symm punit.star⟩ } @[simp] lemma from_comma_obj (X) : (from_comma F).obj X = ⟨X.right, X.hom (punit.star)⟩ := rfl @[simp] lemma from_comma_map {X Y} (f : X ⟶ Y) : (from_comma F).map f = ⟨f.right, congr_fun f.w'.symm punit.star⟩ := rfl /-- The equivalence between the category of elements `F.elements` and the comma category `(*, F)`. -/ def comma_equivalence : F.elements ≌ comma (functor.from_punit punit) F := equivalence.mk (to_comma F) (from_comma F) (nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy)) (nat_iso.of_components (λ X, { hom := { right := 𝟙 _ }, inv := { right := 𝟙 _ } }) (by tidy)) @[simp] lemma comma_equivalence_functor : (comma_equivalence F).functor = to_comma F := rfl @[simp] lemma comma_equivalence_inverse : (comma_equivalence F).inverse = from_comma F := rfl end category_of_elements end category_theory
795ecd6707457f33cc6b9eff47373499c1d34cd7
0c9c1ff8e5013c525bf1d72338b62db639374733
/library/init/meta/converter/interactive.lean
5a0541ec6e0971e97ce5220bafea202f25b004c6
[ "Apache-2.0" ]
permissive
semorrison/lean
1f2bb450c3400098666ff6e43aa29b8e1e3cdc3a
85dcb385d5219f2fca8c73b2ebca270fe81337e0
refs/heads/master
1,638,526,143,586
1,634,825,588,000
1,634,825,588,000
258,650,844
0
0
Apache-2.0
1,587,772,955,000
1,587,772,954,000
null
UTF-8
Lean
false
false
6,901
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Converter monad for building simplifiers. -/ prelude import init.meta.interactive import init.meta.converter.conv namespace conv meta def save_info (p : pos) : conv unit := do s ← tactic.read, tactic.save_info_thunk p (λ _, s.to_format tt) meta def step {α : Type} (c : conv α) : conv unit := c >> return () meta def istep {α : Type} (line0 col0 line col ast : nat) (c : conv α) : conv unit := tactic.istep line0 col0 line col ast c meta def execute (c : conv unit) : tactic unit := c meta def solve1 (c : conv unit) : conv unit := tactic.solve1 $ c >> tactic.try (tactic.any_goals tactic.reflexivity) namespace interactive open lean open lean.parser open _root_.interactive open interactive.types open tactic_result meta def itactic : Type := conv unit meta def skip : conv unit := conv.skip meta def whnf : conv unit := conv.whnf meta def dsimp (no_dflt : parse only_flag) (es : parse tactic.simp_arg_list) (attr_names : parse with_ident_list) (cfg : tactic.dsimp_config := {}) : conv unit := do (s, u) ← tactic.mk_simp_set no_dflt attr_names es, conv.dsimp (some s) u cfg meta def trace_lhs : conv unit := lhs >>= tactic.trace meta def change (p : parse texpr) : conv unit := tactic.i_to_expr p >>= conv.change meta def congr : conv unit := conv.congr meta def funext : conv unit := conv.funext private meta def is_relation : conv unit := (lhs >>= tactic.relation_lhs_rhs >> return ()) <|> tactic.fail "current expression is not a relation" meta def to_lhs : conv unit := is_relation >> congr >> tactic.swap >> skip meta def to_rhs : conv unit := is_relation >> congr >> skip meta def done : conv unit := tactic.done meta def find (p : parse parser.pexpr) (c : itactic) : conv unit := do (r, lhs, _) ← tactic.target_lhs_rhs, pat ← tactic.pexpr_to_pattern p, s ← simp_lemmas.mk_default, -- to be able to use congruence lemmas @[congr] -- we have to thread the tactic errors through `ext_simplify_core` manually st ← tactic.read, (found_result, new_lhs, pr) ← tactic.ext_simplify_core (success ff st) -- loop counter {zeta := ff, beta := ff, single_pass := tt, eta := ff, proj := ff, fail_if_unchanged := ff, memoize := ff} s (λ u, return u) (λ found_result s r p e, do found ← tactic.unwrap found_result, guard (not found), matched ← (tactic.match_pattern pat e >> return tt) <|> return ff, guard matched, res ← tactic.capture (c.convert e r), -- If an error occurs in conversion, capture it; `ext_simplify_core` will not -- propagate it. match res with | (success r s') := return (success tt s', r.fst, some r.snd, ff) | (exception f p s') := return (exception f p s', e, none, ff) end) (λ a s r p e, tactic.failed) r lhs, found ← tactic.unwrap found_result, when (not found) $ tactic.fail "find converter failed, pattern was not found", update_lhs new_lhs pr meta def for (p : parse parser.pexpr) (occs : parse (list_of small_nat)) (c : itactic) : conv unit := do (r, lhs, _) ← tactic.target_lhs_rhs, pat ← tactic.pexpr_to_pattern p, s ← simp_lemmas.mk_default, -- to be able to use congruence lemmas @[congr] -- we have to thread the tactic errors through `ext_simplify_core` manually st ← tactic.read, (found_result, new_lhs, pr) ← tactic.ext_simplify_core (success 1 st) -- loop counter, and whether the conversion tactic failed {zeta := ff, beta := ff, single_pass := tt, eta := ff, proj := ff, fail_if_unchanged := ff, memoize := ff} s (λ u, return u) (λ found_result s r p e, do i ← tactic.unwrap found_result, matched ← (tactic.match_pattern pat e >> return tt) <|> return ff, guard matched, if i ∈ occs then do res ← tactic.capture (c.convert e r), -- If an error occurs in conversion, capture it; `ext_simplify_core` will not -- propagate it. match res with | (success r s') := return (success (i+1) s', r.fst, some r.snd, tt) | (exception f p s') := return (exception f p s', e, none, tt) end else do st ← tactic.read, return (success (i+1) st, e, none, tt)) (λ a s r p e, tactic.failed) r lhs, tactic.unwrap found_result, update_lhs new_lhs pr meta def simp (no_dflt : parse only_flag) (hs : parse tactic.simp_arg_list) (attr_names : parse with_ident_list) (cfg : tactic.simp_config_ext := {}) : conv unit := do (s, u) ← tactic.mk_simp_set no_dflt attr_names hs, (r, lhs, rhs) ← tactic.target_lhs_rhs, (new_lhs, pr, lms) ← tactic.simplify s u lhs cfg.to_simp_config r cfg.discharger, update_lhs new_lhs pr, return () meta def guard_lhs (p : parse texpr) : tactic unit := do t ← lhs, tactic.interactive.guard_expr_eq t p section rw open tactic.interactive (rw_rules rw_rule get_rule_eqn_lemmas to_expr') open tactic (rewrite_cfg) private meta def rw_lhs (h : expr) (cfg : rewrite_cfg) : conv unit := do l ← conv.lhs, (new_lhs, prf, _) ← tactic.rewrite h l cfg, update_lhs new_lhs prf private meta def rw_core (rs : list rw_rule) (cfg : rewrite_cfg) : conv unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do h ← to_expr' r.rule, rw_lhs h {symm := r.symm, ..cfg}) (eq_lemmas.mfirst $ λ n, do e ← tactic.mk_const n, rw_lhs e {symm := r.symm, ..cfg}) (eq_lemmas.empty) meta def rewrite (q : parse rw_rules) (cfg : rewrite_cfg := {}) : conv unit := rw_core q.rules cfg meta def rw (q : parse rw_rules) (cfg : rewrite_cfg := {}) : conv unit := rw_core q.rules cfg end rw end interactive end conv namespace tactic namespace interactive open lean open lean.parser open _root_.interactive open interactive.types open tactic local postfix `?`:9001 := optional private meta def conv_at (h_name : name) (c : conv unit) : tactic unit := do h ← get_local h_name, h_type ← infer_type h, (new_h_type, pr) ← c.convert h_type, replace_hyp h new_h_type pr, return () private meta def conv_target (c : conv unit) : tactic unit := do t ← target, (new_t, pr) ← c.convert t, replace_target new_t pr, try tactic.triv, try (tactic.reflexivity reducible) meta def conv (loc : parse (tk "at" *> ident)?) (p : parse (tk "in" *> parser.pexpr)?) (c : conv.interactive.itactic) : tactic unit := do let c := match p with | some p := _root_.conv.interactive.find p c | none := c end, match loc with | some h := conv_at h c | none := conv_target c end end interactive end tactic
b1b6b03a73aadad2f8b3c0ac9d3eb4b76fd469e1
93b17e1ec33b7fd9fb0d8f958cdc9f2214b131a2
/src/top/alexandrov.lean
791f2d971ad217016d44506645012759c3e1ba8d
[]
no_license
intoverflow/timesink
93f8535cd504bc128ba1b57ce1eda4efc74e5136
c25be4a2edb866ad0a9a87ee79e209afad6ab303
refs/heads/master
1,620,033,920,087
1,524,995,105,000
1,524,995,105,000
120,576,102
1
0
null
null
null
null
UTF-8
Lean
false
false
14,350
lean
/- Topological spaces - -/ import .basic namespace Top universes ℓ ℓ₁ ℓ₂ ℓ₁₁ ℓ₂₂ structure PreOrder : Type.{ℓ+1} := (pt : Type.{ℓ}) (rel : pt → pt → Prop) (refl : ∀ a, rel a a) (trans : ∀ a b c, rel a b → rel b c → rel a c) (join : ∀ x y, { z // ∀ w, rel x w ∧ rel y w ↔ rel z w}) def PreOrder.OpenBasis (A : PreOrder.{ℓ₁}) : OpenBasis A.pt := { OI := A.pt , Open := λ x y, A.rel x y , Cover := begin apply funext, intro x, apply eq.symm, apply iff.to_eq, apply iff.intro, { intro H, constructor }, { intro H, clear H, exact exists.intro _ (exists.intro (exists.intro _ rfl) (A.refl _)) } end , inter := λ x y, (A.join x y).val , Ointer := λ x y , begin apply funext, intro w, apply iff.to_eq, apply iff.intro, { intro H, apply ((A.join x y).property _).2, exact H }, { intro H, apply ((A.join x y).property _).1, exact H } end } def PreOrder.Top (A : PreOrder.{ℓ₁}) : Topology A.pt := A.OpenBasis.Topology -- open Sep -- structure PreOrder.Fn (A : PreOrder.{ℓ₁}) -- (alg : A.pt → OrdAlg.{ℓ₂}) -- (res : ∀ p q, A.rel q p → OrdRel (alg p) (alg q)) -- (U : A.Top.OI) -- := (fn : ∀ (p : {p // p ∈ A.Top.Open U}) -- , (alg p.val).alg.τ) -- (continuous : ∀ (p q : {p // p ∈ A.Top.Open U}) -- (H : A.rel q.val p.val) -- , (res p.val q.val H).rel (fn p) (fn q)) -- def PreOrder.Fn.eq {A : PreOrder.{ℓ₁}} -- {alg : A.pt → OrdAlg.{ℓ₂}} -- {res : ∀ p q, A.rel q p → OrdRel (alg p) (alg q)} -- {U : A.Top.OI} -- (s t : A.Fn alg res U) -- (E : s.fn = t.fn) -- : s = t -- := begin cases s, cases t, simp at E, subst E end -- def PreOrder.Sec (A : PreOrder.{ℓ₁}) -- (alg : A.pt → OrdAlg.{ℓ₂}) -- (closed : (∀ a, (alg a).ord.UpClosed) ∨ (∀ a, (alg a).ord.DownClosed)) -- (res : ∀ p q, A.rel q p → OrdRel (alg p) (alg q)) -- (U : A.Top.OI) -- : OrdAlg -- := { alg := -- { τ := A.Fn alg res U -- , join := λ s₁ s₂ s₃ -- , ∀ (p : {p // p ∈ A.Top.Open U}) -- , (alg p.val).alg.join (s₁.fn p) (s₂.fn p) (s₃.fn p) -- , comm := λ s₁ s₂ s₃ J p -- , (alg p.val).alg.comm (J p) -- , assoc := λ s₁ s₂ s₃ s₁₂ s₁₂₃ J₁₂ J₁₂₃ P C -- , sorry -- } -- , ord := λ s t, ∀ (p : {p // p ∈ A.Top.Open U}) -- , s.fn p ≤ t.fn p -- , refl := λ s p, (alg p.val).refl _ -- , trans := λ a b c H₁₂ H₁₂₃ p -- , (alg p.val).trans _ _ _ (H₁₂ p) (H₁₂₃ p) -- , closed -- := begin -- cases closed with H H, -- { apply or.inl, -- intros x₁ x₂ x₃ y₃ J R, -- exact sorry -- }, -- { apply or.inr, -- exact sorry -- } -- end -- } -- def PreOrder.ρ (A : PreOrder.{ℓ₁}) -- (alg : A.pt → OrdAlg.{ℓ₂}) -- (closed : (∀ a, (alg a).ord.UpClosed) ∨ (∀ a, (alg a).ord.DownClosed)) -- (res : ∀ p q, A.rel q p → OrdRel (alg p) (alg q)) -- (U₁ U₂ : (PreOrder.Top A).OI) -- (HU₁U₂ : (PreOrder.Top A).Open U₂ ⊆ (PreOrder.Top A).Open U₁) -- : OrdRel (PreOrder.Sec A alg closed res U₁) (PreOrder.Sec A alg closed res U₂) -- := { rel := λ s t -- , ∀ (p : {p // p ∈ A.Top.Open U₁}) -- (q : {p // p ∈ A.Top.Open U₂}) -- (R : A.rel q.val p.val) -- , (res p.val q.val R).rel (s.fn p) (t.fn q) -- , action -- := begin -- apply funext, intro s, apply funext, intro t, -- apply iff.to_eq, apply iff.intro, -- { intro H, -- cases H with t' H, cases H with H Rt, -- cases H with s' H, cases H with Rs H, -- intros p q R, -- have Qt := Rt q, -- have Qs := Rs p, -- have Q₁ := H p q R, clear H, -- rw (res (p.val) (q.val) R).action.symm, -- refine exists.intro _ (and.intro _ Qt), -- exact exists.intro _ (and.intro Qs Q₁) -- }, -- { intro H, -- existsi t, -- refine and.intro _ _, -- { existsi s, -- apply and.intro, -- { intro p, apply OrdAlg.refl }, -- { intros p q R, apply H } -- }, -- { intro p, apply OrdAlg.refl } -- } -- end -- } -- def PreOrder.Sheaf (A : PreOrder.{ℓ₁}) -- (alg : A.pt → OrdAlg.{ℓ₂}) -- (closed : (∀ a, (alg a).ord.UpClosed) ∨ (∀ a, (alg a).ord.DownClosed)) -- (res : ∀ p q, A.rel q p → OrdRel (alg p) (alg q)) -- (res_id : ∀ p H, res p p H = OrdAlg.IdRel _) -- (glue : ∀ p q H x' x y -- , x' ≤ x -- → (res p q H).rel x' y -- → (res p q H).rel x y) -- : Sheaf A.Top -- := { Section := A.Sec alg closed res -- , Stalk := λ p, true.intro -- , ρ := A.ρ alg closed res -- , ρ_id := λ U HUU -- , begin -- apply OrdRel.eq, -- apply funext, intro s, apply funext, intro t, -- apply iff.to_eq, apply iff.intro, -- { intros H p, -- have Q := (H p p (A.refl _)), -- rw res_id at Q, -- exact Q -- }, -- { intros H p q R, -- have Q := s.continuous p q R, -- rw (res (p.val) (q.val) R).action.symm, -- refine exists.intro _ (and.intro _ (H q)), -- refine exists.intro _ (and.intro _ Q), -- apply OrdAlg.refl -- } -- end -- , ρ_circ := λ U₁ U₂ U₃ H₂₁ H₃₂ H₃₁ -- , begin -- apply OrdRel.eq, simp, -- apply funext, intro s, apply funext, intro t, -- apply iff.to_eq, apply iff.intro, -- { intros H p₁ p₃ R, -- let p₂ : {p // p ∈ (PreOrder.Top A).Open U₂} -- := { val := p₃.val -- , property := H₃₂ p₃.property -- }, -- cases H with t' H, cases H with H Rt, -- cases H with s' H, cases H with Rs H, -- have Qt := Rt p₂ p₃ (A.refl _), -- have Qs := Rs p₁ p₂ R, -- exact sorry -- }, -- { intros H, -- exact sorry -- -- refine exists.intro _ (and.intro (exists.intro _ (and.intro _ (OrdAlg.refl _ _))) _), -- -- { refine { fn := λ p -- -- , let p' : {p // p ∈ (PreOrder.Top A).Open U₁} -- -- := { val := p.val, property := H₂₁ p.property } -- -- in res p' p (A.refl _) (s.fn p') -- -- , continuous := _ -- -- }, -- -- intros p q R, -- -- cases p with p Hp, cases q with q Hq, -- -- apply and.intro, -- -- { have Q := s.continuous { val := q, property := H₂₁ Hq } -- -- { val := q, property := H₂₁ Hq } -- -- (A.refl _), -- -- apply OrdAlg.trans _ _ _ _ Q.2, clear Q, -- -- have Q := s.continuous { val := p, property := H₂₁ Hp } -- -- { val := q, property := H₂₁ Hq } -- -- R, -- -- apply OrdAlg.trans _ _ _ _ Q.1, clear Q, -- -- apply action, -- -- have Q := s.continuous { val := p, property := H₂₁ Hp } -- -- { val := p, property := H₂₁ Hp } -- -- (A.refl _), -- -- exact Q.1 -- -- }, -- -- { have Q := s.continuous { val := q, property := H₂₁ Hq } -- -- { val := q, property := H₂₁ Hq } -- -- (A.refl _), -- -- apply OrdAlg.trans _ _ _ _ _ Q.1, clear Q, -- -- have Q := s.continuous { val := p, property := H₂₁ Hp } -- -- { val := q, property := H₂₁ Hq } -- -- R, -- -- apply OrdAlg.trans _ _ _ _ _ Q.2, clear Q, -- -- apply action, -- -- have Q := s.continuous { val := p, property := H₂₁ Hp } -- -- { val := p, property := H₂₁ Hp } -- -- (A.refl _), -- -- exact Q.2 -- -- } -- -- }, -- -- { intros p q R, -- -- simp, -- -- let q' : {p // p ∈ A.Top.Open U₁} -- -- := { val := q.val, property := H₂₁ q.property }, -- -- have Q := s.continuous q' q' (A.refl _), -- -- apply OrdAlg.trans _ _ _ _ _ Q.1, clear Q, -- -- have Q := s.continuous p q' R, -- -- apply OrdAlg.trans _ _ _ _ _ Q.2, clear Q, -- -- apply action, -- -- apply OrdAlg.refl, -- -- }, -- -- { intros p q R, -- -- simp, -- -- let p' : {p // p ∈ A.Top.Open U₁} -- -- := { val := p.val, property := H₂₁ p.property }, -- -- let q' : {p // p ∈ A.Top.Open U₁} -- -- := { val := q.val, property := H₃₁ q.property }, -- -- refine OrdAlg.trans _ _ _ _ _ (H p' q R), -- -- apply action, -- -- have Q := (s.continuous p' p' (A.refl _)), -- -- apply Q.2 -- -- } -- } -- end -- , glue := λ U cover in_cover sub_cover X loc E -- , begin -- refine exists.intro -- { rel := λ x s, -- ∀ (p : {p // p ∈ A.Top.Open U}) -- , ∃ s', (loc p).rel x s' -- ∧ (A.ρ alg closed res U (cover p) (sub_cover p)).rel s s' -- , action := _ -- } -- (and.intro _ _), -- { apply funext, intro x, apply funext, intro s, -- dsimp at *, -- apply iff.to_eq, apply iff.intro, -- { intros H p, -- cases H with s' H, cases H with H Rs, -- cases H with x' H, cases H with Rx H, -- have Q := H p, clear H, -- cases Q with t Q, cases Q with Rxt Rts, -- existsi t, -- apply and.intro, -- { rw (loc p).action.symm, -- refine exists.intro _ (and.intro _ (OrdAlg.refl _ _)), -- exact exists.intro _ (and.intro Rx Rxt) -- }, -- { intros a b Hab, -- have Qa := Rs a, -- have Qb := Rts a b Hab, -- apply glue _ _ _ _ _ _ Qa Qb -- } -- }, -- { intro H, -- refine exists.intro { fn := _, continuous := _ } (and.intro _ _), -- { intro p, -- have Q := classical.indefinite_description _ (H p), -- cases Q with s' Q, -- exact s'.fn { val := p, property := in_cover p } -- }, -- { intros p q R, -- cases classical.indefinite_description _ (H p) with wp Qp, -- cases classical.indefinite_description _ (H q) with wq Qq, -- dsimp, -- -- -- have Q := congr_fun (congr_fun (congr_arg OrdRel.rel (E p q)) x) -- { fn := λ z, s.fn { val := z.val, property := begin apply sub_cover p, exact sorry end } -- , continuous := begin intros z₁ z₂ R, exact sorry end -- }, -- -- -- exact sorry -- }, -- { exact sorry -- }, -- { exact sorry -- } -- } -- }, -- { exact sorry -- }, -- { exact sorry -- } -- end -- } end Top
e816a6234cca9fabf0681d62527535491c67c3f1
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/topological_spaces/subspace.lean
533dc95d9ee042dc22bd28cb1647e4519493f20a
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
1,674
lean
import .category import for_mathlib.data_set_basic open category_theory local notation f ` ∘ `:80 g:80 := g ≫ f universe u namespace homotopy_theory.topological_spaces namespace Top local notation `Top` := Top.{u} def incl {X : Top} (A : set X) : Top.mk_ob A ⟶ X := Top.mk_hom subtype.val def embedding_incl {X : Top} (A : set X) : embedding (incl A) := embedding_subtype_coe noncomputable def factor_through_embedding {W X Y : Top} {f : W ⟶ Y} {g : X ⟶ Y} (hf : set.range f ⊆ set.range g) (hg : embedding g) : W ⟶ X := Top.mk_hom (classical.some $ (factors_iff f g).mpr hf) $ by rw [hg.continuous_iff, ←classical.some_spec ((factors_iff f g).mpr hf)]; exact f.2 @[simp] lemma factor_through_embedding_commutes {W X Y : Top} {f : W ⟶ Y} {g : X ⟶ Y} {hf : set.range f ⊆ set.range g} {hg : embedding g} : factor_through_embedding hf hg ≫ g = f := Top.hom_eq2.mpr $ (classical.some_spec ((factors_iff f g).mpr hf)).symm def factor_through_incl {W X : Top} (f : W ⟶ X) (A : set X) (h : set.range f ⊆ A) : W ⟶ Top.mk_ob A := Top.mk_hom (λ (w : W), ⟨f w, h (set.mem_range_self w)⟩) (by continuity) @[simp] lemma factor_through_incl_commutes {W X : Top} (f : W ⟶ X) (A : set X) (h : set.range f ⊆ A) : incl A ∘ factor_through_incl f A h = f := by ext; refl lemma embedding_of_embedding_comp {X Y Z : Top} {f : X ⟶ Y} (g : Y ⟶ Z) (hgf : embedding (g ∘ f)) : embedding f := embedding_of_embedding_compose f.2 g.2 hgf def incl' {X : Top} (A B : set X) (h : A ⊆ B) : Top.mk_ob A ⟶ Top.mk_ob B := Top.mk_hom (λ a, ⟨a.val, h a.property⟩) (by continuity!) end «Top» end homotopy_theory.topological_spaces
b5dd8f4cd7c5b2c016a5e715c7f30acb3d4ee5ce
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/nat/factors.lean
b06dac80eaf84e155ff1ad6b6e995cab7a662717
[ "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
9,962
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.nat.prime import data.list.prime import data.list.sort import tactic.nth_rewrite /-! # Prime numbers This file deals with the factors of natural numbers. ## Important declarations - `nat.factors n`: the prime factorization of `n` - `nat.factors_unique`: uniqueness of the prime factorisation -/ open bool subtype open_locale nat namespace nat /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) @[simp] lemma factors_zero : factors 0 = [] := by rw factors @[simp] lemma factors_one : factors 1 = [] := by rw factors lemma prime_of_mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := by simp | 1 := by simp | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 (by rwa [factors] at h), or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) prime_of_mem_factors lemma pos_of_mem_factors {n p : ℕ} (h : p ∈ factors n) : 0 < p := prime.pos (prime_of_mem_factors h) lemma prod_factors : ∀ {n}, n ≠ 0 → list.prod (factors n) = n | 0 := by simp | 1 := by simp | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show (factors n).prod = n, from have h₁ : n / m ≠ 0 := λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [factors, list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] lemma factors_prime {p : ℕ} (hp : nat.prime p) : p.factors = [p] := begin have : p = (p - 2) + 2 := (tsub_eq_iff_eq_add_of_le hp.two_le).mp rfl, rw [this, nat.factors], simp only [eq.symm this], have : nat.min_fac p = p := (nat.prime_def_min_fac.mp hp).2, split, { exact this, }, { simp only [this, nat.factors, nat.div_self (nat.prime.pos hp)], }, end lemma factors_chain : ∀ {n a}, (∀ p, prime p → p ∣ n → a ≤ p) → list.chain (≤) a (factors n) | 0 := λ a h, by simp | 1 := λ a h, by simp | n@(k+2) := λ a h, let m := min_fac n in have n / m < n := factors_lemma, begin rw factors, refine list.chain.cons ((le_min_fac.2 h).resolve_left dec_trivial) (factors_chain _), exact λ p pp d, min_fac_le_of_dvd pp.two_le (d.trans $ div_dvd_of_dvd $ min_fac_dvd _), end lemma factors_chain_2 (n) : list.chain (≤) 2 (factors n) := factors_chain $ λ p pp _, pp.two_le lemma factors_chain' (n) : list.chain' (≤) (factors n) := @list.chain'.tail _ _ (_::_) (factors_chain_2 _) lemma factors_sorted (n : ℕ) : list.sorted (≤) (factors n) := list.chain'_iff_pairwise.1 (factors_chain' _) /-- `factors` can be constructed inductively by extracting `min_fac`, for sufficiently large `n`. -/ lemma factors_add_two (n : ℕ) : factors (n+2) = min_fac (n+2) :: factors ((n+2) / min_fac (n+2)) := by rw factors @[simp] lemma factors_eq_nil (n : ℕ) : n.factors = [] ↔ n = 0 ∨ n = 1 := begin split; intro h, { rcases n with (_ | _ | n), { exact or.inl rfl }, { exact or.inr rfl }, { rw factors at h, injection h }, }, { rcases h with (rfl | rfl), { exact factors_zero }, { exact factors_one }, } end lemma eq_of_perm_factors {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) (h : a.factors ~ b.factors) : a = b := by simpa [prod_factors ha, prod_factors hb] using list.perm.prod_eq h section open list lemma mem_factors_iff_dvd {n p : ℕ} (hn : n ≠ 0) (hp : prime p) : p ∈ factors n ↔ p ∣ n := ⟨λ h, prod_factors hn ▸ list.dvd_prod h, λ h, mem_list_primes_of_dvd_prod (prime_iff.mp hp) (λ p h, prime_iff.mp (prime_of_mem_factors h)) ((prod_factors hn).symm ▸ h)⟩ lemma dvd_of_mem_factors {n p : ℕ} (h : p ∈ n.factors) : p ∣ n := begin rcases n.eq_zero_or_pos with rfl | hn, { exact dvd_zero p }, { rwa ←mem_factors_iff_dvd hn.ne' (prime_of_mem_factors h) } end lemma mem_factors {n p} (hn : n ≠ 0) : p ∈ factors n ↔ prime p ∧ p ∣ n := ⟨λ h, ⟨prime_of_mem_factors h, dvd_of_mem_factors h⟩, λ ⟨hprime, hdvd⟩, (mem_factors_iff_dvd hn hprime).mpr hdvd⟩ lemma le_of_mem_factors {n p : ℕ} (h : p ∈ n.factors) : p ≤ n := begin rcases n.eq_zero_or_pos with rfl | hn, { rw factors_zero at h, cases h }, { exact le_of_dvd hn (dvd_of_mem_factors h) }, end /-- **Fundamental theorem of arithmetic**-/ lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := begin refine perm_of_prod_eq_prod _ _ _, { rw h₁, refine (prod_factors _).symm, rintro rfl, rw prod_eq_zero_iff at h₁, exact prime.ne_zero (h₂ 0 h₁) rfl }, { simp_rw ←prime_iff, exact h₂ }, { simp_rw ←prime_iff, exact (λ p, prime_of_mem_factors) }, end lemma prime.factors_pow {p : ℕ} (hp : p.prime) (n : ℕ) : (p ^ n).factors = list.repeat p n := begin symmetry, rw ← list.repeat_perm, apply nat.factors_unique (list.prod_repeat p n), intros q hq, rwa eq_of_mem_repeat hq, end lemma eq_prime_pow_of_unique_prime_dvd {n p : ℕ} (hpos : n ≠ 0) (h : ∀ {d}, nat.prime d → d ∣ n → d = p) : n = p ^ n.factors.length := begin set k := n.factors.length, rw [←prod_factors hpos, ←prod_repeat p k, eq_repeat_of_mem (λ d hd, h (prime_of_mem_factors hd) (dvd_of_mem_factors hd))], end /-- For positive `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/ lemma perm_factors_mul {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) : (a * b).factors ~ a.factors ++ b.factors := begin refine (factors_unique _ _).symm, { rw [list.prod_append, prod_factors ha, prod_factors hb] }, { intros p hp, rw list.mem_append at hp, cases hp; exact prime_of_mem_factors hp }, end /-- For coprime `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/ lemma perm_factors_mul_of_coprime {a b : ℕ} (hab : coprime a b) : (a * b).factors ~ a.factors ++ b.factors := begin rcases a.eq_zero_or_pos with rfl | ha, { simp [(coprime_zero_left _).mp hab] }, rcases b.eq_zero_or_pos with rfl | hb, { simp [(coprime_zero_right _).mp hab] }, exact perm_factors_mul ha.ne' hb.ne', end lemma factors_sublist_right {n k : ℕ} (h : k ≠ 0) : n.factors <+ (n * k).factors := begin cases n, { rw zero_mul }, apply sublist_of_subperm_of_sorted _ (factors_sorted _) (factors_sorted _), rw (perm_factors_mul n.succ_ne_zero h).subperm_left, exact (sublist_append_left _ _).subperm, end lemma factors_sublist_of_dvd {n k : ℕ} (h : n ∣ k) (h' : k ≠ 0) : n.factors <+ k.factors := begin obtain ⟨a, rfl⟩ := h, exact factors_sublist_right (right_ne_zero_of_mul h'), end lemma factors_subset_right {n k : ℕ} (h : k ≠ 0) : n.factors ⊆ (n * k).factors := (factors_sublist_right h).subset lemma factors_subset_of_dvd {n k : ℕ} (h : n ∣ k) (h' : k ≠ 0) : n.factors ⊆ k.factors := (factors_sublist_of_dvd h h').subset lemma dvd_of_factors_subperm {a b : ℕ} (ha : a ≠ 0) (h : a.factors <+~ b.factors) : a ∣ b := begin rcases b.eq_zero_or_pos with rfl | hb, { exact dvd_zero _ }, rcases a with (_|_|a), { exact (ha rfl).elim }, { exact one_dvd _ }, use (b.factors.diff a.succ.succ.factors).prod, nth_rewrite 0 ←nat.prod_factors ha, rw [←list.prod_append, list.perm.prod_eq $ list.subperm_append_diff_self_of_count_le $ list.subperm_ext_iff.mp h, nat.prod_factors hb.ne'] end end lemma mem_factors_mul {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) {p : ℕ} : p ∈ (a * b).factors ↔ p ∈ a.factors ∨ p ∈ b.factors := begin rw [mem_factors (mul_ne_zero ha hb), mem_factors ha, mem_factors hb, ←and_or_distrib_left], simpa only [and.congr_right_iff] using prime.dvd_mul end /-- The sets of factors of coprime `a` and `b` are disjoint -/ lemma coprime_factors_disjoint {a b : ℕ} (hab : a.coprime b) : list.disjoint a.factors b.factors := begin intros q hqa hqb, apply not_prime_one, rw ←(eq_one_of_dvd_coprimes hab (dvd_of_mem_factors hqa) (dvd_of_mem_factors hqb)), exact prime_of_mem_factors hqa end lemma mem_factors_mul_of_coprime {a b : ℕ} (hab : coprime a b) (p : ℕ): p ∈ (a * b).factors ↔ p ∈ a.factors ∪ b.factors := begin rcases a.eq_zero_or_pos with rfl | ha, { simp [(coprime_zero_left _).mp hab] }, rcases b.eq_zero_or_pos with rfl | hb, { simp [(coprime_zero_right _).mp hab] }, rw [mem_factors_mul ha.ne' hb.ne', list.mem_union] end open list /-- If `p` is a prime factor of `a` then `p` is also a prime factor of `a * b` for any `b > 0` -/ lemma mem_factors_mul_left {p a b : ℕ} (hpa : p ∈ a.factors) (hb : b ≠ 0) : p ∈ (a*b).factors := begin rcases eq_or_ne a 0 with rfl | ha, { simpa using hpa }, apply (mem_factors_mul ha hb).2 (or.inl hpa), end /-- If `p` is a prime factor of `b` then `p` is also a prime factor of `a * b` for any `a > 0` -/ lemma mem_factors_mul_right {p a b : ℕ} (hpb : p ∈ b.factors) (ha : a ≠ 0) : p ∈ (a*b).factors := by { rw mul_comm, exact mem_factors_mul_left hpb ha } lemma eq_two_pow_or_exists_odd_prime_and_dvd (n : ℕ) : (∃ k : ℕ, n = 2 ^ k) ∨ ∃ p, nat.prime p ∧ p ∣ n ∧ odd p := (eq_or_ne n 0).elim (λ hn, (or.inr ⟨3, prime_three, hn.symm ▸ dvd_zero 3, ⟨1, rfl⟩⟩)) (λ hn, or_iff_not_imp_right.mpr (λ H, ⟨n.factors.length, eq_prime_pow_of_unique_prime_dvd hn (λ p hprime hdvd, hprime.eq_two_or_odd'.resolve_right (λ hodd, H ⟨p, hprime, hdvd, hodd⟩))⟩)) end nat assert_not_exists multiset
31b9ccdc471e6633b06f0521c6232adc968f5eb4
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/graph.lean
893e90ac5800e3f9ae69a335865f61c88869addb
[]
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
4,636
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan and Scott Morrison import .functor import .examples.types.types open tqft.categories namespace tqft.categories.graph structure {u v} Graph := ( vertices : Type u ) ( edges : vertices → vertices → Type v ) open Graph inductive {u v} path { G : Graph.{u v} } : vertices G → vertices G → Type (max u v) | nil : Π ( h : G.vertices ), path h h | cons : Π { h s t : G.vertices } ( e : G.edges h s ) ( l : path s t ), path h t notation a :: b := path.cons a b notation `p[` l:(foldr `, ` (h t, path.cons h t) path.nil _ `]`) := l inductive {u v} path_of_paths { G : Graph.{u v} } : vertices G → vertices G → Type (max u v) | nil : Π ( h : G.vertices ), path_of_paths h h | cons : Π { h s t : G.vertices } ( e : path h s ) ( l : path_of_paths s t ), path_of_paths h t notation a :: b := path_of_paths.cons a b notation `pp[` l:(foldr `, ` (h t, path_of_paths.cons h t) path_of_paths.nil _ `]`) := l -- The pattern matching trick used here was explained by Jeremy Avigad at https://groups.google.com/d/msg/lean-user/JqaI12tdk3g/F9MZDxkFDAAJ definition concatenate_paths { G : Graph } : Π { x y z : G.vertices }, path x y → path y z → path x z | ._ ._ _ (path.nil _) q := q | ._ ._ _ (@path.cons ._ _ _ _ e p') q := path.cons e (concatenate_paths p' q) definition concatenate_path_of_paths { G : Graph } : Π { x y : G.vertices }, path_of_paths x y → path x y | ._ ._ (path_of_paths.nil X) := path.nil X | ._ ._ (@path_of_paths.cons ._ _ _ _ e p') := concatenate_paths e (concatenate_path_of_paths p') definition PathCategory ( G : Graph ) : Category := { Obj := G.vertices, Hom := λ x y, path x y, identity := λ x, path.nil x, compose := λ _ _ _ f g, concatenate_paths f g, left_identity := ♮, right_identity := begin blast, induction f, -- when f is nil dsimp, trivial, -- when f is cons dsimp, exact congr_arg (λ p, path.cons e p) ih_1 end, associativity := begin blast, induction f, -- when f is nil dsimp, trivial, -- when f is cons dsimp, exact congr_arg (λ p, path.cons e p) (ih_1 g) end } structure GraphHomomorphism ( G H : Graph ) := ( onVertices : G.vertices → H.vertices ) ( onEdges : ∀ { X Y : G.vertices }, G.edges X Y → H.edges (onVertices X) (onVertices Y) ) definition Graph.from_Category ( C : Category ) : Graph := { vertices := C.Obj, edges := λ X Y, C.Hom X Y } instance Category_to_Graph_coercion: has_coe Category Graph := { coe := Graph.from_Category } open tqft.categories.functor definition path_to_morphism { G : Graph } { C : Category } ( H : GraphHomomorphism G C ) : Π { X Y : G.vertices }, path X Y → C.Hom (H.onVertices X) (H.onVertices Y) | ._ ._ (path.nil Z) := C.identity (H.onVertices Z) | ._ ._ (@path.cons ._ _ _ _ e p) := C.compose (H.onEdges e) (path_to_morphism p) -- PROJECT obtain this as the left adjoint to the forgetful functor. -- set_option pp.implicit true definition Functor.from_GraphHomomorphism { G : Graph } { C : Category } ( H : GraphHomomorphism G C ) : Functor (PathCategory G) C := { onObjects := H.onVertices, onMorphisms := λ _ _ f, path_to_morphism H f, identities := ♮, functoriality := begin blast, unfold PathCategory, dsimp, induction f, blast, dsimp, pose p := ih_1 g, unfold concatenate_paths, unfold path_to_morphism, rewrite p, dsimp, -- FIXME, this and the next line are required because of https://github.com/leanprover/lean/issues/1509 unfold Graph.from_Category, rewrite - C.associativity, end } instance GraphHomomorphism_to_Functor_coercion { G : Graph } { C : Category }: has_coe (GraphHomomorphism G C) (Functor (PathCategory G) C) := { coe := Functor.from_GraphHomomorphism } end tqft.categories.graph
86f341393750a91372b73c3af037d0b2a9f582fe
e151e9053bfd6d71740066474fc500a087837323
/src/hott/algebra/ring.lean
5f99e2a22527fb187ce85ca7db62cae932bae787
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
20,929
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Structures with multiplicative and additive components, including semirings, rings, and fields. The development is modeled after Isabelle's library. -/ import .group universes u v w hott_theory set_option old_structure_cmd true namespace hott open algebra variable {A : Type _} namespace algebra /- auxiliary classes -/ @[hott, class] structure distrib (A : Type _) extends has_mul A, has_add A := (left_distrib : Πa b c, mul a (add b c) = add (mul a b) (mul a c)) (right_distrib : Πa b c, mul (add a b) c = add (mul a c) (mul b c)) @[hott] def left_distrib [s : distrib A] (a b c : A) : a * (b + c) = a * b + a * c := distrib.left_distrib _ _ _ @[hott] def right_distrib [s: distrib A] (a b c : A) : (a + b) * c = a * c + b * c := distrib.right_distrib _ _ _ @[hott, class] structure mul_zero_class (A : Type _) extends has_mul A, has_zero A := (zero_mul : Πa, mul zero a = zero) (mul_zero : Πa, mul a zero = zero) @[hott] def zero_mul [s : mul_zero_class A] (a : A) : 0 * a = 0 := mul_zero_class.zero_mul _ @[hott] def mul_zero [s : mul_zero_class A] (a : A) : a * 0 = 0 := mul_zero_class.mul_zero _ @[hott, class] structure zero_ne_one_class (A : Type _) extends has_zero A, has_one A := (zero_ne_one : zero ≠ one) @[hott] theorem zero_ne_one [s: zero_ne_one_class A] : 0 ≠ (1:A) := @zero_ne_one_class.zero_ne_one A s /- semiring -/ @[hott] structure semiring (A : Type _) extends comm_monoid A renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero mul_comm→add_comm, monoid A, distrib A, mul_zero_class A /- we make it a class now (and not as part of the structure) to avoid semiring.to_comm_monoid to be an instance -/ attribute [class] semiring @[hott, reducible, instance] def add_comm_monoid_of_semiring (A : Type _) [H : semiring A] : add_comm_monoid A := @semiring.to_comm_monoid A H @[hott, reducible, instance] def monoid_of_semiring (A : Type _) [H : semiring A] : monoid A := @semiring.to_monoid A H @[hott, reducible, instance] def distrib_of_semiring (A : Type _) [H : semiring A] : distrib A := @semiring.to_distrib A H @[hott, reducible, instance] def mul_zero_class_of_semiring (A : Type _) [H : semiring A] : mul_zero_class A := @semiring.to_mul_zero_class A H section semiring variables [s : semiring A] (a b c : A) include s @[hott] theorem As {a b c : A} : a + b + c = a + (b + c) := add.assoc _ _ _ @[hott] theorem one_add_one_eq_two : 1 + 1 = 2 :> A := by refl @[hott] theorem ne_zero_of_mul_ne_zero_right {a b : A} (H : a * b ≠ 0) : a ≠ 0 := λthis, have a * b = 0, by rwr [this, zero_mul], H this @[hott] theorem ne_zero_of_mul_ne_zero_left {a b : A} (H : a * b ≠ 0) : b ≠ 0 := λthis, have a * b = 0, by rwr [this, mul_zero], H this @[hott] theorem distrib_three_right (a b c d : A) : (a + b + c) * d = a * d + b * d + c * d := by rwr [right_distrib, right_distrib] @[hott] theorem mul_two : a * 2 = a + a := by rwr [←one_add_one_eq_two, left_distrib, mul_one] @[hott] theorem two_mul : 2 * a = a + a := by rwr [←one_add_one_eq_two, right_distrib, one_mul] end semiring /- comm semiring -/ @[hott, class] structure comm_semiring (A : Type _) extends semiring A, comm_monoid A -- TODO: we could also define a cancelative comm_semiring, i.e. satisfying -- c ≠ 0 → c * a = c * b → a = b. -- section comm_semiring -- variables [s : comm_semiring A] (a b c : A) -- include s -- @[hott] protected def algebra.dvd (a b : A) : Type _ := Σc, b = a * c -- @[hott, instance, priority 500] def comm_semiring_has_dvd : has_dvd A := -- has_dvd.mk hott.algebra.dvd -- @[hott] theorem dvd.intro {a b c : A} (H : a * c = b) : a ∣ b := -- sigma.mk _ H⁻¹ -- @[hott] theorem dvd_of_mul_right_eq {a b c : A} (H : a * c = b) : a ∣ b := dvd.intro H -- @[hott] theorem dvd.intro_left {a b c : A} (H : c * a = b) : a ∣ b := -- by rwr mul.comm at H; exact dvd.intro H -- @[hott] theorem dvd_of_mul_left_eq {a b c : A} (H : c * a = b) : a ∣ b := dvd.intro_left H -- @[hott] theorem exists_eq_mul_right_of_dvd {a b : A} (H : a ∣ b) : Σc, b = a * c := H -- @[hott] theorem dvd.elim {P : Type _} {a b : A} (H₁ : a ∣ b) (H₂ : Πc, b = a * c → P) : P := -- sigma.rec_on H₁ H₂ -- @[hott] theorem exists_eq_mul_left_of_dvd {a b : A} (H : a ∣ b) : Σc, b = c * a := -- dvd.elim H (take c, assume H1 : b = a * c, sigma.mk c (H1 ⬝ mul.comm _ _)) -- @[hott] theorem dvd.elim_left {P : Type _} {a b : A} (H₁ : a ∣ b) (H₂ : Πc, b = c * a → P) : P := -- sigma.rec_on (exists_eq_mul_left_of_dvd H₁) (take c, assume H₃ : b = c * a, H₂ c H₃) -- @[hott] theorem dvd.refl : a ∣ a := dvd.intro (mul_one _) -- @[hott] theorem dvd.trans {a b c : A} (H₁ : a ∣ b) (H₂ : b ∣ c) : a ∣ c := -- dvd.elim H₁ -- (take d, assume H₃ : b = a * d, -- dvd.elim H₂ -- (take e, assume H₄ : c = b * e, -- dvd.intro -- (show a * (d * e) = c, by rwr [←mul.assoc, -H₃, H₄]))) -- @[hott] theorem eq_zero_of_zero_dvd {a : A} (H : 0 ∣ a) : a = 0 := -- dvd.elim H (take c, assume H' : a = 0 * c, H' ⬝ (zero_mul _)) -- @[hott] theorem dvd_zero : a ∣ 0 := dvd.intro (mul_zero _) -- @[hott] theorem one_dvd : 1 ∣ a := dvd.intro (one_mul _) -- @[hott] theorem dvd_mul_right : a ∣ a * b := dvd.intro rfl -- @[hott] theorem dvd_mul_left : a ∣ b * a := -- by rwr mul.comm; apply dvd_mul_right -- @[hott] theorem dvd_mul_of_dvd_left {a b : A} (H : a ∣ b) (c : A) : a ∣ b * c := -- dvd.elim H -- (take d, -- suppose b = a * d, -- dvd.intro -- (show a * (d * c) = b * c, from by rwr [←mul.assoc]; substvars)) -- @[hott] theorem dvd_mul_of_dvd_right {a b : A} (H : a ∣ b) (c : A) : a ∣ c * b := -- by rwr mul.comm; exact dvd_mul_of_dvd_left H _ -- @[hott] theorem mul_dvd_mul {a b c d : A} (dvd_ab : a ∣ b) (dvd_cd : c ∣ d) : a * c ∣ b * d := -- dvd.elim dvd_ab -- (take e, suppose b = a * e, -- dvd.elim dvd_cd -- (take f, suppose d = c * f, -- dvd.intro -- (show a * c * (e * f) = b * d, -- by rwr [mul.assoc, {c*_}mul.left_comm, -mul.assoc]; substvars))) -- @[hott] theorem dvd_of_mul_right_dvd {a b c : A} (H : a * b ∣ c) : a ∣ c := -- dvd.elim H (take d, assume Habdc : c = a * b * d, dvd.intro ((mul.assoc _ _ _)⁻¹ ⬝ (Habdc _ _ _ _)⁻¹)) -- @[hott] theorem dvd_of_mul_left_dvd {a b c : A} (H : a * b ∣ c) : b ∣ c := -- by apply dvd_of_mul_right_dvd; rwr mul.comm; exact H -- @[hott] theorem dvd_add {a b c : A} (Hab : a ∣ b) (Hac : a ∣ c) : a ∣ b + c := -- dvd.elim Hab -- (take d, suppose b = a * d, -- dvd.elim Hac -- (take e, suppose c = a * e, -- dvd.intro (show a * (d + e) = b + c, -- by rwr [left_distrib]; substvars))) -- end comm_semiring /- ring -/ @[hott] structure ring (A : Type _) extends ab_group A renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero inv→neg mul_left_inv→add_left_inv mul_comm→add_comm, monoid A, distrib A /- we make it a class now (and not as part of the structure) to avoid ring.to_ab_group to be an instance -/ attribute [class] ring @[hott, reducible, instance] def add_ab_group_of_ring (A : Type _) [H : ring A] : add_ab_group A := @ring.to_ab_group A H @[hott, reducible, instance] def monoid_of_ring (A : Type _) [H : ring A] : monoid A := @ring.to_monoid A H @[hott, reducible, instance] def distrib_of_ring (A : Type _) [H : ring A] : distrib A := @ring.to_distrib A H @[hott] def ring.mul_zero [s : ring A] (a : A) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * 0 : by rwr add_zero ... = a * (0 + 0) : by rwr add_zero ... = a * 0 + a * 0 : left_distrib a 0 0, show a * 0 = 0, from (add.left_cancel this)⁻¹ @[hott] def ring.zero_mul [s : ring A] (a : A) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = 0 * a : by rwr add_zero ... = (0 + 0) * a : by rwr add_zero ... = 0 * a + 0 * a : right_distrib 0 0 a, show 0 * a = 0, from (add.left_cancel this)⁻¹ @[hott, reducible, instance] def ring.to_semiring [s : ring A] : semiring A := { mul_zero := ring.mul_zero, zero_mul := ring.zero_mul, ..s} section variables [s : ring A] (a b c d e : A) include s @[hott] def neg_mul_eq_neg_mul : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rwr [←right_distrib, add.right_inv, zero_mul] end @[hott] def neg_mul_eq_mul_neg : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rwr [←left_distrib, add.right_inv, mul_zero] end @[hott] def neg_mul_eq_neg_mul_symm : - a * b = - (a * b) := (neg_mul_eq_neg_mul _ _)⁻¹ᵖ @[hott] def mul_neg_eq_neg_mul_symm : a * - b = - (a * b) := (neg_mul_eq_mul_neg _ _)⁻¹ᵖ @[hott] theorem neg_mul_neg : -a * -b = a * b := calc -a * -b = -(a * -b) : by rwr ←neg_mul_eq_neg_mul ... = - -(a * b) : by rwr ←neg_mul_eq_mul_neg ... = a * b : by rwr neg_neg @[hott] theorem neg_mul_comm : -a * b = a * -b := (neg_mul_eq_neg_mul _ _)⁻¹ ⬝ (neg_mul_eq_mul_neg _ _) @[hott] def neg_eq_neg_one_mul : -a = - 1 * a := calc -a = -(1 * a) : by rwr one_mul ... = - 1 * a : by rwr neg_mul_eq_neg_mul @[hott] def mul_sub_left_distrib : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib _ _ _ ... = a * b + - (a * c) : by rwr ←neg_mul_eq_mul_neg ... = a * b - a * c : rfl @[hott] def mul_sub_right_distrib : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib _ _ _ ... = a * c + - (b * c) : by rwr neg_mul_eq_neg_mul ... = a * c - b * c : rfl @[hott] theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by rwr add.comm (b*e) ... ↔ a * e + c - b * e = d : iff.symm (sub_eq_iff_eq_add _ _ _) ... ↔ a * e - b * e + c = d : by rwr sub_add_eq_add_sub ... ↔ (a - b) * e + c = d : by rwr mul_sub_right_distrib @[hott] theorem mul_add_eq_mul_add_of_sub_mul_add_eq : (a - b) * e + c = d → a * e + c = b * e + d := iff.mpr (mul_add_eq_mul_add_iff_sub_mul_add_eq _ _ _ _ _) @[hott] theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := iff.mp (mul_add_eq_mul_add_iff_sub_mul_add_eq _ _ _ _ _) @[hott] theorem mul_neg_one_eq_neg : a * (- 1) = -a := have a + a * - 1 = 0, from calc a + a * - 1 = a * 1 + a * - 1 : by rwr mul_one ... = a * (1 + - 1) : by rwr left_distrib ... = a * 0 : by rwr add.right_inv ... = 0 : by rwr mul_zero, (neg_eq_of_add_eq_zero this)⁻¹ @[hott] theorem ne_zero_prod_ne_zero_of_mul_ne_zero {a b : A} (H : a * b ≠ 0) : a ≠ 0 × b ≠ 0 := have H1 : a ≠ 0, from (λthis, have a * b = 0, by rwr [this, zero_mul], absurd this H), have b ≠ 0, from (λthis, have a * b = 0, by rwr [this, mul_zero], absurd this H), prod.mk H1 this end @[hott, class] structure comm_ring (A : Type _) extends ring A, comm_semigroup A @[hott, reducible, instance] def comm_ring.to_comm_semiring [s : comm_ring A] : comm_semiring A := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section variables [s : comm_ring A] (a b c d e : A) include s @[hott] theorem mul_self_sub_mul_self_eq : a * a - b * b = (a + b) * (a - b) := begin change a * a + - (b * b) = (a + b) * (a + - b), rwr [left_distrib, right_distrib, right_distrib, add.assoc], rwr [←add.assoc (b*a), ←neg_mul_eq_mul_neg, ←neg_mul_eq_mul_neg, mul.comm a b, add.right_inv, zero_add] end @[hott] theorem mul_self_sub_one_eq : a * a - 1 = (a + 1) * (a - 1) := by rwr [←mul_self_sub_mul_self_eq, mul_one] -- @[hott] theorem dvd_neg_iff_dvd : (a ∣ -b) ↔ (a ∣ b) := -- iff.intro -- (suppose a ∣ -b, -- dvd.elim this -- (take c, suppose -b = a * c, -- dvd.intro -- (show a * -c = b, -- by rwr [←neg_mul_eq_mul_neg, -this, neg_neg]))) -- (suppose a ∣ b, -- dvd.elim this -- (take c, suppose b = a * c, -- dvd.intro -- (show a * -c = -b, -- by rwr [←neg_mul_eq_mul_neg, -this]))) -- @[hott] theorem dvd_neg_of_dvd : (a ∣ b) → (a ∣ -b) := -- iff.mpr (dvd_neg_iff_dvd _ _) -- @[hott] theorem dvd_of_dvd_neg : (a ∣ -b) → (a ∣ b) := -- iff.mp (dvd_neg_iff_dvd _ _) -- @[hott] theorem neg_dvd_iff_dvd : (-a ∣ b) ↔ (a ∣ b) := -- iff.intro -- (suppose -a ∣ b, -- dvd.elim this -- (take c, suppose b = -a * c, -- dvd.intro -- (show a * -c = b, by rwr [←neg_mul_comm, this]))) -- (suppose a ∣ b, -- dvd.elim this -- (take c, suppose b = a * c, -- dvd.intro -- (show -a * -c = b, by rwr [neg_mul_neg, this]))) -- @[hott] theorem neg_dvd_of_dvd : (a ∣ b) → (-a ∣ b) := -- iff.mpr (neg_dvd_iff_dvd _ _) -- @[hott] theorem dvd_of_neg_dvd : (-a ∣ b) → (a ∣ b) := -- iff.mp (neg_dvd_iff_dvd _ _) -- @[hott] theorem dvd_sub (H₁ : (a ∣ b)) (H₂ : (a ∣ c)) : (a ∣ b - c) := -- dvd_add H₁ (dvd_neg_of_dvd H₂) end /- integral domains -/ @[hott, class] structure no_zero_divisors (A : Type _) extends has_mul A, has_zero A := (eq_zero_sum_eq_zero_of_mul_eq_zero : Πa b, mul a b = zero → a = zero ⊎ b = zero) @[hott] def eq_zero_sum_eq_zero_of_mul_eq_zero {A : Type _} [s : no_zero_divisors A] {a b : A} (H : a * b = 0) : a = 0 ⊎ b = 0 := no_zero_divisors.eq_zero_sum_eq_zero_of_mul_eq_zero _ _ H @[hott, class] structure integral_domain (A : Type _) extends comm_ring A, no_zero_divisors A, zero_ne_one_class A section variables [s : integral_domain A] (a b c d e : A) include s @[hott] theorem mul_ne_zero {a b : A} (H1 : a ≠ 0) (H2 : b ≠ 0) : a * b ≠ 0 := λthis, sum.elim (eq_zero_sum_eq_zero_of_mul_eq_zero this) (assume H3, H1 H3) (assume H4, H2 H4) -- @[hott] theorem eq_of_mul_eq_mul_right {a b c : A} (Ha : a ≠ 0) (H : b * a = c * a) : b = c := -- have b * a - c * a = 0, from iff.mp (eq_iff_sub_eq_zero _ _) H, -- have (b - c) * a = 0, by rwr [mul_sub_right_distrib, this], -- have b - c = 0, from sum_resolve_left (eq_zero_sum_eq_zero_of_mul_eq_zero this) Ha, -- iff.elim_right (eq_iff_sub_eq_zero _ _) this -- @[hott] theorem eq_of_mul_eq_mul_left {a b c : A} (Ha : a ≠ 0) (H : a * b = a * c) : b = c := -- have a * b - a * c = 0, from iff.mp (eq_iff_sub_eq_zero _ _) H, -- have a * (b - c) = 0, by rwr [mul_sub_left_distrib, this], -- have b - c = 0, from sum_resolve_right (eq_zero_sum_eq_zero_of_mul_eq_zero this) Ha, -- iff.elim_right (eq_iff_sub_eq_zero _ _) this -- -- TODO: do we want the iff versions? -- @[hott] theorem eq_zero_of_mul_eq_self_right {a b : A} (H₁ : b ≠ 1) (H₂ : a * b = a) : a = 0 := -- have b - 1 ≠ 0, by intro this; apply H₁; rwr zero_add; apply eq_add_of_sub_eq; exact this, -- have a * b - a = 0, by rwr H₂; apply sub_self, -- have a * (b - 1) = 0, by rwr [mul_sub_left_distrib, mul_one]; apply this, -- show a = 0, from sum_resolve_left (eq_zero_sum_eq_zero_of_mul_eq_zero this) `b - 1 ≠ 0` -- @[hott] theorem eq_zero_of_mul_eq_self_left {a b : A} (H₁ : b ≠ 1) (H₂ : b * a = a) : a = 0 := -- by apply eq_zero_of_mul_eq_self_right H₁; by rwr mul.comm; exact H₂ -- @[hott] theorem mul_self_eq_mul_self_iff (a b : A) : a * a = b * b ↔ a = b ⊎ a = -b := -- iff.intro -- (suppose a * a = b * b, -- have (a - b) * (a + b) = 0, -- by rwr [mul.comm, -mul_self_sub_mul_self_eq, this, sub_self], -- have a - b = 0 ⊎ a + b = 0, from eq_zero_sum_eq_zero_of_mul_eq_zero this, -- sum.elim this -- (suppose a - b = 0, sum.inl (eq_of_sub_eq_zero this)) -- (suppose a + b = 0, sum.inr (eq_neg_of_add_eq_zero this))) -- (suppose a = b ⊎ a = -b, sum.elim this -- (suppose a = b, by rwr this) -- (suppose a = -b, by rwr [this, neg_mul_neg])) -- @[hott] theorem mul_self_eq_one_iff (a : A) : a * a = 1 ↔ a = 1 ⊎ a = - 1 := -- have a * a = 1 * 1 ↔ a = 1 ⊎ a = - 1, from mul_self_eq_mul_self_iff a 1, -- by rwr mul_one at this; exact this -- -- TODO: c - b * c → c = 0 ⊎ b = 1 and variants -- @[hott] theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) := -- dvd.elim Hdvd -- (take d, -- suppose a * c = a * b * d, -- have b * d = c, by apply eq_of_mul_eq_mul_left Ha; rwr [mul.assoc, this], -- dvd.intro this) -- @[hott] theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) := -- dvd.elim Hdvd -- (take d, -- suppose c * a = b * a * d, -- have b * d * a = c * a, from by rwr [mul.right_comm, -this], -- have b * d = c, from eq_of_mul_eq_mul_right Ha this, -- dvd.intro this) end namespace norm_num -- @[hott] theorem mul_zero [s : mul_zero_class A] (a : A) : a * zero = zero := -- by rwr [↑zero, mul_zero] -- @[hott] theorem zero_mul [s : mul_zero_class A] (a : A) : zero * a = zero := -- by rwr [↑zero, zero_mul] -- @[hott] theorem mul_one [s : monoid A] (a : A) : a * one = a := -- by rwr [↑one, mul_one] -- @[hott] theorem mul_bit0 [s : distrib A] (a b : A) : a * (bit0 b) = bit0 (a * b) := -- by rwr [↑bit0, left_distrib] -- @[hott] theorem mul_bit0_helper [s : distrib A] (a b t : A) (H : a * b = t) : a * (bit0 b) = bit0 t := -- by rwr ←H; apply mul_bit0 -- @[hott] theorem mul_bit1 [s : semiring A] (a b : A) : a * (bit1 b) = bit0 (a * b) + a := -- by rwr [↑bit1, ↑bit0, +left_distrib, ↑one, mul_one] -- @[hott] theorem mul_bit1_helper [s : semiring A] (a b s t : A) (Hs : a * b = s) (Ht : bit0 s + a = t) : -- a * (bit1 b) = t := -- begin rwr [←Ht, -Hs, mul_bit1] end -- @[hott] theorem subst_into_prod [s : has_mul A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr) -- (prt : tl * tr = t) : -- l * r = t := -- by rwr [prl, prr, prt] -- @[hott] theorem mk_cong (op : A → A) (a b : A) (H : a = b) : op a = op b := -- by congruence; exact H -- @[hott] theorem mk_eq (a : A) : a = a := rfl -- @[hott] theorem neg_add_neg_eq_of_add_add_eq_zero [s : add_ab_group A] (a b c : A) (H : c + a + b = 0) : -- -a + -b = c := -- begin -- apply add_neg_eq_of_eq_add, -- apply neg_eq_of_add_eq_zero, -- rwr [add.comm, add.assoc, add.comm b, -add.assoc, H] -- end -- @[hott] theorem neg_add_neg_helper [s : add_ab_group A] (a b c : A) (H : a + b = c) : -a + -b = -c := -- begin apply iff.mp (neg_eq_neg_iff_eq _ _), rwr [neg_add, *neg_neg, H] end -- @[hott] theorem neg_add_pos_eq_of_eq_add [s : add_ab_group A] (a b c : A) (H : b = c + a) : -a + b = c := -- begin apply neg_add_eq_of_eq_add, rwr add.comm, exact H end -- @[hott] theorem neg_add_pos_helper1 [s : add_ab_group A] (a b c : A) (H : b + c = a) : -a + b = -c := -- begin apply neg_add_eq_of_eq_add, apply eq_add_neg_of_add_eq H end -- @[hott] theorem neg_add_pos_helper2 [s : add_ab_group A] (a b c : A) (H : a + c = b) : -a + b = c := -- begin apply neg_add_eq_of_eq_add, rwr H end -- @[hott] theorem pos_add_neg_helper [s : add_ab_group A] (a b c : A) (H : b + a = c) : a + b = c := -- by rwr [add.comm, H] -- @[hott] theorem sub_eq_add_neg_helper [s : add_ab_group A] (t₁ t₂ e w₁ w₂: A) (H₁ : t₁ = w₁) -- (H₂ : t₂ = w₂) (H : w₁ + -w₂ = e) : t₁ - t₂ = e := -- by rwr [sub_eq_add_neg, H₁, H₂, H] -- @[hott] theorem pos_add_pos_helper [s : add_ab_group A] (a b c h₁ h₂ : A) (H₁ : a = h₁) (H₂ : b = h₂) -- (H : h₁ + h₂ = c) : a + b = c := -- by rwr [H₁, H₂, H] -- @[hott] theorem subst_into_subtr [s : add_group A] (l r t : A) (prt : l + -r = t) : l - r = t := -- by rwr [sub_eq_add_neg, prt] -- @[hott] theorem neg_neg_helper [s : add_group A] (a b : A) (H : a = -b) : -a = b := -- by rwr [H, neg_neg] -- @[hott] theorem neg_mul_neg_helper [s : ring A] (a b c : A) (H : a * b = c) : (-a) * (-b) = c := -- begin rwr [neg_mul_neg, H] end -- @[hott] theorem neg_mul_pos_helper [s : ring A] (a b c : A) (H : a * b = c) : (-a) * b = -c := -- begin rwr [←neg_mul_eq_neg_mul, H] end -- @[hott] theorem pos_mul_neg_helper [s : ring A] (a b c : A) (H : a * b = c) : a * (-b) = -c := -- begin rwr [←neg_mul_comm, -neg_mul_eq_neg_mul, H] end end norm_num end algebra end hott
fad1369aeeb287b3bfd03ac64fb129bce6ccaa24
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/measure/lebesgue.lean
98bee1d37bfaac3d873e14fc2407bb65d284a679
[ "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
22,897
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Sébastien Gouëzel, Yury Kudryashov -/ import dynamics.ergodic.measure_preserving import linear_algebra.determinant import linear_algebra.matrix.diagonal import linear_algebra.matrix.transvection import measure_theory.constructions.pi import measure_theory.measure.stieltjes /-! # Lebesgue measure on the real line and on `ℝⁿ` We construct Lebesgue measure on the real line, as a particular case of Stieltjes measure associated to the function `x ↦ x`. We obtain as a consequence Lebesgue measure on `ℝⁿ`. We prove that they are translation invariant. We show that, on `ℝⁿ`, a linear map acts on Lebesgue measure by rescaling it through the absolute value of its determinant, in `real.map_linear_map_volume_pi_eq_smul_volume_pi`. More properties of the Lebesgue measure are deduced from this in `haar_lebesgue.lean`, where they are proved more generally for any additive Haar measure on a finite-dimensional real vector space. -/ noncomputable theory open classical set filter measure_theory measure_theory.measure open ennreal (of_real) open_locale big_operators ennreal nnreal topological_space /-! ### Definition of the Lebesgue measure and lengths of intervals -/ /-- Lebesgue measure on the Borel sigma algebra, giving measure `b - a` to the interval `[a, b]`. -/ instance real.measure_space : measure_space ℝ := ⟨stieltjes_function.id.measure⟩ namespace real variables {ι : Type*} [fintype ι] open_locale topological_space theorem volume_val (s) : volume s = stieltjes_function.id.measure s := rfl @[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := by simp [volume_val] @[simp] lemma volume_univ : volume (univ : set ℝ) = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, calc (r : ℝ≥0∞) = volume (Icc (0 : ℝ) r) : by simp ... ≤ volume univ : measure_mono (subset_univ _) @[simp] lemma volume_ball (a r : ℝ) : volume (metric.ball a r) = of_real (2 * r) := by rw [ball_eq_Ioo, volume_Ioo, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_closed_ball (a r : ℝ) : volume (metric.closed_ball a r) = of_real (2 * r) := by rw [closed_ball_eq_Icc, volume_Icc, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_emetric_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [metric.emetric_ball_top, volume_univ, two_mul, ennreal.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_ball_nnreal, volume_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end @[simp] lemma volume_emetric_closed_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.closed_ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [emetric.closed_ball_top, volume_univ, two_mul, ennreal.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_closed_ball_nnreal, volume_closed_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) := ⟨λ x, volume_singleton⟩ @[simp] lemma volume_interval {a b : ℝ} : volume (interval a b) = of_real (|b - a|) := by rw [interval, volume_Icc, max_sub_min_eq_abs] @[simp] lemma volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo a (a + n)) : by simp ... ≤ volume (Ioi a) : measure_mono Ioo_subset_Ioi_self @[simp] lemma volume_Ici {a : ℝ} : volume (Ici a) = ∞ := by simp [← measure_congr Ioi_ae_eq_Ici] @[simp] lemma volume_Iio {a : ℝ} : volume (Iio a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo (a - n) a) : by simp ... ≤ volume (Iio a) : measure_mono Ioo_subset_Iio_self @[simp] lemma volume_Iic {a : ℝ} : volume (Iic a) = ∞ := by simp [← measure_congr Iio_ae_eq_Iic] instance locally_finite_volume : is_locally_finite_measure (volume : measure ℝ) := ⟨λ x, ⟨Ioo (x - 1) (x + 1), is_open.mem_nhds is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩, by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩ instance is_finite_measure_restrict_Icc (x y : ℝ) : is_finite_measure (volume.restrict (Icc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ico (x y : ℝ) : is_finite_measure (volume.restrict (Ico x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioc (x y : ℝ) : is_finite_measure (volume.restrict (Ioc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioo (x y : ℝ) : is_finite_measure (volume.restrict (Ioo x y)) := ⟨by simp⟩ /-! ### Volume of a box in `ℝⁿ` -/ lemma volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ennreal.of_real (b i - a i) := begin rw [← pi_univ_Icc, volume_pi_pi], simp only [real.volume_Icc] end @[simp] lemma volume_Icc_pi_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (Icc a b)).to_real = ∏ i, (b i - a i) := by simp only [volume_Icc_pi, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioo {a b : ι → ℝ} : volume (pi univ (λ i, Ioo (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioo_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioo (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioo, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioc {a b : ι → ℝ} : volume (pi univ (λ i, Ioc (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioc_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioc (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioc, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ico {a b : ι → ℝ} : volume (pi univ (λ i, Ico (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ico_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ico (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ico, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] @[simp] lemma volume_pi_ball (a : ι → ℝ) {r : ℝ} (hr : 0 < r) : volume (metric.ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_ball a hr, volume_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr.le) _).symm end @[simp] lemma volume_pi_closed_ball (a : ι → ℝ) {r : ℝ} (hr : 0 ≤ r) : volume (metric.closed_ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_closed_ball a hr, volume_closed_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr) _).symm end lemma volume_le_diam (s : set ℝ) : volume s ≤ emetric.diam s := begin by_cases hs : metric.bounded s, { rw [real.ediam_eq hs, ← volume_Icc], exact volume.mono (real.subset_Icc_Inf_Sup_of_bounded hs) }, { rw metric.ediam_of_unbounded hs, exact le_top } end lemma volume_pi_le_prod_diam (s : set (ι → ℝ)) : volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) := calc volume s ≤ volume (pi univ (λ i, closure (function.eval i '' s))) : volume.mono $ subset.trans (subset_pi_eval_image univ s) $ pi_mono $ λ i hi, subset_closure ... = ∏ i, volume (closure $ function.eval i '' s) : volume_pi_pi _ ... ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : finset.prod_le_prod' $ λ i hi, (volume_le_diam _).trans_eq (emetric.diam_closure _) lemma volume_pi_le_diam_pow (s : set (ι → ℝ)) : volume s ≤ emetric.diam s ^ fintype.card ι := calc volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : volume_pi_le_prod_diam s ... ≤ ∏ i : ι, (1 : ℝ≥0) * emetric.diam s : finset.prod_le_prod' $ λ i hi, (lipschitz_with.eval i).ediam_image_le s ... = emetric.diam s ^ fintype.card ι : by simp only [ennreal.coe_one, one_mul, finset.prod_const, fintype.card] /-! ### Images of the Lebesgue measure under translation/multiplication in ℝ -/ instance is_add_left_invariant_real_volume : is_add_left_invariant (volume : measure ℝ) := ⟨λ a, eq.symm $ real.measure_ext_Ioo_rat $ λ p q, by simp [measure.map_apply (measurable_const_add a) measurable_set_Ioo, sub_sub_sub_cancel_right]⟩ lemma smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map ((*) a) volume = volume := begin refine (real.measure_ext_Ioo_rat $ λ p q, _).symm, cases lt_or_gt_of_ne h with h h, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, neg_sub_neg, neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub, smul_eq_mul, mul_div_cancel' _ (ne_of_lt h)] }, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, preimage_const_mul_Ioo _ _ h, abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h), smul_eq_mul] } end lemma map_volume_mul_left {a : ℝ} (h : a ≠ 0) : measure.map ((*) a) volume = ennreal.of_real (|a⁻¹|) • volume := by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one, one_smul] } @[simp] lemma volume_preimage_mul_left {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume (((*) a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume (((*) a) ⁻¹' s) = measure.map ((*) a) volume s : ((homeomorph.mul_left₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_left h, refl } lemma smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map (* a) volume = volume := by simpa only [mul_comm] using real.smul_map_volume_mul_left h lemma map_volume_mul_right {a : ℝ} (h : a ≠ 0) : measure.map (* a) volume = ennreal.of_real (|a⁻¹|) • volume := by simpa only [mul_comm] using real.map_volume_mul_left h @[simp] lemma volume_preimage_mul_right {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume ((* a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume ((* a) ⁻¹' s) = measure.map (* a) volume s : ((homeomorph.mul_right₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_right h, refl } instance : is_neg_invariant (volume : measure ℝ) := ⟨eq.symm $ real.measure_ext_Ioo_rat $ λ p q, by simp [show volume.neg (Ioo (p : ℝ) q) = _, from measure.map_apply measurable_neg measurable_set_Ioo]⟩ /-! ### Images of the Lebesgue measure under translation/linear maps in ℝⁿ -/ open matrix /-- A diagonal matrix rescales Lebesgue according to its determinant. This is a special case of `real.map_matrix_volume_pi_eq_smul_volume_pi`, that one should use instead (and whose proof uses this particular case). -/ lemma smul_map_diagonal_volume_pi [decidable_eq ι] {D : ι → ℝ} (h : det (diagonal D) ≠ 0) : ennreal.of_real (abs (det (diagonal D))) • measure.map ((diagonal D).to_lin') volume = volume := begin refine (measure.pi_eq (λ s hs, _)).symm, simp only [det_diagonal, measure.coe_smul, algebra.id.smul_eq_mul, pi.smul_apply], rw [measure.map_apply _ (measurable_set.univ_pi_fintype hs)], swap, { exact continuous.measurable (linear_map.continuous_on_pi _) }, have : (matrix.to_lin' (diagonal D)) ⁻¹' (set.pi set.univ (λ (i : ι), s i)) = set.pi set.univ (λ (i : ι), ((*) (D i)) ⁻¹' (s i)), { ext f, simp only [linear_map.coe_proj, algebra.id.smul_eq_mul, linear_map.smul_apply, mem_univ_pi, mem_preimage, linear_map.pi_apply, diagonal_to_lin'] }, have B : ∀ i, of_real (abs (D i)) * volume (has_mul.mul (D i) ⁻¹' s i) = volume (s i), { assume i, have A : D i ≠ 0, { simp only [det_diagonal, ne.def] at h, exact finset.prod_ne_zero_iff.1 h i (finset.mem_univ i) }, rw [volume_preimage_mul_left A, ← mul_assoc, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_inv_cancel A, abs_one, ennreal.of_real_one, one_mul] }, rw [this, volume_pi_pi, finset.abs_prod, ennreal.of_real_prod_of_nonneg (λ i hi, abs_nonneg (D i)), ← finset.prod_mul_distrib], simp only [B] end /-- A transvection preserves Lebesgue measure. -/ lemma volume_preserving_transvection_struct [decidable_eq ι] (t : transvection_struct ι ℝ) : measure_preserving (t.to_matrix.to_lin') := begin /- We separate the coordinate along which there is a shearing from the other ones, and apply Fubini. Along this coordinate (and when all the other coordinates are fixed), it acts like a translation, and therefore preserves Lebesgue. -/ let p : ι → Prop := λ i, i ≠ t.i, let α : Type* := {x // p x}, let β : Type* := {x // ¬ (p x)}, let g : (α → ℝ) → (β → ℝ) → (β → ℝ) := λ a b, (λ x, t.c * a ⟨t.j, t.hij.symm⟩) + b, let F : (α → ℝ) × (β → ℝ) → (α → ℝ) × (β → ℝ) := λ p, (id p.1, g p.1 p.2), let e : (ι → ℝ) ≃ᵐ (α → ℝ) × (β → ℝ) := measurable_equiv.pi_equiv_pi_subtype_prod (λ i : ι, ℝ) p, have : (t.to_matrix.to_lin' : (ι → ℝ) → (ι → ℝ)) = e.symm ∘ F ∘ e, { cases t, ext f k, simp only [linear_equiv.map_smul, dite_eq_ite, linear_map.id_coe, p, ite_not, algebra.id.smul_eq_mul, one_mul, dot_product, std_basis_matrix, measurable_equiv.pi_equiv_pi_subtype_prod_symm_apply, id.def, transvection, pi.add_apply, zero_mul, linear_map.smul_apply, function.comp_app, measurable_equiv.pi_equiv_pi_subtype_prod_apply, matrix.transvection_struct.to_matrix_mk, matrix.mul_vec, linear_equiv.map_add, ite_mul, e, matrix.to_lin'_apply, pi.smul_apply, subtype.coe_mk, g, linear_map.add_apply, finset.sum_congr, matrix.to_lin'_one], by_cases h : t_i = k, { simp only [h, true_and, finset.mem_univ, if_true, eq_self_iff_true, finset.sum_ite_eq, one_apply, boole_mul, add_comm], }, { simp only [h, ne.symm h, add_zero, if_false, finset.sum_const_zero, false_and, mul_zero] } }, rw this, have A : measure_preserving e, { convert volume_preserving_pi_equiv_pi_subtype_prod (λ i : ι, ℝ) p }, have B : measure_preserving F, { have g_meas : measurable (function.uncurry g), { have : measurable (λ (c : (α → ℝ)), c ⟨t.j, t.hij.symm⟩) := measurable_pi_apply ⟨t.j, t.hij.symm⟩, refine (measurable_pi_lambda _ (λ i, measurable.const_mul _ _)).add measurable_snd, exact this.comp measurable_fst }, exact (measure_preserving.id _).skew_product g_meas (eventually_of_forall (λ a, map_add_left_eq_self _ _)) }, exact ((A.symm e).comp B).comp A, end /-- Any invertible matrix rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_matrix_volume_pi_eq_smul_volume_pi [decidable_eq ι] {M : matrix ι ι ℝ} (hM : det M ≠ 0) : measure.map M.to_lin' volume = ennreal.of_real (abs (det M)⁻¹) • volume := begin -- This follows from the cases we have already proved, of diagonal matrices and transvections, -- as these matrices generate all invertible matrices. apply diagonal_transvection_induction_of_det_ne_zero _ M hM (λ D hD, _) (λ t, _) (λ A B hA hB IHA IHB, _), { conv_rhs { rw [← smul_map_diagonal_volume_pi hD] }, rw [smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel hD, abs_one, ennreal.of_real_one, one_smul] }, { simp only [matrix.transvection_struct.det, ennreal.of_real_one, (volume_preserving_transvection_struct _).map_eq, one_smul, _root_.inv_one, abs_one] }, { rw [to_lin'_mul, det_mul, linear_map.coe_comp, ← measure.map_map, IHB, measure.map_smul, IHA, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_comm, mul_inv], { apply continuous.measurable, apply linear_map.continuous_on_pi }, { apply continuous.measurable, apply linear_map.continuous_on_pi } } end /-- Any invertible linear map rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_linear_map_volume_pi_eq_smul_volume_pi {f : (ι → ℝ) →ₗ[ℝ] (ι → ℝ)} (hf : f.det ≠ 0) : measure.map f volume = ennreal.of_real (abs (f.det)⁻¹) • volume := begin -- this is deduced from the matrix case classical, let M := f.to_matrix', have A : f.det = det M, by simp only [linear_map.det_to_matrix'], have B : f = M.to_lin', by simp only [to_lin'_to_matrix'], rw [A, B], apply map_matrix_volume_pi_eq_smul_volume_pi, rwa A at hf end end real open_locale topological_space lemma filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : ∀ᶠ x in 𝓝 a, p x) : (0 : ℝ≥0∞) < volume {x | p x} := begin rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩, refine lt_of_lt_of_le _ (measure_mono hs), simpa [-mem_Ioo] using hx.1.trans hx.2 end section region_between open_locale classical variable {α : Type*} /-- The region between two real-valued functions on an arbitrary set. -/ def region_between (f g : α → ℝ) (s : set α) : set (α × ℝ) := {p : α × ℝ | p.1 ∈ s ∧ p.2 ∈ Ioo (f p.1) (g p.1)} lemma region_between_subset (f g : α → ℝ) (s : set α) : region_between f g s ⊆ s ×ˢ (univ : set ℝ) := by simpa only [prod_univ, region_between, set.preimage, set_of_subset_set_of] using λ a, and.left variables [measurable_space α] {μ : measure α} {f g : α → ℝ} {s : set α} /-- The region between two measurable functions on a measurable set is measurable. -/ lemma measurable_set_region_between (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set (region_between f g s) := begin dsimp only [region_between, Ioo, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter (measurable_set_lt measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs end theorem volume_region_between_eq_lintegral' (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin rw measure.prod_apply, { have h : (λ x, volume {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)}) = s.indicator (λ x, ennreal.of_real (g x - f x)), { funext x, rw indicator_apply, split_ifs, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = Ioo (f x) (g x) := by simp [h, Ioo], simp only [hx, real.volume_Ioo, sub_zero] }, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = ∅ := by simp [h], simp only [hx, measure_empty] } }, dsimp only [region_between, preimage_set_of_eq], rw [h, lintegral_indicator]; simp only [hs, pi.sub_apply] }, { exact measurable_set_region_between hf hg hs }, end /-- The volume of the region between two almost everywhere measurable functions on a measurable set can be represented as a Lebesgue integral. -/ theorem volume_region_between_eq_lintegral [sigma_finite μ] (hf : ae_measurable f (μ.restrict s)) (hg : ae_measurable g (μ.restrict s)) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin have h₁ : (λ y, ennreal.of_real ((g - f) y)) =ᵐ[μ.restrict s] λ y, ennreal.of_real ((ae_measurable.mk g hg - ae_measurable.mk f hf) y) := (hg.ae_eq_mk.sub hf.ae_eq_mk).fun_comp _, have h₂ : (μ.restrict s).prod volume (region_between f g s) = (μ.restrict s).prod volume (region_between (ae_measurable.mk f hf) (ae_measurable.mk g hg) s), { apply measure_congr, apply eventually_eq.rfl.inter, exact ((ae_eq_comp' measurable_fst.ae_measurable hf.ae_eq_mk measure.prod_fst_absolutely_continuous).comp₂ _ eventually_eq.rfl).inter (eventually_eq.rfl.comp₂ _ (ae_eq_comp' measurable_fst.ae_measurable hg.ae_eq_mk measure.prod_fst_absolutely_continuous)) }, rw [lintegral_congr_ae h₁, ← volume_region_between_eq_lintegral' hf.measurable_mk hg.measurable_mk hs], convert h₂ using 1, { rw measure.restrict_prod_eq_prod_univ, exact (measure.restrict_eq_self _ (region_between_subset f g s)).symm, }, { rw measure.restrict_prod_eq_prod_univ, exact (measure.restrict_eq_self _ (region_between_subset (ae_measurable.mk f hf) (ae_measurable.mk g hg) s)).symm }, end theorem volume_region_between_eq_integral' [sigma_finite μ] (f_int : integrable_on f s μ) (g_int : integrable_on g s μ) (hs : measurable_set s) (hfg : f ≤ᵐ[μ.restrict s] g ) : μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) := begin have h : g - f =ᵐ[μ.restrict s] (λ x, real.to_nnreal (g x - f x)), from hfg.mono (λ x hx, (real.coe_to_nnreal _ $ sub_nonneg.2 hx).symm), rw [volume_region_between_eq_lintegral f_int.ae_measurable g_int.ae_measurable hs, integral_congr_ae h, lintegral_congr_ae, lintegral_coe_eq_integral _ ((integrable_congr h).mp (g_int.sub f_int))], simpa only, end /-- If two functions are integrable on a measurable set, and one function is less than or equal to the other on that set, then the volume of the region between the two functions can be represented as an integral. -/ theorem volume_region_between_eq_integral [sigma_finite μ] (f_int : integrable_on f s μ) (g_int : integrable_on g s μ) (hs : measurable_set s) (hfg : ∀ x ∈ s, f x ≤ g x) : μ.prod volume (region_between f g s) = ennreal.of_real (∫ y in s, (g - f) y ∂μ) := volume_region_between_eq_integral' f_int g_int hs ((ae_restrict_iff' hs).mpr (eventually_of_forall hfg)) end region_between
abe9f9762159d5722f699b5434e23bfa9175d6cd
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/delta_issue1.lean
1c46bee60871d15d76c5c3290728a10841c31452
[ "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
1,403
lean
import data.set.basic open set definition preimage {X Y : Type} (f : X → Y) (b : set Y) : set X := λ x, f x ∈ b example {X Y : Type} {b : set Y} (f : X → Y) (x : X) (H : x ∈ preimage f b) : f x ∈ b := H theorem preimage_subset {X Y : Type} {a b : set Y} (f : X → Y) (H : a ⊆ b) : preimage f a ⊆ preimage f b := λ (x : X) (H' : x ∈ preimage f a), show x ∈ preimage f b, from @H (f x) H' example {X Y : Type} {a b : set Y} (f : X → Y) (H : a ⊆ b) : preimage f a ⊆ preimage f b := λ (x : X) (H' : x ∈ preimage f a), have f x ∈ a, from H', have f x ∈ b, from mem_of_subset_of_mem H this, this example {X Y : Type} {a b : set Y} (f : X → Y) (H : a ⊆ b) : preimage f a ⊆ preimage f b := λ (x : X) (H' : x ∈ preimage f a), have f x ∈ b, from mem_of_subset_of_mem H H', this example {X Y : Type} {a b : set Y} (f : X → Y) (H : a ⊆ b) : preimage f a ⊆ preimage f b := λ (x : X) (H' : x ∈ preimage f a), @H (f x) H' lemma mem_preimage_of_mem {X Y : Type} {f : X → Y} {s : set Y} {x : X} : f x ∈ s → x ∈ preimage f s := assume H, H lemma mem_of_mem_preimage {X Y : Type} {f : X → Y} {s : set Y} {x : X} : x ∈ preimage f s → f x ∈ s := assume H, H example {X Y : Type} {a b : set Y} (f : X → Y) (H : a ⊆ b) : preimage f a ⊆ preimage f b := take x, assume H', mem_preimage_of_mem (mem_of_subset_of_mem H (mem_of_mem_preimage H'))
8e8cfc3528807414d1761100cea427b450277ec3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/subset_properties.lean
613c07c84dcd9f4a3fd93e7151cc36bab5988d37
[]
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
48,519
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, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.bases import Mathlib.data.finset.order import Mathlib.PostPort universes u v u_1 l u_2 namespace Mathlib /-! # Properties of subsets of topological spaces In this file we define various properties of subsets of a topological space, and some classes on topological spaces. ## Main definitions We define the following properties for sets in a topological space: * `is_compact`: each open cover has a finite subcover. This is defined in mathlib using filters. The main property of a compact set is `is_compact.elim_finite_subcover`. * `is_clopen`: a set that is both open and closed. * `is_irreducible`: a nonempty set that has contains no non-trivial pair of disjoint opens. See also the section below in the module doc. * `is_connected`: a nonempty set that has no non-trivial open partition. See also the section below in the module doc. `connected_component` is the connected component of an element in the space. * `is_totally_disconnected`: all of its connected components are singletons. * `is_totally_separated`: any two points can be separated by two disjoint opens that cover the set. For each of these definitions (except for `is_clopen`), we also have a class stating that the whole space satisfies that property: `compact_space`, `irreducible_space`, `connected_space`, `totally_disconnected_space`, `totally_separated_space`. Furthermore, we have two more classes: * `locally_compact_space`: for every point `x`, every open neighborhood of `x` contains a compact neighborhood of `x`. The definition is formulated in terms of the neighborhood filter. * `sigma_compact_space`: a space that is the union of a countably many compact subspaces. ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible and connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible` and `is_preconnected` respectively. In other words, the only difference is whether the empty space counts as irreducible and/or connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ /- compact sets -/ /-- A set `s` is compact if for every filter `f` that contains `s`, every set of `f` also meets every neighborhood of some `a ∈ s`. -/ def is_compact {α : Type u} [topological_space α] (s : set α) := ∀ {f : filter α} [_inst_2 : filter.ne_bot f], f ≤ filter.principal s → ∃ (a : α), ∃ (H : a ∈ s), cluster_pt a f /-- The complement to a compact set belongs to a filter `f` if it belongs to each filter `𝓝 a ⊓ f`, `a ∈ s`. -/ theorem is_compact.compl_mem_sets {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) {f : filter α} (hf : ∀ (a : α), a ∈ s → sᶜ ∈ nhds a ⊓ f) : sᶜ ∈ f := sorry /-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t` within `s` such that `tᶜ` belongs to `f`. -/ theorem is_compact.compl_mem_sets_of_nhds_within {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) {f : filter α} (hf : ∀ (a : α) (H : a ∈ s), ∃ (t : set α), ∃ (H : t ∈ nhds_within a s), tᶜ ∈ f) : sᶜ ∈ f := sorry /-- If `p : set α → Prop` is stable under restriction and union, and each point `x` of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/ theorem is_compact.induction_on {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅) (hmono : ∀ {s t : set α}, s ⊆ t → p t → p s) (hunion : ∀ {s t : set α}, p s → p t → p (s ∪ t)) (hnhds : ∀ (x : α) (H : x ∈ s), ∃ (t : set α), ∃ (H : t ∈ nhds_within x s), p t) : p s := sorry /-- The intersection of a compact set and a closed set is a compact set. -/ theorem is_compact.inter_right {α : Type u} [topological_space α] {s : set α} {t : set α} (hs : is_compact s) (ht : is_closed t) : is_compact (s ∩ t) := sorry /-- The intersection of a closed set and a compact set is a compact set. -/ theorem is_compact.inter_left {α : Type u} [topological_space α] {s : set α} {t : set α} (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) := set.inter_comm t s ▸ is_compact.inter_right ht hs /-- The set difference of a compact set and an open set is a compact set. -/ theorem compact_diff {α : Type u} [topological_space α] {s : set α} {t : set α} (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) := is_compact.inter_right hs (iff.mpr is_closed_compl_iff ht) /-- A closed subset of a compact set is a compact set. -/ theorem compact_of_is_closed_subset {α : Type u} [topological_space α] {s : set α} {t : set α} (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) : is_compact t := set.inter_eq_self_of_subset_right h ▸ is_compact.inter_right hs ht theorem is_compact.adherence_nhdset {α : Type u} [topological_space α] {s : set α} {t : set α} {f : filter α} (hs : is_compact s) (hf₂ : f ≤ filter.principal s) (ht₁ : is_open t) (ht₂ : ∀ (a : α), a ∈ s → cluster_pt a f → a ∈ t) : t ∈ f := sorry theorem compact_iff_ultrafilter_le_nhds {α : Type u} [topological_space α] {s : set α} : is_compact s ↔ ∀ (f : ultrafilter α), ↑f ≤ filter.principal s → ∃ (a : α), ∃ (H : a ∈ s), ↑f ≤ nhds a := sorry theorem is_compact.ultrafilter_le_nhds {α : Type u} [topological_space α] {s : set α} : is_compact s → ∀ (f : ultrafilter α), ↑f ≤ filter.principal s → ∃ (a : α), ∃ (H : a ∈ s), ↑f ≤ nhds a := iff.mp compact_iff_ultrafilter_le_nhds /-- For every open cover of a compact set, there exists a finite subcover. -/ theorem is_compact.elim_finite_subcover {α : Type u} [topological_space α] {s : set α} {ι : Type v} (hs : is_compact s) (U : ι → set α) (hUo : ∀ (i : ι), is_open (U i)) (hsU : s ⊆ set.Union fun (i : ι) => U i) : ∃ (t : finset ι), s ⊆ set.Union fun (i : ι) => set.Union fun (H : i ∈ t) => U i := sorry /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ theorem is_compact.elim_finite_subfamily_closed {α : Type u} [topological_space α] {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀ (i : ι), is_closed (Z i)) (hsZ : (s ∩ set.Inter fun (i : ι) => Z i) = ∅) : ∃ (t : finset ι), (s ∩ set.Inter fun (i : ι) => set.Inter fun (H : i ∈ t) => Z i) = ∅ := sorry /-- To show that a compact set intersects the intersection of a family of closed sets, it is sufficient to show that it intersects every finite subfamily. -/ theorem is_compact.inter_Inter_nonempty {α : Type u} [topological_space α] {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀ (i : ι), is_closed (Z i)) (hsZ : ∀ (t : finset ι), set.nonempty (s ∩ set.Inter fun (i : ι) => set.Inter fun (H : i ∈ t) => Z i)) : set.nonempty (s ∩ set.Inter fun (i : ι) => Z i) := sorry /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ theorem is_compact.nonempty_Inter_of_directed_nonempty_compact_closed {α : Type u} [topological_space α] {ι : Type v} [hι : Nonempty ι] (Z : ι → set α) (hZd : directed superset Z) (hZn : ∀ (i : ι), set.nonempty (Z i)) (hZc : ∀ (i : ι), is_compact (Z i)) (hZcl : ∀ (i : ι), is_closed (Z i)) : set.nonempty (set.Inter fun (i : ι) => Z i) := sorry /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ theorem is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed {α : Type u} [topological_space α] (Z : ℕ → set α) (hZd : ∀ (i : ℕ), Z (i + 1) ⊆ Z i) (hZn : ∀ (i : ℕ), set.nonempty (Z i)) (hZ0 : is_compact (Z 0)) (hZcl : ∀ (i : ℕ), is_closed (Z i)) : set.nonempty (set.Inter fun (i : ℕ) => Z i) := sorry /-- For every open cover of a compact set, there exists a finite subcover. -/ theorem is_compact.elim_finite_subcover_image {α : Type u} {β : Type v} [topological_space α] {s : set α} {b : set β} {c : β → set α} (hs : is_compact s) (hc₁ : ∀ (i : β), i ∈ b → is_open (c i)) (hc₂ : s ⊆ set.Union fun (i : β) => set.Union fun (H : i ∈ b) => c i) : ∃ (b' : set β), ∃ (H : b' ⊆ b), set.finite b' ∧ s ⊆ set.Union fun (i : β) => set.Union fun (H : i ∈ b') => c i := sorry /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_of_finite_subfamily_closed {α : Type u} [topological_space α] {s : set α} (h : ∀ {ι : Type u} (Z : ι → set α), (∀ (i : ι), is_closed (Z i)) → (s ∩ set.Inter fun (i : ι) => Z i) = ∅ → ∃ (t : finset ι), (s ∩ set.Inter fun (i : ι) => set.Inter fun (H : i ∈ t) => Z i) = ∅) : is_compact s := sorry /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ theorem compact_of_finite_subcover {α : Type u} [topological_space α] {s : set α} (h : ∀ {ι : Type u} (U : ι → set α), (∀ (i : ι), is_open (U i)) → (s ⊆ set.Union fun (i : ι) => U i) → ∃ (t : finset ι), s ⊆ set.Union fun (i : ι) => set.Union fun (H : i ∈ t) => U i) : is_compact s := sorry /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ theorem compact_iff_finite_subcover {α : Type u} [topological_space α] {s : set α} : is_compact s ↔ ∀ {ι : Type u} (U : ι → set α), (∀ (i : ι), is_open (U i)) → (s ⊆ set.Union fun (i : ι) => U i) → ∃ (t : finset ι), s ⊆ set.Union fun (i : ι) => set.Union fun (H : i ∈ t) => U i := { mp := fun (hs : is_compact s) (ι : Type u) => is_compact.elim_finite_subcover hs, mpr := compact_of_finite_subcover } /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_iff_finite_subfamily_closed {α : Type u} [topological_space α] {s : set α} : is_compact s ↔ ∀ {ι : Type u} (Z : ι → set α), (∀ (i : ι), is_closed (Z i)) → (s ∩ set.Inter fun (i : ι) => Z i) = ∅ → ∃ (t : finset ι), (s ∩ set.Inter fun (i : ι) => set.Inter fun (H : i ∈ t) => Z i) = ∅ := { mp := fun (hs : is_compact s) (ι : Type u) => is_compact.elim_finite_subfamily_closed hs, mpr := compact_of_finite_subfamily_closed } @[simp] theorem compact_empty {α : Type u} [topological_space α] : is_compact ∅ := fun (f : filter α) (hnf : filter.ne_bot f) (hsf : f ≤ filter.principal ∅) => not.elim hnf (iff.mp filter.empty_in_sets_eq_bot (iff.mp filter.le_principal_iff hsf)) @[simp] theorem compact_singleton {α : Type u} [topological_space α] {a : α} : is_compact (singleton a) := sorry theorem set.subsingleton.is_compact {α : Type u} [topological_space α] {s : set α} (hs : set.subsingleton s) : is_compact s := set.subsingleton.induction_on hs compact_empty fun (x : α) => compact_singleton theorem set.finite.compact_bUnion {α : Type u} {β : Type v} [topological_space α] {s : set β} {f : β → set α} (hs : set.finite s) (hf : ∀ (i : β), i ∈ s → is_compact (f i)) : is_compact (set.Union fun (i : β) => set.Union fun (H : i ∈ s) => f i) := sorry theorem compact_Union {α : Type u} {β : Type v} [topological_space α] {f : β → set α} [fintype β] (h : ∀ (i : β), is_compact (f i)) : is_compact (set.Union fun (i : β) => f i) := eq.mpr (id (Eq._oldrec (Eq.refl (is_compact (set.Union fun (i : β) => f i))) (Eq.symm (set.bUnion_univ fun (i : β) => f i)))) (set.finite.compact_bUnion set.finite_univ fun (i : β) (_x : i ∈ set.univ) => h i) theorem set.finite.is_compact {α : Type u} [topological_space α] {s : set α} (hs : set.finite s) : is_compact s := set.bUnion_of_singleton s ▸ set.finite.compact_bUnion hs fun (_x : α) (_x_1 : _x ∈ s) => compact_singleton theorem is_compact.union {α : Type u} [topological_space α] {s : set α} {t : set α} (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) := eq.mpr (id (Eq._oldrec (Eq.refl (is_compact (s ∪ t))) set.union_eq_Union)) (compact_Union fun (b : Bool) => bool.cases_on b ht hs) theorem is_compact.insert {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) (a : α) : is_compact (insert a s) := is_compact.union compact_singleton hs /-- `filter.cocompact` is the filter generated by complements to compact sets. -/ def filter.cocompact (α : Type u_1) [topological_space α] : filter α := infi fun (s : set α) => infi fun (hs : is_compact s) => filter.principal (sᶜ) theorem filter.has_basis_cocompact {α : Type u} [topological_space α] : filter.has_basis (filter.cocompact α) is_compact compl := sorry theorem filter.mem_cocompact {α : Type u} [topological_space α] {s : set α} : s ∈ filter.cocompact α ↔ ∃ (t : set α), is_compact t ∧ tᶜ ⊆ s := iff.trans (filter.has_basis.mem_iff filter.has_basis_cocompact) (exists_congr fun (t : set α) => exists_prop) theorem filter.mem_cocompact' {α : Type u} [topological_space α] {s : set α} : s ∈ filter.cocompact α ↔ ∃ (t : set α), is_compact t ∧ sᶜ ⊆ t := iff.trans filter.mem_cocompact (exists_congr fun (t : set α) => and_congr_right fun (ht : is_compact t) => set.compl_subset_comm) theorem is_compact.compl_mem_cocompact {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) : sᶜ ∈ filter.cocompact α := filter.has_basis.mem_of_mem filter.has_basis_cocompact hs /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes {α : Type u} {β : Type v} [topological_space α] [topological_space β] (s : set α) (t : set β) := ∀ (n : set (α × β)), is_open n → set.prod s t ⊆ n → ∃ (u : set α), ∃ (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n theorem nhds_contain_boxes.symm {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := sorry theorem nhds_contain_boxes.comm {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := { mp := nhds_contain_boxes.symm, mpr := nhds_contain_boxes.symm } theorem nhds_contain_boxes_of_singleton {α : Type u} {β : Type v} [topological_space α] [topological_space β] {x : α} {y : β} : nhds_contain_boxes (singleton x) (singleton y) := sorry theorem nhds_contain_boxes_of_compact {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} (hs : is_compact s) (t : set β) (H : ∀ (x : α), x ∈ s → nhds_contain_boxes (singleton x) t) : nhds_contain_boxes s t := sorry /-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/ theorem generalized_tube_lemma {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α), ∃ (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := sorry /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type u_1) [topological_space α] where compact_univ : is_compact set.univ protected instance subsingleton.compact_space {α : Type u} [topological_space α] [subsingleton α] : compact_space α := compact_space.mk (set.subsingleton.is_compact set.subsingleton_univ) theorem compact_univ {α : Type u} [topological_space α] [h : compact_space α] : is_compact set.univ := compact_space.compact_univ theorem cluster_point_of_compact {α : Type u} [topological_space α] [compact_space α] (f : filter α) [filter.ne_bot f] : ∃ (x : α), cluster_pt x f := sorry theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α] (h : ∀ {ι : Type u} (Z : ι → set α), (∀ (i : ι), is_closed (Z i)) → (set.Inter fun (i : ι) => Z i) = ∅ → ∃ (t : finset ι), (set.Inter fun (i : ι) => set.Inter fun (H : i ∈ t) => Z i) = ∅) : compact_space α := sorry theorem is_closed.compact {α : Type u} [topological_space α] [compact_space α] {s : set α} (h : is_closed s) : is_compact s := compact_of_is_closed_subset compact_univ h (set.subset_univ s) theorem is_compact.image_of_continuous_on {α : Type u} {β : Type v} [topological_space α] {s : set α} [topological_space β] {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : is_compact (f '' s) := sorry theorem is_compact.image {α : Type u} {β : Type v} [topological_space α] {s : set α} [topological_space β] {f : α → β} (hs : is_compact s) (hf : continuous f) : is_compact (f '' s) := is_compact.image_of_continuous_on hs (continuous.continuous_on hf) theorem compact_range {α : Type u} {β : Type v} [topological_space α] [topological_space β] [compact_space α] {f : α → β} (hf : continuous f) : is_compact (set.range f) := eq.mpr (id (Eq._oldrec (Eq.refl (is_compact (set.range f))) (Eq.symm set.image_univ))) (is_compact.image compact_univ hf) /-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_compact {X : Type u_1} [topological_space X] [compact_space X] {Y : Type u_2} [topological_space Y] : is_closed_map prod.snd := sorry theorem embedding.compact_iff_compact_image {α : Type u} {β : Type v} [topological_space α] {s : set α} [topological_space β] {f : α → β} (hf : embedding f) : is_compact s ↔ is_compact (f '' s) := sorry theorem compact_iff_compact_in_subtype {α : Type u} [topological_space α] {p : α → Prop} {s : set (Subtype fun (a : α) => p a)} : is_compact s ↔ is_compact (coe '' s) := embedding.compact_iff_compact_image embedding_subtype_coe theorem compact_iff_compact_univ {α : Type u} [topological_space α] {s : set α} : is_compact s ↔ is_compact set.univ := sorry theorem compact_iff_compact_space {α : Type u} [topological_space α] {s : set α} : is_compact s ↔ compact_space ↥s := iff.trans compact_iff_compact_univ { mp := fun (h : is_compact set.univ) => compact_space.mk h, mpr := compact_space.compact_univ } theorem is_compact.prod {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) : is_compact (set.prod s t) := sorry /-- Finite topological spaces are compact. -/ protected instance fintype.compact_space {α : Type u} [topological_space α] [fintype α] : compact_space α := compact_space.mk (set.finite.is_compact set.finite_univ) /-- The product of two compact spaces is compact. -/ protected instance prod.compact_space {α : Type u} {β : Type v} [topological_space α] [topological_space β] [compact_space α] [compact_space β] : compact_space (α × β) := compact_space.mk (eq.mpr (id (Eq._oldrec (Eq.refl (is_compact set.univ)) (Eq.symm set.univ_prod_univ))) (is_compact.prod compact_univ compact_univ)) /-- The disjoint union of two compact spaces is compact. -/ protected instance sum.compact_space {α : Type u} {β : Type v} [topological_space α] [topological_space β] [compact_space α] [compact_space β] : compact_space (α ⊕ β) := compact_space.mk (eq.mpr (id (Eq._oldrec (Eq.refl (is_compact set.univ)) (Eq.symm set.range_inl_union_range_inr))) (is_compact.union (compact_range continuous_inl) (compact_range continuous_inr))) /-- Tychonoff's theorem -/ theorem compact_pi_infinite {ι : Type u_1} {π : ι → Type u_2} [(i : ι) → topological_space (π i)] {s : (i : ι) → set (π i)} : (∀ (i : ι), is_compact (s i)) → is_compact (set_of fun (x : (i : ι) → π i) => ∀ (i : ι), x i ∈ s i) := sorry /-- A version of Tychonoff's theorem that uses `set.pi`. -/ theorem compact_univ_pi {ι : Type u_1} {π : ι → Type u_2} [(i : ι) → topological_space (π i)] {s : (i : ι) → set (π i)} (h : ∀ (i : ι), is_compact (s i)) : is_compact (set.pi set.univ s) := sorry protected instance pi.compact {ι : Type u_1} {π : ι → Type u_2} [(i : ι) → topological_space (π i)] [∀ (i : ι), compact_space (π i)] : compact_space ((i : ι) → π i) := sorry protected instance quot.compact_space {α : Type u} [topological_space α] {r : α → α → Prop} [compact_space α] : compact_space (Quot r) := compact_space.mk (eq.mpr (id (Eq._oldrec (Eq.refl (is_compact set.univ)) (Eq.symm (set.range_quot_mk r)))) (compact_range continuous_quot_mk)) protected instance quotient.compact_space {α : Type u} [topological_space α] {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type u_1) [topological_space α] where local_compact_nhds : ∀ (x : α) (n : set α) (H : n ∈ nhds x), ∃ (s : set α), ∃ (H : s ∈ nhds x), s ⊆ n ∧ is_compact s /-- A reformulation of the definition of locally compact space: In a locally compact space, every open set containing `x` has a compact subset containing `x` in its interior. -/ theorem exists_compact_subset {α : Type u} [topological_space α] [locally_compact_space α] {x : α} {U : set α} (hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U := sorry /-- In a locally compact space every point has a compact neighborhood. -/ theorem exists_compact_mem_nhds {α : Type u} [topological_space α] [locally_compact_space α] (x : α) : ∃ (K : set α), is_compact K ∧ K ∈ nhds x := sorry theorem ultrafilter.le_nhds_Lim {α : Type u} [topological_space α] [compact_space α] (F : ultrafilter α) : ↑F ≤ nhds (Lim ↑F) := sorry /-- A σ-compact space is a space that is the union of a countable collection of compact subspaces. Note that a locally compact separable T₂ space need not be σ-compact. The sequence can be extracted using `topological_space.compact_covering`. -/ class sigma_compact_space (α : Type u_1) [topological_space α] where exists_compact_covering : ∃ (K : ℕ → set α), (∀ (n : ℕ), is_compact (K n)) ∧ (set.Union fun (n : ℕ) => K n) = set.univ protected instance compact_space.sigma_compact {α : Type u} [topological_space α] [compact_space α] : sigma_compact_space α := sigma_compact_space.mk (Exists.intro (fun (_x : ℕ) => set.univ) { left := fun (_x : ℕ) => compact_univ, right := set.Union_const set.univ }) theorem sigma_compact_space.of_countable {α : Type u} [topological_space α] (S : set (set α)) (Hc : set.countable S) (Hcomp : ∀ (s : set α), s ∈ S → is_compact s) (HU : ⋃₀S = set.univ) : sigma_compact_space α := sigma_compact_space.mk (iff.mpr (set.exists_seq_cover_iff_countable (Exists.intro ∅ compact_empty)) (Exists.intro S { left := Hc, right := { left := Hcomp, right := HU } })) theorem sigma_compact_space_of_locally_compact_second_countable {α : Type u} [topological_space α] [locally_compact_space α] [topological_space.second_countable_topology α] : sigma_compact_space α := sorry /-- An arbitrary compact covering of a σ-compact space. -/ def compact_covering (α : Type u) [topological_space α] [sigma_compact_space α] : ℕ → set α := classical.some sigma_compact_space.exists_compact_covering theorem is_compact_compact_covering (α : Type u) [topological_space α] [sigma_compact_space α] (n : ℕ) : is_compact (compact_covering α n) := and.left (classical.some_spec sigma_compact_space.exists_compact_covering) n theorem Union_compact_covering (α : Type u) [topological_space α] [sigma_compact_space α] : (set.Union fun (n : ℕ) => compact_covering α n) = set.univ := and.right (classical.some_spec sigma_compact_space.exists_compact_covering) /-- A set is clopen if it is both open and closed. -/ def is_clopen {α : Type u} [topological_space α] (s : set α) := is_open s ∧ is_closed s theorem is_clopen_union {α : Type u} [topological_space α] {s : set α} {t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := { left := is_open_union (and.left hs) (and.left ht), right := is_closed_union (and.right hs) (and.right ht) } theorem is_clopen_inter {α : Type u} [topological_space α] {s : set α} {t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := { left := is_open_inter (and.left hs) (and.left ht), right := is_closed_inter (and.right hs) (and.right ht) } @[simp] theorem is_clopen_empty {α : Type u} [topological_space α] : is_clopen ∅ := { left := is_open_empty, right := is_closed_empty } @[simp] theorem is_clopen_univ {α : Type u} [topological_space α] : is_clopen set.univ := { left := is_open_univ, right := is_closed_univ } theorem is_clopen_compl {α : Type u} [topological_space α] {s : set α} (hs : is_clopen s) : is_clopen (sᶜ) := { left := and.right hs, right := iff.mpr is_closed_compl_iff (and.left hs) } @[simp] theorem is_clopen_compl_iff {α : Type u} [topological_space α] {s : set α} : is_clopen (sᶜ) ↔ is_clopen s := { mp := fun (h : is_clopen (sᶜ)) => compl_compl s ▸ is_clopen_compl h, mpr := is_clopen_compl } theorem is_clopen_diff {α : Type u} [topological_space α] {s : set α} {t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) := is_clopen_inter hs (is_clopen_compl ht) theorem is_clopen_Inter {α : Type u} [topological_space α] {β : Type u_1} [fintype β] {s : β → set α} (h : ∀ (i : β), is_clopen (s i)) : is_clopen (set.Inter fun (i : β) => s i) := { left := is_open_Inter (and.left (iff.mp forall_and_distrib h)), right := is_closed_Inter (and.right (iff.mp forall_and_distrib h)) } theorem is_clopen_bInter {α : Type u} [topological_space α] {β : Type u_1} {s : finset β} {f : β → set α} (h : ∀ (i : β), i ∈ s → is_clopen (f i)) : is_clopen (set.Inter fun (i : β) => set.Inter fun (H : i ∈ s) => f i) := sorry theorem continuous_on.preimage_clopen_of_clopen {α : Type u} [topological_space α] {β : Type u_1} [topological_space β] {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ f ⁻¹' t) := { left := continuous_on.preimage_open_of_open hf (and.left hs) (and.left ht), right := continuous_on.preimage_closed_of_closed hf (and.right hs) (and.right ht) } /-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/ theorem is_clopen_inter_of_disjoint_cover_clopen {α : Type u} [topological_space α] {Z : set α} {a : set α} {b : set α} (h : is_clopen Z) (cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : a ∩ b = ∅) : is_clopen (Z ∩ a) := sorry /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible {α : Type u} [topological_space α] (s : set α) := ∀ (u v : set α), is_open u → is_open v → set.nonempty (s ∩ u) → set.nonempty (s ∩ v) → set.nonempty (s ∩ (u ∩ v)) /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible {α : Type u} [topological_space α] (s : set α) := set.nonempty s ∧ is_preirreducible s theorem is_irreducible.nonempty {α : Type u} [topological_space α] {s : set α} (h : is_irreducible s) : set.nonempty s := and.left h theorem is_irreducible.is_preirreducible {α : Type u} [topological_space α] {s : set α} (h : is_irreducible s) : is_preirreducible s := and.right h theorem is_preirreducible_empty {α : Type u} [topological_space α] : is_preirreducible ∅ := sorry theorem is_irreducible_singleton {α : Type u} [topological_space α] {x : α} : is_irreducible (singleton x) := sorry theorem is_preirreducible.closure {α : Type u} [topological_space α] {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := sorry theorem is_irreducible.closure {α : Type u} [topological_space α] {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := { left := set.nonempty.closure (is_irreducible.nonempty h), right := is_preirreducible.closure (is_irreducible.is_preirreducible h) } theorem exists_preirreducible {α : Type u} [topological_space α] (s : set α) (H : is_preirreducible s) : ∃ (t : set α), is_preirreducible t ∧ s ⊆ t ∧ ∀ (u : set α), is_preirreducible u → t ⊆ u → u = t := sorry /-- A maximal irreducible set that contains a given point. -/ def irreducible_component {α : Type u} [topological_space α] (x : α) : set α := classical.some sorry theorem irreducible_component_property {α : Type u} [topological_space α] (x : α) : is_preirreducible (irreducible_component x) ∧ singleton x ⊆ irreducible_component x ∧ ∀ (u : set α), is_preirreducible u → irreducible_component x ⊆ u → u = irreducible_component x := classical.some_spec (exists_preirreducible (singleton x) (is_irreducible.is_preirreducible is_irreducible_singleton)) theorem mem_irreducible_component {α : Type u} [topological_space α] {x : α} : x ∈ irreducible_component x := iff.mp set.singleton_subset_iff (and.left (and.right (irreducible_component_property x))) theorem is_irreducible_irreducible_component {α : Type u} [topological_space α] {x : α} : is_irreducible (irreducible_component x) := { left := Exists.intro x mem_irreducible_component, right := and.left (irreducible_component_property x) } theorem eq_irreducible_component {α : Type u} [topological_space α] {x : α} {s : set α} : is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := and.right (and.right (irreducible_component_property x)) theorem is_closed_irreducible_component {α : Type u} [topological_space α] {x : α} : is_closed (irreducible_component x) := iff.mp closure_eq_iff_is_closed (eq_irreducible_component (is_preirreducible.closure (is_irreducible.is_preirreducible is_irreducible_irreducible_component)) subset_closure) /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] where is_preirreducible_univ : is_preirreducible set.univ /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends Nonempty α, preirreducible_space α where to_nonempty : Nonempty α theorem nonempty_preirreducible_inter {α : Type u} [topological_space α] [preirreducible_space α] {s : set α} {t : set α} : is_open s → is_open t → set.nonempty s → set.nonempty t → set.nonempty (s ∩ t) := sorry theorem is_preirreducible.image {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := sorry theorem is_irreducible.image {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := { left := iff.mpr set.nonempty_image_iff (is_irreducible.nonempty H), right := is_preirreducible.image (is_irreducible.is_preirreducible H) f hf } theorem subtype.preirreducible_space {α : Type u} [topological_space α] {s : set α} (h : is_preirreducible s) : preirreducible_space ↥s := sorry theorem subtype.irreducible_space {α : Type u} [topological_space α] {s : set α} (h : is_irreducible s) : irreducible_space ↥s := irreducible_space.mk (set.nonempty.to_subtype (is_irreducible.nonempty h)) /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ theorem is_irreducible_iff_sInter {α : Type u} [topological_space α] {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)), (∀ (u : set α), u ∈ U → is_open u) → (∀ (u : set α), u ∈ U → set.nonempty (s ∩ u)) → set.nonempty (s ∩ ⋂₀↑U) := sorry /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ theorem is_preirreducible_iff_closed_union_closed {α : Type u} [topological_space α] {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := sorry /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ theorem is_irreducible_iff_sUnion_closed {α : Type u} [topological_space α] {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)), (∀ (z : set α), z ∈ Z → is_closed z) → ∀ (H : s ⊆ ⋃₀↑Z), ∃ (z : set α), ∃ (H : z ∈ Z), s ⊆ z := sorry /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected {α : Type u} [topological_space α] (s : set α) := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → set.nonempty (s ∩ u) → set.nonempty (s ∩ v) → set.nonempty (s ∩ (u ∩ v)) /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected {α : Type u} [topological_space α] (s : set α) := set.nonempty s ∧ is_preconnected s theorem is_connected.nonempty {α : Type u} [topological_space α] {s : set α} (h : is_connected s) : set.nonempty s := and.left h theorem is_connected.is_preconnected {α : Type u} [topological_space α] {s : set α} (h : is_connected s) : is_preconnected s := and.right h theorem is_preirreducible.is_preconnected {α : Type u} [topological_space α] {s : set α} (H : is_preirreducible s) : is_preconnected s := fun (_x _x_1 : set α) (hu : is_open _x) (hv : is_open _x_1) (_x_2 : s ⊆ _x ∪ _x_1) => H _x _x_1 hu hv theorem is_irreducible.is_connected {α : Type u} [topological_space α] {s : set α} (H : is_irreducible s) : is_connected s := { left := is_irreducible.nonempty H, right := is_preirreducible.is_preconnected (is_irreducible.is_preirreducible H) } theorem is_preconnected_empty {α : Type u} [topological_space α] : is_preconnected ∅ := is_preirreducible.is_preconnected is_preirreducible_empty theorem is_connected_singleton {α : Type u} [topological_space α] {x : α} : is_connected (singleton x) := is_irreducible.is_connected is_irreducible_singleton /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {α : Type u} [topological_space α] {s : set α} (x : α) (H : ∀ (y : α) (H : y ∈ s), ∃ (t : set α), ∃ (H : t ⊆ s), x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := sorry /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {α : Type u} [topological_space α] {s : set α} (H : ∀ (x y : α) (H : x ∈ s) (H : y ∈ s), ∃ (t : set α), ∃ (H : t ⊆ s), x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := sorry /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion {α : Type u} [topological_space α] (x : α) (c : set (set α)) (H1 : ∀ (s : set α), s ∈ c → x ∈ s) (H2 : ∀ (s : set α), s ∈ c → is_preconnected s) : is_preconnected (⋃₀c) := sorry theorem is_preconnected.union {α : Type u} [topological_space α] (x : α) {s : set α} {t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sorry theorem is_connected.union {α : Type u} [topological_space α] {s : set α} {t : set α} (H : set.nonempty (s ∩ t)) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := sorry theorem is_preconnected.closure {α : Type u} [topological_space α] {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := sorry theorem is_connected.closure {α : Type u} [topological_space α] {s : set α} (H : is_connected s) : is_connected (closure s) := { left := set.nonempty.closure (is_connected.nonempty H), right := is_preconnected.closure (is_connected.is_preconnected H) } theorem is_preconnected.image {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := sorry theorem is_connected.image {α : Type u} {β : Type v} [topological_space α] [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := { left := iff.mpr set.nonempty_image_iff (is_connected.nonempty H), right := is_preconnected.image (is_connected.is_preconnected H) f hf } theorem is_preconnected_closed_iff {α : Type u} [topological_space α] {s : set α} : is_preconnected s ↔ ∀ (t t' : set α), is_closed t → is_closed t' → s ⊆ t ∪ t' → set.nonempty (s ∩ t) → set.nonempty (s ∩ t') → set.nonempty (s ∩ (t ∩ t')) := sorry /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component {α : Type u} [topological_space α] (x : α) : set α := ⋃₀set_of fun (s : set α) => is_preconnected s ∧ x ∈ s /-- The connected component of a point inside a set. -/ def connected_component_in {α : Type u} [topological_space α] (F : set α) (x : ↥F) : set α := coe '' connected_component x theorem mem_connected_component {α : Type u} [topological_space α] {x : α} : x ∈ connected_component x := set.mem_sUnion_of_mem (set.mem_singleton x) { left := is_connected.is_preconnected is_connected_singleton, right := set.mem_singleton x } theorem is_connected_connected_component {α : Type u} [topological_space α] {x : α} : is_connected (connected_component x) := sorry theorem subset_connected_component {α : Type u} [topological_space α] {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := fun (z : α) (hz : z ∈ s) => set.mem_sUnion_of_mem hz { left := H1, right := H2 } theorem is_closed_connected_component {α : Type u} [topological_space α] {x : α} : is_closed (connected_component x) := sorry theorem irreducible_component_subset_connected_component {α : Type u} [topological_space α] {x : α} : irreducible_component x ⊆ connected_component x := subset_connected_component (is_connected.is_preconnected (is_irreducible.is_connected is_irreducible_irreducible_component)) mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] where is_preconnected_univ : is_preconnected set.univ /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α, Nonempty α where to_nonempty : Nonempty α theorem is_connected_range {α : Type u} {β : Type v} [topological_space α] [topological_space β] [connected_space α] {f : α → β} (h : continuous f) : is_connected (set.range f) := sorry theorem connected_space_iff_connected_component {α : Type u} [topological_space α] : connected_space α ↔ ∃ (x : α), connected_component x = set.univ := sorry protected instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := preconnected_space.mk (is_preirreducible.is_preconnected (preirreducible_space.is_preirreducible_univ α)) protected instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := connected_space.mk (irreducible_space.to_nonempty α) theorem nonempty_inter {α : Type u} [topological_space α] [preconnected_space α] {s : set α} {t : set α} : is_open s → is_open t → s ∪ t = set.univ → set.nonempty s → set.nonempty t → set.nonempty (s ∩ t) := sorry theorem is_clopen_iff {α : Type u} [topological_space α] [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = set.univ := sorry theorem eq_univ_of_nonempty_clopen {α : Type u} [topological_space α] [preconnected_space α] {s : set α} (h : set.nonempty s) (h' : is_clopen s) : s = set.univ := sorry theorem subtype.preconnected_space {α : Type u} [topological_space α] {s : set α} (h : is_preconnected s) : preconnected_space ↥s := sorry theorem subtype.connected_space {α : Type u} [topological_space α] {s : set α} (h : is_connected s) : connected_space ↥s := connected_space.mk (set.nonempty.to_subtype (is_connected.nonempty h)) theorem is_preconnected_iff_preconnected_space {α : Type u} [topological_space α] {s : set α} : is_preconnected s ↔ preconnected_space ↥s := sorry theorem is_connected_iff_connected_space {α : Type u} [topological_space α] {s : set α} : is_connected s ↔ connected_space ↥s := sorry /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_disjoint {α : Type u} [topological_space α] {s : set α} : is_preconnected s ↔ ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → s ∩ (u ∩ v) = ∅ → s ⊆ u ∨ s ⊆ v := sorry /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ theorem is_connected_iff_sUnion_disjoint_open {α : Type u} [topological_space α] {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → set.nonempty (s ∩ (u ∩ v)) → u = v), (∀ (u : set α), u ∈ U → is_open u) → s ⊆ ⋃₀↑U → ∃ (u : set α), ∃ (H : u ∈ U), s ⊆ u := sorry /-- Preconnected sets are either contained in or disjoint to any given clopen set. -/ theorem subset_or_disjoint_of_clopen {α : Type u_1} [topological_space α] {s : set α} {t : set α} (h : is_preconnected t) (h1 : is_clopen s) : s ∩ t = ∅ ∨ t ⊆ s := sorry /-- A set `s` is preconnected if and only if for every cover by two closed sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_disjoint_closed {α : Type u_1} {s : set α} [topological_space α] : is_preconnected s ↔ ∀ (u v : set α), is_closed u → is_closed v → s ⊆ u ∪ v → s ∩ (u ∩ v) = ∅ → s ⊆ u ∨ s ⊆ v := sorry /-- A closed set `s` is preconnected if and only if for every cover by two closed sets that are disjoint, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_fully_disjoint_closed {α : Type u} [topological_space α] {s : set α} (hs : is_closed s) : is_preconnected s ↔ ∀ (u v : set α), is_closed u → is_closed v → s ⊆ u ∪ v → u ∩ v = ∅ → s ⊆ u ∨ s ⊆ v := sorry /-- The connected component of a point is always a subset of the intersection of all its clopen neighbourhoods. -/ theorem connected_component_subset_Inter_clopen {α : Type u} [topological_space α] {x : α} : connected_component x ⊆ set.Inter fun (Z : Subtype fun (Z : set α) => is_clopen Z ∧ x ∈ Z) => ↑Z := sorry /-- A set is called totally disconnected if all of its connected components are singletons. -/ def is_totally_disconnected {α : Type u} [topological_space α] (s : set α) := ∀ (t : set α), t ⊆ s → is_preconnected t → subsingleton ↥t theorem is_totally_disconnected_empty {α : Type u} [topological_space α] : is_totally_disconnected ∅ := sorry theorem is_totally_disconnected_singleton {α : Type u} [topological_space α] {x : α} : is_totally_disconnected (singleton x) := sorry /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] where is_totally_disconnected_univ : is_totally_disconnected set.univ protected instance pi.totally_disconnected_space {α : Type u_1} {β : α → Type u_2} [t₂ : (a : α) → topological_space (β a)] [∀ (a : α), totally_disconnected_space (β a)] : totally_disconnected_space ((a : α) → β a) := sorry protected instance subtype.totally_disconnected_space {α : Type u_1} {p : α → Prop} [topological_space α] [totally_disconnected_space α] : totally_disconnected_space (Subtype p) := totally_disconnected_space.mk fun (s : set (Subtype p)) (h1 : s ⊆ set.univ) (h2 : is_preconnected s) => set.subsingleton_of_image subtype.val_injective s (totally_disconnected_space.is_totally_disconnected_univ (subtype.val '' s) (set.subset_univ (subtype.val '' s)) (is_preconnected.image h2 subtype.val (continuous.continuous_on continuous_subtype_val))) /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated {α : Type u} [topological_space α] (s : set α) := ∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → x ≠ y → ∃ (u : set α), ∃ (v : set α), is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty {α : Type u} [topological_space α] : is_totally_separated ∅ := fun (x : α) => false.elim theorem is_totally_separated_singleton {α : Type u} [topological_space α] {x : α} : is_totally_separated (singleton x) := fun (p : α) (hp : p ∈ singleton x) (q : α) (hq : q ∈ singleton x) (hpq : p ≠ q) => false.elim (hpq (Eq.symm (set.eq_of_mem_singleton hp) ▸ Eq.symm (set.eq_of_mem_singleton hq))) theorem is_totally_disconnected_of_is_totally_separated {α : Type u} [topological_space α] {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := sorry /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] where is_totally_separated_univ : is_totally_separated set.univ protected instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := totally_disconnected_space.mk (is_totally_disconnected_of_is_totally_separated (totally_separated_space.is_totally_separated_univ α)) protected instance totally_separated_space.of_discrete (α : Type u_1) [topological_space α] [discrete_topology α] : totally_separated_space α := sorry
712cfe5e3a1a9afcbda4515f1ed056209572e22f
92b50235facfbc08dfe7f334827d47281471333b
/tests/lean/print_ax2.lean
c1fffdd241b2a7271e7bb3af470705c8ba5e28fb
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
58
lean
import logic.axioms.hilbert logic.axioms.em print axioms
4283408092d47755deb86018cd73167709231b3d
b147e1312077cdcfea8e6756207b3fa538982e12
/set_theory/zfc.lean
5039779a3fd6ee21f681fde67f51b0a6c9b16d52
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,850
lean
import data.set.basic universes u v /-- The type of `n`-ary functions `α → α → ... → α`. -/ def arity (α : Type u) : nat → Type u | 0 := α | (n+1) := α → arity n /-- The type of pre-sets in universe `u`. A pre-set is a family of pre-sets indexed by a type in `Type u`. The ZFC universe is defined as a quotient of this to ensure extensionality. -/ inductive pSet : Type (u+1) | mk (α : Type u) (A : α → pSet) : pSet namespace pSet /-- The underlying type of a pre-set -/ def type : pSet → Type u | ⟨α, A⟩ := α /-- The underlying pre-set family of a pre-set -/ def func : Π (x : pSet), x.type → pSet | ⟨α, A⟩ := A theorem mk_type_func : Π (x : pSet), mk x.type x.func = x | ⟨α, A⟩ := rfl /-- Two pre-sets are extensionally equivalent if every element of the first family is extensionally equivalent to some element of the second family and vice-versa. -/ def equiv (x y : pSet) : Prop := pSet.rec (λα z m ⟨β, B⟩, (∀a, ∃b, m a (B b)) ∧ (∀b, ∃a, m a (B b))) x y theorem equiv.refl (x) : equiv x x := pSet.rec_on x $ λα A IH, ⟨λa, ⟨a, IH a⟩, λa, ⟨a, IH a⟩⟩ theorem equiv.euc {x} : Π {y z}, equiv x y → equiv z y → equiv x z := pSet.rec_on x $ λα A IH y, pSet.rec_on y $ λβ B _ ⟨γ, Γ⟩ ⟨αβ, βα⟩ ⟨γβ, βγ⟩, ⟨λa, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, IH a ab bc⟩, λc, let ⟨b, cb⟩ := γβ c, ⟨a, ba⟩ := βα b in ⟨a, IH a ba cb⟩⟩ theorem equiv.symm {x y} : equiv x y → equiv y x := equiv.euc (equiv.refl y) theorem equiv.trans {x y z} (h1 : equiv x y) (h2 : equiv y z) : equiv x z := equiv.euc h1 (equiv.symm h2) instance setoid : setoid pSet := ⟨pSet.equiv, equiv.refl, λx y, equiv.symm, λx y z, equiv.trans⟩ protected def subset : pSet → pSet → Prop | ⟨α, A⟩ ⟨β, B⟩ := ∀a, ∃b, equiv (A a) (B b) instance : has_subset pSet := ⟨pSet.subset⟩ theorem equiv.ext : Π (x y : pSet), equiv x y ↔ (x ⊆ y ∧ y ⊆ x) | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ⟨αβ, βα⟩, ⟨αβ, λb, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩, λ⟨αβ, βα⟩, ⟨αβ, λb, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩⟩ theorem subset.congr_left : Π {x y z : pSet}, equiv x y → (x ⊆ z ↔ y ⊆ z) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λαγ b, let ⟨a, ba⟩ := βα b, ⟨c, ac⟩ := αγ a in ⟨c, equiv.trans (equiv.symm ba) ac⟩, λβγ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, equiv.trans ab bc⟩⟩ theorem subset.congr_right : Π {x y z : pSet}, equiv x y → (z ⊆ x ↔ z ⊆ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λγα c, let ⟨a, ca⟩ := γα c, ⟨b, ab⟩ := αβ a in ⟨b, equiv.trans ca ab⟩, λγβ c, let ⟨b, cb⟩ := γβ c, ⟨a, ab⟩ := βα b in ⟨a, equiv.trans cb (equiv.symm ab)⟩⟩ /-- `x ∈ y` as pre-sets if `x` is extensionally equivalent to a member of the family `y`. -/ def mem : pSet → pSet → Prop | x ⟨β, B⟩ := ∃b, equiv x (B b) instance : has_mem pSet.{u} pSet.{u} := ⟨mem⟩ theorem mem.mk {α: Type u} (A : α → pSet) (a : α) : A a ∈ mk α A := show mem (A a) ⟨α, A⟩, from ⟨a, equiv.refl (A a)⟩ theorem mem.ext : Π {x y : pSet.{u}}, (∀w:pSet.{u}, w ∈ x ↔ w ∈ y) → equiv x y | ⟨α, A⟩ ⟨β, B⟩ h := ⟨λa, (h (A a)).1 (mem.mk A a), λb, let ⟨a, ha⟩ := (h (B b)).2 (mem.mk B b) in ⟨a, equiv.symm ha⟩⟩ theorem mem.congr_right : Π {x y : pSet.{u}}, equiv x y → (∀{w:pSet.{u}}, w ∈ x ↔ w ∈ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩ w := ⟨λ⟨a, ha⟩, let ⟨b, hb⟩ := αβ a in ⟨b, equiv.trans ha hb⟩, λ⟨b, hb⟩, let ⟨a, ha⟩ := βα b in ⟨a, equiv.euc hb ha⟩⟩ theorem equiv_iff_mem {x y : pSet.{u}} : equiv x y ↔ (∀{w:pSet.{u}}, w ∈ x ↔ w ∈ y) := ⟨mem.congr_right, match x, y with | ⟨α, A⟩, ⟨β, B⟩, h := ⟨λ a, h.1 (mem.mk A a), λ b, let ⟨a, h⟩ := h.2 (mem.mk B b) in ⟨a, h.symm⟩⟩ end⟩ theorem mem.congr_left : Π {x y : pSet.{u}}, equiv x y → (∀{w : pSet.{u}}, x ∈ w ↔ y ∈ w) | x y h ⟨α, A⟩ := ⟨λ⟨a, ha⟩, ⟨a, equiv.trans (equiv.symm h) ha⟩, λ⟨a, ha⟩, ⟨a, equiv.trans h ha⟩⟩ /-- Convert a pre-set to a `set` of pre-sets. -/ def to_set (u : pSet.{u}) : set pSet.{u} := {x | x ∈ u} /-- Two pre-sets are equivalent iff they have the same members. -/ theorem equiv.eq {x y : pSet} : equiv x y ↔ to_set x = to_set y := equiv_iff_mem.trans (set.ext_iff _ _).symm instance : has_coe pSet (set pSet) := ⟨to_set⟩ /-- The empty pre-set -/ protected def empty : pSet := ⟨ulift empty, λe, match e with end⟩ instance : has_emptyc pSet := ⟨pSet.empty⟩ theorem mem_empty (x : pSet.{u}) : x ∉ (∅:pSet.{u}) := λe, match e with end /-- Insert an element into a pre-set -/ protected def insert : pSet → pSet → pSet | u ⟨α, A⟩ := ⟨option α, λo, option.rec u A o⟩ instance : has_insert pSet pSet := ⟨pSet.insert⟩ /-- The n-th von Neumann ordinal -/ def of_nat : ℕ → pSet | 0 := ∅ | (n+1) := pSet.insert (of_nat n) (of_nat n) /-- The von Neumann ordinal ω -/ def omega : pSet := ⟨ulift ℕ, λn, of_nat n.down⟩ /-- The separation operation `{x ∈ a | p x}` -/ protected def sep (p : set pSet) : pSet → pSet | ⟨α, A⟩ := ⟨{a // p (A a)}, λx, A x.1⟩ instance : has_sep pSet pSet := ⟨pSet.sep⟩ /-- The powerset operator -/ def powerset : pSet → pSet | ⟨α, A⟩ := ⟨set α, λp, ⟨{a // p a}, λx, A x.1⟩⟩ theorem mem_powerset : Π {x y : pSet}, y ∈ powerset x ↔ y ⊆ x | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ⟨p, e⟩, (subset.congr_left e).2 $ λ⟨a, pa⟩, ⟨a, equiv.refl (A a)⟩, λβα, ⟨{a | ∃b, equiv (B b) (A a)}, λb, let ⟨a, ba⟩ := βα b in ⟨⟨a, b, ba⟩, ba⟩, λ⟨a, b, ba⟩, ⟨b, ba⟩⟩⟩ /-- The set union operator -/ def Union : pSet → pSet | ⟨α, A⟩ := ⟨Σx, (A x).type, λ⟨x, y⟩, (A x).func y⟩ theorem mem_Union : Π {x y : pSet.{u}}, y ∈ Union x ↔ ∃ z:pSet.{u}, ∃_:z ∈ x, y ∈ z | ⟨α, A⟩ y := ⟨λ⟨⟨a, c⟩, (e : equiv y ((A a).func c))⟩, have func (A a) c ∈ mk (A a).type (A a).func, from mem.mk (A a).func c, ⟨_, mem.mk _ _, (mem.congr_left e).2 (by rwa mk_type_func at this)⟩, λ⟨⟨β, B⟩, ⟨a, (e:equiv (mk β B) (A a))⟩, ⟨b, yb⟩⟩, by rw ←(mk_type_func (A a)) at e; exact let ⟨βt, tβ⟩ := e, ⟨c, bc⟩ := βt b in ⟨⟨a, c⟩, equiv.trans yb bc⟩⟩ /-- The image of a function -/ def image (f : pSet.{u} → pSet.{u}) : pSet.{u} → pSet | ⟨α, A⟩ := ⟨α, λa, f (A a)⟩ theorem mem_image {f : pSet.{u} → pSet.{u}} (H : ∀{x y}, equiv x y → equiv (f x) (f y)) : Π {x y : pSet.{u}}, y ∈ image f x ↔ ∃z ∈ x, equiv y (f z) | ⟨α, A⟩ y := ⟨λ⟨a, ya⟩, ⟨A a, mem.mk A a, ya⟩, λ⟨z, ⟨a, za⟩, yz⟩, ⟨a, equiv.trans yz (H za)⟩⟩ /-- Universe lift operation -/ protected def lift : pSet.{u} → pSet.{max u v} | ⟨α, A⟩ := ⟨ulift α, λ⟨x⟩, lift (A x)⟩ /-- Embedding of one universe in another -/ def embed : pSet.{max (u+1) v} := ⟨ulift.{v u+1} pSet, λ⟨x⟩, pSet.lift.{u (max (u+1) v)} x⟩ theorem lift_mem_embed : Π (x : pSet.{u}), pSet.lift.{u (max (u+1) v)} x ∈ embed.{u v} := λx, ⟨⟨x⟩, equiv.refl _⟩ /-- Function equivalence is defined so that `f ~ g` iff `∀ x y, x ~ y → f x ~ g y`. This extends to equivalence of n-ary functions. -/ def arity.equiv : Π {n}, arity pSet.{u} n → arity pSet.{u} n → Prop | 0 a b := equiv a b | (n+1) a b := ∀ x y, equiv x y → arity.equiv (a x) (b y) /-- `resp n` is the collection of n-ary functions on `pSet` that respect equivalence, i.e. when the inputs are equivalent the output is as well. -/ def resp (n) := { x : arity pSet.{u} n // arity.equiv x x } def resp.f {n} (f : resp (n+1)) (x : pSet) : resp n := ⟨f.1 x, f.2 _ _ $ equiv.refl x⟩ def resp.equiv {n} (a b : resp n) : Prop := arity.equiv a.1 b.1 theorem resp.refl {n} (a : resp n) : resp.equiv a a := a.2 theorem resp.euc : Π {n} {a b c : resp n}, resp.equiv a b → resp.equiv c b → resp.equiv a c | 0 a b c hab hcb := equiv.euc hab hcb | (n+1) a b c hab hcb := by delta resp.equiv; simp [arity.equiv]; exact λx y h, @resp.euc n (a.f x) (b.f y) (c.f y) (hab _ _ h) (hcb _ _ $ equiv.refl y) instance resp.setoid {n} : setoid (resp n) := ⟨resp.equiv, resp.refl, λx y h, resp.euc (resp.refl y) h, λx y z h1 h2, resp.euc h1 $ resp.euc (resp.refl z) h2⟩ end pSet /-- The ZFC universe of sets consists of the type of pre-sets, quotiented by extensional equivalence. -/ def Set : Type (u+1) := quotient pSet.setoid.{u} namespace pSet namespace resp def eval_aux : Π {n}, { f : resp n → arity Set.{u} n // ∀ (a b : resp n), resp.equiv a b → f a = f b } | 0 := ⟨λa, ⟦a.1⟧, λa b h, quotient.sound h⟩ | (n+1) := let F : resp (n + 1) → arity Set (n + 1) := λa, @quotient.lift _ _ pSet.setoid (λx, eval_aux.1 (a.f x)) (λb c h, eval_aux.2 _ _ (a.2 _ _ h)) in ⟨F, λb c h, funext $ @quotient.ind _ _ (λq, F b q = F c q) $ λz, eval_aux.2 (resp.f b z) (resp.f c z) (h _ _ (equiv.refl z))⟩ /-- An equivalence-respecting function yields an n-ary Set function. -/ def eval (n) : resp n → arity Set.{u} n := eval_aux.1 @[simp] theorem eval_val {n f x} : (@eval (n+1) f : Set → arity Set n) ⟦x⟧ = eval n (resp.f f x) := rfl end resp /-- A set function is "definable" if it is the image of some n-ary pre-set function. This isn't exactly definability, but is useful as a sufficient condition for functions that have a computable image. -/ @[class] inductive definable (n) : arity Set.{u} n → Type (u+1) | mk (f) : definable (resp.eval _ f) attribute [instance] definable.mk def definable.eq_mk {n} (f) : Π {s : arity Set.{u} n} (H : resp.eval _ f = s), definable n s | ._ rfl := ⟨f⟩ def definable.resp {n} : Π (s : arity Set.{u} n) [definable n s], resp n | ._ ⟨f⟩ := f theorem definable.eq {n} : Π (s : arity Set.{u} n) [H : definable n s], (@definable.resp n s H).eval _ = s | ._ ⟨f⟩ := rfl end pSet namespace classical open pSet noncomputable theorem all_definable : Π {n} (F : arity Set.{u} n), definable n F | 0 F := let p := @quotient.exists_rep pSet _ F in definable.eq_mk ⟨some p, equiv.refl _⟩ (some_spec p) | (n+1) (F : arity Set.{u} (n + 1)) := begin have I := λx, (all_definable (F x)), refine definable.eq_mk ⟨λx:pSet, (@definable.resp _ _ (I ⟦x⟧)).1, _⟩ _, { dsimp [arity.equiv], introsI x y h, rw @quotient.sound pSet _ _ _ h, exact (definable.resp (F ⟦y⟧)).2 }, exact funext (λq, quotient.induction_on q $ λx, by simp [resp.f]; exact @definable.eq _ (F ⟦x⟧) (I ⟦x⟧)) end end classical namespace Set open pSet def mk : pSet → Set := quotient.mk @[simp] theorem mk_eq (x : pSet) : @eq Set ⟦x⟧ (mk x) := rfl def mem : Set → Set → Prop := quotient.lift₂ pSet.mem (λx y x' y' hx hy, propext (iff.trans (mem.congr_left hx) (mem.congr_right hy))) instance : has_mem Set Set := ⟨mem⟩ /-- Convert a ZFC set into a `set` of sets -/ def to_set (u : Set.{u}) : set Set.{u} := {x | x ∈ u} protected def subset (x y : Set.{u}) := ∀ ⦃z⦄, z ∈ x → z ∈ y instance has_subset : has_subset Set := ⟨Set.subset⟩ theorem subset_iff : Π (x y : pSet), mk x ⊆ mk y ↔ x ⊆ y | ⟨α, A⟩ ⟨β, B⟩ := ⟨λh a, @h ⟦A a⟧ (mem.mk A a), λh z, quotient.induction_on z (λz ⟨a, za⟩, let ⟨b, ab⟩ := h a in ⟨b, equiv.trans za ab⟩)⟩ theorem ext {x y : Set.{u}} : (∀z:Set.{u}, z ∈ x ↔ z ∈ y) → x = y := quotient.induction_on₂ x y (λu v h, quotient.sound (mem.ext (λw, h ⟦w⟧))) theorem ext_iff {x y : Set.{u}} : (∀z:Set.{u}, z ∈ x ↔ z ∈ y) ↔ x = y := ⟨ext, λh, by simp [h]⟩ /-- The empty set -/ def empty : Set := mk ∅ instance : has_emptyc Set := ⟨empty⟩ instance : inhabited Set := ⟨∅⟩ @[simp] theorem mem_empty (x) : x ∉ (∅:Set.{u}) := quotient.induction_on x pSet.mem_empty theorem eq_empty (x : Set.{u}) : x = ∅ ↔ ∀y:Set.{u}, y ∉ x := ⟨λh, by rw h; exact mem_empty, λh, ext (λy, ⟨λyx, absurd yx (h y), λy0, absurd y0 (mem_empty _)⟩)⟩ /-- `insert x y` is the set `{x} ∪ y` -/ protected def insert : Set → Set → Set := resp.eval 2 ⟨pSet.insert, λu v uv ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λo, match o with | some a := let ⟨b, hb⟩ := αβ a in ⟨some b, hb⟩ | none := ⟨none, uv⟩ end, λo, match o with | some b := let ⟨a, ha⟩ := βα b in ⟨some a, ha⟩ | none := ⟨none, uv⟩ end⟩⟩ instance : has_insert Set Set := ⟨Set.insert⟩ @[simp] theorem mem_insert {x y z : Set.{u}} : x ∈ insert y z ↔ x = y ∨ x ∈ z := quotient.induction_on₃ x y z (λx y ⟨α, A⟩, show x ∈ pSet.mk (option α) (λo, option.rec y A o) ↔ mk x = mk y ∨ x ∈ pSet.mk α A, from ⟨λm, match m with | ⟨some a, ha⟩ := or.inr ⟨a, ha⟩ | ⟨none, h⟩ := or.inl (quotient.sound h) end, λm, match m with | or.inr ⟨a, ha⟩ := ⟨some a, ha⟩ | or.inl h := ⟨none, quotient.exact h⟩ end⟩) @[simp] theorem mem_singleton {x y : Set.{u}} : x ∈ @singleton Set.{u} Set.{u} _ _ y ↔ x = y := iff.trans mem_insert ⟨λo, or.rec (λh, h) (λn, absurd n (mem_empty _)) o, or.inl⟩ @[simp] theorem mem_singleton' {x y : Set.{u}} : x ∈ @insert Set.{u} Set.{u} _ y ∅ ↔ x = y := mem_singleton @[simp] theorem mem_pair {x y z : Set.{u}} : x ∈ ({y, z} : Set) ↔ x = y ∨ x = z := iff.trans mem_insert $ iff.trans or.comm $ let m := @mem_singleton x y in ⟨or.imp_left m.1, or.imp_left m.2⟩ /-- `omega` is the first infinite von Neumann ordinal -/ def omega : Set := mk omega @[simp] theorem omega_zero : ∅ ∈ omega := show pSet.mem ∅ pSet.omega, from ⟨⟨0⟩, equiv.refl _⟩ @[simp] theorem omega_succ {n} : n ∈ omega.{u} → insert n n ∈ omega.{u} := quotient.induction_on n (λx ⟨⟨n⟩, h⟩, ⟨⟨n+1⟩, have Set.insert ⟦x⟧ ⟦x⟧ = Set.insert ⟦of_nat n⟧ ⟦of_nat n⟧, by rw (@quotient.sound pSet _ _ _ h), quotient.exact this⟩) /-- `{x ∈ a | p x}` is the set of elements in `a` satisfying `p` -/ protected def sep (p : Set → Prop) : Set → Set := resp.eval 1 ⟨pSet.sep (λy, p ⟦y⟧), λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ⟨a, pa⟩, let ⟨b, hb⟩ := αβ a in ⟨⟨b, by rwa ←(@quotient.sound pSet _ _ _ hb)⟩, hb⟩, λ⟨b, pb⟩, let ⟨a, ha⟩ := βα b in ⟨⟨a, by rwa (@quotient.sound pSet _ _ _ ha)⟩, ha⟩⟩⟩ instance : has_sep Set Set := ⟨Set.sep⟩ @[simp] theorem mem_sep {p : Set.{u} → Prop} {x y : Set.{u}} : y ∈ {y ∈ x | p y} ↔ y ∈ x ∧ p y := quotient.induction_on₂ x y (λ⟨α, A⟩ y, ⟨λ⟨⟨a, pa⟩, h⟩, ⟨⟨a, h⟩, by rw (@quotient.sound pSet _ _ _ h); exact pa⟩, λ⟨⟨a, h⟩, pa⟩, ⟨⟨a, by rw ←(@quotient.sound pSet _ _ _ h); exact pa⟩, h⟩⟩) /-- The powerset operation, the collection of subsets of a set -/ def powerset : Set → Set := resp.eval 1 ⟨powerset, λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λp, ⟨{b | ∃a, p a ∧ equiv (A a) (B b)}, λ⟨a, pa⟩, let ⟨b, ab⟩ := αβ a in ⟨⟨b, a, pa, ab⟩, ab⟩, λ⟨b, a, pa, ab⟩, ⟨⟨a, pa⟩, ab⟩⟩, λq, ⟨{a | ∃b, q b ∧ equiv (A a) (B b)}, λ⟨a, b, qb, ab⟩, ⟨⟨b, qb⟩, ab⟩, λ⟨b, qb⟩, let ⟨a, ab⟩ := βα b in ⟨⟨a, b, qb, ab⟩, ab⟩⟩⟩⟩ @[simp] theorem mem_powerset {x y : Set} : y ∈ powerset x ↔ y ⊆ x := quotient.induction_on₂ x y (λ⟨α, A⟩ ⟨β, B⟩, show (⟨β, B⟩ : pSet) ∈ (pSet.powerset ⟨α, A⟩) ↔ _, by simp [mem_powerset, subset_iff]) theorem Union_lem {α β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀a, ∃b, equiv (A a) (B b)) : ∀a, ∃b, (equiv ((Union ⟨α, A⟩).func a) ((Union ⟨β, B⟩).func b)) | ⟨a, c⟩ := let ⟨b, hb⟩ := αβ a in begin induction ea : A a with γ Γ, induction eb : B b with δ Δ, rw [ea, eb] at hb, cases hb with γδ δγ, exact let c : type (A a) := c, ⟨d, hd⟩ := γδ (by rwa ea at c) in have equiv ((A a).func c) ((B b).func (eq.rec d (eq.symm eb))), from match A a, B b, ea, eb, c, d, hd with ._, ._, rfl, rfl, x, y, hd := hd end, ⟨⟨b, eq.rec d (eq.symm eb)⟩, this⟩ end /-- The union operator, the collection of elements of elements of a set -/ def Union : Set → Set := resp.eval 1 ⟨pSet.Union, λ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨Union_lem A B αβ, λa, exists.elim (Union_lem B A (λb, exists.elim (βα b) (λc hc, ⟨c, equiv.symm hc⟩)) a) (λb hb, ⟨b, equiv.symm hb⟩)⟩⟩ notation `⋃` := Union @[simp] theorem mem_Union {x y : Set.{u}} : y ∈ Union x ↔ ∃ z ∈ x, y ∈ z := quotient.induction_on₂ x y (λx y, iff.trans mem_Union ⟨λ⟨z, h⟩, ⟨⟦z⟧, h⟩, λ⟨z, h⟩, quotient.induction_on z (λz h, ⟨z, h⟩) h⟩) @[simp] theorem Union_singleton {x : Set.{u}} : Union {x} = x := ext $ λy, by simp; exact ⟨λ⟨z, zx, yz⟩, by subst z; exact yz, λyx, ⟨x, by simp, yx⟩⟩ theorem singleton_inj {x y : Set.{u}} (H : ({x} : Set) = {y}) : x = y := let this := congr_arg Union H in by rwa [Union_singleton, Union_singleton] at this /-- The binary union operation -/ protected def union (x y : Set.{u}) : Set.{u} := ⋃ {x, y} /-- The binary intersection operation -/ protected def inter (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∈ y} /-- The set difference operation -/ protected def diff (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∉ y} instance : has_union Set := ⟨Set.union⟩ instance : has_inter Set := ⟨Set.inter⟩ instance : has_sdiff Set := ⟨Set.diff⟩ @[simp] theorem mem_union {x y z : Set.{u}} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := iff.trans mem_Union ⟨λ⟨w, wxy, zw⟩, match mem_pair.1 wxy with | or.inl wx := or.inl (by rwa ←wx) | or.inr wy := or.inr (by rwa ←wy) end, λzxy, match zxy with | or.inl zx := ⟨x, mem_pair.2 (or.inl rfl), zx⟩ | or.inr zy := ⟨y, mem_pair.2 (or.inr rfl), zy⟩ end⟩ @[simp] theorem mem_inter {x y z : Set.{u}} : z ∈ x ∩ y ↔ z ∈ x ∧ z ∈ y := @@mem_sep (λz:Set.{u}, z ∈ y) @[simp] theorem mem_diff {x y z : Set.{u}} : z ∈ x \ y ↔ z ∈ x ∧ z ∉ y := @@mem_sep (λz:Set.{u}, z ∉ y) theorem induction_on {p : Set → Prop} (x) (h : ∀x, (∀y ∈ x, p y) → p x) : p x := quotient.induction_on x $ λu, pSet.rec_on u $ λα A IH, h _ $ λy, show @has_mem.mem _ _ Set.has_mem y ⟦⟨α, A⟩⟧ → p y, from quotient.induction_on y (λv ⟨a, ha⟩, by rw (@quotient.sound pSet _ _ _ ha); exact IH a) theorem regularity (x : Set.{u}) (h : x ≠ ∅) : ∃ y ∈ x, x ∩ y = ∅ := classical.by_contradiction $ λne, h $ (eq_empty x).2 $ λy, induction_on y $ λz (IH : ∀w:Set.{u}, w ∈ z → w ∉ x), show z ∉ x, from λzx, ne ⟨z, zx, (eq_empty _).2 (λw wxz, let ⟨wx, wz⟩ := mem_inter.1 wxz in IH w wz wx)⟩ /-- The image of a (definable) set function -/ def image (f : Set → Set) [H : definable 1 f] : Set → Set := let r := @definable.resp 1 f _ in resp.eval 1 ⟨image r.1, λx y e, mem.ext $ λz, iff.trans (mem_image r.2) $ iff.trans (by exact ⟨λ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).1 h1, h2⟩, λ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).2 h1, h2⟩⟩) $ iff.symm (mem_image r.2)⟩ theorem image.mk : Π (f : Set.{u} → Set.{u}) [H : definable 1 f] (x) {y} (h : y ∈ x), f y ∈ @image f H x | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ⟨α, A⟩ y ⟨a, ya⟩, ⟨a, F.2 _ _ ya⟩ @[simp] theorem mem_image : Π {f : Set.{u} → Set.{u}} [H : definable 1 f] {x y : Set.{u}}, y ∈ @image f H x ↔ ∃z ∈ x, f z = y | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ⟨α, A⟩ y, ⟨λ⟨a, ya⟩, ⟨⟦A a⟧, mem.mk A a, eq.symm $ quotient.sound ya⟩, λ⟨z, hz, e⟩, e ▸ image.mk _ _ hz⟩ /-- Kuratowski ordered pair -/ def pair (x y : Set.{u}) : Set.{u} := {{x}, {x, y}} /-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/ def pair_sep (p : Set.{u} → Set.{u} → Prop) (x y : Set.{u}) : Set.{u} := {z ∈ powerset (powerset (x ∪ y)) | ∃a ∈ x, ∃b ∈ y, z = pair a b ∧ p a b} @[simp] theorem mem_pair_sep {p} {x y z : Set.{u}} : z ∈ pair_sep p x y ↔ ∃a ∈ x, ∃b ∈ y, z = pair a b ∧ p a b := by refine iff.trans mem_sep ⟨and.right, λe, ⟨_, e⟩⟩; exact let ⟨a, ax, b, bY, ze, pab⟩ := e in by rw ze; exact mem_powerset.2 (λu uz, mem_powerset.2 $ (mem_pair.1 uz).elim (λua, by rw ua; exact λv vu, by rw mem_singleton.1 vu; exact mem_union.2 (or.inl ax)) (λuab, by rw uab; exact λv vu, (mem_pair.1 vu).elim (λva, by rw va; exact mem_union.2 (or.inl ax)) (λvb, by rw vb; exact mem_union.2 (or.inr bY)))) theorem pair_inj {x y x' y' : Set.{u}} (H : pair x y = pair x' y') : x = x' ∧ y = y' := begin have ae := ext_iff.2 H, simp [pair] at ae, have : x = x', { cases (ae {x}).1 (by simp) with h h, { exact singleton_inj h }, { have m : x' ∈ ({x} : Set), { rw h, simp }, simp at m, simp [*] } }, subst x', have he : y = x → y = y', { intro yx, subst y, cases (ae {x, y'}).2 (by simp) with xy'x xy'xx, { have y'x : y' ∈ ({x} : Set) := by rw ← xy'x; simp, simp at y'x, simp [*] }, { have yxx := (ext_iff.2 xy'xx y').1 (by simp), simp at yxx, subst y' } }, have xyxy' := (ae {x, y}).1 (by simp), cases xyxy' with xyx xyy', { have yx := (ext_iff.2 xyx y).1 (by simp), simp at yx, simp [he yx] }, { have yxy' := (ext_iff.2 xyy' y).1 (by simp), simp at yxy', cases yxy' with yx yy', { simp [he yx] }, { simp [yy'] } } end /-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/ def prod : Set.{u} → Set.{u} → Set.{u} := pair_sep (λa b, true) @[simp] theorem mem_prod {x y z : Set.{u}} : z ∈ prod x y ↔ ∃a ∈ x, ∃b ∈ y, z = pair a b := by simp [prod] @[simp] theorem pair_mem_prod {x y a b : Set.{u}} : pair a b ∈ prod x y ↔ a ∈ x ∧ b ∈ y := ⟨λh, let ⟨a', a'x, b', b'y, e⟩ := mem_prod.1 h in match a', b', pair_inj e, a'x, b'y with ._, ._, ⟨rfl, rfl⟩, ax, bY := ⟨ax, bY⟩ end, λ⟨ax, bY⟩, by simp; exact ⟨a, ax, b, bY, rfl⟩⟩ /-- `is_func x y f` is the assertion `f : x → y` where `f` is a ZFC function (a set of ordered pairs) -/ def is_func (x y f : Set.{u}) : Prop := f ⊆ prod x y ∧ ∀z:Set.{u}, z ∈ x → ∃! w, pair z w ∈ f /-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/ def funs (x y : Set.{u}) : Set.{u} := {f ∈ powerset (prod x y) | is_func x y f} @[simp] theorem mem_funs {x y f : Set.{u}} : f ∈ funs x y ↔ is_func x y f := by simp [funs]; exact and_iff_right_of_imp and.left -- TODO(Mario): Prove this computably noncomputable instance map_definable_aux (f : Set → Set) [H : definable 1 f] : definable 1 (λy, pair y (f y)) := @classical.all_definable 1 _ /-- Graph of a function: `map f x` is the ZFC function which maps `a ∈ x` to `f a` -/ noncomputable def map (f : Set → Set) [H : definable 1 f] : Set → Set := image (λy, pair y (f y)) @[simp] theorem mem_map {f : Set → Set} [H : definable 1 f] {x y : Set} : y ∈ map f x ↔ ∃z ∈ x, pair z (f z) = y := mem_image theorem map_unique {f : Set.{u} → Set.{u}} [H : definable 1 f] {x z : Set.{u}} (zx : z ∈ x) : ∃! w, pair z w ∈ map f x := ⟨f z, image.mk _ _ zx, λy yx, let ⟨w, wx, we⟩ := mem_image.1 yx, ⟨wz, fy⟩ := pair_inj we in by rw[←fy, wz]⟩ @[simp] theorem map_is_func {f : Set → Set} [H : definable 1 f] {x y : Set} : is_func x y (map f x) ↔ ∀z ∈ x, f z ∈ y := ⟨λ⟨ss, h⟩ z zx, let ⟨t, t1, t2⟩ := h z zx in by rw (t2 (f z) (image.mk _ _ zx)); exact (pair_mem_prod.1 (ss t1)).right, λh, ⟨λy yx, let ⟨z, zx, ze⟩ := mem_image.1 yx in by rw ←ze; exact pair_mem_prod.2 ⟨zx, h z zx⟩, λz, map_unique⟩⟩ end Set def Class := set Set namespace Class instance : has_subset Class := ⟨set.subset⟩ instance : has_sep Set Class := ⟨set.sep⟩ instance : has_emptyc Class := ⟨λ a, false⟩ instance : has_insert Set Class := ⟨set.insert⟩ instance : has_union Class := ⟨set.union⟩ instance : has_inter Class := ⟨set.inter⟩ instance : has_neg Class := ⟨set.compl⟩ instance : has_sdiff Class := ⟨set.diff⟩ /-- Coerce a set into a class -/ def of_Set (x : Set.{u}) : Class.{u} := {y | y ∈ x} instance : has_coe Set Class := ⟨of_Set⟩ /-- The universal class -/ def univ : Class := set.univ /-- Assert that `A` is a set satisfying `p` -/ def to_Set (p : Set.{u} → Prop) (A : Class.{u}) : Prop := ∃x, ↑x = A ∧ p x /-- `A ∈ B` if `A` is a set which is a member of `B` -/ protected def mem (A B : Class.{u}) : Prop := to_Set.{u} B A instance : has_mem Class Class := ⟨Class.mem⟩ theorem mem_univ {A : Class.{u}} : A ∈ univ.{u} ↔ ∃ x : Set.{u}, ↑x = A := exists_congr $ λx, and_true _ /-- Convert a conglomerate (a collection of classes) into a class -/ def Cong_to_Class (x : set Class.{u}) : Class.{u} := {y | ↑y ∈ x} /-- Convert a class into a conglomerate (a collection of classes) -/ def Class_to_Cong (x : Class.{u}) : set Class.{u} := {y | y ∈ x} /-- The power class of a class is the class of all subclasses that are sets -/ def powerset (x : Class) : Class := Cong_to_Class (set.powerset x) /-- The union of a class is the class of all members of sets in the class -/ def Union (x : Class) : Class := set.sUnion (Class_to_Cong x) notation `⋃` := Union theorem of_Set.inj {x y : Set.{u}} (h : (x : Class.{u}) = y) : x = y := Set.ext $ λz, by change (x : Class.{u}) z ↔ (y : Class.{u}) z; simp [*] @[simp] theorem to_Set_of_Set (p : Set.{u} → Prop) (x : Set.{u}) : to_Set p x ↔ p x := ⟨λ⟨y, yx, py⟩, by rwa of_Set.inj yx at py, λpx, ⟨x, rfl, px⟩⟩ @[simp] theorem mem_hom_left (x : Set.{u}) (A : Class.{u}) : (x : Class.{u}) ∈ A ↔ A x := to_Set_of_Set _ _ @[simp] theorem mem_hom_right (x y : Set.{u}) : (y : Class.{u}) x ↔ x ∈ y := iff.refl _ @[simp] theorem subset_hom (x y : Set.{u}) : (x : Class.{u}) ⊆ y ↔ x ⊆ y := iff.refl _ @[simp] theorem sep_hom (p : Set.{u} → Prop) (x : Set.{u}) : (↑{y ∈ x | p y} : Class.{u}) = {y ∈ x | p y} := set.ext $ λy, Set.mem_sep @[simp] theorem empty_hom : ↑(∅ : Set.{u}) = (∅ : Class.{u}) := set.ext $ λy, show _ ↔ false, by simp; exact Set.mem_empty y @[simp] theorem insert_hom (x y : Set.{u}) : (@insert Set.{u} Class.{u} _ x y) = ↑(insert x y) := set.ext $ λz, iff.symm Set.mem_insert @[simp] theorem union_hom (x y : Set.{u}) : (x : Class.{u}) ∪ y = (x ∪ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_union @[simp] theorem inter_hom (x y : Set.{u}) : (x : Class.{u}) ∩ y = (x ∩ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_inter @[simp] theorem diff_hom (x y : Set.{u}) : (x : Class.{u}) \ y = (x \ y : Set.{u}) := set.ext $ λz, iff.symm Set.mem_diff @[simp] theorem powerset_hom (x : Set.{u}) : powerset.{u} x = Set.powerset x := set.ext $ λz, iff.symm Set.mem_powerset @[simp] theorem Union_hom (x : Set.{u}) : Union.{u} x = Set.Union x := set.ext $ λz, by refine iff.trans _ (iff.symm Set.mem_Union); exact ⟨λ⟨._, ⟨a, rfl, ax⟩, za⟩, ⟨a, ax, za⟩, λ⟨a, ax, za⟩, ⟨_, ⟨a, rfl, ax⟩, za⟩⟩ /-- The definite description operator, which is {x} if `{a | p a} = {x}` and ∅ otherwise -/ def iota (p : Set → Prop) : Class := Union {x | ∀y, p y ↔ y = x} theorem iota_val (p : Set → Prop) (x : Set) (H : ∀y, p y ↔ y = x) : iota p = ↑x := set.ext $ λy, ⟨λ⟨._, ⟨x', rfl, h⟩, yx'⟩, by rwa ←((H x').1 $ (h x').2 rfl), λyx, ⟨_, ⟨x, rfl, H⟩, yx⟩⟩ /-- Unlike the other set constructors, the `iota` definite descriptor is a set for any set input, but not constructively so, so there is no associated `(Set → Prop) → Set` function. -/ theorem iota_ex (p) : iota.{u} p ∈ univ.{u} := mem_univ.2 $ or.elim (classical.em $ ∃x, ∀y, p y ↔ y = x) (λ⟨x, h⟩, ⟨x, eq.symm $ iota_val p x h⟩) (λhn, ⟨∅, by simp; exact set.ext (λz, ⟨false.rec _, λ⟨._, ⟨x, rfl, H⟩, zA⟩, hn ⟨x, H⟩⟩)⟩) /-- Function value -/ def fval (F A : Class.{u}) : Class.{u} := iota (λy, to_Set (λx, F (Set.pair x y)) A) infixl `′`:100 := fval theorem fval_ex (F A : Class.{u}) : F ′ A ∈ univ.{u} := iota_ex _ end Class namespace Set @[simp] theorem map_fval {f : Set.{u} → Set.{u}} [H : pSet.definable 1 f] {x y : Set.{u}} (h : y ∈ x) : (Set.map f x ′ y : Class.{u}) = f y := Class.iota_val _ _ (λz, by simp; exact ⟨λ⟨w, wz, pr⟩, let ⟨wy, fw⟩ := Set.pair_inj pr in by rw[←fw, wy], λe, by cases e; exact ⟨_, h, rfl⟩⟩) variables (x : Set.{u}) (h : ∅ ∉ x) /-- A choice function on the set of nonempty sets `x` -/ noncomputable def choice : Set := @map (λy, classical.epsilon (λz, z ∈ y)) (classical.all_definable _) x include h theorem choice_mem_aux (y : Set.{u}) (yx : y ∈ x) : classical.epsilon (λz:Set.{u}, z ∈ y) ∈ y := @classical.epsilon_spec _ (λz:Set.{u}, z ∈ y) $ classical.by_contradiction $ λn, h $ by rwa ←((eq_empty y).2 $ λz zx, n ⟨z, zx⟩) theorem choice_is_func : is_func x (Union x) (choice x) := (@map_is_func _ (classical.all_definable _) _ _).2 $ λy yx, by simp; exact ⟨y, yx, choice_mem_aux x h y yx⟩ theorem choice_mem (y : Set.{u}) (yx : y ∈ x) : (choice x ′ y : Class.{u}) ∈ (y : Class.{u}) := by delta choice; rw map_fval yx; simp [choice_mem_aux x h y yx] end Set
48536311775c1d6541088215df5070f1229bb8a1
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/LCNF/CompilerM.lean
534f65111b209a57c680361273502dfaeb03223f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
14,664
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.CoreM import Lean.Compiler.LCNF.Basic import Lean.Compiler.LCNF.LCtx import Lean.Compiler.LCNF.ConfigOptions namespace Lean.Compiler.LCNF /-- The pipeline phase a certain `Pass` is supposed to happen in. -/ inductive Phase where /-- Here we still carry most of the original type information, most of the dependent portion is already (partially) erased though. -/ | base /-- In this phase polymorphism has been eliminated. -/ | mono /-- In this phase impure stuff such as RC or efficient BaseIO transformations happen. -/ | impure deriving Inhabited /-- The state managed by the `CompilerM` `Monad`. -/ structure CompilerM.State where /-- A `LocalContext` to store local declarations from let binders and other constructs in as we move through `Expr`s. -/ lctx : LCtx := {} /-- Next auxiliary variable suffix -/ nextIdx : Nat := 1 deriving Inhabited structure CompilerM.Context where phase : Phase config : ConfigOptions deriving Inhabited abbrev CompilerM := ReaderT CompilerM.Context $ StateRefT CompilerM.State CoreM @[inline] def withPhase (phase : Phase) (x : CompilerM α) : CompilerM α := withReader (fun ctx => { ctx with phase }) x def getPhase : CompilerM Phase := return (← read).phase instance : AddMessageContext CompilerM where addMessageContext msgData := do let env ← getEnv let lctx := (← get).lctx.toLocalContext let opts ← getOptions return MessageData.withContext { env, lctx, opts, mctx := {} } msgData def getType (fvarId : FVarId) : CompilerM Expr := do let lctx := (← get).lctx if let some decl := lctx.letDecls.find? fvarId then return decl.type else if let some decl := lctx.params.find? fvarId then return decl.type else if let some decl := lctx.funDecls.find? fvarId then return decl.type else throwError "unknown free variable {fvarId.name}" def getBinderName (fvarId : FVarId) : CompilerM Name := do let lctx := (← get).lctx if let some decl := lctx.letDecls.find? fvarId then return decl.binderName else if let some decl := lctx.params.find? fvarId then return decl.binderName else if let some decl := lctx.funDecls.find? fvarId then return decl.binderName else throwError "unknown free variable {fvarId.name}" def findParam? (fvarId : FVarId) : CompilerM (Option Param) := return (← get).lctx.params.find? fvarId def findLetDecl? (fvarId : FVarId) : CompilerM (Option LetDecl) := return (← get).lctx.letDecls.find? fvarId def findFunDecl? (fvarId : FVarId) : CompilerM (Option FunDecl) := return (← get).lctx.funDecls.find? fvarId def getParam (fvarId : FVarId) : CompilerM Param := do let some param ← findParam? fvarId | throwError "unknown parameter {fvarId.name}" return param def getLetDecl (fvarId : FVarId) : CompilerM LetDecl := do let some decl ← findLetDecl? fvarId | throwError "unknown let-declaration {fvarId.name}" return decl def getFunDecl (fvarId : FVarId) : CompilerM FunDecl := do let some decl ← findFunDecl? fvarId | throwError "unknown local function {fvarId.name}" return decl @[inline] def modifyLCtx (f : LCtx → LCtx) : CompilerM Unit := do modify fun s => { s with lctx := f s.lctx } def eraseLetDecl (decl : LetDecl) : CompilerM Unit := do modifyLCtx fun lctx => lctx.eraseLetDecl decl def eraseFunDecl (decl : FunDecl) (recursive := true) : CompilerM Unit := do modifyLCtx fun lctx => lctx.eraseFunDecl decl recursive def eraseCode (code : Code) : CompilerM Unit := do modifyLCtx fun lctx => lctx.eraseCode code def eraseParam (param : Param) : CompilerM Unit := modifyLCtx fun lctx => lctx.eraseParam param def eraseParams (params : Array Param) : CompilerM Unit := modifyLCtx fun lctx => lctx.eraseParams params def eraseCodeDecl (decl : CodeDecl) : CompilerM Unit := do match decl with | .let decl => eraseLetDecl decl | .jp decl | .fun decl => eraseFunDecl decl /-- Erase all free variables occurring in `decls` from the local context. -/ def eraseCodeDecls (decls : Array CodeDecl) : CompilerM Unit := do decls.forM fun decl => eraseCodeDecl decl def eraseDecl (decl : Decl) : CompilerM Unit := do eraseParams decl.params eraseCode decl.value /-- A free variable substitution. We use these substitutions when inlining definitions and "internalizing" LCNF code into `CompilerM`. During the internalization process, we ensure all free variables in the LCNF code do not collide with existing ones at the `CompilerM` local context. Remark: in LCNF, (computationally relevant) data is in A-normal form, but this is not the case for types and type formers. So, when inlining we often want to replace a free variable with a type or type former. The substitution contains entries `fvarId ↦ e` s.t., `e` is a valid LCNF argument. That is, it is a free variable, a type (or type former), or `lcErased`. `Check.lean` contains a substitution validator. -/ abbrev FVarSubst := HashMap FVarId Expr /-- Replace the free variables in `e` using the given substitution. If `translator = true`, then we assume the free variables occurring in the range of the substitution are in another local context. For example, `translator = true` during internalization where we are making sure all free variables in a given expression are replaced with new ones that do not collide with the ones in the current local context. If `translator = false`, we assume the substitution contains free variable replacements in the same local context, and given entries such as `x₁ ↦ x₂`, `x₂ ↦ x₃`, ..., `xₙ₋₁ ↦ xₙ`, and the expression `f x₁ x₂`, we want the resulting expression to be `f xₙ xₙ`. We use this setting, for example, in the simplifier. -/ private partial def normExprImp (s : FVarSubst) (e : Expr) (translator : Bool) : Expr := go e where goApp (e : Expr) : Expr := match e with | .app f a => e.updateApp! (goApp f) (go a) | _ => go e go (e : Expr) : Expr := if e.hasFVar then match e with | .fvar fvarId => match s.find? fvarId with | some e => if translator then e else go e | none => e | .lit .. | .const .. | .sort .. | .mvar .. | .bvar .. => e | .app f a => e.updateApp! (goApp f) (go a) |>.headBeta | .mdata _ b => e.updateMData! (go b) | .proj _ _ b => e.updateProj! (go b) | .forallE _ d b _ => e.updateForallE! (go d) (go b) | .lam _ d b _ => e.updateLambdaE! (go d) (go b) | .letE .. => unreachable! -- Valid LCNF does not contain `let`-declarations else e /-- Normalize the given free variable. See `normExprImp` for documentation on the `translator` parameter. This function is meant to be used in contexts where the input free-variable is computationally relevant. This function panics if the substitution is mapping `fvarId` to an expression that is not another free variable. That is, it is not a type (or type former), nor `lcErased`. Recall that a valid `FVarSubst` contains only expressions that are free variables, `lcErased`, or type formers. -/ private partial def normFVarImp (s : FVarSubst) (fvarId : FVarId) (translator : Bool) : FVarId := match s.find? fvarId with | some (.fvar fvarId') => if translator then fvarId' else normFVarImp s fvarId' translator | some e => panic! s!"invalid LCNF substitution of free variable with expression {e}" | none => fvarId /-- Interface for monads that have a free substitutions. -/ class MonadFVarSubst (m : Type → Type) (translator : outParam Bool) where getSubst : m FVarSubst export MonadFVarSubst (getSubst) instance (m n) [MonadLift m n] [MonadFVarSubst m t] : MonadFVarSubst n t where getSubst := liftM (getSubst : m _) class MonadFVarSubstState (m : Type → Type) where modifySubst : (FVarSubst → FVarSubst) → m Unit export MonadFVarSubstState (modifySubst) instance (m n) [MonadLift m n] [MonadFVarSubstState m] : MonadFVarSubstState n where modifySubst f := liftM (modifySubst f : m _) /-- Add the entry `fvarId ↦ fvarId'` to the free variable substitution. -/ @[inline] def addFVarSubst [MonadFVarSubstState m] (fvarId : FVarId) (fvarId' : FVarId) : m Unit := modifySubst fun s => s.insert fvarId (.fvar fvarId') /-- Add the substitution `fvarId ↦ e`, `e` must be a valid LCNF argument. That is, it must be a free variable, type (or type former), or `lcErased`. See `Check.lean` for the free variable substitution checker. -/ @[inline] def addSubst [MonadFVarSubstState m] (fvarId : FVarId) (e : Expr) : m Unit := modifySubst fun s => s.insert fvarId e @[inline, inheritDoc normFVarImp] def normFVar [MonadFVarSubst m t] [Monad m] (fvarId : FVarId) : m FVarId := return normFVarImp (← getSubst) fvarId t @[inline, inheritDoc normExprImp] def normExpr [MonadFVarSubst m t] [Monad m] (e : Expr) : m Expr := return normExprImp (← getSubst) e t /-- Normalize the given expressions using the current substitution. -/ def normExprs [MonadFVarSubst m t] [Monad m] (es : Array Expr) : m (Array Expr) := es.mapMonoM normExpr def mkFreshBinderName (binderName := `_x): CompilerM Name := do let declName := .num binderName (← get).nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1 } return declName /-! Helper functions for creating LCNF local declarations. -/ def mkParam (binderName : Name) (type : Expr) (borrow : Bool) : CompilerM Param := do let fvarId ← mkFreshFVarId let param := { fvarId, binderName, type, borrow } modifyLCtx fun lctx => lctx.addParam param return param def mkLetDecl (binderName : Name) (type : Expr) (value : Expr) : CompilerM LetDecl := do let fvarId ← mkFreshFVarId let decl := { fvarId, binderName, type, value } modifyLCtx fun lctx => lctx.addLetDecl decl return decl def mkFunDecl (binderName : Name) (type : Expr) (params : Array Param) (value : Code) : CompilerM FunDecl := do let fvarId ← mkFreshFVarId let funDecl := { fvarId, binderName, type, params, value } modifyLCtx fun lctx => lctx.addFunDecl funDecl return funDecl private unsafe def updateParamImp (p : Param) (type : Expr) : CompilerM Param := do if ptrEq type p.type then return p else let p := { p with type } modifyLCtx fun lctx => lctx.addParam p return p @[implementedBy updateParamImp] opaque Param.update (p : Param) (type : Expr) : CompilerM Param private unsafe def updateLetDeclImp (decl : LetDecl) (type : Expr) (value : Expr) : CompilerM LetDecl := do if ptrEq type decl.type && ptrEq value decl.value then return decl else let decl := { decl with type, value } modifyLCtx fun lctx => lctx.addLetDecl decl return decl @[implementedBy updateLetDeclImp] opaque LetDecl.update (decl : LetDecl) (type : Expr) (value : Expr) : CompilerM LetDecl def LetDecl.updateValue (decl : LetDecl) (value : Expr) : CompilerM LetDecl := decl.update decl.type value private unsafe def updateFunDeclImp (decl: FunDecl) (type : Expr) (params : Array Param) (value : Code) : CompilerM FunDecl := do if ptrEq type decl.type && ptrEq params decl.params && ptrEq value decl.value then return decl else let decl := { decl with type, params, value } modifyLCtx fun lctx => lctx.addFunDecl decl return decl @[implementedBy updateFunDeclImp] opaque FunDeclCore.update (decl: FunDecl) (type : Expr) (params : Array Param) (value : Code) : CompilerM FunDecl abbrev FunDeclCore.update' (decl : FunDecl) (type : Expr) (value : Code) : CompilerM FunDecl := decl.update type decl.params value abbrev FunDeclCore.updateValue (decl : FunDecl) (value : Code) : CompilerM FunDecl := decl.update decl.type decl.params value @[inline] def normParam [MonadLiftT CompilerM m] [Monad m] [MonadFVarSubst m t] (p : Param) : m Param := do p.update (← normExpr p.type) def normParams [MonadLiftT CompilerM m] [Monad m] [MonadFVarSubst m t] (ps : Array Param) : m (Array Param) := ps.mapMonoM normParam def normLetDecl [MonadLiftT CompilerM m] [Monad m] [MonadFVarSubst m t] (decl : LetDecl) : m LetDecl := do decl.update (← normExpr decl.type) (← normExpr decl.value) abbrev NormalizerM (_translator : Bool) := ReaderT FVarSubst CompilerM instance : MonadFVarSubst (NormalizerM t) t where getSubst := read mutual partial def normFunDeclImp (decl : FunDecl) : NormalizerM t FunDecl := do let type ← normExpr decl.type let params ← normParams decl.params let value ← normCodeImp decl.value decl.update type params value partial def normCodeImp (code : Code) : NormalizerM t Code := do match code with | .let decl k => return code.updateLet! (← normLetDecl decl) (← normCodeImp k) | .fun decl k | .jp decl k => return code.updateFun! (← normFunDeclImp decl) (← normCodeImp k) | .return fvarId => return code.updateReturn! (← normFVar fvarId) | .jmp fvarId args => return code.updateJmp! (← normFVar fvarId) (← normExprs args) | .unreach type => return code.updateUnreach! (← normExpr type) | .cases c => let resultType ← normExpr c.resultType let discr ← normFVar c.discr let alts ← c.alts.mapMonoM fun alt => match alt with | .alt _ params k => return alt.updateAlt! (← normParams params) (← normCodeImp k) | .default k => return alt.updateCode (← normCodeImp k) return code.updateCases! resultType discr alts end @[inline] def normFunDecl [MonadLiftT CompilerM m] [Monad m] [MonadFVarSubst m t] (decl : FunDecl) : m FunDecl := do normFunDeclImp (t := t) decl (← getSubst) /-- Similar to `internalize`, but does not refresh `FVarId`s. -/ @[inline] def normCode [MonadLiftT CompilerM m] [Monad m] [MonadFVarSubst m t] (code : Code) : m Code := do normCodeImp (t := t) code (← getSubst) def replaceExprFVars (e : Expr) (s : FVarSubst) (translator : Bool) : CompilerM Expr := (normExpr e : NormalizerM translator Expr).run s def replaceFVars (code : Code) (s : FVarSubst) (translator : Bool) : CompilerM Code := (normCode code : NormalizerM translator Code).run s def mkFreshJpName : CompilerM Name := do mkFreshBinderName `_jp def mkAuxParam (type : Expr) (borrow := false) : CompilerM Param := do mkParam (← mkFreshBinderName `_y) type borrow def getConfig : CompilerM ConfigOptions := return (← read).config def CompilerM.run (x : CompilerM α) (s : State := {}) (phase : Phase := .base) : CoreM α := do x { phase, config := toConfigOptions (← getOptions) } |>.run' s end Lean.Compiler.LCNF
151d1c6a233d2f1ac040294c43a17dec68f60d3b
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/MultPointedSemigroup.lean
85c3b771846264ecce48766abe4f0ee1a8858c96
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
7,629
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section MultPointedSemigroup structure MultPointedSemigroup (A : Type) : Type := (one : A) (times : (A → (A → A))) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) open MultPointedSemigroup structure Sig (AS : Type) : Type := (oneS : AS) (timesS : (AS → (AS → AS))) structure Product (A : Type) : Type := (oneP : (Prod A A)) (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) structure Hom {A1 : Type} {A2 : Type} (Mu1 : (MultPointedSemigroup A1)) (Mu2 : (MultPointedSemigroup A2)) : Type := (hom : (A1 → A2)) (pres_one : (hom (one Mu1)) = (one Mu2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Mu1) x1 x2)) = ((times Mu2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Mu1 : (MultPointedSemigroup A1)) (Mu2 : (MultPointedSemigroup A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_one : (interp (one Mu1) (one Mu2))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Mu1) x1 x2) ((times Mu2) y1 y2)))))) inductive MultPointedSemigroupTerm : Type | oneL : MultPointedSemigroupTerm | timesL : (MultPointedSemigroupTerm → (MultPointedSemigroupTerm → MultPointedSemigroupTerm)) open MultPointedSemigroupTerm inductive ClMultPointedSemigroupTerm (A : Type) : Type | sing : (A → ClMultPointedSemigroupTerm) | oneCl : ClMultPointedSemigroupTerm | timesCl : (ClMultPointedSemigroupTerm → (ClMultPointedSemigroupTerm → ClMultPointedSemigroupTerm)) open ClMultPointedSemigroupTerm inductive OpMultPointedSemigroupTerm (n : ℕ) : Type | v : ((fin n) → OpMultPointedSemigroupTerm) | oneOL : OpMultPointedSemigroupTerm | timesOL : (OpMultPointedSemigroupTerm → (OpMultPointedSemigroupTerm → OpMultPointedSemigroupTerm)) open OpMultPointedSemigroupTerm inductive OpMultPointedSemigroupTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpMultPointedSemigroupTerm2) | sing2 : (A → OpMultPointedSemigroupTerm2) | oneOL2 : OpMultPointedSemigroupTerm2 | timesOL2 : (OpMultPointedSemigroupTerm2 → (OpMultPointedSemigroupTerm2 → OpMultPointedSemigroupTerm2)) open OpMultPointedSemigroupTerm2 def simplifyCl {A : Type} : ((ClMultPointedSemigroupTerm A) → (ClMultPointedSemigroupTerm A)) | oneCl := oneCl | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpMultPointedSemigroupTerm n) → (OpMultPointedSemigroupTerm n)) | oneOL := oneOL | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpMultPointedSemigroupTerm2 n A) → (OpMultPointedSemigroupTerm2 n A)) | oneOL2 := oneOL2 | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((MultPointedSemigroup A) → (MultPointedSemigroupTerm → A)) | Mu oneL := (one Mu) | Mu (timesL x1 x2) := ((times Mu) (evalB Mu x1) (evalB Mu x2)) def evalCl {A : Type} : ((MultPointedSemigroup A) → ((ClMultPointedSemigroupTerm A) → A)) | Mu (sing x1) := x1 | Mu oneCl := (one Mu) | Mu (timesCl x1 x2) := ((times Mu) (evalCl Mu x1) (evalCl Mu x2)) def evalOpB {A : Type} {n : ℕ} : ((MultPointedSemigroup A) → ((vector A n) → ((OpMultPointedSemigroupTerm n) → A))) | Mu vars (v x1) := (nth vars x1) | Mu vars oneOL := (one Mu) | Mu vars (timesOL x1 x2) := ((times Mu) (evalOpB Mu vars x1) (evalOpB Mu vars x2)) def evalOp {A : Type} {n : ℕ} : ((MultPointedSemigroup A) → ((vector A n) → ((OpMultPointedSemigroupTerm2 n A) → A))) | Mu vars (v2 x1) := (nth vars x1) | Mu vars (sing2 x1) := x1 | Mu vars oneOL2 := (one Mu) | Mu vars (timesOL2 x1 x2) := ((times Mu) (evalOp Mu vars x1) (evalOp Mu vars x2)) def inductionB {P : (MultPointedSemigroupTerm → Type)} : ((P oneL) → ((∀ (x1 x2 : MultPointedSemigroupTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → (∀ (x : MultPointedSemigroupTerm) , (P x)))) | p1l ptimesl oneL := p1l | p1l ptimesl (timesL x1 x2) := (ptimesl _ _ (inductionB p1l ptimesl x1) (inductionB p1l ptimesl x2)) def inductionCl {A : Type} {P : ((ClMultPointedSemigroupTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P oneCl) → ((∀ (x1 x2 : (ClMultPointedSemigroupTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → (∀ (x : (ClMultPointedSemigroupTerm A)) , (P x))))) | psing p1cl ptimescl (sing x1) := (psing x1) | psing p1cl ptimescl oneCl := p1cl | psing p1cl ptimescl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing p1cl ptimescl x1) (inductionCl psing p1cl ptimescl x2)) def inductionOpB {n : ℕ} {P : ((OpMultPointedSemigroupTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P oneOL) → ((∀ (x1 x2 : (OpMultPointedSemigroupTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → (∀ (x : (OpMultPointedSemigroupTerm n)) , (P x))))) | pv p1ol ptimesol (v x1) := (pv x1) | pv p1ol ptimesol oneOL := p1ol | pv p1ol ptimesol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv p1ol ptimesol x1) (inductionOpB pv p1ol ptimesol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpMultPointedSemigroupTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P oneOL2) → ((∀ (x1 x2 : (OpMultPointedSemigroupTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → (∀ (x : (OpMultPointedSemigroupTerm2 n A)) , (P x)))))) | pv2 psing2 p1ol2 ptimesol2 (v2 x1) := (pv2 x1) | pv2 psing2 p1ol2 ptimesol2 (sing2 x1) := (psing2 x1) | pv2 psing2 p1ol2 ptimesol2 oneOL2 := p1ol2 | pv2 psing2 p1ol2 ptimesol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 p1ol2 ptimesol2 x1) (inductionOp pv2 psing2 p1ol2 ptimesol2 x2)) def stageB : (MultPointedSemigroupTerm → (Staged MultPointedSemigroupTerm)) | oneL := (Now oneL) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClMultPointedSemigroupTerm A) → (Staged (ClMultPointedSemigroupTerm A))) | (sing x1) := (Now (sing x1)) | oneCl := (Now oneCl) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpMultPointedSemigroupTerm n) → (Staged (OpMultPointedSemigroupTerm n))) | (v x1) := (const (code (v x1))) | oneOL := (Now oneOL) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpMultPointedSemigroupTerm2 n A) → (Staged (OpMultPointedSemigroupTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | oneOL2 := (Now oneOL2) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (oneT : (Repr A)) (timesT : ((Repr A) → ((Repr A) → (Repr A)))) end MultPointedSemigroup
27e0dae10eecdcf76a7ec430a8b9063f51a4d366
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/eq_to_hom.lean
c3c30dea4260aceeb88d799d0fec5989bcabb3b1
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
8,523
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison -/ import category_theory.opposites /-! # Morphisms from equations between objects. When working categorically, sometimes one encounters an equation `h : X = Y` between objects. Your initial aversion to this is natural and appropriate: you're in for some trouble, and if there is another way to approach the problem that won't rely on this equality, it may be worth pursuing. You have two options: 1. Use the equality `h` as one normally would in Lean (e.g. using `rw` and `subst`). This may immediately cause difficulties, because in category theory everything is dependently typed, and equations between objects quickly lead to nasty goals with `eq.rec`. 2. Promote `h` to a morphism using `eq_to_hom h : X ⟶ Y`, or `eq_to_iso h : X ≅ Y`. This file introduces various `simp` lemmas which in favourable circumstances result in the various `eq_to_hom` morphisms to drop out at the appropriate moment! -/ universes v₁ v₂ v₃ u₁ u₂ u₃ -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory open opposite variables {C : Type u₁} [category.{v₁} C] /-- An equality `X = Y` gives us a morphism `X ⟶ Y`. It is typically better to use this, rather than rewriting by the equality then using `𝟙 _` which usually leads to dependent type theory hell. -/ def eq_to_hom {X Y : C} (p : X = Y) : X ⟶ Y := by rw p; exact 𝟙 _ @[simp] lemma eq_to_hom_refl (X : C) (p : X = X) : eq_to_hom p = 𝟙 X := rfl @[simp, reassoc] lemma eq_to_hom_trans {X Y Z : C} (p : X = Y) (q : Y = Z) : eq_to_hom p ≫ eq_to_hom q = eq_to_hom (p.trans q) := by { cases p, cases q, simp, } /-- If we (perhaps unintentionally) perform equational rewriting on the source object of a morphism, we can replace the resulting `_.mpr f` term by a composition with an `eq_to_hom`. It may be advisable to introduce any necessary `eq_to_hom` morphisms manually, rather than relying on this lemma firing. -/ @[simp] lemma congr_arg_mpr_hom_left {X Y Z : C} (p : X = Y) (q : Y ⟶ Z) : (congr_arg (λ W : C, W ⟶ Z) p).mpr q = eq_to_hom p ≫ q := by { cases p, simp, } /-- If we (perhaps unintentionally) perform equational rewriting on the target object of a morphism, we can replace the resulting `_.mpr f` term by a composition with an `eq_to_hom`. It may be advisable to introduce any necessary `eq_to_hom` morphisms manually, rather than relying on this lemma firing. -/ @[simp] lemma congr_arg_mpr_hom_right {X Y Z : C} (p : X ⟶ Y) (q : Z = Y) : (congr_arg (λ W : C, X ⟶ W) q).mpr p = p ≫ eq_to_hom q.symm := by { cases q, simp, } /-- An equality `X = Y` gives us an isomorphism `X ≅ Y`. It is typically better to use this, rather than rewriting by the equality then using `iso.refl _` which usually leads to dependent type theory hell. -/ def eq_to_iso {X Y : C} (p : X = Y) : X ≅ Y := ⟨eq_to_hom p, eq_to_hom p.symm, by simp, by simp⟩ @[simp] lemma eq_to_iso.hom {X Y : C} (p : X = Y) : (eq_to_iso p).hom = eq_to_hom p := rfl @[simp] lemma eq_to_iso.inv {X Y : C} (p : X = Y) : (eq_to_iso p).inv = eq_to_hom p.symm := rfl @[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) := by ext; simp @[simp] lemma eq_to_hom_op {X Y : C} (h : X = Y) : (eq_to_hom h).op = eq_to_hom (congr_arg op h.symm) := by { cases h, refl, } @[simp] lemma eq_to_hom_unop {X Y : Cᵒᵖ} (h : X = Y) : (eq_to_hom h).unop = eq_to_hom (congr_arg unop h.symm) := by { cases h, refl, } instance {X Y : C} (h : X = Y) : is_iso (eq_to_hom h) := is_iso.of_iso (eq_to_iso h) @[simp] lemma inv_eq_to_hom {X Y : C} (h : X = Y) : inv (eq_to_hom h) = eq_to_hom h.symm := by { ext, simp, } variables {D : Type u₂} [category.{v₂} D] namespace functor /-- Proving equality between functors. This isn't an extensionality lemma, because usually you don't really want to do this. -/ lemma ext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ X Y f, F.map f = eq_to_hom (h_obj X) ≫ G.map f ≫ eq_to_hom (h_obj Y).symm) : F = G := begin cases F with F_obj _ _ _, cases G with G_obj _ _ _, obtain rfl : F_obj = G_obj, by { ext X, apply h_obj }, congr, funext X Y f, simpa using h_map X Y f end /-- Two morphisms are conjugate via eq_to_hom if and only if they are heterogeneously equal. --/ lemma conj_eq_to_hom_iff_heq {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) (h : W = Y) (h' : X = Z) : f = eq_to_hom h ≫ g ≫ eq_to_hom h'.symm ↔ f == g := by { cases h, cases h', simp } /-- Proving equality between functors using heterogeneous equality. -/ lemma hext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ X Y (f : X ⟶ Y), F.map f == G.map f) : F = G := functor.ext h_obj (λ _ _ f, (conj_eq_to_hom_iff_heq _ _ (h_obj _) (h_obj _)).2 $ h_map _ _ f) -- Using equalities between functors. lemma congr_obj {F G : C ⥤ D} (h : F = G) (X) : F.obj X = G.obj X := by subst h lemma congr_hom {F G : C ⥤ D} (h : F = G) {X Y} (f : X ⟶ Y) : F.map f = eq_to_hom (congr_obj h X) ≫ G.map f ≫ eq_to_hom (congr_obj h Y).symm := by subst h; simp lemma congr_inv_of_congr_hom (F G : C ⥤ D) {X Y : C} (e : X ≅ Y) (hX : F.obj X = G.obj X) (hY : F.obj Y = G.obj Y) (h₂ : F.map e.hom = eq_to_hom (by rw hX) ≫ G.map e.hom ≫ eq_to_hom (by rw hY)) : F.map e.inv = eq_to_hom (by rw hY) ≫ G.map e.inv ≫ eq_to_hom (by rw hX) := by simp only [← is_iso.iso.inv_hom e, functor.map_inv, h₂, is_iso.inv_comp, inv_eq_to_hom, category.assoc] lemma congr_map (F : C ⥤ D) {X Y : C} {f g : X ⟶ Y} (h : f = g) : F.map f = F.map g := by rw h section heq /- Composition of functors and maps w.r.t. heq -/ variables {E : Type u₃} [category.{v₃} E] {F G : C ⥤ D} {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} lemma map_comp_heq (hx : F.obj X = G.obj X) (hy : F.obj Y = G.obj Y) (hz : F.obj Z = G.obj Z) (hf : F.map f == G.map f) (hg : F.map g == G.map g) : F.map (f ≫ g) == G.map (f ≫ g) := by { rw [F.map_comp, G.map_comp], congr' } lemma map_comp_heq' (hobj : ∀ X : C, F.obj X = G.obj X) (hmap : ∀ {X Y} (f : X ⟶ Y), F.map f == G.map f) : F.map (f ≫ g) == G.map (f ≫ g) := by rw functor.hext hobj (λ _ _, hmap) lemma precomp_map_heq (H : E ⥤ C) (hmap : ∀ {X Y} (f : X ⟶ Y), F.map f == G.map f) {X Y : E} (f : X ⟶ Y) : (H ⋙ F).map f == (H ⋙ G).map f := hmap _ lemma postcomp_map_heq (H : D ⥤ E) (hx : F.obj X = G.obj X) (hy : F.obj Y = G.obj Y) (hmap : F.map f == G.map f) : (F ⋙ H).map f == (G ⋙ H).map f := by { dsimp, congr' } lemma postcomp_map_heq' (H : D ⥤ E) (hobj : ∀ X : C, F.obj X = G.obj X) (hmap : ∀ {X Y} (f : X ⟶ Y), F.map f == G.map f) : (F ⋙ H).map f == (G ⋙ H).map f := by rw functor.hext hobj (λ _ _, hmap) lemma hcongr_hom {F G : C ⥤ D} (h : F = G) {X Y} (f : X ⟶ Y) : F.map f == G.map f := by subst h end heq end functor /-- This is not always a good idea as a `@[simp]` lemma, as we lose the ability to use results that interact with `F`, e.g. the naturality of a natural transformation. In some files it may be appropriate to use `local attribute [simp] eq_to_hom_map`, however. -/ lemma eq_to_hom_map (F : C ⥤ D) {X Y : C} (p : X = Y) : F.map (eq_to_hom p) = eq_to_hom (congr_arg F.obj p) := by cases p; simp /-- See the note on `eq_to_hom_map` regarding using this as a `simp` lemma. -/ lemma eq_to_iso_map (F : C ⥤ D) {X Y : C} (p : X = Y) : F.map_iso (eq_to_iso p) = eq_to_iso (congr_arg F.obj p) := by ext; cases p; simp @[simp] lemma eq_to_hom_app {F G : C ⥤ D} (h : F = G) (X : C) : (eq_to_hom h : F ⟶ G).app X = eq_to_hom (functor.congr_obj h X) := by subst h; refl lemma nat_trans.congr {F G : C ⥤ D} (α : F ⟶ G) {X Y : C} (h : X = Y) : α.app X = F.map (eq_to_hom h) ≫ α.app Y ≫ G.map (eq_to_hom h.symm) := by { rw [α.naturality_assoc], simp [eq_to_hom_map], } lemma eq_conj_eq_to_hom {X Y : C} (f : X ⟶ Y) : f = eq_to_hom rfl ≫ f ≫ eq_to_hom rfl := by simp only [category.id_comp, eq_to_hom_refl, category.comp_id] lemma dcongr_arg {ι : Type*} {F G : ι → C} (α : ∀ i, F i ⟶ G i) {i j : ι} (h : i = j) : α i = eq_to_hom (congr_arg F h) ≫ α j ≫ eq_to_hom (congr_arg G h.symm) := by { subst h, simp } end category_theory
8b15c9d13ba9e5041059db7fbcb079743d987ee0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/G_delta_auto.lean
dab75efd029c57c8a3d414e64cc2b699dea332e5
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,631
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.metric_space.emetric_space import Mathlib.PostPort universes u_1 u_4 u_2 namespace Mathlib /-! # `Gδ` sets In this file we define `Gδ` sets and prove their basic properties. ## Main definitions * `is_Gδ`: a set `s` is a `Gδ` set if it can be represented as an intersection of countably many open sets; * `residual`: the filter of residual sets. A set `s` is called *residual* if it includes a dense `Gδ` set. In a Baire space (e.g., in a complete (e)metric space), residual sets form a filter. For technical reasons, we define `residual` in any topological space but the definition agrees with the description above only in Baire spaces. ## Main results We prove that finite or countable intersections of Gδ sets is a Gδ set. We also prove that the continuity set of a function from a topological space to an (e)metric space is a Gδ set. ## Tags Gδ set, residual set -/ /-- A Gδ set is a countable intersection of open sets. -/ def is_Gδ {α : Type u_1} [topological_space α] (s : set α) := ∃ (T : set (set α)), (∀ (t : set α), t ∈ T → is_open t) ∧ set.countable T ∧ s = ⋂₀T /-- An open set is a Gδ set. -/ theorem is_open.is_Gδ {α : Type u_1} [topological_space α] {s : set α} (h : is_open s) : is_Gδ s := sorry theorem is_Gδ_univ {α : Type u_1} [topological_space α] : is_Gδ set.univ := is_open.is_Gδ is_open_univ theorem is_Gδ_bInter_of_open {α : Type u_1} {ι : Type u_4} [topological_space α] {I : set ι} (hI : set.countable I) {f : ι → set α} (hf : ∀ (i : ι), i ∈ I → is_open (f i)) : is_Gδ (set.Inter fun (i : ι) => set.Inter fun (H : i ∈ I) => f i) := sorry theorem is_Gδ_Inter_of_open {α : Type u_1} {ι : Type u_4} [topological_space α] [encodable ι] {f : ι → set α} (hf : ∀ (i : ι), is_open (f i)) : is_Gδ (set.Inter fun (i : ι) => f i) := sorry /-- A countable intersection of Gδ sets is a Gδ set. -/ theorem is_Gδ_sInter {α : Type u_1} [topological_space α] {S : set (set α)} (h : ∀ (s : set α), s ∈ S → is_Gδ s) (hS : set.countable S) : is_Gδ (⋂₀S) := sorry theorem is_Gδ_Inter {α : Type u_1} {ι : Type u_4} [topological_space α] [encodable ι] {s : ι → set α} (hs : ∀ (i : ι), is_Gδ (s i)) : is_Gδ (set.Inter fun (i : ι) => s i) := is_Gδ_sInter (iff.mpr set.forall_range_iff hs) (set.countable_range s) theorem is_Gδ_bInter {α : Type u_1} {ι : Type u_4} [topological_space α] {s : set ι} (hs : set.countable s) {t : (i : ι) → i ∈ s → set α} (ht : ∀ (i : ι) (H : i ∈ s), is_Gδ (t i H)) : is_Gδ (set.Inter fun (i : ι) => set.Inter fun (H : i ∈ s) => t i H) := sorry theorem is_Gδ.inter {α : Type u_1} [topological_space α] {s : set α} {t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∩ t) := eq.mpr (id (Eq._oldrec (Eq.refl (is_Gδ (s ∩ t))) set.inter_eq_Inter)) (is_Gδ_Inter (iff.mpr bool.forall_bool { left := ht, right := hs })) /-- The union of two Gδ sets is a Gδ set. -/ theorem is_Gδ.union {α : Type u_1} [topological_space α] {s : set α} {t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∪ t) := sorry theorem is_Gδ_set_of_continuous_at_of_countably_generated_uniformity {α : Type u_1} {β : Type u_2} [topological_space α] [uniform_space β] (hU : filter.is_countably_generated (uniformity β)) (f : α → β) : is_Gδ (set_of fun (x : α) => continuous_at f x) := sorry /-- The set of points where a function is continuous is a Gδ set. -/ theorem is_Gδ_set_of_continuous_at {α : Type u_1} {β : Type u_2} [topological_space α] [emetric_space β] (f : α → β) : is_Gδ (set_of fun (x : α) => continuous_at f x) := is_Gδ_set_of_continuous_at_of_countably_generated_uniformity emetric.uniformity_has_countable_basis f /-- A set `s` is called *residual* if it includes a dense `Gδ` set. If `α` is a Baire space (e.g., a complete metric space), then residual sets form a filter, see `mem_residual`. For technical reasons we define the filter `residual` in any topological space but in a non-Baire space it is not useful because it may contain some non-residual sets. -/ def residual (α : Type u_1) [topological_space α] : filter α := infi fun (t : set α) => infi fun (ht : is_Gδ t) => infi fun (ht' : dense t) => filter.principal t end Mathlib
5b89d87e24332a327a9fc65d89767d194f747dad
e38e95b38a38a99ecfa1255822e78e4b26f65bb0
/src/certigrad/lemmas.lean
c1e9be380a8fee03768e99b023c4663d9b0f4ab4
[ "Apache-2.0" ]
permissive
ColaDrill/certigrad
fefb1be3670adccd3bed2f3faf57507f156fd501
fe288251f623ac7152e5ce555f1cd9d3a20203c2
refs/heads/master
1,593,297,324,250
1,499,903,753,000
1,499,903,753,000
97,075,797
1
0
null
1,499,916,210,000
1,499,916,210,000
null
UTF-8
Lean
false
false
42,934
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Miscellaneous lemmas. -/ import .predicates .tcont .expected_value namespace certigrad open list lemma env_not_has_key_insert {m : env} {ref₁ ref₂ : reference} {x : T ref₂.2} : ref₁ ≠ ref₂ → (¬ env.has_key ref₁ m) → (¬ env.has_key ref₁ (env.insert ref₂ x m)) := begin intros H_neq H_nin H_in, exact H_nin (env.has_key_insert_diff H_neq H_in) end lemma env_in_nin_ne {m : env} {ref₁ ref₂ : reference} : env.has_key ref₁ m → (¬ env.has_key ref₂ m) → ref₁ ≠ ref₂ := begin intros H_in H_nin H_eq, subst H_eq, exact H_nin H_in end lemma ref_notin_parents {n : node} {nodes : list node} {m : env} : all_parents_in_env m (n::nodes) → uniq_ids (n::nodes) m → n^.ref ∉ n^.parents := begin cases n with ref parents op, intros H_ps_in_env H_uids H_ref_in_parents, dsimp [uniq_ids] at H_uids, dsimp at H_ref_in_parents, dsimp [all_parents_in_env] at H_ps_in_env, exact H_uids^.left (H_ps_in_env^.left ref H_ref_in_parents) end lemma ref_ne_tgt {n : node} {nodes : list node} {m : env} {tgt : reference} : env.has_key tgt m → uniq_ids (n::nodes) m → tgt ≠ n^.ref := begin cases n with ref parents op, intros H_tgt H_uids, exact env_in_nin_ne H_tgt H_uids^.left end lemma wf_at_next {costs : list ID} {n : node} {nodes : list node} {x : T n^.ref.2} {inputs : env} {tgt : reference} : let next_inputs : env := env.insert n^.ref x inputs in well_formed_at costs (n::nodes) inputs tgt → well_formed_at costs nodes next_inputs tgt ∧ well_formed_at costs nodes next_inputs n^.ref := begin intros next_inputs H_wf, cases n with ref parents op, assertv H_uids_next : uniq_ids nodes next_inputs := H_wf^.uids^.right x, assertv H_ps_in_env_next : all_parents_in_env next_inputs nodes := H_wf^.ps_in_env^.right x, assertv H_costs_scalars_next : all_costs_scalars costs nodes := H_wf^.costs_scalars^.right, assert H_m_contains_tgt : env.has_key tgt next_inputs, begin dsimp, apply env.has_key_insert, exact H_wf^.m_contains_tgt end, assert H_m_contains_ref : env.has_key ref next_inputs, begin dsimp, apply env.has_key_insert_same end, assertv H_cost_scalar_tgt : tgt.1 ∈ costs → tgt.2 = [] := H_wf^.tgt_cost_scalar, assertv H_cost_scalar_ref : ref.1 ∈ costs → ref.2 = [] := H_wf^.costs_scalars^.left, assertv H_wf_tgt : well_formed_at costs nodes next_inputs tgt := ⟨H_uids_next, H_ps_in_env_next, H_costs_scalars_next, H_m_contains_tgt, H_cost_scalar_tgt⟩, assertv H_wf_ref : well_formed_at costs nodes next_inputs ref := ⟨H_uids_next, H_ps_in_env_next, H_costs_scalars_next, H_m_contains_ref, H_cost_scalar_ref⟩, exact ⟨H_wf_tgt, H_wf_ref⟩ end lemma can_diff_under_ints_alt1 {costs : list ID} {ref : reference} {parents : list reference} {op : rand.op parents^.p2 ref.2} {nodes : list node} {inputs : env} {tgt : reference} : let θ : T tgt.2 := env.get tgt inputs in let g : T ref.2 → T tgt.2 → ℝ := (λ (x : T ref.2) (θ₀ : T tgt.2), E (graph.to_dist (λ (inputs : env), ⟦sum_costs inputs costs⟧) (env.insert ref x (env.insert tgt θ₀ inputs)) nodes) dvec.head) in let next_inputs := (λ (y : T ref.2), env.insert ref y inputs) in can_differentiate_under_integrals costs (⟨ref, parents, operator.rand op⟩ :: nodes) inputs tgt → T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T (ref.snd)), rand.op.pdf op (env.get_ks parents (env.insert tgt θ inputs)) x ⬝ g x θ₀) θ := begin dsimp [can_differentiate_under_integrals], intro H_cdi, note H := H_cdi^.left^.left, clear H_cdi, apply T.uint_right (λ θ₁ θ₂ x, rand.op.pdf op (env.get_ks parents (env.insert tgt θ₁ inputs)) x ⬝ E (graph.to_dist (λ (inputs : env), ⟦sum_costs inputs costs⟧) (env.insert ref x (env.insert tgt θ₂ inputs)) nodes) dvec.head) _ H end lemma pdfs_exist_at_ignore {ref₀ : reference} {x₁ x₂ : T ref₀.2} : ∀ {nodes : list node} {inputs : env}, all_parents_in_env inputs nodes → (¬ env.has_key ref₀ inputs) → ref₀ ∉ map node.ref nodes → pdfs_exist_at nodes (env.insert ref₀ x₁ inputs) → pdfs_exist_at nodes (env.insert ref₀ x₂ inputs) | [] _ _ _ _ _ := true.intro | (⟨ref, parents, operator.det op⟩ :: nodes) inputs H_ps_in_env H_fresh₁ H_fresh₂ H_pdfs_exist_at := begin dsimp [pdfs_exist_at] at H_pdfs_exist_at, dsimp [pdfs_exist_at], assertv H_ref₀_notin_parents : ref₀ ∉ parents := λ H_contra, H_fresh₁ (H_ps_in_env^.left ref₀ H_contra), assert H_ref₀_neq_ref : ref₀ ≠ ref, { intro H_contra, subst H_contra, exact H_fresh₂ mem_of_cons_same }, rw env.get_ks_insert_diff H_ref₀_notin_parents, rw env.insert_insert_flip _ _ _ (ne.symm H_ref₀_neq_ref), rw env.get_ks_insert_diff H_ref₀_notin_parents at H_pdfs_exist_at, rw env.insert_insert_flip _ _ _ (ne.symm H_ref₀_neq_ref) at H_pdfs_exist_at, apply (pdfs_exist_at_ignore (H_ps_in_env^.right _) _ _ H_pdfs_exist_at), { intro H_contra, exact H_fresh₁ (env.has_key_insert_diff H_ref₀_neq_ref H_contra) }, { exact not_mem_of_not_mem_cons H_fresh₂ } end | (⟨ref, parents, operator.rand op⟩ :: nodes) inputs H_ps_in_env H_fresh₁ H_fresh₂ H_pdfs_exist_at := begin dsimp [pdfs_exist_at] at H_pdfs_exist_at, dsimp [pdfs_exist_at], assertv H_ref₀_notin_parents : ref₀ ∉ parents := λ H_contra, H_fresh₁ (H_ps_in_env^.left ref₀ H_contra), assert H_ref₀_neq_ref : ref₀ ≠ ref, { intro H_contra, subst H_contra, exact H_fresh₂ mem_of_cons_same }, rw env.get_ks_insert_diff H_ref₀_notin_parents, rw env.get_ks_insert_diff H_ref₀_notin_parents at H_pdfs_exist_at, apply and.intro, { exact H_pdfs_exist_at^.left }, intro y, note H_pdfs_exist_at_next := H_pdfs_exist_at^.right y, rw env.insert_insert_flip _ _ _ (ne.symm H_ref₀_neq_ref), rw env.insert_insert_flip _ _ _ (ne.symm H_ref₀_neq_ref) at H_pdfs_exist_at_next, apply (pdfs_exist_at_ignore (H_ps_in_env^.right _) _ _ H_pdfs_exist_at_next), { intro H_contra, exact H_fresh₁ (env.has_key_insert_diff H_ref₀_neq_ref H_contra) }, { exact not_mem_of_not_mem_cons H_fresh₂ } end lemma pdf_continuous {ref : reference} {parents : list reference} {op : rand.op parents^.p2 ref.2} {nodes : list node} {inputs : env} {tgt : reference} : ∀ {idx : ℕ}, at_idx parents idx tgt → env.has_key tgt inputs → grads_exist_at (⟨ref, parents, operator.rand op⟩ :: nodes) inputs tgt → ∀ (y : T ref.2), T.is_continuous (λ (x : T tgt.2), (op^.pdf (dvec.update_at x (env.get_ks parents (env.insert tgt (env.get tgt inputs) inputs)) idx) y)) (env.get tgt inputs) := begin intros idx H_at_idx H_tgt_in_inputs H_gs_exist y, assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_at_idx, assertv H_pre_satisfied : op^.pre (env.get_ks parents inputs) := H_gs_exist^.left H_tgt_in_parents, simp [env.insert_get_same H_tgt_in_inputs], dsimp, simp [eq.symm (env.dvec_get_get_ks inputs H_at_idx)], exact (op^.cont (at_idx_p2 H_at_idx) H_pre_satisfied) end -- TODO(dhs): this will need to be `differentiable_of_grads_exist` lemma continuous_of_grads_exist {costs : list ID} : Π {nodes : list node} {tgt : reference} {inputs : env}, well_formed_at costs nodes inputs tgt → grads_exist_at nodes inputs tgt → T.is_continuous (λ (θ₀ : T tgt.2), E (graph.to_dist (λ (env₀ : env), ⟦sum_costs env₀ costs⟧) (env.insert tgt θ₀ inputs) nodes) dvec.head) (env.get tgt inputs) | [] tgt inputs H_wf_at H_gs_exist := begin dunfold graph.to_dist, simp [E.E_ret], dunfold dvec.head sum_costs, apply T.continuous_sumr, intros cost H_cost_in_costs, assertv H_em : (cost, []) = tgt ∨ (cost, []) ≠ tgt := decidable.em _, cases H_em with H_eq H_neq, -- case 1 begin cases tgt with tgt₁ tgt₂, injection H_eq with H_eq₁ H_eq₂, rw [H_eq₁, H_eq₂], dsimp, simp [env.get_insert_same], apply T.continuous_id, end, -- case 2 begin simp [λ (x₀ : T tgt.2), @env.get_insert_diff (cost, []) tgt x₀ inputs H_neq], apply T.continuous_const end end | (⟨ref, parents, operator.det op⟩ :: nodes) tgt inputs H_wf H_gs_exist := let θ := env.get tgt inputs in let x := op^.f (env.get_ks parents inputs) in let next_inputs := env.insert ref x inputs in -- 0. Collect useful helpers have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same, have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids, have H_tgt_neq_ref : tgt ≠ ref, from ref_ne_tgt H_wf^.m_contains_tgt H_wf^.uids, have H_get_ks_next_inputs : env.get_ks parents next_inputs = env.get_ks parents inputs, begin dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents) end, have H_get_ref_next : env.get ref next_inputs = op^.f (env.get_ks parents inputs), begin dsimp, rw env.get_insert_same end, have H_can_insert : env.get tgt next_inputs = env.get tgt inputs, begin dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, have H_insert_next : ∀ (y : T ref.2), env.insert ref y inputs = env.insert ref y next_inputs, begin intro y, dsimp, rw env.insert_insert_same end, have H_wfs : well_formed_at costs nodes next_inputs tgt ∧ well_formed_at costs nodes next_inputs ref, from wf_at_next H_wf, have H_gs_exist_tgt : grads_exist_at nodes next_inputs tgt, from H_gs_exist^.left, begin dunfold graph.to_dist, simp [E.E_bind, E.E_ret], dunfold operator.to_dist, simp [E.E_ret], assertv H_em_tgt_in_parents : tgt ∈ parents ∨ tgt ∉ parents := decidable.em _, cases H_em_tgt_in_parents with H_tgt_in_parents H_tgt_notin_parents, -- case 1 begin definev chain₁ : T tgt.2 → T ref.2 := λ (θ₀ : T tgt.2), op^.f (env.get_ks parents (env.insert tgt θ₀ inputs)), definev chain₂ : T tgt.2 → T ref.2 → ℝ := λ (θ₀ : T tgt.2) (x₀ : T ref.2), E (graph.to_dist (λ (env₀ : env), ⟦sum_costs env₀ costs⟧) (env.insert ref x₀ (env.insert tgt θ₀ inputs)) nodes) dvec.head, change T.is_continuous (λ (θ₀ : T tgt.2), chain₂ θ₀ (chain₁ θ₀)) (env.get tgt inputs), assert H_chain₁ : T.is_continuous (λ (θ₀ : T tgt.2), chain₁ θ₀) (env.get tgt inputs), begin dsimp, apply T.continuous_multiple_args, intros idx H_at_idx, simp [env.insert_get_same H_wf^.m_contains_tgt], rw -(env.dvec_get_get_ks _ H_at_idx), apply (op^.is_ocont (env.get_ks parents inputs) (at_idx_p2 H_at_idx) (H_gs_exist^.right $ mem_of_at_idx H_at_idx)^.left), end, assert H_chain₂_θ : T.is_continuous (λ (x₀ : T tgt.2), chain₂ x₀ (chain₁ (env.get tgt inputs))) (env.get tgt inputs), begin dsimp, simp [env.insert_get_same H_wf^.m_contains_tgt], simp [λ (v₁ : T ref.2) (v₂ : T tgt.2) m, env.insert_insert_flip v₁ v₂ m (ne.symm H_tgt_neq_ref)], rw -H_can_insert, exact (continuous_of_grads_exist H_wfs^.left H_gs_exist_tgt) end, assert H_chain₂_f : T.is_continuous (chain₂ (env.get tgt inputs)) ((λ (θ₀ : T (tgt^.snd)), chain₁ θ₀) (env.get tgt inputs)), begin assertv H_gs_exist_ref : grads_exist_at nodes next_inputs ref := (H_gs_exist^.right H_tgt_in_parents)^.right, dsimp, simp [env.insert_get_same H_wf^.m_contains_tgt], rw -H_get_ref_next, simp [H_insert_next], apply (continuous_of_grads_exist H_wfs^.right H_gs_exist_ref), end, exact (T.continuous_chain_full H_chain₁ H_chain₂_θ H_chain₂_f) end, -- case 2 begin assert H_nodep_tgt : ∀ (θ₀ : T tgt.2), env.get_ks parents (env.insert tgt θ₀ inputs) = env.get_ks parents inputs, begin intro θ₀, rw env.get_ks_insert_diff H_tgt_notin_parents end, simp [H_nodep_tgt], simp [λ (v₁ : T ref.2) (v₂ : T tgt.2) m, env.insert_insert_flip v₁ v₂ m (ne.symm H_tgt_neq_ref)], rw -H_can_insert, exact (continuous_of_grads_exist H_wfs^.left H_gs_exist_tgt) end end | (⟨ref, parents, operator.rand op⟩ :: nodes) tgt inputs H_wf H_gs_exist := let θ := env.get tgt inputs in let next_inputs := λ (y : T ref.2), env.insert ref y inputs in have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same, have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids, have H_tgt_neq_ref : tgt ≠ ref, from ref_ne_tgt H_wf^.m_contains_tgt H_wf^.uids, have H_insert_θ : env.insert tgt θ inputs = inputs, by rw env.insert_get_same H_wf^.m_contains_tgt, have H_parents_match : ∀ y, env.get_ks parents (next_inputs y) = env.get_ks parents inputs, begin intro y, dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents), end, have H_can_insert_y : ∀ y, env.get tgt (next_inputs y) = env.get tgt inputs, begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, have H_wfs : ∀ y, well_formed_at costs nodes (next_inputs y) tgt ∧ well_formed_at costs nodes (next_inputs y) ref, from assume y, wf_at_next H_wf, have H_pdf_continuous : ∀ (y : T ref.2), T.is_continuous (λ (θ₀ : T tgt.2), op^.pdf (env.get_ks parents (env.insert tgt θ₀ inputs)) y) (env.get tgt inputs), from assume (y : T ref.2), begin apply (T.continuous_multiple_args parents [] tgt inputs (λ xs, op^.pdf xs y) (env.get tgt inputs)), intros idx H_at_idx, dsimp, apply (pdf_continuous H_at_idx H_wf^.m_contains_tgt H_gs_exist) end, have H_rest_continuous : ∀ (x : dvec T [ref.2]), T.is_continuous (λ (θ₀ : T tgt.2), E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert ref x^.head (env.insert tgt θ₀ inputs)) nodes) dvec.head) (env.get tgt inputs), from assume x, have H_can_insert_x : ∀ (x : T ref.2), env.get tgt (env.insert ref x inputs) = env.get tgt inputs, begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, begin dsimp, simp [λ θ₀, env.insert_insert_flip x^.head θ₀ inputs (ne.symm H_tgt_neq_ref)], simp [eq.symm (H_can_insert_x x^.head)], exact (continuous_of_grads_exist (H_wfs _)^.left (H_gs_exist^.right _)) end, begin dunfold graph.to_dist operator.to_dist, simp [E.E_bind], apply (E.E_continuous op (λ θ₀, env.get_ks parents (env.insert tgt θ₀ inputs)) _ _ H_pdf_continuous H_rest_continuous) end lemma rest_continuous {costs : list ID} {n : node} {nodes : list node} {inputs : env} {tgt : reference} {x : T n^.ref.2} : ∀ (x : dvec T [n^.ref.2]), tgt ≠ n^.ref → well_formed_at costs nodes (env.insert n^.ref x^.head inputs) tgt → grads_exist_at nodes (env.insert n^.ref x^.head inputs) tgt → T.is_continuous (λ (θ₀ : T tgt.2), E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert n^.ref x^.head (env.insert tgt θ₀ inputs)) nodes) dvec.head) (env.get tgt inputs) := assume x H_tgt_neq_ref H_wf_tgt H_gs_exist_tgt, have H_can_insert_x : ∀ (x : T n^.ref.2), env.get tgt (env.insert n^.ref x inputs) = env.get tgt inputs, begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, begin dsimp, simp [λ θ₀, env.insert_insert_flip x^.head θ₀ inputs (ne.symm H_tgt_neq_ref)], simp [eq.symm (H_can_insert_x x^.head)], exact (continuous_of_grads_exist H_wf_tgt H_gs_exist_tgt) end private lemma fref_notin_parents : Π {n : node} {nodes : list node} {inputs : env} {fref : reference}, all_parents_in_env inputs (n::nodes) → (¬ env.has_key fref inputs) → fref ∉ n^.parents := begin intro n, cases n with ref parents op, dsimp, intros nodes inputs fref H_ps_in_env H_fref_fresh H_fref_in_ps, dunfold all_parents_in_env at H_ps_in_env, exact H_fref_fresh (H_ps_in_env^.left fref H_fref_in_ps) end private lemma fref_neq_ref : Π {n : node} {nodes : list node} {inputs : env} {fref : reference}, (¬ env.has_key fref inputs) → fref ∉ map node.ref (n::nodes) → fref ≠ n^.ref := begin intros n nodes inputs fref H_fref_fresh₁ H_fref_fresh₂, intro H_contra, subst H_contra, exact (ne_of_not_mem_cons H_fref_fresh₂) rfl end lemma to_dist_congr_insert : Π {costs : list ID} {nodes : list node} {inputs : env} {fref : reference} {fval : T fref.2}, all_parents_in_env inputs nodes → (¬ env.has_key fref inputs) → fref ∉ map node.ref nodes → fref.1 ∉ costs → E (graph.to_dist (λ env₀, ⟦sum_costs env₀ costs⟧) (env.insert fref fval inputs) nodes) dvec.head = E (graph.to_dist (λ env₀, ⟦sum_costs env₀ costs⟧) inputs nodes) dvec.head | costs [] inputs fref fval H_ps_in_env H_fresh₁ H_fresh₂ H_not_cost := begin dunfold graph.to_dist, simp [E.E_ret], dunfold dvec.head sum_costs map, induction costs with cost costs IH_cost, -- case 1 reflexivity, -- case 2 dunfold map sumr, assertv H_neq : (cost, []) ≠ fref := begin intro H_contra, cases fref with fid fshape, injection H_contra with H_cost H_ignore, dsimp at H_not_cost, rw H_cost at H_not_cost, exact (ne_of_not_mem_cons H_not_cost rfl) end, assertv H_notin : fref.1 ∉ costs := not_mem_of_not_mem_cons H_not_cost, simp [env.get_insert_diff fval inputs H_neq], rw IH_cost H_notin end | costs (⟨ref, parents, operator.det op⟩::nodes) inputs fref fval H_ps_in_env H_fresh₁ H_fresh₂ H_not_cost := begin dunfold graph.to_dist operator.to_dist, simp [E.E_bind, E.E_ret], assertv H_fref_notin_parents : fref ∉ parents := fref_notin_parents H_ps_in_env H_fresh₁, assertv H_fref_neq_ref : fref ≠ ref := fref_neq_ref H_fresh₁ H_fresh₂, rw env.get_ks_insert_diff H_fref_notin_parents, rw env.insert_insert_flip _ _ _ (ne.symm H_fref_neq_ref), dsimp, apply (to_dist_congr_insert (H_ps_in_env^.right _) _ _ H_not_cost), { intro H_contra, exact H_fresh₁ (env.has_key_insert_diff H_fref_neq_ref H_contra) }, { exact not_mem_of_not_mem_cons H_fresh₂ } end | costs (⟨ref, parents, operator.rand op⟩::nodes) inputs fref fval H_ps_in_env H_fresh₁ H_fresh₂ H_not_cost := begin dunfold graph.to_dist operator.to_dist, simp [E.E_bind, E.E_ret], assertv H_fref_notin_parents : fref ∉ parents := fref_notin_parents H_ps_in_env H_fresh₁, assertv H_fref_neq_ref : fref ≠ ref := fref_neq_ref H_fresh₁ H_fresh₂, rw env.get_ks_insert_diff H_fref_notin_parents, apply congr_arg, apply funext, intro x, rw env.insert_insert_flip _ _ _ (ne.symm H_fref_neq_ref), apply (to_dist_congr_insert (H_ps_in_env^.right _) _ _ H_not_cost), { intro H_contra, exact H_fresh₁ (env.has_key_insert_diff H_fref_neq_ref H_contra) }, { exact not_mem_of_not_mem_cons H_fresh₂ } end lemma map_filter_expand_helper {costs : list ID} (ref : reference) (parents : list reference) (op : rand.op parents^.p2 ref.2) (nodes : list node) (inputs : env) (tgt : reference) : well_formed_at costs (⟨ref, parents, operator.rand op⟩::nodes) inputs tgt → grads_exist_at (⟨ref, parents, operator.rand op⟩::nodes) inputs tgt → ∀ (y : T ref.2), map (λ (idx : ℕ), E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert ref y inputs) nodes) dvec.head ⬝ ∇ (λ (θ₀ : T (tgt.snd)), T.log (rand.op.pdf op (dvec.update_at θ₀ (env.get_ks parents inputs) idx) y)) (env.get tgt inputs)) (filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))) = map (λ (x : ℕ), E (graph.to_dist (λ (m : env), ⟦(λ (m : env) (idx : ℕ), sum_downstream_costs nodes costs ref m ⬝ rand.op.glogpdf op (env.get_ks parents m) (env.get ref m) idx (tgt.snd)) m x⟧) ((λ (y : T (ref.snd)), env.insert ref y inputs) y) nodes) dvec.head) (filter (λ (idx : ℕ), tgt = dnth parents idx) (riota (length parents))) := assume H_wf H_gs_exist y, let θ := env.get tgt inputs in let next_inputs := λ (y : T ref.2), env.insert ref y inputs in have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same, have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids, have H_get_ks_next_inputs : env.get_ks parents (next_inputs y) = env.get_ks parents inputs, begin dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents) end, have H_wfs : ∀ y, well_formed_at costs nodes (next_inputs y) tgt ∧ well_formed_at costs nodes (next_inputs y) ref, from assume y, wf_at_next H_wf, begin -- Apply map_filter_congr apply map_filter_congr, intros idx H_idx_in_riota H_tgt_dnth_parents_idx, assertv H_tgt_at_idx : at_idx parents idx tgt := ⟨in_riota_lt H_idx_in_riota, H_tgt_dnth_parents_idx⟩, assertv H_tshape_at_idx : at_idx parents^.p2 idx tgt.2 := at_idx_p2 H_tgt_at_idx, assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_tgt_at_idx, -- 7. Replace `m` with `inputs`/`next_inputs` so that we can use the gradient rule for the logpdf dunfold sum_downstream_costs, assert H_swap_m_for_inputs : (graph.to_dist (λ (m : env), ⟦sum_costs m costs ⬝ rand.op.glogpdf op (env.get_ks parents m) (env.get ref m) idx (tgt^.snd)⟧) (env.insert ref y inputs) nodes) = (graph.to_dist (λ (m : env), ⟦sum_costs m costs ⬝ rand.op.glogpdf op (env.get_ks parents (next_inputs y)) (env.get ref (next_inputs y)) idx (tgt^.snd)⟧) (env.insert ref y inputs) nodes), begin apply graph.to_dist_congr, exact (H_wfs y)^.left^.uids, dsimp, intros m H_envs_match, apply dvec.singleton_congr, assert H_parents_match : env.get_ks parents m = env.get_ks parents (next_inputs y), begin apply env.get_ks_env_eq, intros parent H_parent_in_parents, apply H_envs_match, apply env.has_key_insert, exact (H_wf^.ps_in_env^.left parent H_parent_in_parents) end, assert H_ref_matches : env.get ref m = y, begin assertv H_env.has_key_ref : env.has_key ref (next_inputs y) := env.has_key_insert_same _ _, rw [H_envs_match ref H_env.has_key_ref, env.get_insert_same] end, simp [H_parents_match, H_ref_matches, env.get_insert_same], end, erw H_swap_m_for_inputs, clear H_swap_m_for_inputs, -- 8. push E over ⬝ and cancel the first terms rw E.E_k_scale, apply congr_arg, -- 9. Use glogpdf correct assertv H_glogpdf_pre : op^.pre (env.get_ks parents (next_inputs y)) := begin dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents), exact (H_gs_exist^.left H_tgt_in_parents) end, rw (op^.glogpdf_correct H_tshape_at_idx H_glogpdf_pre), -- 10. Clean-up dunfold E dvec.head, dsimp, simp [H_get_ks_next_inputs, env.get_insert_same], rw (env.dvec_get_get_ks inputs H_tgt_at_idx) end lemma sum_costs_differentiable : Π (costs : list ID) (tgt : reference) (inputs : env), T.is_cdifferentiable (λ (θ₀ : T (tgt.snd)), sumr (map (λ (cost : ID), env.get (cost, @nil ℕ) (env.insert tgt θ₀ inputs)) costs)) (env.get tgt inputs) := begin intros costs tgt inputs, induction costs with cost costs IHcosts, { dunfold sumr map, apply T.is_cdifferentiable_const }, { dunfold sumr map, apply iff.mp (T.is_cdifferentiable_add_fs _ _ _), split, tactic.swap, exact IHcosts, assertv H_em : tgt = (cost, []) ∨ tgt ≠ (cost, []) := decidable.em _, cases H_em with H_eq H_neq, -- case 1: tgt = (cost, []) { rw H_eq, simp only [env.get_insert_same], apply T.is_cdifferentiable_id }, -- case 2: tgt ≠ (cost, []) { simp only [λ (x : T tgt.2), env.get_insert_diff x inputs (ne.symm H_neq), H_neq], apply T.is_cdifferentiable_const } } end lemma pd_is_cdifferentiable (costs : list ID) : Π (tgt : reference) (inputs : env) (nodes : list node), well_formed_at costs nodes inputs tgt → grads_exist_at nodes inputs tgt → pdfs_exist_at nodes inputs → can_differentiate_under_integrals costs nodes inputs tgt → T.is_cdifferentiable (λ (θ₀ : T tgt.2), E (graph.to_dist (λ m, ⟦sum_costs m costs⟧) (env.insert tgt θ₀ inputs) nodes) dvec.head) (env.get tgt inputs) | tgt inputs [] := assume H_wf H_gs_exist H_pdfs_exist H_diff_under_int, sum_costs_differentiable costs tgt inputs | tgt inputs (⟨ref, parents, operator.det op⟩ :: nodes) := assume H_wf H_gs_exist H_pdfs_exist H_diff_under_int, let θ := env.get tgt inputs in let x := op^.f (env.get_ks parents inputs) in let next_inputs := env.insert ref x inputs in -- 0. Collect useful helpers have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same, have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids, have H_tgt_neq_ref : tgt ≠ ref, from ref_ne_tgt H_wf^.m_contains_tgt H_wf^.uids, have H_can_insert : env.get tgt next_inputs = env.get tgt inputs, begin dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, have H_wfs : well_formed_at costs nodes next_inputs tgt ∧ well_formed_at costs nodes next_inputs ref, from wf_at_next H_wf, have H_gs_exist_tgt : grads_exist_at nodes next_inputs tgt, from H_gs_exist^.left, have H_pdfs_exist_next : pdfs_exist_at nodes next_inputs, from H_pdfs_exist, begin note H_pdiff_tgt := pd_is_cdifferentiable tgt next_inputs nodes H_wfs^.left H_gs_exist_tgt H_pdfs_exist_next H_diff_under_int^.left, dsimp [graph.to_dist, operator.to_dist], simp only [E.E_ret, E.E_bind, dvec.head], apply T.is_cdifferentiable_binary (λ θ₁ θ₂, E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert ref (det.op.f op (env.get_ks parents (env.insert tgt θ₂ inputs))) (env.insert tgt θ₁ inputs)) nodes) dvec.head), { -- case 1, simple recursive case dsimp, simp only [λ (x : T ref.2) (θ : T tgt.2), env.insert_insert_flip x θ inputs (ne.symm H_tgt_neq_ref)], simp only [env.insert_get_same H_wf^.m_contains_tgt], simp only [H_can_insert] at H_pdiff_tgt, exact H_pdiff_tgt }, -- end case 1, simple recursive case -- start case 2 dsimp, simp only [λ (x : T ref.2) (θ : T tgt.2), env.insert_insert_flip x θ inputs (ne.symm H_tgt_neq_ref)], apply T.is_cdifferentiable_multiple_args _ _ _ op^.f _ (λ (x' : T ref.snd), E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert tgt (env.get tgt inputs) (env.insert ref x' inputs)) nodes) dvec.head), intros idx H_idx_in_riota H_tgt_eq_dnth_idx, assertv H_tgt_at_idx : at_idx parents idx tgt := ⟨in_riota_lt H_idx_in_riota, H_tgt_eq_dnth_idx⟩, assertv H_tshape_at_idx : at_idx parents^.p2 idx tgt.2 := at_idx_p2 H_tgt_at_idx, assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_tgt_at_idx, dsimp, assertv H_gs_exist_ref : grads_exist_at nodes next_inputs ref := (H_gs_exist^.right H_tgt_in_parents)^.right, assertv H_diff_under_int_ref : can_differentiate_under_integrals costs nodes next_inputs ref := H_diff_under_int^.right H_tgt_in_parents, note H_pdiff_ref := pd_is_cdifferentiable ref next_inputs nodes H_wfs^.right H_gs_exist_ref H_pdfs_exist_next H_diff_under_int_ref, simp only [env.insert_get_same H_wf^.m_contains_tgt], note H_odiff := op^.is_odiff (env.get_ks parents inputs) (H_gs_exist^.right H_tgt_in_parents)^.left idx tgt.2 H_tshape_at_idx (λ x', E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert tgt (env.get tgt inputs) (env.insert ref x' inputs)) nodes) dvec.head), simp only [λ m, env.dvec_get_get_ks m H_tgt_at_idx] at H_odiff, apply H_odiff, dsimp at H_pdiff_ref, simp only [env.get_insert_same] at H_pdiff_ref, simp only [λ (x : T ref.2) (θ : T tgt.2), env.insert_insert_flip θ x inputs H_tgt_neq_ref, env.insert_get_same H_wf^.m_contains_tgt], simp only [env.insert_insert_same] at H_pdiff_ref, exact H_pdiff_ref end | tgt inputs (⟨ref, parents, operator.rand op⟩ :: nodes) := assume H_wf H_gs_exist H_pdfs_exist H_diff_under_int, let θ := env.get tgt inputs in let next_inputs := λ (y : T ref.2), env.insert ref y inputs in -- 0. Collect useful helpers have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same, have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids, have H_tgt_neq_ref : tgt ≠ ref, from ref_ne_tgt H_wf^.m_contains_tgt H_wf^.uids, have H_insert_θ : env.insert tgt θ inputs = inputs, by rw env.insert_get_same H_wf^.m_contains_tgt, have H_parents_match : ∀ y, env.get_ks parents (next_inputs y) = env.get_ks parents inputs, begin intro y, dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents), end, have H_can_insert_y : ∀ y, env.get tgt (next_inputs y) = env.get tgt inputs, begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, have H_wfs : ∀ y, well_formed_at costs nodes (next_inputs y) tgt ∧ well_formed_at costs nodes (next_inputs y) ref, from assume y, wf_at_next H_wf, have H_parents_match : ∀ y, env.get_ks parents (next_inputs y) = env.get_ks parents inputs, begin intro y, dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents), end, have H_can_insert_y : ∀ y, env.get tgt (next_inputs y) = env.get tgt inputs, begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, have H_op_pre : op^.pre (env.get_ks parents inputs), from H_pdfs_exist^.left, let g : T ref.2 → T tgt.2 → ℝ := (λ (x : T ref.2) (θ₀ : T tgt.2), E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert ref x (env.insert tgt θ₀ inputs)) nodes) dvec.head) in have H_g_uint : T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T (ref.snd)), rand.op.pdf op (env.get_ks parents (env.insert tgt θ₀ inputs)) x ⬝ E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert ref x (env.insert tgt θ₀ inputs)) nodes) dvec.head) (env.get tgt inputs), from H_diff_under_int^.left^.left, have H_g_grad_uint : T.is_uniformly_integrable_around (λ (θ₀ : T (tgt.snd)) (x : T (ref.snd)), ∇ (λ (θ₁ : T (tgt.snd)), (λ (x : T (ref.snd)) (θ₀ : T (tgt.snd)), rand.op.pdf op (env.get_ks parents (env.insert tgt θ₀ inputs)) x ⬝ E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert ref x (env.insert tgt θ₀ inputs)) nodes) dvec.head) x θ₁) θ₀) (env.get tgt inputs), from H_diff_under_int^.left^.right^.left^.left, begin dunfold graph.to_dist operator.to_dist, simp only [E.E_bind], note H_pdiff_tgt := λ y, pd_is_cdifferentiable tgt (next_inputs y) nodes (H_wfs y)^.left (H_gs_exist^.right y) (H_pdfs_exist^.right y) (H_diff_under_int^.right y), dunfold E T.dintegral dvec.head, apply T.is_cdifferentiable_integral _ _ _ H_g_uint H_g_grad_uint, intro y, apply T.is_cdifferentiable_binary (λ θ₁ θ₂, rand.op.pdf op (env.get_ks parents (env.insert tgt θ₁ inputs)) y ⬝ E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert ref y (env.insert tgt θ₂ inputs)) nodes) dvec.head), begin -- start PDF differentiable dsimp, apply iff.mp (T.is_cdifferentiable_fscale _ _ _), apply T.is_cdifferentiable_multiple_args _ _ _ (λ θ, op^.pdf θ y) _ (λ y : ℝ, y), intros idx H_idx_in_riota H_tgt_eq_dnth_idx, assertv H_tgt_at_idx : at_idx parents idx tgt := ⟨in_riota_lt H_idx_in_riota, H_tgt_eq_dnth_idx⟩, assertv H_tshape_at_idx : at_idx parents^.p2 idx tgt.2 := at_idx_p2 H_tgt_at_idx, assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_tgt_at_idx, dsimp, note H_pdf_cdiff := @rand.op.pdf_cdiff _ _ op (env.get_ks parents inputs) y idx tgt.2 H_tshape_at_idx H_pdfs_exist^.left, dsimp [rand.pdf_cdiff] at H_pdf_cdiff, simp only [env.insert_get_same H_wf^.m_contains_tgt], simp only [λ m, env.dvec_get_get_ks m H_tgt_at_idx] at H_pdf_cdiff, exact H_pdf_cdiff, end, -- end PDF differentiable begin -- start E differentiable dsimp, dsimp at H_pdiff_tgt, apply iff.mp (T.is_cdifferentiable_scale_f _ _ _), simp only [λ x y z, env.insert_insert_flip x y z H_tgt_neq_ref] at H_pdiff_tgt, simp only [λ x y, env.get_insert_diff x y H_tgt_neq_ref] at H_pdiff_tgt, apply H_pdiff_tgt end -- end E differentiable end lemma is_gdifferentiable_of_pre {costs : list ID} : Π (tgt : reference) (inputs : env) (nodes : list node), well_formed_at costs nodes inputs tgt → grads_exist_at nodes inputs tgt → pdfs_exist_at nodes inputs → can_differentiate_under_integrals costs nodes inputs tgt → is_gdifferentiable (λ m, ⟦sum_costs m costs⟧) tgt inputs nodes dvec.head | tgt inputs [] := λ H_wf H_gs_exist H_pdfs_exist H_diff_under_int, trivial | tgt inputs (⟨ref, parents, operator.det op⟩ :: nodes) := assume H_wf H_gs_exist H_pdfs_exist H_diff_under_int, let θ := env.get tgt inputs in let x := op^.f (env.get_ks parents inputs) in let next_inputs := env.insert ref x inputs in have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same, have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids, have H_tgt_neq_ref : tgt ≠ ref, from ref_ne_tgt H_wf^.m_contains_tgt H_wf^.uids, have H_can_insert : env.get tgt next_inputs = env.get tgt inputs, begin dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, have H_wfs : well_formed_at costs nodes next_inputs tgt ∧ well_formed_at costs nodes next_inputs ref, from wf_at_next H_wf, have H_gs_exist_tgt : grads_exist_at nodes next_inputs tgt, from H_gs_exist^.left, have H_pdfs_exist_next : pdfs_exist_at nodes next_inputs, from H_pdfs_exist, have H_gdiff_tgt : is_gdifferentiable (λ m, ⟦sum_costs m costs⟧) tgt next_inputs nodes dvec.head, from is_gdifferentiable_of_pre tgt next_inputs nodes H_wfs^.left H_gs_exist_tgt H_pdfs_exist_next H_diff_under_int^.left, begin dsimp [grads_exist_at] at H_gs_exist, dsimp [pdfs_exist_at] at H_pdfs_exist, dsimp [is_gdifferentiable] at H_gdiff_tgt, dsimp [is_gdifferentiable], -- TODO(dhs): replace once `apply` tactic can handle nesting split, tactic.rotate 1, split, tactic.rotate 1, split, tactic.rotate 2, ----------------------------------- start 1/4 begin simp only [env.insert_get_same H_wf^.m_contains_tgt, env.get_insert_same], note H_pdiff := pd_is_cdifferentiable costs tgt next_inputs nodes H_wfs^.left H_gs_exist_tgt H_pdfs_exist_next H_diff_under_int^.left, dsimp at H_pdiff, simp only [H_can_insert] at H_pdiff, simp only [λ (x : T ref.2) (θ : T tgt.2), env.insert_insert_flip θ x inputs H_tgt_neq_ref] at H_pdiff, exact H_pdiff, end, ----------------------------------- end 1/4 ----------------------------------- start 2/4 begin apply T.is_cdifferentiable_sumr, intros idx H_idx_in_filter, cases of_in_filter _ _ _ H_idx_in_filter with H_idx_in_riota H_tgt_eq_dnth_idx, assertv H_tgt_at_idx : at_idx parents idx tgt := ⟨in_riota_lt H_idx_in_riota, H_tgt_eq_dnth_idx⟩, assertv H_tshape_at_idx : at_idx parents^.p2 idx tgt.2 := at_idx_p2 H_tgt_at_idx, assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_tgt_at_idx, assertv H_gs_exist_ref : grads_exist_at nodes next_inputs ref := (H_gs_exist^.right H_tgt_in_parents)^.right, note H_pdiff := pd_is_cdifferentiable costs ref next_inputs nodes H_wfs^.right H_gs_exist_ref H_pdfs_exist_next (H_diff_under_int^.right H_tgt_in_parents), dsimp at H_pdiff, simp only [env.insert_get_same H_wf^.m_contains_tgt], simp only [env.get_insert_same, env.insert_insert_same] at H_pdiff, note H_odiff := op^.is_odiff (env.get_ks parents inputs) (H_gs_exist^.right H_tgt_in_parents)^.left idx tgt.2 H_tshape_at_idx (λ x', E (graph.to_dist (λ (m : env), ⟦sum_costs m costs⟧) (env.insert tgt (env.get tgt inputs) (env.insert ref x' inputs)) nodes) dvec.head), simp only [λ m, env.dvec_get_get_ks m H_tgt_at_idx] at H_odiff, simp only [λ (x : T ref.2) (θ : T tgt.2), env.insert_insert_flip θ x inputs H_tgt_neq_ref, env.insert_get_same H_wf^.m_contains_tgt] at H_odiff, apply H_odiff, exact H_pdiff end, ----------------------------------- end 2/4 ----------------------------------- start 3/4 begin exact H_gdiff_tgt end, ----------------------------------- end 3/4 ----------------------------------- start 4/4 begin intros idx H_idx_in_riota H_tgt_eq_dnth_idx, assertv H_tgt_at_idx : at_idx parents idx tgt := ⟨in_riota_lt H_idx_in_riota, H_tgt_eq_dnth_idx⟩, assertv H_tshape_at_idx : at_idx parents^.p2 idx tgt.2 := at_idx_p2 H_tgt_at_idx, assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_tgt_at_idx, assertv H_gs_exist_ref : grads_exist_at nodes next_inputs ref := (H_gs_exist^.right H_tgt_in_parents)^.right, apply is_gdifferentiable_of_pre ref next_inputs nodes H_wfs^.right H_gs_exist_ref H_pdfs_exist_next (H_diff_under_int^.right H_tgt_in_parents), end, ----------------------------------- end 4/4 end | tgt inputs (⟨ref, parents, operator.rand op⟩ :: nodes) := assume H_wf H_gs_exist H_pdfs_exist H_diff_under_int, let θ := env.get tgt inputs in let next_inputs := λ (y : T ref.2), env.insert ref y inputs in -- 0. Collect useful helpers have H_ref_in_refs : ref ∈ ref :: map node.ref nodes, from mem_of_cons_same, have H_ref_notin_parents : ref ∉ parents, from ref_notin_parents H_wf^.ps_in_env H_wf^.uids, have H_tgt_neq_ref : tgt ≠ ref, from ref_ne_tgt H_wf^.m_contains_tgt H_wf^.uids, have H_insert_θ : env.insert tgt θ inputs = inputs, by rw env.insert_get_same H_wf^.m_contains_tgt, have H_parents_match : ∀ y, env.get_ks parents (next_inputs y) = env.get_ks parents inputs, begin intro y, dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents), end, have H_can_insert_y : ∀ y, env.get tgt (next_inputs y) = env.get tgt inputs, begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, have H_wfs : ∀ y, well_formed_at costs nodes (next_inputs y) tgt ∧ well_formed_at costs nodes (next_inputs y) ref, from assume y, wf_at_next H_wf, have H_parents_match : ∀ y, env.get_ks parents (next_inputs y) = env.get_ks parents inputs, begin intro y, dsimp, rw (env.get_ks_insert_diff H_ref_notin_parents), end, have H_can_insert_y : ∀ y, env.get tgt (next_inputs y) = env.get tgt inputs, begin intro y, dsimp, rw (env.get_insert_diff _ _ H_tgt_neq_ref) end, have H_op_pre : op^.pre (env.get_ks parents inputs), from H_pdfs_exist^.left, begin dsimp [is_gdifferentiable], -- TODO(dhs): use apply and.intro _ (and.intro _ _) once tactic is fixed split, tactic.rotate 1, split, tactic.rotate 2, ----------------------------------- start 1/3 begin dunfold E T.dintegral, note H_g_uint := can_diff_under_ints_alt1 H_diff_under_int, note H_g_grad_uint := H_diff_under_int^.left^.right^.left^.right, apply T.is_cdifferentiable_integral _ _ _ H_g_uint H_g_grad_uint, intro y, apply iff.mp (T.is_cdifferentiable_scale_f _ _ _), note H_pdiff := pd_is_cdifferentiable costs tgt (next_inputs y) nodes (H_wfs y)^.left (H_gs_exist^.right y) (H_pdfs_exist^.right y) (H_diff_under_int^.right y), dsimp [dvec.head], dsimp at H_pdiff, simp only [H_can_insert_y] at H_pdiff, simp only [λ (x : T ref.2) (θ : T tgt.2), env.insert_insert_flip θ x inputs H_tgt_neq_ref, env.insert_get_same H_wf^.m_contains_tgt] at H_pdiff, exact H_pdiff end, ----------------------------------- end 1/3 ----------------------------------- start 2/3 begin apply T.is_cdifferentiable_sumr, intros idx H_idx_in_filter, cases of_in_filter _ _ _ H_idx_in_filter with H_idx_in_riota H_tgt_eq_dnth_idx, assertv H_tgt_at_idx : at_idx parents idx tgt := ⟨in_riota_lt H_idx_in_riota, H_tgt_eq_dnth_idx⟩, assertv H_tshape_at_idx : at_idx parents^.p2 idx tgt.2 := at_idx_p2 H_tgt_at_idx, assertv H_tgt_in_parents : tgt ∈ parents := mem_of_at_idx H_tgt_at_idx, note H_g_uint_idx := H_diff_under_int^.left^.right^.right^.left _ H_tgt_at_idx, note H_g_grad_uint_idx := H_diff_under_int^.left^.right^.right^.right _ H_tgt_at_idx, dunfold E T.dintegral, apply T.is_cdifferentiable_integral _ _ _ H_g_uint_idx H_g_grad_uint_idx, tactic.rotate 2, dsimp [dvec.head], intro y, apply iff.mp (T.is_cdifferentiable_fscale _ _ _), note H_pdf_cdiff := @rand.op.pdf_cdiff _ _ op (env.get_ks parents inputs) y idx tgt.2 H_tshape_at_idx H_pdfs_exist^.left, dsimp [rand.pdf_cdiff] at H_pdf_cdiff, simp only [env.insert_get_same H_wf^.m_contains_tgt], simp only [λ m, env.dvec_get_get_ks m H_tgt_at_idx] at H_pdf_cdiff, exact H_pdf_cdiff, end, ----------------------------------- end 2/3 ----------------------------------- start 3/3 begin exact λ y, is_gdifferentiable_of_pre _ _ _ (H_wfs y)^.left (H_gs_exist^.right y) (H_pdfs_exist^.right y) (H_diff_under_int^.right y) end ----------------------------------- end 3/3 end lemma can_diff_under_ints_of_all_pdfs_std (costs : list ID) : Π (nodes : list node) (m : env) (tgt : reference), all_pdfs_std nodes → can_diff_under_ints_pdfs_std costs nodes m tgt → can_differentiate_under_integrals costs nodes m tgt | [] m tgt H_std H_cdi := trivial | (⟨ref, parents, operator.det op⟩ :: nodes) m tgt H_std H_cdi := begin simp [all_pdfs_std_det] at H_std, dsimp [can_diff_under_ints_pdfs_std] at H_cdi, dsimp [can_differentiate_under_integrals], split, apply can_diff_under_ints_of_all_pdfs_std, exact H_std, exact H_cdi^.left, intro H_in, apply can_diff_under_ints_of_all_pdfs_std, exact H_std, exact H_cdi^.right H_in end | (⟨(ref, .(shape)), [], operator.rand (rand.op.mvn_iso_std shape)⟩ :: nodes) m tgt H_std H_cdi := begin dsimp [all_pdfs_std] at H_std, dsimp [can_diff_under_ints_pdfs_std] at H_cdi, dsimp [can_differentiate_under_integrals], split, split, exact H_cdi^.left^.left, split, exact and.intro H_cdi^.left^.right H_cdi^.left^.right, split, intros H H_contra, exfalso, exact list.at_idx_over H_contra (nat.not_lt_zero _), intros H H_contra, exfalso, exact list.at_idx_over H_contra (nat.not_lt_zero _), intro y, apply can_diff_under_ints_of_all_pdfs_std, exact H_std, exact H_cdi^.right y end | (⟨(ref, .(shape)), [(parent₁, .(shape)), (parent₂, .(shape))], operator.rand (rand.op.mvn_iso shape)⟩ :: nodes) m tgt H_std H_cdi := begin dsimp [all_pdfs_std] at H_std, exfalso, exact H_std end end certigrad
6e2b26b47c74a1d5eba9614dd4e334f73f2681cc
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/normed_space/pointwise.lean
65e8d118b8b4706785285575f3e74f769034d37e
[ "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
16,499
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yaël Dillies -/ import analysis.normed.group.add_torsor import analysis.normed.group.pointwise import analysis.normed_space.basic /-! # Properties of pointwise scalar multiplication of sets in normed spaces. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We explore the relationships between scalar multiplication of sets in vector spaces, and the norm. Notably, we express arbitrary balls as rescaling of other balls, and we show that the multiplication of bounded sets remain bounded. -/ open metric set open_locale pointwise topology variables {𝕜 E : Type*} [normed_field 𝕜] section seminormed_add_comm_group variables [seminormed_add_comm_group E] [normed_space 𝕜 E] theorem smul_ball {c : 𝕜} (hc : c ≠ 0) (x : E) (r : ℝ) : c • ball x r = ball (c • x) (‖c‖ * r) := begin ext y, rw mem_smul_set_iff_inv_smul_mem₀ hc, conv_lhs { rw ←inv_smul_smul₀ hc x }, simp [← div_eq_inv_mul, div_lt_iff (norm_pos_iff.2 hc), mul_comm _ r, dist_smul₀], end lemma smul_unit_ball {c : 𝕜} (hc : c ≠ 0) : c • ball (0 : E) (1 : ℝ) = ball (0 : E) (‖c‖) := by rw [smul_ball hc, smul_zero, mul_one] theorem smul_sphere' {c : 𝕜} (hc : c ≠ 0) (x : E) (r : ℝ) : c • sphere x r = sphere (c • x) (‖c‖ * r) := begin ext y, rw mem_smul_set_iff_inv_smul_mem₀ hc, conv_lhs { rw ←inv_smul_smul₀ hc x }, simp only [mem_sphere, dist_smul₀, norm_inv, ← div_eq_inv_mul, div_eq_iff (norm_pos_iff.2 hc).ne', mul_comm r], end theorem smul_closed_ball' {c : 𝕜} (hc : c ≠ 0) (x : E) (r : ℝ) : c • closed_ball x r = closed_ball (c • x) (‖c‖ * r) := by simp only [← ball_union_sphere, set.smul_set_union, smul_ball hc, smul_sphere' hc] lemma metric.bounded.smul {s : set E} (hs : bounded s) (c : 𝕜) : bounded (c • s) := begin obtain ⟨R, hR⟩ : ∃ (R : ℝ), ∀ x ∈ s, ‖x‖ ≤ R := hs.exists_norm_le, refine bounded_iff_forall_norm_le.2 ⟨‖c‖ * R, λ z hz, _⟩, obtain ⟨y, ys, rfl⟩ : ∃ (y : E), y ∈ s ∧ c • y = z := mem_smul_set.1 hz, calc ‖c • y‖ = ‖c‖ * ‖y‖ : norm_smul _ _ ... ≤ ‖c‖ * R : mul_le_mul_of_nonneg_left (hR y ys) (norm_nonneg _) end /-- If `s` is a bounded set, then for small enough `r`, the set `{x} + r • s` is contained in any fixed neighborhood of `x`. -/ lemma eventually_singleton_add_smul_subset {x : E} {s : set E} (hs : bounded s) {u : set E} (hu : u ∈ 𝓝 x) : ∀ᶠ r in 𝓝 (0 : 𝕜), {x} + r • s ⊆ u := begin obtain ⟨ε, εpos, hε⟩ : ∃ ε (hε : 0 < ε), closed_ball x ε ⊆ u := nhds_basis_closed_ball.mem_iff.1 hu, obtain ⟨R, Rpos, hR⟩ : ∃ (R : ℝ), 0 < R ∧ s ⊆ closed_ball 0 R := hs.subset_ball_lt 0 0, have : metric.closed_ball (0 : 𝕜) (ε / R) ∈ 𝓝 (0 : 𝕜) := closed_ball_mem_nhds _ (div_pos εpos Rpos), filter_upwards [this] with r hr, simp only [image_add_left, singleton_add], assume y hy, obtain ⟨z, zs, hz⟩ : ∃ (z : E), z ∈ s ∧ r • z = -x + y, by simpa [mem_smul_set] using hy, have I : ‖r • z‖ ≤ ε := calc ‖r • z‖ = ‖r‖ * ‖z‖ : norm_smul _ _ ... ≤ (ε / R) * R : mul_le_mul (mem_closed_ball_zero_iff.1 hr) (mem_closed_ball_zero_iff.1 (hR zs)) (norm_nonneg _) (div_pos εpos Rpos).le ... = ε : by field_simp [Rpos.ne'], have : y = x + r • z, by simp only [hz, add_neg_cancel_left], apply hε, simpa only [this, dist_eq_norm, add_sub_cancel', mem_closed_ball] using I, end variables [normed_space ℝ E] {x y z : E} {δ ε : ℝ} /-- In a real normed space, the image of the unit ball under scalar multiplication by a positive constant `r` is the ball of radius `r`. -/ lemma smul_unit_ball_of_pos {r : ℝ} (hr : 0 < r) : r • ball 0 1 = ball (0 : E) r := by rw [smul_unit_ball hr.ne', real.norm_of_nonneg hr.le] -- This is also true for `ℚ`-normed spaces lemma exists_dist_eq (x z : E) {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : ∃ y, dist x y = b * dist x z ∧ dist y z = a * dist x z := begin use a • x + b • z, nth_rewrite 0 [←one_smul ℝ x], nth_rewrite 3 [←one_smul ℝ z], simp [dist_eq_norm, ←hab, add_smul, ←smul_sub, norm_smul_of_nonneg, ha, hb], end lemma exists_dist_le_le (hδ : 0 ≤ δ) (hε : 0 ≤ ε) (h : dist x z ≤ ε + δ) : ∃ y, dist x y ≤ δ ∧ dist y z ≤ ε := begin obtain rfl | hε' := hε.eq_or_lt, { exact ⟨z, by rwa zero_add at h, (dist_self _).le⟩ }, have hεδ := add_pos_of_pos_of_nonneg hε' hδ, refine (exists_dist_eq x z (div_nonneg hε $ add_nonneg hε hδ) (div_nonneg hδ $ add_nonneg hε hδ) $ by rw [←add_div, div_self hεδ.ne']).imp (λ y hy, _), rw [hy.1, hy.2, div_mul_comm, div_mul_comm ε], rw ←div_le_one hεδ at h, exact ⟨mul_le_of_le_one_left hδ h, mul_le_of_le_one_left hε h⟩, end -- This is also true for `ℚ`-normed spaces lemma exists_dist_le_lt (hδ : 0 ≤ δ) (hε : 0 < ε) (h : dist x z < ε + δ) : ∃ y, dist x y ≤ δ ∧ dist y z < ε := begin refine (exists_dist_eq x z (div_nonneg hε.le $ add_nonneg hε.le hδ) (div_nonneg hδ $ add_nonneg hε.le hδ) $ by rw [←add_div, div_self (add_pos_of_pos_of_nonneg hε hδ).ne']).imp (λ y hy, _), rw [hy.1, hy.2, div_mul_comm, div_mul_comm ε], rw ←div_lt_one (add_pos_of_pos_of_nonneg hε hδ) at h, exact ⟨mul_le_of_le_one_left hδ h.le, mul_lt_of_lt_one_left hε h⟩, end -- This is also true for `ℚ`-normed spaces lemma exists_dist_lt_le (hδ : 0 < δ) (hε : 0 ≤ ε) (h : dist x z < ε + δ) : ∃ y, dist x y < δ ∧ dist y z ≤ ε := begin obtain ⟨y, yz, xy⟩ := exists_dist_le_lt hε hδ (show dist z x < δ + ε, by simpa only [dist_comm, add_comm] using h), exact ⟨y, by simp [dist_comm x y, dist_comm y z, *]⟩, end -- This is also true for `ℚ`-normed spaces lemma exists_dist_lt_lt (hδ : 0 < δ) (hε : 0 < ε) (h : dist x z < ε + δ) : ∃ y, dist x y < δ ∧ dist y z < ε := begin refine (exists_dist_eq x z (div_nonneg hε.le $ add_nonneg hε.le hδ.le) (div_nonneg hδ.le $ add_nonneg hε.le hδ.le) $ by rw [←add_div, div_self (add_pos hε hδ).ne']).imp (λ y hy, _), rw [hy.1, hy.2, div_mul_comm, div_mul_comm ε], rw ←div_lt_one (add_pos hε hδ) at h, exact ⟨mul_lt_of_lt_one_left hδ h, mul_lt_of_lt_one_left hε h⟩, end -- This is also true for `ℚ`-normed spaces lemma disjoint_ball_ball_iff (hδ : 0 < δ) (hε : 0 < ε) : disjoint (ball x δ) (ball y ε) ↔ δ + ε ≤ dist x y := begin refine ⟨λ h, le_of_not_lt $ λ hxy, _, ball_disjoint_ball⟩, rw add_comm at hxy, obtain ⟨z, hxz, hzy⟩ := exists_dist_lt_lt hδ hε hxy, rw dist_comm at hxz, exact h.le_bot ⟨hxz, hzy⟩, end -- This is also true for `ℚ`-normed spaces lemma disjoint_ball_closed_ball_iff (hδ : 0 < δ) (hε : 0 ≤ ε) : disjoint (ball x δ) (closed_ball y ε) ↔ δ + ε ≤ dist x y := begin refine ⟨λ h, le_of_not_lt $ λ hxy, _, ball_disjoint_closed_ball⟩, rw add_comm at hxy, obtain ⟨z, hxz, hzy⟩ := exists_dist_lt_le hδ hε hxy, rw dist_comm at hxz, exact h.le_bot ⟨hxz, hzy⟩, end -- This is also true for `ℚ`-normed spaces lemma disjoint_closed_ball_ball_iff (hδ : 0 ≤ δ) (hε : 0 < ε) : disjoint (closed_ball x δ) (ball y ε) ↔ δ + ε ≤ dist x y := by rw [disjoint.comm, disjoint_ball_closed_ball_iff hε hδ, add_comm, dist_comm]; apply_instance lemma disjoint_closed_ball_closed_ball_iff (hδ : 0 ≤ δ) (hε : 0 ≤ ε) : disjoint (closed_ball x δ) (closed_ball y ε) ↔ δ + ε < dist x y := begin refine ⟨λ h, lt_of_not_ge $ λ hxy, _, closed_ball_disjoint_closed_ball⟩, rw add_comm at hxy, obtain ⟨z, hxz, hzy⟩ := exists_dist_le_le hδ hε hxy, rw dist_comm at hxz, exact h.le_bot ⟨hxz, hzy⟩, end open emetric ennreal @[simp] lemma inf_edist_thickening (hδ : 0 < δ) (s : set E) (x : E) : inf_edist x (thickening δ s) = inf_edist x s - ennreal.of_real δ := begin obtain hs | hs := lt_or_le (inf_edist x s) (ennreal.of_real δ), { rw [inf_edist_zero_of_mem, tsub_eq_zero_of_le hs.le], exact hs }, refine (tsub_le_iff_right.2 inf_edist_le_inf_edist_thickening_add).antisymm' _, refine le_sub_of_add_le_right of_real_ne_top _, refine le_inf_edist.2 (λ z hz, le_of_forall_lt' $ λ r h, _), cases r, { exact add_lt_top.2 ⟨lt_top_iff_ne_top.2 $ inf_edist_ne_top ⟨z, self_subset_thickening hδ _ hz⟩, of_real_lt_top⟩ }, have hr : 0 < ↑r - δ, { refine sub_pos_of_lt _, have := hs.trans_lt ((inf_edist_le_edist_of_mem hz).trans_lt h), rw [of_real_eq_coe_nnreal hδ.le, some_eq_coe] at this, exact_mod_cast this }, rw [some_eq_coe, edist_lt_coe, ←dist_lt_coe, ←add_sub_cancel'_right δ (↑r)] at h, obtain ⟨y, hxy, hyz⟩ := exists_dist_lt_lt hr hδ h, refine (ennreal.add_lt_add_right of_real_ne_top $ inf_edist_lt_iff.2 ⟨_, mem_thickening_iff.2 ⟨_, hz, hyz⟩, edist_lt_of_real.2 hxy⟩).trans_le _, rw [←of_real_add hr.le hδ.le, sub_add_cancel, of_real_coe_nnreal], exact le_rfl, end @[simp] lemma thickening_thickening (hε : 0 < ε) (hδ : 0 < δ) (s : set E) : thickening ε (thickening δ s) = thickening (ε + δ) s := (thickening_thickening_subset _ _ _).antisymm $ λ x, begin simp_rw mem_thickening_iff, rintro ⟨z, hz, hxz⟩, rw add_comm at hxz, obtain ⟨y, hxy, hyz⟩ := exists_dist_lt_lt hε hδ hxz, exact ⟨y, ⟨_, hz, hyz⟩, hxy⟩, end @[simp] lemma cthickening_thickening (hε : 0 ≤ ε) (hδ : 0 < δ) (s : set E) : cthickening ε (thickening δ s) = cthickening (ε + δ) s := (cthickening_thickening_subset hε _ _).antisymm $ λ x, begin simp_rw [mem_cthickening_iff, ennreal.of_real_add hε hδ.le, inf_edist_thickening hδ], exact tsub_le_iff_right.2, end -- Note: `interior (cthickening δ s) ≠ thickening δ s` in general @[simp] lemma closure_thickening (hδ : 0 < δ) (s : set E) : closure (thickening δ s) = cthickening δ s := by { rw [←cthickening_zero, cthickening_thickening le_rfl hδ, zero_add], apply_instance } @[simp] lemma inf_edist_cthickening (δ : ℝ) (s : set E) (x : E) : inf_edist x (cthickening δ s) = inf_edist x s - ennreal.of_real δ := begin obtain hδ | hδ := le_or_lt δ 0, { rw [cthickening_of_nonpos hδ, inf_edist_closure, of_real_of_nonpos hδ, tsub_zero] }, { rw [←closure_thickening hδ, inf_edist_closure, inf_edist_thickening hδ]; apply_instance } end @[simp] lemma thickening_cthickening (hε : 0 < ε) (hδ : 0 ≤ δ) (s : set E) : thickening ε (cthickening δ s) = thickening (ε + δ) s := begin obtain rfl | hδ := hδ.eq_or_lt, { rw [cthickening_zero, thickening_closure, add_zero] }, { rw [←closure_thickening hδ, thickening_closure, thickening_thickening hε hδ]; apply_instance } end @[simp] lemma cthickening_cthickening (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (s : set E) : cthickening ε (cthickening δ s) = cthickening (ε + δ) s := (cthickening_cthickening_subset hε hδ _).antisymm $ λ x, begin simp_rw [mem_cthickening_iff, ennreal.of_real_add hε hδ, inf_edist_cthickening], exact tsub_le_iff_right.2, end @[simp] lemma thickening_ball (hε : 0 < ε) (hδ : 0 < δ) (x : E) : thickening ε (ball x δ) = ball x (ε + δ) := by rw [←thickening_singleton, thickening_thickening hε hδ, thickening_singleton]; apply_instance @[simp] lemma thickening_closed_ball (hε : 0 < ε) (hδ : 0 ≤ δ) (x : E) : thickening ε (closed_ball x δ) = ball x (ε + δ) := by rw [←cthickening_singleton _ hδ, thickening_cthickening hε hδ, thickening_singleton]; apply_instance @[simp] lemma cthickening_ball (hε : 0 ≤ ε) (hδ : 0 < δ) (x : E) : cthickening ε (ball x δ) = closed_ball x (ε + δ) := by rw [←thickening_singleton, cthickening_thickening hε hδ, cthickening_singleton _ (add_nonneg hε hδ.le)]; apply_instance @[simp] lemma cthickening_closed_ball (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (x : E) : cthickening ε (closed_ball x δ) = closed_ball x (ε + δ) := by rw [←cthickening_singleton _ hδ, cthickening_cthickening hε hδ, cthickening_singleton _ (add_nonneg hε hδ)]; apply_instance lemma ball_add_ball (hε : 0 < ε) (hδ : 0 < δ) (a b : E) : ball a ε + ball b δ = ball (a + b) (ε + δ) := by rw [ball_add, thickening_ball hε hδ b, metric.vadd_ball, vadd_eq_add] lemma ball_sub_ball (hε : 0 < ε) (hδ : 0 < δ) (a b : E) : ball a ε - ball b δ = ball (a - b) (ε + δ) := by simp_rw [sub_eq_add_neg, neg_ball, ball_add_ball hε hδ] lemma ball_add_closed_ball (hε : 0 < ε) (hδ : 0 ≤ δ) (a b : E) : ball a ε + closed_ball b δ = ball (a + b) (ε + δ) := by rw [ball_add, thickening_closed_ball hε hδ b, metric.vadd_ball, vadd_eq_add] lemma ball_sub_closed_ball (hε : 0 < ε) (hδ : 0 ≤ δ) (a b : E) : ball a ε - closed_ball b δ = ball (a - b) (ε + δ) := by simp_rw [sub_eq_add_neg, neg_closed_ball, ball_add_closed_ball hε hδ] lemma closed_ball_add_ball (hε : 0 ≤ ε) (hδ : 0 < δ) (a b : E) : closed_ball a ε + ball b δ = ball (a + b) (ε + δ) := by rw [add_comm, ball_add_closed_ball hδ hε b, add_comm, add_comm δ] lemma closed_ball_sub_ball (hε : 0 ≤ ε) (hδ : 0 < δ) (a b : E) : closed_ball a ε - ball b δ = ball (a - b) (ε + δ) := by simp_rw [sub_eq_add_neg, neg_ball, closed_ball_add_ball hε hδ] lemma closed_ball_add_closed_ball [proper_space E] (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (a b : E) : closed_ball a ε + closed_ball b δ = closed_ball (a + b) (ε + δ) := by rw [(is_compact_closed_ball _ _).add_closed_ball hδ b, cthickening_closed_ball hδ hε a, metric.vadd_closed_ball, vadd_eq_add, add_comm, add_comm δ] lemma closed_ball_sub_closed_ball [proper_space E] (hε : 0 ≤ ε) (hδ : 0 ≤ δ) (a b : E) : closed_ball a ε - closed_ball b δ = closed_ball (a - b) (ε + δ) := by simp_rw [sub_eq_add_neg, neg_closed_ball, closed_ball_add_closed_ball hε hδ] end seminormed_add_comm_group section normed_add_comm_group variables [normed_add_comm_group E] [normed_space 𝕜 E] theorem smul_closed_ball (c : 𝕜) (x : E) {r : ℝ} (hr : 0 ≤ r) : c • closed_ball x r = closed_ball (c • x) (‖c‖ * r) := begin rcases eq_or_ne c 0 with rfl|hc, { simp [hr, zero_smul_set, set.singleton_zero, ← nonempty_closed_ball] }, { exact smul_closed_ball' hc x r } end lemma smul_closed_unit_ball (c : 𝕜) : c • closed_ball (0 : E) (1 : ℝ) = closed_ball (0 : E) (‖c‖) := by rw [smul_closed_ball _ _ zero_le_one, smul_zero, mul_one] variables [normed_space ℝ E] /-- In a real normed space, the image of the unit closed ball under multiplication by a nonnegative number `r` is the closed ball of radius `r` with center at the origin. -/ lemma smul_closed_unit_ball_of_nonneg {r : ℝ} (hr : 0 ≤ r) : r • closed_ball 0 1 = closed_ball (0 : E) r := by rw [smul_closed_unit_ball, real.norm_of_nonneg hr] /-- In a nontrivial real normed space, a sphere is nonempty if and only if its radius is nonnegative. -/ @[simp] lemma normed_space.sphere_nonempty [nontrivial E] {x : E} {r : ℝ} : (sphere x r).nonempty ↔ 0 ≤ r := begin obtain ⟨y, hy⟩ := exists_ne x, refine ⟨λ h, nonempty_closed_ball.1 (h.mono sphere_subset_closed_ball), λ hr, ⟨r • ‖y - x‖⁻¹ • (y - x) + x, _⟩⟩, have : ‖y - x‖ ≠ 0, by simpa [sub_eq_zero], simp [norm_smul, this, real.norm_of_nonneg hr], end lemma smul_sphere [nontrivial E] (c : 𝕜) (x : E) {r : ℝ} (hr : 0 ≤ r) : c • sphere x r = sphere (c • x) (‖c‖ * r) := begin rcases eq_or_ne c 0 with rfl|hc, { simp [zero_smul_set, set.singleton_zero, hr] }, { exact smul_sphere' hc x r } end /-- Any ball `metric.ball x r`, `0 < r` is the image of the unit ball under `λ y, x + r • y`. -/ lemma affinity_unit_ball {r : ℝ} (hr : 0 < r) (x : E) : x +ᵥ r • ball 0 1 = ball x r := by rw [smul_unit_ball_of_pos hr, vadd_ball_zero] /-- Any closed ball `metric.closed_ball x r`, `0 ≤ r` is the image of the unit closed ball under `λ y, x + r • y`. -/ lemma affinity_unit_closed_ball {r : ℝ} (hr : 0 ≤ r) (x : E) : x +ᵥ r • closed_ball 0 1 = closed_ball x r := by rw [smul_closed_unit_ball, real.norm_of_nonneg hr, vadd_closed_ball_zero] end normed_add_comm_group
c46fcbd423ff5decdd39c6b7065f0c82bd16aa7b
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/binomialHeap.lean
c2aa052ac491d71ac0950c8cf6f556282c85ea33
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
561
lean
import Std open Std open BinomialHeap def h₁ : BinomialHeap Nat (· < ·) := BinomialHeap.ofList _ [2, 1, 3, 5, 4] def h₂ : BinomialHeap Nat (· < ·) := BinomialHeap.ofList _ [0, 1, 6] #eval h₁.head #eval h₁.tail.toList #eval h₁.deleteMin.map (·.fst) #eval h₁.deleteMin.map (·.snd.toList) #eval h₁.toList #eval h₁.toArray #eval h₁.toArrayUnordered.qsort (· < ·) #eval h₁.toListUnordered.toArray.qsort (· < ·) #eval h₁.insert 7 |>.toList #eval h₁.insert 0 |>.toList #eval h₁.insert 4 |>.toList #eval h₁.merge h₂ |>.toList
2b9b7319d180771ac54d6f1366e4ac4d7ed80511
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/degree/definitions.lean
60e1e96c701cfbeaf19052de1975597ec4be3852
[ "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
48,658
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.nat.with_bot import data.polynomial.induction import data.polynomial.monomial /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ noncomputable theory open finsupp finset open_locale big_operators classical polynomial namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b c d : R} {n m : ℕ} section semiring variables [semiring R] {p q r : R[X]} /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : R[X]) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : R[X], degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded R[X] := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : R[X]) : ℕ := (degree p).get_or_else 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : R[X]) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : R[X]) := leading_coeff p = (1 : R) @[nontriviality] lemma monic_of_subsingleton [subsingleton R] (p : R[X]) : monic p := subsingleton.elim _ _ lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : R[X]} (hp : p.monic) : leading_coeff p = 1 := hp lemma monic.coeff_nat_degree {p : R[X]} (hp : p.monic) : p.coeff p.nat_degree = 1 := hp @[simp] lemma degree_zero : degree (0 : R[X]) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : R[X]) = 0 := rfl @[simp] lemma coeff_nat_degree : coeff p (nat_degree p) = leading_coeff p := rfl lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ @[nontriviality] lemma degree_of_subsingleton [subsingleton R] : degree p = ⊥ := by rw [subsingleton.elim p 0, degree_zero] @[nontriviality] lemma nat_degree_of_subsingleton [subsingleton R] : nat_degree p = 0 := by rw [subsingleton.elim p 0, nat_degree_zero] lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : R[X]} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : R[X]} {n : ℕ} (hn : 0 < n) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : R[X]} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := with_bot.gi_get_or_else_bot.gc.le_u_l _ lemma nat_degree_eq_of_degree_eq [semiring S] {q : S[X]} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma le_nat_degree_of_mem_supp (a : ℕ) : a ∈ p.support → a ≤ nat_degree p:= le_nat_degree_of_ne_zero ∘ mem_support_iff.mp lemma degree_mono [semiring S] {f : R[X]} {g : S[X]} (h : f.support ⊆ g.support) : f.degree ≤ g.degree := finset.sup_mono h lemma supp_subset_range (h : nat_degree p < m) : p.support ⊆ finset.range m := λ n hn, mem_range.2 $ (le_nat_degree_of_mem_supp _ hn).trans_lt h lemma supp_subset_range_nat_degree_succ : p.support ⊆ finset.range (nat_degree p + 1) := supp_subset_range (nat.lt_succ_self _) lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end lemma degree_ne_of_nat_degree_ne {n : ℕ} : p.nat_degree ≠ n → degree p ≠ n := mt $ λ h, by rw [nat_degree, h, option.get_or_else_coe] theorem nat_degree_le_iff_degree_le {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ n := with_bot.get_or_else_bot_le_iff lemma nat_degree_lt_iff_degree_lt (hp : p ≠ 0) : p.nat_degree < n ↔ p.degree < ↑n := with_bot.get_or_else_bot_lt_iff $ degree_eq_bot.not.mpr hp alias polynomial.nat_degree_le_iff_degree_le ↔ .. lemma nat_degree_le_nat_degree [semiring S] {q : S[X]} (hpq : p.degree ≤ q.degree) : p.nat_degree ≤ q.nat_degree := with_bot.gi_get_or_else_bot.gc.monotone_l hpq @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := by { rw [degree, ← monomial_zero_left, support_monomial 0 _ ha, sup_singleton], refl } lemma degree_C_le : degree (C a) ≤ 0 := begin by_cases h : a = 0, { rw [h, C_0], exact bot_le }, { rw [degree_C h], exact le_rfl } end lemma degree_C_lt : degree (C a) < 1 := degree_C_le.trans_lt $ with_bot.coe_lt_coe.mpr zero_lt_one lemma degree_one_le : degree (1 : R[X]) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : R[X]) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : R[X]) = 0 := by simp only [←C_eq_nat_cast, nat_degree_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := by rw [degree, support_monomial _ _ ha]; refl @[simp] lemma degree_C_mul_X_pow (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← monomial_eq_C_mul_X, degree_monomial n ha] lemma degree_C_mul_X (ha : a ≠ 0) : degree (C a * X) = 1 := by simpa only [pow_one] using degree_C_mul_X_pow 1 ha lemma degree_monomial_le (n : ℕ) (a : R) : degree (monomial n a) ≤ n := if h : a = 0 then by rw [h, (monomial n).map_zero]; exact bot_le else le_of_eq (degree_monomial n h) lemma degree_C_mul_X_pow_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := by { rw C_mul_X_pow_eq_monomial, apply degree_monomial_le } lemma degree_C_mul_X_le (a : R) : degree (C a * X) ≤ 1 := by simpa only [pow_one] using degree_C_mul_X_pow_le 1 a @[simp] lemma nat_degree_C_mul_X_pow (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha) @[simp] lemma nat_degree_C_mul_X (a : R) (ha : a ≠ 0) : nat_degree (C a * X) = 1 := by simpa only [pow_one] using nat_degree_C_mul_X_pow 1 a ha @[simp] lemma nat_degree_monomial [decidable_eq R] (i : ℕ) (r : R) : nat_degree (monomial i r) = if r = 0 then 0 else i := begin split_ifs with hr, { simp [hr] }, { rw [← C_mul_X_pow_eq_monomial, nat_degree_C_mul_X_pow i r hr] } end lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : R[X]} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end @[simp] lemma coeff_nat_degree_succ_eq_zero {p : R[X]} : p.coeff (p.nat_degree + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one _) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : R[X]) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite _ (n < 1 + nat_degree p) I (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum_support (p : R[X]) : p = ∑ i in p.support, monomial i (p.coeff i) := (sum_monomial_eq p).symm lemma as_sum_support_C_mul_X_pow (p : R[X]) : p = ∑ i in p.support, C (p.coeff i) * X^i := trans p.as_sum_support $ by simp only [C_mul_X_pow_eq_monomial] /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ lemma sum_over_range' [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) (n : ℕ) (w : p.nat_degree < n) : p.sum f = ∑ (a : ℕ) in range n, f a (coeff p a) := begin rcases p, have := supp_subset_range w, simp only [polynomial.sum, support, coeff, nat_degree, degree] at ⊢ this, exact finsupp.sum_of_support_subset _ this _ (λ n hn, h n) end /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ lemma sum_over_range [add_comm_monoid S] (p : R[X]) {f : ℕ → R → S} (h : ∀ n, f n 0 = 0) : p.sum f = ∑ (a : ℕ) in range (p.nat_degree + 1), f a (coeff p a) := sum_over_range' p h (p.nat_degree + 1) (lt_add_one _) -- TODO this is essentially a duplicate of `sum_over_range`, and should be removed. lemma sum_fin [add_comm_monoid S] (f : ℕ → R → S) (hf : ∀ i, f i 0 = 0) {n : ℕ} {p : R[X]} (hn : p.degree < n) : ∑ (i : fin n), f i (p.coeff i) = p.sum f := begin by_cases hp : p = 0, { rw [hp, sum_zero_index, finset.sum_eq_zero], intros i _, exact hf i }, rw [sum_over_range' _ hf n ((nat_degree_lt_iff_degree_lt hp).mpr hn), fin.sum_univ_eq_sum_range (λ i, f i (p.coeff i))], end lemma as_sum_range' (p : R[X]) (n : ℕ) (w : p.nat_degree < n) : p = ∑ i in range n, monomial i (coeff p i) := p.sum_monomial_eq.symm.trans $ p.sum_over_range' monomial_zero_right _ w lemma as_sum_range (p : R[X]) : p = ∑ i in range (p.nat_degree + 1), monomial i (coeff p i) := p.sum_monomial_eq.symm.trans $ p.sum_over_range $ monomial_zero_right lemma as_sum_range_C_mul_X_pow (p : R[X]) : p = ∑ i in range (p.nat_degree + 1), C (coeff p i) * X ^ i := p.as_sum_range.trans $ by simp only [C_mul_X_pow_eq_monomial] lemma coeff_ne_zero_of_eq_degree (hn : degree p = n) : coeff p n ≠ 0 := λ h, mem_support_iff.mp (mem_of_max hn) h lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_rfl)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) lemma eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := eq_X_add_C_of_degree_le_one $ degree_le_of_nat_degree_le h lemma exists_eq_X_add_C_of_nat_degree_le_one (h : nat_degree p ≤ 1) : ∃ a b, p = C a * X + C b := ⟨p.coeff 1, p.coeff 0, eq_X_add_C_of_nat_degree_le_one h⟩ theorem degree_X_pow_le (n : ℕ) : degree (X^n : R[X]) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le n (1:R) theorem degree_X_le : degree (X : R[X]) ≤ 1 := degree_monomial_le _ _ lemma nat_degree_X_le : (X : R[X]).nat_degree ≤ 1 := nat_degree_le_of_degree_le degree_X_le lemma support_C_mul_X_pow (c : R) (n : ℕ) : (C c * X ^ n).support ⊆ singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_monomial' _ _ end lemma mem_support_C_mul_X_pow {n a : ℕ} {c : R} (h : a ∈ (C c * X ^ n).support) : a = n := mem_singleton.1 $ support_C_mul_X_pow _ _ h lemma card_support_C_mul_X_pow_le_one {c : R} {n : ℕ} : (C c * X ^ n).support.card ≤ 1 := begin rw ← card_singleton n, apply card_le_of_subset (support_C_mul_X_pow c n), end lemma card_supp_le_succ_nat_degree (p : R[X]) : p.support.card ≤ p.nat_degree + 1 := begin rw ← finset.card_range (p.nat_degree + 1), exact finset.card_le_of_subset supp_subset_range_nat_degree_succ, end lemma le_degree_of_mem_supp (a : ℕ) : a ∈ p.support → ↑a ≤ degree p := le_degree_of_ne_zero ∘ mem_support_iff.mp lemma nonempty_support_iff : p.support.nonempty ↔ p ≠ 0 := by rw [ne.def, nonempty_iff_ne_empty, ne.def, ← support_eq_empty] lemma support_C_mul_X_pow_nonzero {c : R} {n : ℕ} (h : c ≠ 0) : (C c * X ^ n).support = singleton n := begin rw [C_mul_X_pow_eq_monomial], exact support_monomial _ _ h end end semiring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma degree_one : degree (1 : R[X]) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : R[X]) = 1 := degree_monomial _ one_ne_zero @[simp] lemma nat_degree_X : (X : R[X]).nat_degree = 1 := nat_degree_eq_of_degree_eq_some degree_X end nonzero_semiring section ring variables [ring R] lemma coeff_mul_X_sub_C {p : R[X]} {r : R} {a : ℕ} : coeff (p * (X - C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := by simp [mul_sub] @[simp] lemma degree_neg (p : R[X]) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : R[X]) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : R[X]) = 0 := by simp only [←C_eq_int_cast, nat_degree_C] end ring section semiring variables [semiring R] /-- The second-highest coefficient, or 0 for constants -/ def next_coeff (p : R[X]) : R := if p.nat_degree = 0 then 0 else p.coeff (p.nat_degree - 1) @[simp] lemma next_coeff_C_eq_zero (c : R) : next_coeff (C c) = 0 := by { rw next_coeff, simp } lemma next_coeff_of_pos_nat_degree (p : R[X]) (hp : 0 < p.nat_degree) : next_coeff p = p.coeff (p.nat_degree - 1) := by { rw [next_coeff, if_neg], contrapose! hp, simpa } variables {p q : R[X]} {ι : Type*} lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma ne_zero_of_degree_ge_degree (hpq : p.degree ≤ q.degree) (hp : p ≠ 0) : q ≠ 0 := polynomial.ne_zero_of_degree_gt (lt_of_lt_of_le (bot_lt_iff_ne_bot.mpr (by rwa [ne.def, polynomial.degree_eq_bot])) hpq : q.degree > ⊥) lemma ne_zero_of_nat_degree_gt {n : ℕ} (h : n < nat_degree p) : p ≠ 0 := λ H, by simpa [H, nat.not_lt_zero] using h lemma degree_lt_degree (h : nat_degree p < nat_degree q) : degree p < degree q := begin by_cases hp : p = 0, { simp [hp], rw bot_lt_iff_ne_bot, intro hq, simpa [hp, degree_eq_bot.mp hq, lt_irrefl] using h }, { rw [degree_eq_nat_degree hp, degree_eq_nat_degree $ ne_zero_of_nat_degree_gt h], exact_mod_cast h } end lemma nat_degree_lt_nat_degree_iff (hp : p ≠ 0) : nat_degree p < nat_degree q ↔ degree p < degree q := ⟨degree_lt_degree, begin intro h, have hq : q ≠ 0 := ne_zero_of_degree_gt h, rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq] at h, exact_mod_cast h end⟩ lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin ext (_|n), { simp }, rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt], exact h.trans_lt (with_bot.some_lt_some.2 n.succ_pos), end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_rfl) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : R[X]) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : sup_union lemma degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : degree p ≤ n) (hq : degree q ≤ n) : degree (p + q) ≤ n := (degree_add_le p q).trans $ max_le hp hq lemma nat_degree_add_le (p q : R[X]) : nat_degree (p + q) ≤ max (nat_degree p) (nat_degree q) := begin cases le_max_iff.1 (degree_add_le p q); simp [nat_degree_le_nat_degree h] end lemma nat_degree_add_le_of_degree_le {p q : R[X]} {n : ℕ} (hp : nat_degree p ≤ n) (hq : nat_degree q ≤ n) : nat_degree (p + q) ≤ n := (nat_degree_add_le p q).trans $ max_le hp hq @[simp] lemma leading_coeff_zero : leading_coeff (0 : R[X]) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_ne_zero : leading_coeff p ≠ 0 ↔ p ≠ 0 := by rw [ne.def, leading_coeff_eq_zero] lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma nat_degree_mem_support_of_nonzero (H : p ≠ 0) : p.nat_degree ∈ p.support := by { rw mem_support_iff, exact (not_congr leading_coeff_eq_zero).mpr H } lemma nat_degree_eq_support_max' (h : p ≠ 0) : p.nat_degree = p.support.max' (nonempty_support_iff.mpr h) := (le_max' _ _ $ nat_degree_mem_support_of_nonzero h).antisymm $ max'_le _ _ _ le_nat_degree_of_mem_supp lemma nat_degree_C_mul_X_pow_le (a : R) (n : ℕ) : nat_degree (C a * X ^ n) ≤ n := nat_degree_le_iff_degree_le.2 $ degree_C_mul_X_pow_le _ _ lemma degree_add_eq_left_of_degree_lt (h : degree q < degree p) : degree (p + q) = degree p := le_antisymm (max_eq_left_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, add_zero], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_right_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := by rw [add_comm, degree_add_eq_left_of_degree_lt h] lemma nat_degree_add_eq_left_of_nat_degree_lt (h : nat_degree q < nat_degree p) : nat_degree (p + q) = nat_degree p := nat_degree_eq_of_degree_eq (degree_add_eq_left_of_degree_lt (degree_lt_degree h)) lemma nat_degree_add_eq_right_of_nat_degree_lt (h : nat_degree p < nat_degree q) : nat_degree (p + q) = nat_degree q := nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt (degree_lt_degree h)) lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_right_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_right_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_rfl | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [degree_add_eq_left_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_rfl end lemma degree_erase_le (p : R[X]) (n : ℕ) : degree (p.erase n) ≤ degree p := by { rcases p, simp only [erase, degree, coeff, support], convert sup_mono (erase_subset _ _) } lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := begin apply lt_of_le_of_ne (degree_erase_le _ _), rw [degree_eq_nat_degree hp, degree, support_erase], exact λ h, not_mem_erase _ _ (mem_of_max h), end lemma degree_update_le (p : R[X]) (n : ℕ) (a : R) : degree (p.update n a) ≤ max (degree p) n := begin simp only [degree, coeff_update_apply, le_max_iff, finset.sup_le_iff, mem_support_iff], intros b hb, split_ifs at hb with h, { subst b, exact or.inr le_rfl }, { exact or.inl (le_degree_of_ne_zero hb) } end lemma degree_sum_le (s : finset ι) (f : ι → R[X]) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, sup_eq_max]; exact max_le_max le_rfl ih lemma degree_mul_le (p q : R[X]) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : begin simp only [monomial_eq_C_mul_X.symm], convert degree_sum_le _ _, exact mul_eq_sum_sum end ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_C_mul_X_pow_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : R[X]) : ∀ (n : ℕ), degree (p ^ n) ≤ n • (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add le_rfl (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (monomial n a) = a := begin by_cases ha : a = 0, { simp only [ha, (monomial n).map_zero, leading_coeff_zero] }, { rw [leading_coeff, nat_degree_monomial, if_neg ha, coeff_monomial], simp } end lemma leading_coeff_C_mul_X_pow (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := by rw [C_mul_X_pow_eq_monomial, leading_coeff_monomial] lemma leading_coeff_C_mul_X (a : R) : leading_coeff (C a * X) = a := by simpa only [pow_one] using leading_coeff_C_mul_X_pow a 1 @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X_pow (n : ℕ) : leading_coeff ((X : R[X]) ^ n) = 1 := by simpa only [C_1, one_mul] using leading_coeff_C_mul_X_pow (1 : R) n @[simp] lemma leading_coeff_X : leading_coeff (X : R[X]) = 1 := by simpa only [pow_one] using @leading_coeff_X_pow R _ 1 @[simp] lemma monic_X_pow (n : ℕ) : monic (X ^ n : R[X]) := leading_coeff_X_pow n @[simp] lemma monic_X : monic (X : R[X]) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : R[X]) = 1 := leading_coeff_C 1 @[simp] lemma monic_one : monic (1 : R[X]) := leading_coeff_C _ lemma monic.ne_zero {R : Type*} [semiring R] [nontrivial R] {p : R[X]} (hp : p.monic) : p ≠ 0 := by { rintro rfl, simpa [monic] using hp } lemma monic.ne_zero_of_ne (h : (0:R) ≠ 1) {p : R[X]} (hp : p.monic) : p ≠ 0 := by { nontriviality R, exact hp.ne_zero } lemma monic.ne_zero_of_polynomial_ne {r} (hp : monic p) (hne : q ≠ r) : p ≠ 0 := by { haveI := nontrivial.of_polynomial_ne hne, exact hp.ne_zero } lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_right_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : R[X]) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma monic.degree_mul (hq : monic q) : degree (p * q) = degree p + degree q := if hp : p = 0 then by simp [hp] else degree_mul' $ by rwa [hq.leading_coeff, mul_one, ne.def, leading_coeff_eq_zero] lemma nat_degree_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), nat_degree_eq_of_degree_eq_some $ by rw [degree_mul' h, with_bot.coe_add, degree_eq_nat_degree hp, degree_eq_nat_degree hq] lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul' h, coeff_mul_degree_add_degree], refl end lemma monomial_nat_degree_leading_coeff_eq_self (h : p.support.card ≤ 1) : monomial p.nat_degree p.leading_coeff = p := begin rcases card_support_le_one_iff_monomial.1 h with ⟨n, a, rfl⟩, by_cases ha : a = 0; simp [ha] end lemma C_mul_X_pow_eq_self (h : p.support.card ≤ 1) : C p.leading_coeff * X^p.nat_degree = p := by rw [C_mul_X_pow_eq_monomial, monomial_nat_degree_leading_coeff_eq_self h] lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow' : ∀ {n : ℕ}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n • (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul' h₂, succ_nsmul, degree_pow' h₁] lemma nat_degree_pow' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp theorem leading_coeff_monic_mul {p q : R[X]} (hp : monic p) : leading_coeff (p * q) = leading_coeff q := begin rcases eq_or_ne q 0 with rfl|H, { simp }, { rw [leading_coeff_mul', hp.leading_coeff, one_mul], rwa [hp.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero] } end theorem leading_coeff_mul_monic {p q : R[X]} (hq : monic q) : leading_coeff (p * q) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', hq.leading_coeff, mul_one]; rwa [hq.leading_coeff, mul_one]) @[simp] theorem leading_coeff_mul_X_pow {p : R[X]} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := leading_coeff_mul_monic (monic_X_pow n) @[simp] theorem leading_coeff_mul_X {p : R[X]} : leading_coeff (p * X) = leading_coeff p := leading_coeff_mul_monic monic_X lemma nat_degree_mul_le {p q : R[X]} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := begin apply nat_degree_le_of_degree_le, apply le_trans (degree_mul_le p q), rw with_bot.coe_add, refine add_le_add _ _; apply degree_le_nat_degree, end lemma nat_degree_pow_le {p : R[X]} {n : ℕ} : (p ^ n).nat_degree ≤ n * p.nat_degree := begin induction n with i hi, { simp }, { rw [pow_succ, nat.succ_mul, add_comm], apply le_trans nat_degree_mul_le, exact add_le_add_left hi _ } end @[simp] lemma coeff_pow_mul_nat_degree (p : R[X]) (n : ℕ) : (p ^ n).coeff (n * p.nat_degree) = p.leading_coeff ^ n := begin induction n with i hi, { simp }, { rw [pow_succ', pow_succ', nat.succ_mul], by_cases hp1 : p.leading_coeff ^ i = 0, { rw [hp1, zero_mul], by_cases hp2 : p ^ i = 0, { rw [hp2, zero_mul, coeff_zero] }, { apply coeff_eq_zero_of_nat_degree_lt, have h1 : (p ^ i).nat_degree < i * p.nat_degree, { apply lt_of_le_of_ne nat_degree_pow_le (λ h, hp2 _), rw [←h, hp1] at hi, exact leading_coeff_eq_zero.mp hi }, calc (p ^ i * p).nat_degree ≤ (p ^ i).nat_degree + p.nat_degree : nat_degree_mul_le ... < i * p.nat_degree + p.nat_degree : add_lt_add_right h1 _ } }, { rw [←nat_degree_pow' hp1, ←leading_coeff_pow' hp1], exact coeff_mul_degree_add_degree _ _ } } end lemma subsingleton_of_monic_zero (h : monic (0 : R[X])) : (∀ p q : R[X], p = q) ∧ (∀ a b : R, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma zero_le_degree_iff {p : R[X]} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := ⟨λ h0p hp0, absurd h0p (by rw [hp0, degree_zero]; exact dec_trivial), λ hp0, le_of_not_gt (λ h, by simp [gt, degree_eq_bot, *] at *)⟩ lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := by rw [← nonpos_iff_eq_zero, nat_degree_le_iff_degree_le, with_bot.coe_zero] theorem degree_le_iff_coeff_zero (f : R[X]) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ mem_support_iff.2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, mem_support_iff.1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem degree_lt_iff_coeff_zero (f : R[X]) (n : ℕ) : degree f < n ↔ ∀ m : ℕ, n ≤ m → coeff f m = 0 := begin refine ⟨λ hf m hm, coeff_eq_zero_of_degree_lt (lt_of_lt_of_le hf (with_bot.coe_le_coe.2 hm)), _⟩, simp only [degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, ← @not_le ℕ], exact λ h m, mt (h m), end lemma degree_smul_le (a : R) (p : R[X]) : degree (a • p) ≤ degree p := begin apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _), rw degree_lt_iff_coeff_zero at hm, simp [hm m le_rfl], end lemma nat_degree_smul_le (a : R) (p : R[X]) : nat_degree (a • p) ≤ nat_degree p := nat_degree_le_nat_degree (degree_smul_le a p) lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nontrivial.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma nat_degree_pos_iff_degree_pos : 0 < nat_degree p ↔ 0 < degree p := lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le lemma eq_C_of_nat_degree_le_zero (h : nat_degree p ≤ 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero $ degree_le_of_nat_degree_le h lemma eq_C_of_nat_degree_eq_zero (h : nat_degree p = 0) : p = C (coeff p 0) := eq_C_of_nat_degree_le_zero h.le lemma ne_zero_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : p ≠ 0 := by rw ← degree_nonneg_iff_ne_zero; exact trans (by exact_mod_cast n.zero_le) hdeg lemma le_nat_degree_of_coe_le_degree (hdeg : ↑n ≤ p.degree) : n ≤ p.nat_degree := with_bot.coe_le_coe.mp ((degree_eq_nat_degree $ ne_zero_of_coe_le_degree hdeg) ▸ hdeg) lemma degree_sum_fin_lt {n : ℕ} (f : fin n → R) : degree (∑ i : fin n, C (f i) * X ^ (i : ℕ)) < n := begin haveI : is_commutative (with_bot ℕ) max := ⟨max_comm⟩, haveI : is_associative (with_bot ℕ) max := ⟨max_assoc⟩, calc (∑ i, C (f i) * X ^ (i : ℕ)).degree ≤ finset.univ.fold (⊔) ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : degree_sum_le _ _ ... = finset.univ.fold max ⊥ (λ i, (C (f i) * X ^ (i : ℕ)).degree) : rfl ... < n : (finset.fold_max_lt (n : with_bot ℕ)).mpr ⟨with_bot.bot_lt_coe _, _⟩, rintros ⟨i, hi⟩ -, calc (C (f ⟨i, hi⟩) * X ^ i).degree ≤ (C _).degree + (X ^ i).degree : degree_mul_le _ _ ... ≤ 0 + i : add_le_add degree_C_le (degree_X_pow_le i) ... = i : zero_add _ ... < n : with_bot.some_lt_some.mpr hi, end lemma degree_linear_le : degree (C a * X + C b) ≤ 1 := degree_add_le_of_degree_le (degree_C_mul_X_le _) $ le_trans degree_C_le nat.with_bot.coe_nonneg lemma degree_linear_lt : degree (C a * X + C b) < 2 := degree_linear_le.trans_lt $ with_bot.coe_lt_coe.mpr one_lt_two lemma degree_C_lt_degree_C_mul_X (ha : a ≠ 0) : degree (C b) < degree (C a * X) := by simpa only [degree_C_mul_X ha] using degree_C_lt @[simp] lemma degree_linear (ha : a ≠ 0) : degree (C a * X + C b) = 1 := by rw [degree_add_eq_left_of_degree_lt $ degree_C_lt_degree_C_mul_X ha, degree_C_mul_X ha] lemma nat_degree_linear_le : nat_degree (C a * X + C b) ≤ 1 := nat_degree_le_of_degree_le degree_linear_le @[simp] lemma nat_degree_linear (ha : a ≠ 0) : nat_degree (C a * X + C b) = 1 := nat_degree_eq_of_degree_eq_some $ degree_linear ha @[simp] lemma leading_coeff_linear (ha : a ≠ 0): leading_coeff (C a * X + C b) = a := by rw [add_comm, leading_coeff_add_of_degree_lt (degree_C_lt_degree_C_mul_X ha), leading_coeff_C_mul_X] lemma degree_quadratic_le : degree (C a * X ^ 2 + C b * X + C c) ≤ 2 := by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 2 a) (le_trans degree_linear_le $ with_bot.coe_le_coe.mpr one_le_two) lemma degree_quadratic_lt : degree (C a * X ^ 2 + C b * X + C c) < 3 := degree_quadratic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 2 lemma degree_linear_lt_degree_C_mul_X_sq (ha : a ≠ 0) : degree (C b * X + C c) < degree (C a * X ^ 2) := by simpa only [degree_C_mul_X_pow 2 ha] using degree_linear_lt @[simp] lemma degree_quadratic (ha : a ≠ 0) : degree (C a * X ^ 2 + C b * X + C c) = 2 := begin rw [add_assoc, degree_add_eq_left_of_degree_lt $ degree_linear_lt_degree_C_mul_X_sq ha, degree_C_mul_X_pow 2 ha], refl end lemma nat_degree_quadratic_le : nat_degree (C a * X ^ 2 + C b * X + C c) ≤ 2 := nat_degree_le_of_degree_le degree_quadratic_le @[simp] lemma nat_degree_quadratic (ha : a ≠ 0) : nat_degree (C a * X ^ 2 + C b * X + C c) = 2 := nat_degree_eq_of_degree_eq_some $ degree_quadratic ha @[simp] lemma leading_coeff_quadratic (ha : a ≠ 0) : leading_coeff (C a * X ^ 2 + C b * X + C c) = a := by rw [add_assoc, add_comm, leading_coeff_add_of_degree_lt $ degree_linear_lt_degree_C_mul_X_sq ha, leading_coeff_C_mul_X_pow] lemma degree_cubic_le : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 := by simpa only [add_assoc] using degree_add_le_of_degree_le (degree_C_mul_X_pow_le 3 a) (le_trans degree_quadratic_le $ with_bot.coe_le_coe.mpr $ nat.le_succ 2) lemma degree_cubic_lt : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) < 4 := degree_cubic_le.trans_lt $ with_bot.coe_lt_coe.mpr $ lt_add_one 3 lemma degree_quadratic_lt_degree_C_mul_X_cb (ha : a ≠ 0) : degree (C b * X ^ 2 + C c * X + C d) < degree (C a * X ^ 3) := by simpa only [degree_C_mul_X_pow 3 ha] using degree_quadratic_lt @[simp] lemma degree_cubic (ha : a ≠ 0) : degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 := begin rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), degree_add_eq_left_of_degree_lt $ degree_quadratic_lt_degree_C_mul_X_cb ha, degree_C_mul_X_pow 3 ha], refl end lemma nat_degree_cubic_le : nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) ≤ 3 := nat_degree_le_of_degree_le degree_cubic_le @[simp] lemma nat_degree_cubic (ha : a ≠ 0) : nat_degree (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = 3 := nat_degree_eq_of_degree_eq_some $ degree_cubic ha @[simp] lemma leading_coeff_cubic (ha : a ≠ 0): leading_coeff (C a * X ^ 3 + C b * X ^ 2 + C c * X + C d) = a := by rw [add_assoc, add_assoc, ← add_assoc (C b * X ^ 2), add_comm, leading_coeff_add_of_degree_lt $ degree_quadratic_lt_degree_C_mul_X_cb ha, leading_coeff_C_mul_X_pow] end semiring section nontrivial_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma degree_X_pow (n : ℕ) : degree ((X : R[X]) ^ n) = n := by rw [X_pow_eq_monomial, degree_monomial _ (@one_ne_zero R _ _)] @[simp] lemma nat_degree_X_pow (n : ℕ) : nat_degree ((X : R[X]) ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_X_pow n) theorem not_is_unit_X : ¬ is_unit (X : R[X]) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by { change g * monomial 1 1 = 1 at hgf, rw [← coeff_one_zero, ← hgf], simp } @[simp] lemma degree_mul_X : degree (p * X) = degree p + 1 := by simp [monic_X.degree_mul] @[simp] lemma degree_mul_X_pow : degree (p * X ^ n) = degree p + n := by simp [(monic_X_pow n).degree_mul] end nontrivial_semiring section ring variables [ring R] {p q : R[X]} lemma degree_sub_le (p q : R[X]) : degree (p - q) ≤ max (degree p) (degree q) := by simpa only [sub_eq_add_neg, degree_neg q] using degree_add_le p (-q) lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : monomial (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := monomial_add_erase _ _, have hq : monomial (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := monomial_add_erase _ _, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv { to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg] } ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma nat_degree_X_sub_C_le {r : R} : (X - C r).nat_degree ≤ 1 := nat_degree_le_iff_degree_le.2 $ le_trans (degree_sub_le _ _) $ max_le degree_X_le $ le_trans degree_C_le $ with_bot.coe_le_coe.2 zero_le_one lemma degree_sub_eq_left_of_degree_lt (h : degree q < degree p) : degree (p - q) = degree p := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_left_of_degree_lt h] } lemma degree_sub_eq_right_of_degree_lt (h : degree p < degree q) : degree (p - q) = degree q := by { rw ← degree_neg q at h, rw [sub_eq_add_neg, degree_add_eq_right_of_degree_lt h, degree_neg] } end ring section nonzero_ring variables [nontrivial R] section semiring variable [semiring R] @[simp] lemma degree_X_add_C (a : R) : degree (X + C a) = 1 := have degree (C a) < degree (X : R[X]), from calc degree (C a) ≤ 0 : degree_C_le ... < 1 : with_bot.some_lt_some.mpr zero_lt_one ... = degree X : degree_X.symm, by rw [degree_add_eq_left_of_degree_lt this, degree_X] @[simp] lemma nat_degree_X_add_C (x : R) : (X + C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_add_C x @[simp] lemma next_coeff_X_add_C [semiring S] (c : S) : next_coeff (X + C c) = c := begin nontriviality S, simp [next_coeff_of_pos_nat_degree] end lemma degree_X_pow_add_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : R[X]) ^ n + C a) = n := have degree (C a) < degree ((X : R[X]) ^ n), from calc degree (C a) ≤ 0 : degree_C_le ... < degree ((X : R[X]) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [degree_add_eq_left_of_degree_lt this, degree_X_pow] lemma X_pow_add_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : R[X]) ^ n + C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : R[X]) ^ n + C a) ≠ ⊥, by rw degree_X_pow_add_C hn a; exact dec_trivial) theorem X_add_C_ne_zero (r : R) : X + C r ≠ 0 := pow_one (X : R[X]) ▸ X_pow_add_C_ne_zero zero_lt_one r theorem zero_nmem_multiset_map_X_add_C {α : Type*} (m : multiset α) (f : α → R) : (0 : R[X]) ∉ m.map (λ a, X + C (f a)) := λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_add_C_ne_zero _ ha lemma nat_degree_X_pow_add_C {n : ℕ} {r : R} : (X ^ n + C r).nat_degree = n := begin by_cases hn : n = 0, { rw [hn, pow_zero, ←C_1, ←ring_hom.map_add, nat_degree_C] }, { exact nat_degree_eq_of_degree_eq_some (degree_X_pow_add_C (pos_iff_ne_zero.mpr hn) r) }, end end semiring end nonzero_ring section semiring variable [semiring R] @[simp] lemma leading_coeff_X_pow_add_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n + C r).leading_coeff = 1 := begin nontriviality R, rw [leading_coeff, nat_degree_X_pow_add_C, coeff_add, coeff_X_pow_self, coeff_C, if_neg (pos_iff_ne_zero.mp hn), add_zero] end @[simp] lemma leading_coeff_X_add_C [semiring S] (r : S) : (X + C r).leading_coeff = 1 := by rw [←pow_one (X : S[X]), leading_coeff_X_pow_add_C zero_lt_one] @[simp] lemma leading_coeff_X_pow_add_one {n : ℕ} (hn : 0 < n) : (X ^ n + 1 : R[X]).leading_coeff = 1 := leading_coeff_X_pow_add_C hn @[simp] lemma leading_coeff_pow_X_add_C (r : R) (i : ℕ) : leading_coeff ((X + C r) ^ i) = 1 := by { nontriviality, rw leading_coeff_pow'; simp } end semiring section ring variable [ring R] @[simp] lemma leading_coeff_X_pow_sub_C {n : ℕ} (hn : 0 < n) {r : R} : (X ^ n - C r).leading_coeff = 1 := by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_pow_add_C hn]; apply_instance @[simp] lemma leading_coeff_X_pow_sub_one {n : ℕ} (hn : 0 < n) : (X ^ n - 1 : R[X]).leading_coeff = 1 := leading_coeff_X_pow_sub_C hn variables [nontrivial R] @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := by rw [sub_eq_add_neg, ←map_neg C a, degree_X_add_C] @[simp] lemma nat_degree_X_sub_C (x : R) : (X - C x).nat_degree = 1 := nat_degree_eq_of_degree_eq_some $ degree_X_sub_C x @[simp] lemma next_coeff_X_sub_C [ring S] (c : S) : next_coeff (X - C c) = - c := by rw [sub_eq_add_neg, ←map_neg C c, next_coeff_X_add_C] lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : R[X]) ^ n - C a) = n := by rw [sub_eq_add_neg, ←map_neg C a, degree_X_pow_add_C hn]; apply_instance lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : R[X]) ^ n - C a ≠ 0 := by { rw [sub_eq_add_neg, ←map_neg C a], exact X_pow_add_C_ne_zero hn _ } theorem X_sub_C_ne_zero (r : R) : X - C r ≠ 0 := pow_one (X : R[X]) ▸ X_pow_sub_C_ne_zero zero_lt_one r theorem zero_nmem_multiset_map_X_sub_C {α : Type*} (m : multiset α) (f : α → R) : (0 : R[X]) ∉ m.map (λ a, X - C (f a)) := λ mem, let ⟨a, _, ha⟩ := multiset.mem_map.mp mem in X_sub_C_ne_zero _ ha lemma nat_degree_X_pow_sub_C {n : ℕ} {r : R} : (X ^ n - C r).nat_degree = n := by rw [sub_eq_add_neg, ←map_neg C r, nat_degree_X_pow_add_C] @[simp] lemma leading_coeff_X_sub_C [ring S] (r : S) : (X - C r).leading_coeff = 1 := by rw [sub_eq_add_neg, ←map_neg C r, leading_coeff_X_add_C] end ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} @[simp] lemma degree_mul : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) /-- `degree` as a monoid homomorphism between `R[X]` and `multiplicative (with_bot ℕ)`. This is useful to prove results about multiplication and degree. -/ def degree_monoid_hom [nontrivial R] : R[X] →* multiplicative (with_bot ℕ) := { to_fun := degree, map_one' := degree_one, map_mul' := λ _ _, degree_mul } @[simp] lemma degree_pow [nontrivial R] (p : R[X]) (n : ℕ) : degree (p ^ n) = n • (degree p) := map_pow (@degree_monoid_hom R _ _ _) _ _ @[simp] lemma leading_coeff_mul (p q : R[X]) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` has `no_zero_divisors`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom : R[X] →* R := { to_fun := leading_coeff, map_one' := by simp, map_mul' := leading_coeff_mul } @[simp] lemma leading_coeff_hom_apply (p : R[X]) : leading_coeff_hom p = leading_coeff p := rfl @[simp] lemma leading_coeff_pow (p : R[X]) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := (leading_coeff_hom : R[X] →* R).map_pow p n end no_zero_divisors end polynomial
92548963821e197e435c4b16aa539a0169270eb9
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/str.lean
23900624f9631d7b7f44dccb1af1b813af396f50
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,007
lean
def showChars : Nat → String → String.Pos → IO Unit | 0, _, _ => pure () | n+1, s, idx => do unless s.atEnd idx do IO.println (">> " ++ toString (s.get idx)) *> showChars n s (s.next idx) def main : IO UInt32 := let s₁ := "hello α_world_β"; let b : String.Pos := 0; let e := s₁.endPos; IO.println (s₁.extract b e) *> IO.println (s₁.extract (b+ " ") e) *> IO.println (s₁.extract (b+ " ") (e-⟨1⟩)) *> IO.println (s₁.extract (b+⟨2⟩) (e-⟨2⟩)) *> IO.println (s₁.extract (b+⟨7⟩) e) *> IO.println (s₁.extract (b+⟨8⟩) e) *> IO.println (toString e) *> IO.println (repr " aaa ".trim) *> showChars s₁.length s₁ 0 *> IO.println ("abc".isPrefixOf "abcd") *> IO.println ("abcd".isPrefixOf "abcd") *> IO.println ("".isPrefixOf "abcd") *> IO.println ("".isPrefixOf "") *> IO.println ("ab".isPrefixOf "cb") *> IO.println ("ab".isPrefixOf "a") *> IO.println ("αb".isPrefixOf "αbc") *> IO.println ("\x00a").length *> pure 0
becdb8808b47001bdf18433bf82446e524c48bb3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/logic/equiv/list.lean
8a960fc4133689ceb61c4875fee9caaf9bf9bc7d
[ "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
14,180
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.finset.sort import data.vector.basic import logic.denumerable /-! # Equivalences involving `list`-like types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines some additional constructive equivalences using `encodable` and the pairing function on `ℕ`. -/ open nat list namespace encodable variables {α : Type*} section list variable [encodable α] /-- Explicit encoding function for `list α` -/ def encode_list : list α → ℕ | [] := 0 | (a::l) := succ (mkpair (encode a) (encode_list l)) /-- Explicit decoding function for `list α` -/ def decode_list : ℕ → option (list α) | 0 := some [] | (succ v) := match unpair v, unpair_right_le v with | (v₁, v₂), h := have v₂ < succ v, from lt_succ_of_le h, (::) <$> decode α v₁ <*> decode_list v₂ end /-- If `α` is encodable, then so is `list α`. This uses the `mkpair` and `unpair` functions from `data.nat.pairing`. -/ instance _root_.list.encodable : encodable (list α) := ⟨encode_list, decode_list, λ l, by induction l with a l IH; simp [encode_list, decode_list, unpair_mkpair, encodek, *]⟩ instance _root_.list.countable {α : Type*} [countable α] : countable (list α) := by { haveI := encodable.of_countable α, apply_instance } @[simp] theorem encode_list_nil : encode (@nil α) = 0 := rfl @[simp] theorem encode_list_cons (a : α) (l : list α) : encode (a :: l) = succ (mkpair (encode a) (encode l)) := rfl @[simp] theorem decode_list_zero : decode (list α) 0 = some [] := show decode_list 0 = some [], by rw decode_list @[simp] theorem decode_list_succ (v : ℕ) : decode (list α) (succ v) = (::) <$> decode α v.unpair.1 <*> decode (list α) v.unpair.2 := show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], refl end theorem length_le_encode : ∀ (l : list α), length l ≤ encode l | [] := _root_.zero_le _ | (a :: l) := succ_le_succ $ (length_le_encode l).trans (right_le_mkpair _ _) end list section finset variables [encodable α] private def enle : α → α → Prop := encode ⁻¹'o (≤) private lemma enle.is_linear_order : is_linear_order α enle := (rel_embedding.preimage ⟨encode, encode_injective⟩ (≤)).is_linear_order private def decidable_enle (a b : α) : decidable (enle a b) := by unfold enle order.preimage; apply_instance local attribute [instance] enle.is_linear_order decidable_enle /-- Explicit encoding function for `multiset α` -/ def encode_multiset (s : multiset α) : ℕ := encode (s.sort enle) /-- Explicit decoding function for `multiset α` -/ def decode_multiset (n : ℕ) : option (multiset α) := coe <$> decode (list α) n /-- If `α` is encodable, then so is `multiset α`. -/ instance _root_.multiset.encodable : encodable (multiset α) := ⟨encode_multiset, decode_multiset, λ s, by simp [encode_multiset, decode_multiset, encodek]⟩ /-- If `α` is countable, then so is `multiset α`. -/ instance _root_.multiset.countable {α : Type*} [countable α] : countable (multiset α) := quotient.countable end finset /-- A listable type with decidable equality is encodable. -/ def encodable_of_list [decidable_eq α] (l : list α) (H : ∀ x, x ∈ l) : encodable α := ⟨λ a, index_of a l, l.nth, λ a, index_of_nth (H _)⟩ /-- A finite type is encodable. Because the encoding is not unique, we wrap it in `trunc` to preserve computability. -/ def _root_.fintype.trunc_encodable (α : Type*) [decidable_eq α] [fintype α] : trunc (encodable α) := @@quot.rec_on_subsingleton _ (λ s : multiset α, (∀ x:α, x ∈ s) → trunc (encodable α)) _ finset.univ.1 (λ l H, trunc.mk $ encodable_of_list l H) finset.mem_univ /-- A noncomputable way to arbitrarily choose an ordering on a finite type. It is not made into a global instance, since it involves an arbitrary choice. This can be locally made into an instance with `local attribute [instance] fintype.to_encodable`. -/ noncomputable def _root_.fintype.to_encodable (α : Type*) [fintype α] : encodable α := by { classical, exact (fintype.trunc_encodable α).out } /-- If `α` is encodable, then so is `vector α n`. -/ instance _root_.vector.encodable [encodable α] {n} : encodable (vector α n) := subtype.encodable /-- If `α` is countable, then so is `vector α n`. -/ instance _root_.vector.countable [countable α] {n} : countable (vector α n) := subtype.countable /-- If `α` is encodable, then so is `fin n → α`. -/ instance fin_arrow [encodable α] {n} : encodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance fin_pi (n) (π : fin n → Type*) [∀ i, encodable (π i)] : encodable (Π i, π i) := of_equiv _ (equiv.pi_equiv_subtype_sigma (fin n) π) /-- If `α` is encodable, then so is `finset α`. -/ instance _root_.finset.encodable [encodable α] : encodable (finset α) := by haveI := decidable_eq_of_encodable α; exact of_equiv {s : multiset α // s.nodup} ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- If `α` is countable, then so is `finset α`. -/ instance _root_.finset.countable [countable α] : countable (finset α) := finset.val_injective.countable -- TODO: Unify with `fintype_pi` and find a better name /-- When `α` is finite and `β` is encodable, `α → β` is encodable too. Because the encoding is not unique, we wrap it in `trunc` to preserve computability. -/ def fintype_arrow (α : Type*) (β : Type*) [decidable_eq α] [fintype α] [encodable β] : trunc (encodable (α → β)) := (fintype.trunc_equiv_fin α).map $ λ f, encodable.of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr f (equiv.refl _) /-- When `α` is finite and all `π a` are encodable, `Π a, π a` is encodable too. Because the encoding is not unique, we wrap it in `trunc` to preserve computability. -/ def fintype_pi (α : Type*) (π : α → Type*) [decidable_eq α] [fintype α] [∀ a, encodable (π a)] : trunc (encodable (Π a, π a)) := (fintype.trunc_encodable α).bind $ λ a, (@fintype_arrow α (Σa, π a) _ _ (@sigma.encodable _ _ a _)).bind $ λ f, trunc.mk $ @encodable.of_equiv _ _ (@subtype.encodable _ _ f _) (equiv.pi_equiv_subtype_sigma α π) /-- The elements of a `fintype` as a sorted list. -/ def sorted_univ (α) [fintype α] [encodable α] : list α := finset.univ.sort (encodable.encode' α ⁻¹'o (≤)) @[simp] theorem mem_sorted_univ {α} [fintype α] [encodable α] (x : α) : x ∈ sorted_univ α := (finset.mem_sort _).2 (finset.mem_univ _) @[simp] theorem length_sorted_univ (α) [fintype α] [encodable α] : (sorted_univ α).length = fintype.card α := finset.length_sort _ @[simp] theorem sorted_univ_nodup (α) [fintype α] [encodable α] : (sorted_univ α).nodup := finset.sort_nodup _ _ @[simp] theorem sorted_univ_to_finset (α) [fintype α] [encodable α] [decidable_eq α] : (sorted_univ α).to_finset = finset.univ := finset.sort_to_finset _ _ /-- An encodable `fintype` is equivalent to the same size `fin`. -/ def fintype_equiv_fin {α} [fintype α] [encodable α] : α ≃ fin (fintype.card α) := begin haveI : decidable_eq α := encodable.decidable_eq_of_encodable _, transitivity, { exact ((sorted_univ_nodup α).nth_le_equiv_of_forall_mem_list _ mem_sorted_univ).symm }, exact equiv.cast (congr_arg _ (length_sorted_univ α)) end /-- If `α` and `β` are encodable and `α` is a fintype, then `α → β` is encodable as well. -/ instance fintype_arrow_of_encodable {α β : Type*} [encodable α] [fintype α] [encodable β] : encodable (α → β) := of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr fintype_equiv_fin (equiv.refl _) end encodable namespace denumerable variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable section list theorem denumerable_list_aux : ∀ n : ℕ, ∃ a ∈ @decode_list α _ n, encode_list a = n | 0 := by rw decode_list; exact ⟨_, rfl, rfl⟩ | (succ v) := begin cases e : unpair v with v₁ v₂, have h := unpair_right_le v, rw e at h, rcases have v₂ < succ v, from lt_succ_of_le h, denumerable_list_aux v₂ with ⟨a, h₁, h₂⟩, rw option.mem_def at h₁, use of_nat α v₁ :: a, simp [decode_list, e, h₂, h₁, encode_list, mkpair_unpair' e], end /-- If `α` is denumerable, then so is `list α`. -/ instance denumerable_list : denumerable (list α) := ⟨denumerable_list_aux⟩ @[simp] theorem list_of_nat_zero : of_nat (list α) 0 = [] := by rw [← @encode_list_nil α, of_nat_encode] @[simp] theorem list_of_nat_succ (v : ℕ) : of_nat (list α) (succ v) = of_nat α v.unpair.1 :: of_nat (list α) v.unpair.2 := of_nat_of_decode $ show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], rw [show decode_list v₂ = decode (list α) v₂, from rfl, decode_eq_of_nat]; refl end end list section multiset /-- Outputs the list of differences of the input list, that is `lower [a₁, a₂, ...] n = [a₁ - n, a₂ - a₁, ...]` -/ def lower : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower l m /-- Outputs the list of partial sums of the input list, that is `raise [a₁, a₂, ...] n = [n + a₁, n + a₁ + a₂, ...]` -/ def raise : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise l (m + n) lemma lower_raise : ∀ l n, lower (raise l n) n = l | [] n := rfl | (m :: l) n := by rw [raise, lower, add_tsub_cancel_right, lower_raise] lemma raise_lower : ∀ {l n}, list.sorted (≤) (n :: l) → raise (lower l n) n = l | [] n h := rfl | (m :: l) n h := have n ≤ m, from list.rel_of_sorted_cons h _ (l.mem_cons_self _), by simp [raise, lower, tsub_add_cancel_of_le this, raise_lower h.of_cons] lemma raise_chain : ∀ l n, list.chain (≤) n (raise l n) | [] n := list.chain.nil | (m :: l) n := list.chain.cons (nat.le_add_left _ _) (raise_chain _ _) /-- `raise l n` is an non-decreasing sequence. -/ lemma raise_sorted : ∀ l n, list.sorted (≤) (raise l n) | [] n := list.sorted_nil | (m :: l) n := list.chain_iff_pairwise.1 (raise_chain _ _) /-- If `α` is denumerable, then so is `multiset α`. Warning: this is *not* the same encoding as used in `multiset.encodable`. -/ instance multiset : denumerable (multiset α) := mk' ⟨ λ s : multiset α, encode $ lower ((s.map encode).sort (≤)) 0, λ n, multiset.map (of_nat α) (raise (of_nat (list ℕ) n) 0), λ s, by have := raise_lower (list.sorted_cons.2 ⟨λ n _, zero_le n, (s.map encode).sort_sorted _⟩); simp [-multiset.coe_map, this], λ n, by simp [-multiset.coe_map, list.merge_sort_eq_self _ (raise_sorted _ _), lower_raise]⟩ end multiset section finset /-- Outputs the list of differences minus one of the input list, that is `lower' [a₁, a₂, a₃, ...] n = [a₁ - n, a₂ - a₁ - 1, a₃ - a₂ - 1, ...]`. -/ def lower' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower' l (m + 1) /-- Outputs the list of partial sums plus one of the input list, that is `raise [a₁, a₂, a₃, ...] n = [n + a₁, n + a₁ + a₂ + 1, n + a₁ + a₂ + a₃ + 2, ...]`. Adding one each time ensures the elements are distinct. -/ def raise' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise' l (m + n + 1) lemma lower_raise' : ∀ l n, lower' (raise' l n) n = l | [] n := rfl | (m :: l) n := by simp [raise', lower', add_tsub_cancel_right, lower_raise'] lemma raise_lower' : ∀ {l n}, (∀ m ∈ l, n ≤ m) → list.sorted (<) l → raise' (lower' l n) n = l | [] n h₁ h₂ := rfl | (m :: l) n h₁ h₂ := have n ≤ m, from h₁ _ (l.mem_cons_self _), by simp [raise', lower', tsub_add_cancel_of_le this, raise_lower' (list.rel_of_sorted_cons h₂ : ∀ a ∈ l, m < a) h₂.of_cons] lemma raise'_chain : ∀ l {m n}, m < n → list.chain (<) m (raise' l n) | [] m n h := list.chain.nil | (a :: l) m n h := list.chain.cons (lt_of_lt_of_le h (nat.le_add_left _ _)) (raise'_chain _ (lt_succ_self _)) /-- `raise' l n` is a strictly increasing sequence. -/ lemma raise'_sorted : ∀ l n, list.sorted (<) (raise' l n) | [] n := list.sorted_nil | (m :: l) n := list.chain_iff_pairwise.1 (raise'_chain _ (lt_succ_self _)) /-- Makes `raise' l n` into a finset. Elements are distinct thanks to `raise'_sorted`. -/ def raise'_finset (l : list ℕ) (n : ℕ) : finset ℕ := ⟨raise' l n, (raise'_sorted _ _).imp (@ne_of_lt _ _)⟩ /-- If `α` is denumerable, then so is `finset α`. Warning: this is *not* the same encoding as used in `finset.encodable`. -/ instance finset : denumerable (finset α) := mk' ⟨ λ s : finset α, encode $ lower' ((s.map (eqv α).to_embedding).sort (≤)) 0, λ n, finset.map (eqv α).symm.to_embedding (raise'_finset (of_nat (list ℕ) n) 0), λ s, finset.eq_of_veq $ by simp [-multiset.coe_map, raise'_finset, raise_lower' (λ n _, zero_le n) (finset.sort_sorted_lt _)], λ n, by simp [-multiset.coe_map, finset.map, raise'_finset, finset.sort, list.merge_sort_eq_self (≤) ((raise'_sorted _ _).imp (@le_of_lt _ _)), lower_raise']⟩ end finset end denumerable namespace equiv /-- The type lists on unit is canonically equivalent to the natural numbers. -/ def list_unit_equiv : list unit ≃ ℕ := { to_fun := list.length, inv_fun := λ n, list.replicate n (), left_inv := λ u, list.length_injective (by simp), right_inv := λ n, list.length_replicate n () } /-- `list ℕ` is equivalent to `ℕ`. -/ def list_nat_equiv_nat : list ℕ ≃ ℕ := denumerable.eqv _ /-- If `α` is equivalent to `ℕ`, then `list α` is equivalent to `α`. -/ def list_equiv_self_of_equiv_nat {α : Type*} (e : α ≃ ℕ) : list α ≃ α := calc list α ≃ list ℕ : list_equiv_of_equiv e ... ≃ ℕ : list_nat_equiv_nat ... ≃ α : e.symm end equiv
05b508a40b1bc1a787b6221f90c698e1d2e78114
b8cef56e45969061d92fdcef0878a2e611938718
/src/bad.lean
861febe6672b6f03a72cc47b81bd768cb04f158d
[]
no_license
leanprover-contrib/test-repo-1
259ae7a4f5e12a3a58a7884a1d31149647fdb07e
6673c84f388642216c38dfd9a2188ff8e87651ee
refs/heads/master
1,670,519,631,593
1,598,804,948,000
1,598,804,948,000
283,789,362
0
0
null
null
null
null
UTF-8
Lean
false
false
45
lean
import data.nat.bitwise def nat.bit_ff := 3
ab8173ea2533b15580c2a97a53276cae8b368601
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/assertion1.lean
ba3ed033c6a42a5fd0c61ee9b50c114df2ff349c
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,277
lean
universe variables u v structure Category := (Obj : Type u) (Hom : Obj → Obj → Type v) universe variables u1 v1 u2 v2 structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) := (onObjects : C^.Obj → D^.Obj) @[reducible] definition ProductCategory (C : Category) (D : Category) : Category := { Obj := C^.Obj × D^.Obj, Hom := (λ X Y : C^.Obj × D^.Obj, C^.Hom (X^.fst) (Y^.fst) × D^.Hom (X^.snd) (Y^.snd)) } namespace ProductCategory notation (name := prod) C `×` D := ProductCategory C D end ProductCategory @[reducible] definition TensorProduct ( C: Category ) := Functor ( C × C ) C structure MonoidalCategory extends carrier : Category := (tensor : TensorProduct carrier) instance MonoidalCategory_coercion : has_coe MonoidalCategory Category := ⟨MonoidalCategory.carrier⟩ -- Convenience methods which take two arguments, rather than a pair. (This seems to often help the elaborator avoid getting stuck on `prod.mk`.) @[reducible] definition MonoidalCategory.tensorObjects { C : MonoidalCategory } ( X Y : C^.Obj ) : C^.Obj := C^.tensor^.onObjects (X, Y) definition tensor_on_left { C: MonoidalCategory.{u v} } ( Z: C^.Obj ) : Functor.{u v u v} C C := { onObjects := λ X, C^.tensorObjects Z X }
b2af6dddbe9cf9a678a5fd185d0eecef8c94cd9b
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/integral/peak_function.lean
ac8e5df9b3b59954e8fcb972097e04cfd67b90a7
[ "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
19,517
lean
/- Copyright (c) 2023 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.integral.set_integral import measure_theory.function.locally_integrable /-! # Integrals against peak functions A sequence of peak functions is a sequence of functions with average one concentrating around a point `x₀`. Given such a sequence `φₙ`, then `∫ φₙ g` tends to `g x₀` in many situations, with a whole zoo of possible assumptions on `φₙ` and `g`. This file is devoted to such results. ## Main results * `tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at`: If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `∫ φᵢ • g` converges to `g x₀`. * `tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on`: If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is continuous on `s`. Note that there are related results about convolution with respect to peak functions in the file `analysis.convolution`, such as `convolution_tendsto_right` there. -/ open set filter measure_theory measure_theory.measure topological_space metric open_locale topology ennreal /-- This lemma exists for finsets, but not for sets currently. porting note: move to data.set.basic after the port. -/ lemma set.disjoint_sdiff_inter {α : Type*} (s t : set α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) disjoint_sdiff_left open set variables {α E ι : Type*} {hm : measurable_space α} {μ : measure α} [topological_space α] [borel_space α] [normed_add_comm_group E] [normed_space ℝ E] {g : α → E} {l : filter ι} {x₀ : α} {s : set α} {φ : ι → α → ℝ} /-- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `φᵢ • g` is eventually integrable. -/ lemma integrable_on_peak_smul_of_integrable_on_of_continuous_within_at (hs : measurable_set s) (hlφ : ∀ (u : set α), is_open u → x₀ ∈ u → tendsto_uniformly_on φ 0 l (s \ u)) (hiφ : ∀ᶠ i in l, ∫ x in s, φ i x ∂μ = 1) (hmg : integrable_on g s μ) (hcg : continuous_within_at g s x₀) : ∀ᶠ i in l, integrable_on (λ x, φ i x • g x) s μ := begin obtain ⟨u, u_open, x₀u, hu⟩ : ∃ u, is_open u ∧ x₀ ∈ u ∧ ∀ x ∈ u ∩ s, g x ∈ ball (g x₀) 1, from mem_nhds_within.1 (hcg (ball_mem_nhds _ zero_lt_one)), filter_upwards [tendsto_uniformly_on_iff.1 (hlφ u u_open x₀u) 1 zero_lt_one, hiφ] with i hi h'i, have A : integrable_on (λ x, φ i x • g x) (s \ u) μ, { apply integrable.smul_of_top_right (hmg.mono (diff_subset _ _) le_rfl), apply mem_ℒp_top_of_bound ((integrable_of_integral_eq_one h'i).ae_strongly_measurable.mono_set ((diff_subset _ _))) 1, filter_upwards [self_mem_ae_restrict (hs.diff u_open.measurable_set)] with x hx, simpa only [pi.zero_apply, dist_zero_left] using (hi x hx).le }, have B : integrable_on (λ x, φ i x • g x) (s ∩ u) μ, { apply integrable.smul_of_top_left, { exact integrable_on.mono_set (integrable_of_integral_eq_one h'i) (inter_subset_left _ _) }, { apply mem_ℒp_top_of_bound (hmg.mono_set (inter_subset_left _ _)).ae_strongly_measurable (‖g x₀‖ + 1), filter_upwards [self_mem_ae_restrict (hs.inter u_open.measurable_set)] with x hx, rw inter_comm at hx, exact (norm_lt_of_mem_ball (hu x hx)).le } }, convert A.union B, simp only [diff_union_inter], end variables [complete_space E] /-- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `∫ φᵢ • g` converges to `x₀`. Auxiliary lemma where one assumes additionally `g x₀ = 0`. -/ lemma tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at_aux (hs : measurable_set s) (hnφ : ∀ᶠ i in l, ∀ x ∈ s, 0 ≤ φ i x) (hlφ : ∀ (u : set α), is_open u → x₀ ∈ u → tendsto_uniformly_on φ 0 l (s \ u)) (hiφ : ∀ᶠ i in l, ∫ x in s, φ i x ∂μ = 1) (hmg : integrable_on g s μ) (h'g : g x₀ = 0) (hcg : continuous_within_at g s x₀) : tendsto (λ i : ι, ∫ x in s, φ i x • g x ∂μ) l (𝓝 0) := begin refine metric.tendsto_nhds.2 (λ ε εpos, _), obtain ⟨δ, hδ, δpos⟩ : ∃ δ, δ * ∫ x in s, ‖g x‖ ∂μ + δ < ε ∧ 0 < δ, { have A : tendsto (λ δ, δ * ∫ x in s, ‖g x‖ ∂μ + δ) (𝓝[>] 0) (𝓝 (0 * ∫ x in s, ‖g x‖ ∂μ + 0)), { apply tendsto.mono_left _ nhds_within_le_nhds, exact (tendsto_id.mul tendsto_const_nhds).add tendsto_id }, rw [zero_mul, zero_add] at A, exact (((tendsto_order.1 A).2 ε εpos).and self_mem_nhds_within).exists }, suffices : ∀ᶠ i in l, ‖∫ x in s, φ i x • g x ∂μ‖ ≤ δ * ∫ x in s, ‖g x‖ ∂μ + δ, { filter_upwards [this] with i hi, simp only [dist_zero_right], exact hi.trans_lt hδ }, obtain ⟨u, u_open, x₀u, hu⟩ : ∃ u, is_open u ∧ x₀ ∈ u ∧ ∀ x ∈ u ∩ s, g x ∈ ball (g x₀) δ, from mem_nhds_within.1 (hcg (ball_mem_nhds _ δpos)), filter_upwards [tendsto_uniformly_on_iff.1 (hlφ u u_open x₀u) δ δpos, hiφ, hnφ, integrable_on_peak_smul_of_integrable_on_of_continuous_within_at hs hlφ hiφ hmg hcg] with i hi h'i hφpos h''i, have B : ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ ≤ δ, from calc ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ ≤ ∫ x in s ∩ u, ‖φ i x • g x‖ ∂μ : norm_integral_le_integral_norm _ ... ≤ ∫ x in s ∩ u, ‖φ i x‖ * δ ∂μ : begin refine set_integral_mono_on _ _ (hs.inter u_open.measurable_set) (λ x hx, _), { exact integrable_on.mono_set h''i.norm (inter_subset_left _ _) }, { exact integrable_on.mono_set ((integrable_of_integral_eq_one h'i).norm.mul_const _) (inter_subset_left _ _) }, rw norm_smul, apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), rw [inter_comm, h'g] at hu, exact (mem_ball_zero_iff.1 (hu x hx)).le, end ... ≤ ∫ x in s, ‖φ i x‖ * δ ∂μ : begin apply set_integral_mono_set, { exact ((integrable_of_integral_eq_one h'i).norm.mul_const _) }, { exact eventually_of_forall (λ x, mul_nonneg (norm_nonneg _) δpos.le) }, { apply eventually_of_forall, exact inter_subset_left s u } end ... = ∫ x in s, φ i x * δ ∂μ : begin apply set_integral_congr hs (λ x hx, _), rw real.norm_of_nonneg (hφpos _ hx), end ... = δ : by rw [integral_mul_right, h'i, one_mul], have C : ‖∫ x in s \ u, φ i x • g x ∂μ‖ ≤ δ * ∫ x in s, ‖g x‖ ∂μ, from calc ‖∫ x in s \ u, φ i x • g x ∂μ‖ ≤ ∫ x in s \ u, ‖φ i x • g x‖ ∂μ : norm_integral_le_integral_norm _ ... ≤ ∫ x in s \ u, δ * ‖g x‖ ∂μ : begin refine set_integral_mono_on _ _ (hs.diff u_open.measurable_set) (λ x hx, _), { exact integrable_on.mono_set h''i.norm (diff_subset _ _) }, { exact integrable_on.mono_set (hmg.norm.const_mul _) (diff_subset _ _) }, rw norm_smul, apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), simpa only [pi.zero_apply, dist_zero_left] using (hi x hx).le, end ... ≤ δ * ∫ x in s, ‖g x‖ ∂μ : begin rw integral_mul_left, apply mul_le_mul_of_nonneg_left (set_integral_mono_set hmg.norm _ _) δpos.le, { exact eventually_of_forall (λ x, norm_nonneg _) }, { apply eventually_of_forall, exact diff_subset s u } end, calc ‖∫ x in s, φ i x • g x ∂μ‖ = ‖∫ x in s \ u, φ i x • g x ∂μ + ∫ x in s ∩ u, φ i x • g x ∂μ‖ : begin conv_lhs { rw ← diff_union_inter s u }, rw integral_union (disjoint_sdiff_inter _ _) (hs.inter u_open.measurable_set) (h''i.mono_set (diff_subset _ _)) (h''i.mono_set (inter_subset_left _ _)) end ... ≤ ‖∫ x in s \ u, φ i x • g x ∂μ‖ + ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ : norm_add_le _ _ ... ≤ δ * ∫ x in s, ‖g x‖ ∂μ + δ : add_le_add C B end /- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `∫ φᵢ • g` converges to `x₀`. -/ lemma tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at (hs : measurable_set s) (h's : μ s ≠ ∞) (hnφ : ∀ᶠ i in l, ∀ x ∈ s, 0 ≤ φ i x) (hlφ : ∀ (u : set α), is_open u → x₀ ∈ u → tendsto_uniformly_on φ 0 l (s \ u)) (hiφ : (λ i, ∫ x in s, φ i x ∂μ) =ᶠ[l] 1) (hmg : integrable_on g s μ) (hcg : continuous_within_at g s x₀) : tendsto (λ i : ι, ∫ x in s, φ i x • g x ∂μ) l (𝓝 (g x₀)) := begin let h := g - (λ y, g x₀), have A : tendsto (λ i : ι, ∫ x in s, φ i x • h x ∂μ + (∫ x in s, φ i x ∂μ) • g x₀) l (𝓝 (0 + (1 : ℝ) • g x₀)), { refine tendsto.add _ (tendsto.smul (tendsto_const_nhds.congr' hiφ.symm) tendsto_const_nhds), apply tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at_aux hs hnφ hlφ hiφ, { apply integrable.sub hmg, apply integrable_on_const.2, simp only [h's.lt_top, or_true] }, { simp only [h, pi.sub_apply, sub_self] }, { exact hcg.sub continuous_within_at_const } }, simp only [one_smul, zero_add] at A, refine tendsto.congr' _ A, filter_upwards [integrable_on_peak_smul_of_integrable_on_of_continuous_within_at hs hlφ hiφ hmg hcg, hiφ] with i hi h'i, simp only [h, pi.sub_apply, smul_sub], rw [integral_sub hi, integral_smul_const, sub_add_cancel], exact integrable.smul_const (integrable_of_integral_eq_one h'i) _, end /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is integrable on `s` and continuous at `x₀`. Version assuming that `μ` gives positive mass to all neighborhoods of `x₀` within `s`. For a less precise but more usable version, see `tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on`. -/ lemma tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_measure_nhds_within_pos [metrizable_space α] [is_locally_finite_measure μ] (hs : is_compact s) (hμ : ∀ u, is_open u → x₀ ∈ u → 0 < μ (u ∩ s)) {c : α → ℝ} (hc : continuous_on c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ s) (hmg : integrable_on g s μ) (hcg : continuous_within_at g s x₀) : tendsto (λ (n : ℕ), (∫ x in s, (c x) ^ n ∂μ)⁻¹ • (∫ x in s, (c x) ^ n • g x ∂μ)) at_top (𝓝 (g x₀)) := begin /- We apply the general result `tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at` to the sequence of peak functions `φₙ = (c x) ^ n / ∫ (c x) ^ n`. The only nontrivial bit is to check that this sequence converges uniformly to zero on any set `s \ u` away from `x₀`. By compactness, the function `c` is bounded by `t < c x₀` there. Consider `t' ∈ (t, c x₀)`, and a neighborhood `v` of `x₀` where `c x ≥ t'`, by continuity. Then `∫ (c x) ^ n` is bounded below by `t' ^ n μ v`. It follows that, on `s \ u`, then `φₙ x ≤ t ^ n / (t' ^ n μ v)`, which tends (exponentially fast) to zero with `n`. -/ let φ : ℕ → α → ℝ := λ n x, (∫ x in s, (c x) ^ n ∂μ)⁻¹ * (c x) ^ n, have hnφ : ∀ n, ∀ x ∈ s, 0 ≤ φ n x, { assume n x hx, apply mul_nonneg (inv_nonneg.2 _) (pow_nonneg (hnc x hx) _), exact set_integral_nonneg hs.measurable_set (λ x hx, pow_nonneg (hnc x hx) _) }, have I : ∀ n, integrable_on (λ x, (c x)^n) s μ := λ n, continuous_on.integrable_on_compact hs (hc.pow n), have J : ∀ n, 0 ≤ᵐ[μ.restrict s] λ (x : α), c x ^ n, { assume n, filter_upwards [ae_restrict_mem hs.measurable_set] with x hx, exact pow_nonneg (hnc x hx) n }, have P : ∀ n, 0 < ∫ x in s, (c x) ^ n ∂μ, { assume n, refine (set_integral_pos_iff_support_of_nonneg_ae (J n) (I n)).2 _, obtain ⟨u, u_open, x₀_u, hu⟩ : ∃ (u : set α), is_open u ∧ x₀ ∈ u ∧ u ∩ s ⊆ c ⁻¹' Ioi 0 := _root_.continuous_on_iff.1 hc x₀ h₀ (Ioi (0 : ℝ)) is_open_Ioi hnc₀, apply (hμ u u_open x₀_u).trans_le, exact measure_mono (λ x hx, ⟨ne_of_gt (pow_pos (hu hx) _), hx.2⟩) }, have hiφ : ∀ n, ∫ x in s, φ n x ∂μ = 1 := λ n, by rw [integral_mul_left, inv_mul_cancel (P n).ne'], have A : ∀ (u : set α), is_open u → x₀ ∈ u → tendsto_uniformly_on φ 0 at_top (s \ u), { assume u u_open x₀u, obtain ⟨t, t_pos, tx₀, ht⟩ : ∃ t, 0 ≤ t ∧ t < c x₀ ∧ (∀ x ∈ s \ u, c x ≤ t), { rcases eq_empty_or_nonempty (s \ u) with h|h, { exact ⟨0, le_rfl, hnc₀, by simp only [h, mem_empty_iff_false, is_empty.forall_iff, implies_true_iff]⟩ }, obtain ⟨x, hx, h'x⟩ : ∃ x ∈ s \ u, ∀ y ∈ s \ u, c y ≤ c x := is_compact.exists_forall_ge (hs.diff u_open) h (hc.mono (diff_subset _ _)), refine ⟨c x, hnc x hx.1, h'c x hx.1 _, h'x⟩, rintros rfl, exact hx.2 x₀u }, obtain ⟨t', tt', t'x₀⟩ : ∃ t', t < t' ∧ t' < c x₀ := exists_between tx₀, have t'_pos : 0 < t' := t_pos.trans_lt tt', obtain ⟨v, v_open, x₀_v, hv⟩ : ∃ (v : set α), is_open v ∧ x₀ ∈ v ∧ v ∩ s ⊆ c ⁻¹' Ioi t' := _root_.continuous_on_iff.1 hc x₀ h₀ (Ioi t') is_open_Ioi t'x₀, have M : ∀ n, ∀ x ∈ s \ u, φ n x ≤ (μ (v ∩ s)).to_real ⁻¹ * (t / t') ^ n, { assume n x hx, have B : t' ^ n * (μ (v ∩ s)).to_real ≤ ∫ y in s, (c y) ^ n ∂μ, from calc t' ^ n * (μ (v ∩ s)).to_real = ∫ y in v ∩ s, t' ^ n ∂μ : by simp only [integral_const, measure.restrict_apply, measurable_set.univ, univ_inter, algebra.id.smul_eq_mul, mul_comm] ... ≤ ∫ y in v ∩ s, (c y) ^ n ∂μ : begin apply set_integral_mono_on _ _ (v_open.measurable_set.inter hs.measurable_set) _, { apply integrable_on_const.2 (or.inr _), exact lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) hs.measure_lt_top }, { exact (I n).mono (inter_subset_right _ _) le_rfl }, { assume x hx, exact pow_le_pow_of_le_left t'_pos.le (le_of_lt (hv hx)) _ } end ... ≤ ∫ y in s, (c y) ^ n ∂μ : set_integral_mono_set (I n) (J n) (eventually_of_forall (inter_subset_right _ _)), simp_rw [φ, ← div_eq_inv_mul, div_pow, div_div], apply div_le_div (pow_nonneg t_pos n) _ _ B, { exact pow_le_pow_of_le_left (hnc _ hx.1) (ht x hx) _ }, { apply mul_pos (pow_pos (t_pos.trans_lt tt') _) (ennreal.to_real_pos (hμ v v_open x₀_v).ne' _), have : μ (v ∩ s) ≤ μ s := measure_mono (inter_subset_right _ _), exact ne_of_lt (lt_of_le_of_lt this hs.measure_lt_top) } }, have N : tendsto (λ n, (μ (v ∩ s)).to_real ⁻¹ * (t / t') ^ n) at_top (𝓝 ((μ (v ∩ s)).to_real ⁻¹ * 0)), { apply tendsto.mul tendsto_const_nhds _, { apply_instance }, apply tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg t_pos t'_pos.le), exact (div_lt_one t'_pos).2 tt' }, rw mul_zero at N, refine tendsto_uniformly_on_iff.2 (λ ε εpos, _), filter_upwards [(tendsto_order.1 N).2 ε εpos] with n hn x hx, simp only [pi.zero_apply, dist_zero_left, real.norm_of_nonneg (hnφ n x hx.1)], exact (M n x hx).trans_lt hn }, have : tendsto (λ (i : ℕ), ∫ (x : α) in s, φ i x • g x ∂μ) at_top (𝓝 (g x₀)) := tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at hs.measurable_set hs.measure_lt_top.ne (eventually_of_forall hnφ) A (eventually_of_forall hiφ) hmg hcg, convert this, simp_rw [← smul_smul, integral_smul], end /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is integrable on `s` and continuous at `x₀`. Version assuming that `μ` gives positive mass to all open sets. For a less precise but more usable version, see `tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on`. -/ lemma tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_integrable_on [metrizable_space α] [is_locally_finite_measure μ] [is_open_pos_measure μ] (hs : is_compact s) {c : α → ℝ} (hc : continuous_on c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ closure (interior s)) (hmg : integrable_on g s μ) (hcg : continuous_within_at g s x₀) : tendsto (λ (n : ℕ), (∫ x in s, (c x) ^ n ∂μ)⁻¹ • (∫ x in s, (c x) ^ n • g x ∂μ)) at_top (𝓝 (g x₀)) := begin have : x₀ ∈ s, { rw ← hs.is_closed.closure_eq, exact closure_mono interior_subset h₀ }, apply tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_measure_nhds_within_pos hs _ hc h'c hnc hnc₀ this hmg hcg, assume u u_open x₀_u, calc 0 < μ (u ∩ interior s) : (u_open.inter is_open_interior).measure_pos μ (_root_.mem_closure_iff.1 h₀ u u_open x₀_u) ... ≤ μ (u ∩ s) : measure_mono (inter_subset_inter_right _ interior_subset) end /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is continuous on `s`. -/ lemma tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on [metrizable_space α] [is_locally_finite_measure μ] [is_open_pos_measure μ] (hs : is_compact s) {c : α → ℝ} (hc : continuous_on c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ closure (interior s)) (hmg : continuous_on g s) : tendsto (λ (n : ℕ), (∫ x in s, (c x) ^ n ∂μ)⁻¹ • (∫ x in s, (c x) ^ n • g x ∂μ)) at_top (𝓝 (g x₀)) := begin have : x₀ ∈ s, { rw ← hs.is_closed.closure_eq, exact closure_mono interior_subset h₀ }, exact tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_integrable_on hs hc h'c hnc hnc₀ h₀ (hmg.integrable_on_compact hs) (hmg x₀ this) end
eee86803fa8c385c998881b2237563327f778b6f
4fc5f02f6ed9423b87987589bcc202f985d7e9ff
/src/game/world10/level1.lean
0475f7ea619b8d37098c5ef55be05607099dfcf0
[ "Apache-2.0" ]
permissive
grthomson/natural_number_game
2937533df0b83e73e6a873c0779ee21e30f09778
0a23a327ca724b95406c510ee27c55f5b97e612f
refs/heads/master
1,599,994,591,355
1,588,869,073,000
1,588,869,073,000
222,750,177
0
0
Apache-2.0
1,574,183,960,000
1,574,183,960,000
null
UTF-8
Lean
false
false
3,548
lean
import mynat.le -- import definition of ≤ import game.world9.level4 -- hide import game.world4.level8 -- hide namespace mynat -- hide /- Axiom : le_iff_exists_add (a b : mynat) a ≤ b ↔ ∃ (c : mynat), b = a + c -/ /- Tactic : use ## Summary `use` works on the goal. If your goal is `⊢ ∃ c : mynat, 1 + x = x + c` then `use 1` will turn the goal into `⊢ 1 + x = x + 1`, and the rather more unwise `use 0` will turn it into the impossible-to-prove `⊢ 1 + x = x + 0`. ## Details `use` is a tactic which works on goals of the form `⊢ ∃ c, P(c)` where `P(c)` is some proposition which depends on `c`. With a goal of this form, `use 0` will turn the goal into `⊢ P(0)`, `use x + y` (assuming `x` and `y` are natural numbers in your local context) will turn the goal into `P(x + y)` and so on. -/ -- World name : Inequality world /- # Inequality world. A new import, giving us a new definition. If `a` and `b` are naturals, `a ≤ b` is *defined* to mean `∃ (c : mynat), b = a + c` The upside-down E means "there exists". So in words, $a\le b$ if and only if there exists a natural $c$ such that $b=a+c$. If you really want to change an `a ≤ b` to `∃ c, b = a + c` then you can do so with `rw le_iff_exists_add`: ``` le_iff_exists_add (a b : mynat) : a ≤ b ↔ ∃ (c : mynat), b = a + c ``` But because `a ≤ b` is *defined as* `∃ (c : mynat), b = a + c`, you do not need to `rw le_iff_exists_add`, you can just pretend when you see `a ≤ b` that it says `∃ (c : mynat), b = a + c`. You will see a concrete example of this below. A new construction like `∃` means that we need to learn how to manipulate it. There are two situations. Firstly we need to know how to solve a goal of the form `⊢ ∃ c, ...`, and secondly we need to know how to use a hypothesis of the form `∃ c, ...`. ## Level 1: the `use` tactic. The goal below is to prove $x\le 1+x$ for any natural number $x$. First let's turn the goal explicitly into an existence problem with `rw le_iff_exists_add,` and now the goal has become `∃ c : mynat, 1 + x = x + c`. Clearly this statement is true, and the proof is that $c=1$ will work (we also need the fact that addition is commutative, but we proved that a long time ago). How do we make progress with this goal? The `use` tactic can be used on goals of the form `∃ c, ...`. The idea is that we choose which natural number we want to use, and then we use it. So try `use 1,` and now the goal becomes `⊢ 1 + x = x + 1`. You can solve this by `exact add_comm 1 x`, or if you are lazy you can just use the `ring` tactic, which is a powerful AI which will solve any equality in algebra which can be proved using the standard rules of addition and multiplication. Now look at your proof. We're going to remove a line. ## Important An important time-saver here is to note that because `a ≤ b` is *defined* as `∃ c : mynat, b = a + c`, you *do not need to write* `rw le_iff_exists_add`. The `use` tactic will work directly on a goal of the form `a ≤ b`. Just use the difference `b - a` (note that we have not defined subtraction so this does not formally make sense, but you can do the calculation in your head). If you have written `rw le_iff_exists_add` below, then just put two minus signs `--` before it and comment it out. See that the proof still compiles. -/ /- Lemma : no-side-bar If $x$ is a natural number, then $x\le 1+x$. -/ lemma one_add_le_self (x : mynat) : x ≤ 1 + x := begin rw le_iff_exists_add, use 1, ring, end end mynat -- hide
51938f5b3f99899b7fde3682e4cffa9386c914c7
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Std/Data/BinomialHeap.lean
c16e8b3a87df67d03c6c8fd3138cd11e70accfe6
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,342
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ namespace Std universes u namespace BinomialHeapImp structure HeapNodeAux (α : Type u) (h : Type u) := (val : α) (rank : Nat) (children : List h) inductive Heap (α : Type u) : Type u | empty : Heap α | heap (ns : List (HeapNodeAux α (Heap α))) : Heap α abbrev HeapNode (α) := HeapNodeAux α (Heap α) variables {α : Type u} instance : Inhabited (Heap α) := ⟨Heap.empty⟩ def hRank : List (HeapNode α) → Nat | [] => 0 | h::_ => h.rank def isEmpty : Heap α → Bool | Heap.empty => true | _ => false def singleton (a : α) : Heap α := Heap.heap [{ val := a, rank := 1, children := [] }] @[specialize] def combine (lt : α → α → Bool) (n₁ n₂ : HeapNode α) : HeapNode α := if lt n₂.val n₁.val then { n₂ with rank := n₂.rank + 1, children := n₂.children ++ [Heap.heap [n₁]] } else { n₁ with rank := n₁.rank + 1, children := n₁.children ++ [Heap.heap [n₂]] } @[specialize] partial def mergeNodes (lt : α → α → Bool) : List (HeapNode α) → List (HeapNode α) → List (HeapNode α) | [], h => h | h, [] => h | f@(h₁ :: t₁), s@(h₂ :: t₂) => if h₁.rank < h₂.rank then h₁ :: mergeNodes lt t₁ s else if h₂.rank < h₁.rank then h₂ :: mergeNodes lt t₂ f else let merged := combine lt h₁ h₂; let r := merged.rank; if r != hRank t₁ then if r != hRank t₂ then merged :: mergeNodes lt t₁ t₂ else mergeNodes lt (merged :: t₁) t₂ else if r != hRank t₂ then mergeNodes lt t₁ (merged :: t₂) else merged :: mergeNodes lt t₁ t₂ @[specialize] def merge (lt : α → α → Bool) : Heap α → Heap α → Heap α | Heap.empty, h => h | h, Heap.empty => h | Heap.heap h₁, Heap.heap h₂ => Heap.heap (mergeNodes lt h₁ h₂) @[specialize] def head? (lt : α → α → Bool) : Heap α → Option α | Heap.empty => none | Heap.heap h => h.foldl (init := none) fun r n => match r with | none => some n.val | some v => if lt v n.val then v else some n.val /- O(log n) -/ @[specialize] def head [Inhabited α] (lt : α → α → Bool) : Heap α → α | Heap.empty => arbitrary α | Heap.heap [] => arbitrary α | Heap.heap (h::hs) => hs.foldl (init := h.val) fun r n => if lt r n.val then r else n.val @[specialize] def findMin (lt : α → α → Bool) : List (HeapNode α) → Nat → HeapNode α × Nat → HeapNode α × Nat | [], _, r => r | h::hs, idx, (h', idx') => if lt h.val h'.val then findMin lt hs (idx+1) (h, idx) else findMin lt hs (idx+1) (h', idx') def tail (lt : α → α → Bool) : Heap α → Heap α | Heap.empty => Heap.empty | Heap.heap [] => Heap.empty | Heap.heap [h] => match h.children with | [] => Heap.empty | (h::hs) => hs.foldl (merge lt) h | Heap.heap hhs@(h::hs) => let (min, minIdx) := findMin lt hs 1 (h, 0); let rest := hhs.eraseIdx minIdx; min.children.foldl (merge lt) (Heap.heap rest) partial def toList (lt : α → α → Bool) : Heap α → List α | Heap.empty => [] | h => match head? lt h with | none => [] | some a => a :: toList lt (tail lt h) inductive WellFormed (lt : α → α → Bool) : Heap α → Prop | emptyWff : WellFormed lt Heap.empty | singletonWff (a : α) : WellFormed lt (singleton a) | mergeWff (h₁ h₂ : Heap α) : WellFormed lt h₁ → WellFormed lt h₂ → WellFormed lt (merge lt h₁ h₂) | tailWff (h : Heap α) : WellFormed lt h → WellFormed lt (tail lt h) end BinomialHeapImp open BinomialHeapImp def BinomialHeap (α : Type u) (lt : α → α → Bool) := { h : Heap α // WellFormed lt h } @[inline] def mkBinomialHeap (α : Type u) (lt : α → α → Bool) : BinomialHeap α lt := ⟨Heap.empty, WellFormed.emptyWff⟩ namespace BinomialHeap variables {α : Type u} {lt : α → α → Bool} @[inline] def empty : BinomialHeap α lt := mkBinomialHeap α lt @[inline] def isEmpty : BinomialHeap α lt → Bool | ⟨b, _⟩ => BinomialHeapImp.isEmpty b /- O(1) -/ @[inline] def singleton (a : α) : BinomialHeap α lt := ⟨BinomialHeapImp.singleton a, WellFormed.singletonWff a⟩ /- O(log n) -/ @[inline] def merge : BinomialHeap α lt → BinomialHeap α lt → BinomialHeap α lt | ⟨b₁, h₁⟩, ⟨b₂, h₂⟩ => ⟨BinomialHeapImp.merge lt b₁ b₂, WellFormed.mergeWff b₁ b₂ h₁ h₂⟩ /- O(log n) -/ @[inline] def head [Inhabited α] : BinomialHeap α lt → α | ⟨b, _⟩ => BinomialHeapImp.head lt b /- O(log n) -/ @[inline] def head? : BinomialHeap α lt → Option α | ⟨b, _⟩ => BinomialHeapImp.head? lt b /- O(log n) -/ @[inline] def tail : BinomialHeap α lt → BinomialHeap α lt | ⟨b, h⟩ => ⟨BinomialHeapImp.tail lt b, WellFormed.tailWff b h⟩ /- O(log n) -/ @[inline] def insert (a : α) (h : BinomialHeap α lt) : BinomialHeap α lt := merge (singleton a) h /- O(n log n) -/ @[inline] def toList : BinomialHeap α lt → List α | ⟨b, _⟩ => BinomialHeapImp.toList lt b end BinomialHeap end Std
470126c399740f7bd05da55c5217c88436667016
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/algebra/tower.lean
00cda48b6f8493ab88d89b3769627d9f36e5a3fd
[ "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
12,103
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.subalgebra /-! # Towers of algebras In this file we prove basic facts about towers of algebra. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. An important definition is `to_alg_hom R S A`, the canonical `R`-algebra homomorphism `S →ₐ[R] A`. -/ open_locale pointwise universes u v w u₁ v₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) (M : Type v₁) namespace algebra variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_monoid M] [module R M] [module A M] [is_scalar_tower R A M] variables {A} /-- The `R`-algebra morphism `A → End (M)` corresponding to the representation of the algebra `A` on the `R`-module `M`. This is a stronger version of `distrib_mul_action.to_linear_map`, and could also have been called `algebra.to_module_End`. -/ def lsmul : A →ₐ[R] module.End R M := { to_fun := distrib_mul_action.to_linear_map R M, map_one' := linear_map.ext $ λ _, one_smul A _, map_mul' := λ a b, linear_map.ext $ smul_assoc a b, map_zero' := linear_map.ext $ λ _, zero_smul A _, map_add' := λ a b, linear_map.ext $ λ _, add_smul _ _ _, commutes' := λ r, linear_map.ext $ algebra_map_smul A r, } @[simp] lemma lsmul_coe (a : A) : (lsmul R M a : M → M) = (•) a := rfl lemma lmul_algebra_map (x : R) : lmul R A (algebra_map R A x) = algebra.lsmul R A x := eq.symm $ linear_map.ext $ smul_def'' x end algebra namespace is_scalar_tower section module variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_monoid M] [module R M] [module A M] [is_scalar_tower R A M] variables {R} (A) {M} theorem algebra_map_smul (r : R) (x : M) : algebra_map R A r • x = r • x := by rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] end module section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] variables {R S A} theorem of_algebra_map_eq [algebra R A] (h : ∀ x, algebra_map R A x = algebra_map S A (algebra_map R S x)) : is_scalar_tower R S A := ⟨λ x y z, by simp_rw [algebra.smul_def, ring_hom.map_mul, mul_assoc, h]⟩ /-- See note [partially-applied ext lemmas]. -/ theorem of_algebra_map_eq' [algebra R A] (h : algebra_map R A = (algebra_map S A).comp (algebra_map R S)) : is_scalar_tower R S A := of_algebra_map_eq $ ring_hom.ext_iff.1 h variables (R S A) instance subalgebra (S₀ : subalgebra R S) : is_scalar_tower S₀ S A := of_algebra_map_eq $ λ x, rfl variables [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] theorem algebra_map_eq : algebra_map R A = (algebra_map S A).comp (algebra_map R S) := ring_hom.ext $ λ x, by simp_rw [ring_hom.comp_apply, algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] theorem algebra_map_apply (x : R) : algebra_map R A x = algebra_map S A (algebra_map R S x) := by rw [algebra_map_eq R S A, ring_hom.comp_apply] instance subalgebra' (S₀ : subalgebra R S) : is_scalar_tower R S₀ A := @is_scalar_tower.of_algebra_map_eq R S₀ A _ _ _ _ _ _ $ λ _, (is_scalar_tower.algebra_map_apply R S A _ : _) @[ext] lemma algebra.ext {S : Type u} {A : Type v} [comm_semiring S] [semiring A] (h1 h2 : algebra S A) (h : ∀ {r : S} {x : A}, (by haveI := h1; exact r • x) = r • x) : h1 = h2 := begin unfreezingI { cases h1 with f1 g1 h11 h12, cases h2 with f2 g2 h21 h22, cases f1, cases f2, congr', { ext r x, exact h }, ext r, erw [← mul_one (g1 r), ← h12, ← mul_one (g2 r), ← h22, h], refl } end /-- In a tower, the canonical map from the middle element to the top element is an algebra homomorphism over the bottom element. -/ def to_alg_hom : S →ₐ[R] A := { commutes' := λ _, (algebra_map_apply _ _ _ _).symm, .. algebra_map S A } lemma to_alg_hom_apply (y : S) : to_alg_hom R S A y = algebra_map S A y := rfl @[simp] lemma coe_to_alg_hom : ↑(to_alg_hom R S A) = algebra_map S A := ring_hom.ext $ λ _, rfl @[simp] lemma coe_to_alg_hom' : (to_alg_hom R S A : S → A) = algebra_map S A := rfl variables {R S A B} @[simp, priority 900] lemma _root_.alg_hom.map_algebra_map (f : A →ₐ[S] B) (r : R) : f (algebra_map R A r) = algebra_map R B r := by rw [algebra_map_apply R S A r, f.commutes, ← algebra_map_apply R S B] variables (R) @[simp, priority 900] lemma _root_.alg_hom.comp_algebra_map_of_tower (f : A →ₐ[S] B) : (f : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext f.map_algebra_map variables (R) {S A B} -- conflicts with is_scalar_tower.subalgebra @[priority 999] instance subsemiring (U : subsemiring S) : is_scalar_tower U S A := of_algebra_map_eq $ λ x, rfl @[nolint instance_priority] instance of_ring_hom {R A B : Type*} [comm_semiring R] [comm_semiring A] [comm_semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : @is_scalar_tower R A B _ (f.to_ring_hom.to_algebra.to_has_scalar) _ := by { letI := (f : A →+* B).to_algebra, exact of_algebra_map_eq (λ x, (f.commutes x).symm) } end semiring section division_ring variables [field R] [division_ring S] [algebra R S] [char_zero R] [char_zero S] instance rat : is_scalar_tower ℚ R S := of_algebra_map_eq $ λ x, ((algebra_map R S).map_rat_cast x).symm end division_ring end is_scalar_tower section homs variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] variables [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R) {A S B} open is_scalar_tower namespace alg_hom /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_scalars (f : A →ₐ[S] B) : A →ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A →+* B) } lemma restrict_scalars_apply (f : A →ₐ[S] B) (x : A) : f.restrict_scalars R x = f x := rfl @[simp] lemma coe_restrict_scalars (f : A →ₐ[S] B) : (f.restrict_scalars R : A →+* B) = f := rfl @[simp] lemma coe_restrict_scalars' (f : A →ₐ[S] B) : (restrict_scalars R f : A → B) = f := rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : (A →ₐ[S] B) → (A →ₐ[R] B)) := λ f g h, alg_hom.ext (alg_hom.congr_fun h : _) end alg_hom namespace alg_equiv /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_scalars (f : A ≃ₐ[S] B) : A ≃ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A ≃+* B) } lemma restrict_scalars_apply (f : A ≃ₐ[S] B) (x : A) : f.restrict_scalars R x = f x := rfl @[simp] lemma coe_restrict_scalars (f : A ≃ₐ[S] B) : (f.restrict_scalars R : A ≃+* B) = f := rfl @[simp] lemma coe_restrict_scalars' (f : A ≃ₐ[S] B) : (restrict_scalars R f : A → B) = f := rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : (A ≃ₐ[S] B) → (A ≃ₐ[R] B)) := λ f g h, alg_equiv.ext (alg_equiv.congr_fun h : _) end alg_equiv end homs namespace subalgebra open is_scalar_tower section semiring variables (R) {S A} [comm_semiring R] [comm_semiring S] [semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] /-- Given a scalar tower `R`, `S`, `A` of algebras, reinterpret an `S`-subalgebra of `A` an as an `R`-subalgebra. -/ def restrict_scalars (U : subalgebra S A) : subalgebra R A := { algebra_map_mem' := λ x, by { rw algebra_map_apply R S A, exact U.algebra_map_mem _ }, .. U } @[simp] lemma coe_restrict_scalars {U : subalgebra S A} : (restrict_scalars R U : set A) = (U : set A) := rfl @[simp] lemma restrict_scalars_top : restrict_scalars R (⊤ : subalgebra S A) = ⊤ := set_like.coe_injective rfl @[simp] lemma restrict_scalars_to_submodule {U : subalgebra S A} : (U.restrict_scalars R).to_submodule = U.to_submodule.restrict_scalars R := set_like.coe_injective rfl @[simp] lemma mem_restrict_scalars {U : subalgebra S A} {x : A} : x ∈ restrict_scalars R U ↔ x ∈ U := iff.rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : subalgebra S A → subalgebra R A) := λ U V H, ext $ λ x, by rw [← mem_restrict_scalars R, H, mem_restrict_scalars] /-- Produces a map from `subalgebra.under`. -/ def of_under {R A B : Type*} [comm_semiring R] [comm_semiring A] [semiring B] [algebra R A] [algebra R B] (S : subalgebra R A) (U : subalgebra S A) [algebra S B] [is_scalar_tower R S B] (f : U →ₐ[S] B) : S.under U →ₐ[R] B := { commutes' := λ r, (f.commutes (algebra_map R S r)).trans (algebra_map_apply R S B r).symm, .. f } end semiring end subalgebra namespace is_scalar_tower open subalgebra variables [comm_semiring R] [comm_semiring S] [comm_semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] theorem range_under_adjoin (t : set A) : (to_alg_hom R S A).range.under (algebra.adjoin _ t) = (algebra.adjoin S t).restrict_scalars R := subalgebra.ext $ λ z, show z ∈ subsemiring.closure (set.range (algebra_map (to_alg_hom R S A).range A) ∪ t : set A) ↔ z ∈ subsemiring.closure (set.range (algebra_map S A) ∪ t : set A), from suffices set.range (algebra_map (to_alg_hom R S A).range A) = set.range (algebra_map S A), by rw this, by { ext z, exact ⟨λ ⟨⟨x, y, h1⟩, h2⟩, ⟨y, h2 ▸ h1⟩, λ ⟨y, hy⟩, ⟨⟨z, y, hy⟩, rfl⟩⟩ } end is_scalar_tower section semiring variables {R S A} variables [comm_semiring R] [semiring S] [add_comm_monoid A] variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A] namespace submodule open is_scalar_tower theorem smul_mem_span_smul_of_mem {s : set S} {t : set A} {k : S} (hks : k ∈ span R s) {x : A} (hx : x ∈ t) : k • x ∈ span R (s • t) := span_induction hks (λ c hc, subset_span $ set.mem_smul.2 ⟨c, x, hc, hx, rfl⟩) (by { rw zero_smul, exact zero_mem _ }) (λ c₁ c₂ ih₁ ih₂, by { rw add_smul, exact add_mem _ ih₁ ih₂ }) (λ b c hc, by { rw is_scalar_tower.smul_assoc, exact smul_mem _ _ hc }) theorem smul_mem_span_smul {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R t) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hx) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy }) (λ c x hx, smul_comm c k x ▸ smul_mem _ _ hx) theorem smul_mem_span_smul' {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R (s • t)) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, let ⟨p, q, hp, hq, hpq⟩ := set.mem_smul.1 hx in by { rw [← hpq, smul_smul], exact smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hq }) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy }) (λ c x hx, smul_comm c k x ▸ smul_mem _ _ hx) theorem span_smul {s : set S} (hs : span R s = ⊤) (t : set A) : span R (s • t) = (span S t).restrict_scalars R := le_antisymm (span_le.2 $ λ x hx, let ⟨p, q, hps, hqt, hpqx⟩ := set.mem_smul.1 hx in hpqx ▸ (span S t).smul_mem p (subset_span hqt)) $ λ p hp, span_induction hp (λ x hx, one_smul S x ▸ smul_mem_span_smul hs (subset_span hx)) (zero_mem _) (λ _ _, add_mem _) (λ k x hx, smul_mem_span_smul' hs hx) end submodule end semiring section ring namespace algebra variables [comm_semiring R] [ring A] [algebra R A] variables [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M] lemma lsmul_injective [no_zero_smul_divisors A M] {x : A} (hx : x ≠ 0) : function.injective (lsmul R M x) := smul_right_injective _ hx end algebra end ring
eca2ced533afc69992ac22c2491891d144f7368f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/PersistentHashMap.lean
0701b41686ee0e2eb16e19cbcca76188dcf1c053
[ "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
14,884
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ namespace Lean universe u v w w' namespace PersistentHashMap inductive Entry (α : Type u) (β : Type v) (σ : Type w) where | entry (key : α) (val : β) : Entry α β σ | ref (node : σ) : Entry α β σ | null : Entry α β σ instance {α β σ} : Inhabited (Entry α β σ) := ⟨Entry.null⟩ inductive Node (α : Type u) (β : Type v) : Type (max u v) where | entries (es : Array (Entry α β (Node α β))) : Node α β | collision (ks : Array α) (vs : Array β) (h : ks.size = vs.size) : Node α β instance {α β} : Inhabited (Node α β) := ⟨Node.entries #[]⟩ abbrev shift : USize := 5 abbrev branching : USize := USize.ofNat (2 ^ shift.toNat) abbrev maxDepth : USize := 7 abbrev maxCollisions : Nat := 4 def mkEmptyEntriesArray {α β} : Array (Entry α β (Node α β)) := (Array.mkArray PersistentHashMap.branching.toNat PersistentHashMap.Entry.null) end PersistentHashMap structure PersistentHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] where root : PersistentHashMap.Node α β := PersistentHashMap.Node.entries PersistentHashMap.mkEmptyEntriesArray size : Nat := 0 abbrev PHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := PersistentHashMap α β namespace PersistentHashMap def empty [BEq α] [Hashable α] : PersistentHashMap α β := {} def isEmpty [BEq α] [Hashable α] (m : PersistentHashMap α β) : Bool := m.size == 0 instance [BEq α] [Hashable α] : Inhabited (PersistentHashMap α β) := ⟨{}⟩ def mkEmptyEntries {α β} : Node α β := Node.entries mkEmptyEntriesArray abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) inductive IsCollisionNode : Node α β → Prop where | mk (keys : Array α) (vals : Array β) (h : keys.size = vals.size) : IsCollisionNode (Node.collision keys vals h) abbrev CollisionNode (α β) := { n : Node α β // IsCollisionNode n } inductive IsEntriesNode : Node α β → Prop where | mk (entries : Array (Entry α β (Node α β))) : IsEntriesNode (Node.entries entries) abbrev EntriesNode (α β) := { n : Node α β // IsEntriesNode n } private theorem size_set {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (i : Fin ks.size) (j : Fin vs.size) (k : α) (v : β) : (ks.set i k).size = (vs.set j v).size := by simp [h] private theorem size_push {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (k : α) (v : β) : (ks.push k).size = (vs.push v).size := by simp [h] partial def insertAtCollisionNodeAux [BEq α] : CollisionNode α β → Nat → α → β → CollisionNode α β | n@⟨Node.collision keys vals heq, _⟩, i, k, v => if h : i < keys.size then let idx : Fin keys.size := ⟨i, h⟩; let k' := keys.get idx; if k == k' then let j : Fin vals.size := ⟨i, by rw [←heq]; assumption⟩ ⟨Node.collision (keys.set idx k) (vals.set j v) (size_set heq idx j k v), IsCollisionNode.mk _ _ _⟩ else insertAtCollisionNodeAux n (i+1) k v else ⟨Node.collision (keys.push k) (vals.push v) (size_push heq k v), IsCollisionNode.mk _ _ _⟩ | ⟨Node.entries _, h⟩, _, _, _ => False.elim (nomatch h) def insertAtCollisionNode [BEq α] : CollisionNode α β → α → β → CollisionNode α β := fun n k v => insertAtCollisionNodeAux n 0 k v def getCollisionNodeSize : CollisionNode α β → Nat | ⟨Node.collision keys _ _, _⟩ => keys.size | ⟨Node.entries _, h⟩ => False.elim (nomatch h) def mkCollisionNode (k₁ : α) (v₁ : β) (k₂ : α) (v₂ : β) : Node α β := let ks : Array α := Array.mkEmpty maxCollisions let ks := (ks.push k₁).push k₂ let vs : Array β := Array.mkEmpty maxCollisions let vs := (vs.push v₁).push v₂ Node.collision ks vs rfl partial def insertAux [BEq α] [Hashable α] : Node α β → USize → USize → α → β → Node α β | Node.collision keys vals heq, _, depth, k, v => let newNode := insertAtCollisionNode ⟨Node.collision keys vals heq, IsCollisionNode.mk _ _ _⟩ k v if depth >= maxDepth || getCollisionNodeSize newNode < maxCollisions then newNode.val else match newNode with | ⟨Node.entries _, h⟩ => False.elim (nomatch h) | ⟨Node.collision keys vals heq, _⟩ => let rec traverse (i : Nat) (entries : Node α β) : Node α β := if h : i < keys.size then let k := keys[i] have : i < vals.size := heq ▸ h let v := vals[i] let h := hash k |>.toUSize let h := div2Shift h (shift * (depth - 1)) traverse (i+1) (insertAux entries h depth k v) else entries traverse 0 mkEmptyEntries | Node.entries entries, h, depth, k, v => let j := (mod2Shift h shift).toNat Node.entries $ entries.modify j fun entry => match entry with | Entry.null => Entry.entry k v | Entry.ref node => Entry.ref $ insertAux node (div2Shift h shift) (depth+1) k v | Entry.entry k' v' => if k == k' then Entry.entry k v else Entry.ref $ mkCollisionNode k' v' k v def insert {_ : BEq α} {_ : Hashable α} : PersistentHashMap α β → α → β → PersistentHashMap α β | { root := n, size := sz }, k, v => { root := insertAux n (hash k |>.toUSize) 1 k v, size := sz + 1 } partial def findAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option β := if h : i < keys.size then let k' := keys[i] have : i < vals.size := by rw [←heq]; assumption if k == k' then some vals[i] else findAtAux keys vals heq (i+1) k else none partial def findAux [BEq α] : Node α β → USize → α → Option β | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some v else none | Node.collision keys vals heq, _, k => findAtAux keys vals heq 0 k def find? {_ : BEq α} {_ : Hashable α} : PersistentHashMap α β → α → Option β | { root := n, .. }, k => findAux n (hash k |>.toUSize) k instance {_ : BEq α} {_ : Hashable α} : GetElem (PersistentHashMap α β) α (Option β) fun _ _ => True where getElem m i _ := m.find? i @[inline] def findD {_ : BEq α} {_ : Hashable α} (m : PersistentHashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! {_ : BEq α} {_ : Hashable α} [Inhabited β] (m : PersistentHashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" partial def findEntryAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option (α × β) := if h : i < keys.size then let k' := keys[i] have : i < vals.size := by rw [←heq]; assumption if k == k' then some (k', vals[i]) else findEntryAtAux keys vals heq (i+1) k else none partial def findEntryAux [BEq α] : Node α β → USize → α → Option (α × β) | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findEntryAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some (k', v) else none | Node.collision keys vals heq, _, k => findEntryAtAux keys vals heq 0 k def findEntry? {_ : BEq α} {_ : Hashable α} : PersistentHashMap α β → α → Option (α × β) | { root := n, .. }, k => findEntryAux n (hash k |>.toUSize) k partial def containsAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Bool := if h : i < keys.size then let k' := keys[i] if k == k' then true else containsAtAux keys vals heq (i+1) k else false partial def containsAux [BEq α] : Node α β → USize → α → Bool | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => false | Entry.ref node => containsAux node (div2Shift h shift) k | Entry.entry k' _ => k == k' | Node.collision keys vals heq, _, k => containsAtAux keys vals heq 0 k def contains [BEq α] [Hashable α] : PersistentHashMap α β → α → Bool | { root := n, .. }, k => containsAux n (hash k |>.toUSize) k partial def isUnaryEntries (a : Array (Entry α β (Node α β))) (i : Nat) (acc : Option (α × β)) : Option (α × β) := if h : i < a.size then match a[i] with | Entry.null => isUnaryEntries a (i+1) acc | Entry.ref _ => none | Entry.entry k v => match acc with | none => isUnaryEntries a (i+1) (some (k, v)) | some _ => none else acc def isUnaryNode : Node α β → Option (α × β) | Node.entries entries => isUnaryEntries entries 0 none | Node.collision keys vals heq => if h : 1 = keys.size then have : 0 < keys.size := by rw [←h]; decide have : 0 < vals.size := by rw [←heq]; assumption some (keys[0], vals[0]) else none partial def eraseAux [BEq α] : Node α β → USize → α → Node α β × Bool | n@(Node.collision keys vals heq), _, k => match keys.indexOf? k with | some idx => let ⟨keys', keq⟩ := keys.eraseIdx' idx let ⟨vals', veq⟩ := vals.eraseIdx' (Eq.ndrec idx heq) have : keys.size - 1 = vals.size - 1 := by rw [heq] (Node.collision keys' vals' (keq.trans (this.trans veq.symm)), true) | none => (n, false) | n@(Node.entries entries), h, k => let j := (mod2Shift h shift).toNat let entry := entries.get! j match entry with | Entry.null => (n, false) | Entry.entry k' _ => if k == k' then (Node.entries (entries.set! j Entry.null), true) else (n, false) | Entry.ref node => let entries := entries.set! j Entry.null let (newNode, deleted) := eraseAux node (div2Shift h shift) k if !deleted then (n, false) else match isUnaryNode newNode with | none => (Node.entries (entries.set! j (Entry.ref newNode)), true) | some (k, v) => (Node.entries (entries.set! j (Entry.entry k v)), true) def erase {_ : BEq α} {_ : Hashable α} : PersistentHashMap α β → α → PersistentHashMap α β | { root := n, size := sz }, k => let h := hash k |>.toUSize let (n, del) := eraseAux n h k { root := n, size := if del then sz - 1 else sz } section variable {m : Type w → Type w'} [Monad m] variable {σ : Type w} partial def foldlMAux (f : σ → α → β → m σ) : Node α β → σ → m σ | Node.collision keys vals heq, acc => let rec traverse (i : Nat) (acc : σ) : m σ := do if h : i < keys.size then let k := keys[i] have : i < vals.size := heq ▸ h let v := vals[i] traverse (i+1) (← f acc k v) else pure acc traverse 0 acc | Node.entries entries, acc => entries.foldlM (fun acc entry => match entry with | Entry.null => pure acc | Entry.entry k v => f acc k v | Entry.ref node => foldlMAux f node acc) acc def foldlM {_ : BEq α} {_ : Hashable α} (map : PersistentHashMap α β) (f : σ → α → β → m σ) (init : σ) : m σ := foldlMAux f map.root init def forM {_ : BEq α} {_ : Hashable α} (map : PersistentHashMap α β) (f : α → β → m PUnit) : m PUnit := map.foldlM (fun _ => f) ⟨⟩ def foldl {_ : BEq α} {_ : Hashable α} (map : PersistentHashMap α β) (f : σ → α → β → σ) (init : σ) : σ := Id.run <| map.foldlM f init protected def forIn {_ : BEq α} {_ : Hashable α} [Monad m] (map : PersistentHashMap α β) (init : σ) (f : α × β → σ → m (ForInStep σ)) : m σ := do let intoError : ForInStep σ → Except σ σ | .done s => .error s | .yield s => .ok s let result ← foldlM (m := ExceptT σ m) map (init := init) fun s a b => (intoError <$> f (a, b) s : m _) match result with | .ok s | .error s => pure s instance {_ : BEq α} {_ : Hashable α} : ForIn m (PersistentHashMap α β) (α × β) where forIn := PersistentHashMap.forIn end partial def mapMAux {α : Type u} {β : Type v} {σ : Type u} {m : Type u → Type w} [Monad m] (f : β → m σ) (n : Node α β) : m (Node α σ) := do match n with | .collision keys vals heq => let ⟨vals', h⟩ ← vals.mapM' f return .collision keys vals' (h ▸ heq) | .entries entries => let entries' ← entries.mapM fun | .null => return .null | .entry k v => return .entry k (← f v) | .ref node => return .ref (← mapMAux f node) return .entries entries' def mapM {α : Type u} {β : Type v} {σ : Type u} {m : Type u → Type w} [Monad m] {_ : BEq α} {_ : Hashable α} (pm : PersistentHashMap α β) (f : β → m σ) : m (PersistentHashMap α σ) := do let root ← mapMAux f pm.root return { pm with root } def map {α : Type u} {β : Type v} {σ : Type u} {_ : BEq α} {_ : Hashable α} (pm : PersistentHashMap α β) (f : β → σ) : PersistentHashMap α σ := Id.run <| pm.mapM f def toList {_ : BEq α} {_ : Hashable α} (m : PersistentHashMap α β) : List (α × β) := m.foldl (init := []) fun ps k v => (k, v) :: ps structure Stats where numNodes : Nat := 0 numNull : Nat := 0 numCollisions : Nat := 0 maxDepth : Nat := 0 partial def collectStats : Node α β → Stats → Nat → Stats | Node.collision keys _ _, stats, depth => { stats with numNodes := stats.numNodes + 1, numCollisions := stats.numCollisions + keys.size - 1, maxDepth := Nat.max stats.maxDepth depth } | Node.entries entries, stats, depth => let stats := { stats with numNodes := stats.numNodes + 1, maxDepth := Nat.max stats.maxDepth depth } entries.foldl (fun stats entry => match entry with | Entry.null => { stats with numNull := stats.numNull + 1 } | Entry.ref node => collectStats node stats (depth + 1) | Entry.entry _ _ => stats) stats def stats {_ : BEq α} {_ : Hashable α} (m : PersistentHashMap α β) : Stats := collectStats m.root {} 1 def Stats.toString (s : Stats) : String := s!"\{ nodes := {s.numNodes}, null := {s.numNull}, collisions := {s.numCollisions}, depth := {s.maxDepth}}" instance : ToString Stats := ⟨Stats.toString⟩
d64044cfe90944dc0845b793016826db1a6ed1ea
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/int/default.lean
d38b660d74a519147957a5223cd5faf717edf5b2
[ "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
211
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.int.default Author: Jeremy Avigad -/ import .basic .order .div
e62cd4e5b8f4b7d2a568e2f93b0e0aabf75994a3
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/ring_theory/algebra_operations.lean
303317a8d203bff171fd21aacf29c1207fd3e9dd
[ "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
5,626
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Multiplication of submodules of an algebra. -/ import ring_theory.algebra algebra.pointwise import tactic.chain import tactic.monotonicity.basic universes u v open lattice algebra local attribute [instance] set.pointwise_mul_semiring namespace submodule variables {R : Type u} [comm_ring R] section ring variables {A : Type v} [ring A] [algebra R A] variables (S T : set A) {M N P Q : submodule R A} {m n : A} instance : has_one (submodule R A) := ⟨submodule.map (of_id R A).to_linear_map (⊤ : ideal R)⟩ theorem one_eq_map_top : (1 : submodule R A) = submodule.map (of_id R A).to_linear_map (⊤ : ideal R) := rfl theorem one_eq_span : (1 : submodule R A) = span R {1} := begin apply submodule.ext, intro a, erw [mem_map, mem_span_singleton], apply exists_congr, intro r, simpa [smul_def], end theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P := by simpa only [one_eq_span, span_le, set.singleton_subset_iff] set_option class.instance_max_depth 50 instance : has_mul (submodule R A) := ⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩ set_option class.instance_max_depth 32 theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N := (le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩ theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P := ⟨λ H m hm n hn, H $ mul_mem_mul hm hn, λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩ @[elab_as_eliminator] protected theorem mul_induction_on {C : A → Prop} {r : A} (hr : r ∈ M * N) (hm : ∀ (m ∈ M) (n ∈ N), C (m * n)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := (@mul_le _ _ _ _ _ _ _ ⟨C, h0, ha, hs⟩).2 hm hr variables R theorem span_mul_span : span R S * span R T = span R (S * T) := begin apply le_antisymm, { rw mul_le, intros a ha b hb, apply span_induction ha, work_on_goal 0 { intros, apply span_induction hb, work_on_goal 0 { intros, exact subset_span ⟨_, ‹_›, _, ‹_›, rfl⟩ } }, all_goals { intros, simp only [mul_zero, zero_mul, zero_mem, left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc], try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' }, { rw span_le, rintros _ ⟨a, ha, b, hb, rfl⟩, exact mul_mem_mul (subset_span ha) (subset_span hb) } end variables {R} variables (M N P Q) set_option class.instance_max_depth 50 protected theorem mul_assoc : (M * N) * P = M * (N * P) := le_antisymm (mul_le.2 $ λ mn hmn p hp, suffices M * N ≤ (M * (N * P)).comap ((algebra.lmul R A).flip p), from this hmn, mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from (mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp)) (mul_le.2 $ λ m hm np hnp, suffices N * P ≤ (M * N * P).comap (algebra.lmul R A m), from this hnp, mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp) set_option class.instance_max_depth 32 @[simp] theorem mul_bot : M * ⊥ = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero] @[simp] theorem bot_mul : ⊥ * M = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul] @[simp] protected theorem one_mul : (1 : submodule R A) * M = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] } @[simp] protected theorem mul_one : M * 1 = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] } variables {M N P Q} @[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q := mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn) theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P := mul_le_mul h (le_refl P) theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P := mul_le_mul (le_refl M) h variables (M N P) theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P := le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩) (sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right)) theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P := le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩) (sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right)) variables {M N P} instance : semiring (submodule R A) := { one_mul := submodule.one_mul, mul_one := submodule.mul_one, mul_assoc := submodule.mul_assoc, zero_mul := bot_mul, mul_zero := mul_bot, left_distrib := mul_sup, right_distrib := sup_mul, ..submodule.add_comm_monoid, ..submodule.has_one, ..submodule.has_mul } end ring section comm_ring variables {A : Type v} [comm_ring A] [algebra R A] variables {M N : submodule R A} {m n : A} theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N := mul_comm m n ▸ mul_mem_mul hm hn variables (M N) protected theorem mul_comm : M * N = N * M := le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm) (mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn) instance : comm_semiring (submodule R A) := { mul_comm := submodule.mul_comm, .. submodule.semiring } end comm_ring end submodule
364d3eec0b9b70f429f5cd3633cd18706bb01f27
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/matrix/kronecker.lean
a810b104a51e3eb7aa65488e3536b7f11f4f8d18
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
15,616
lean
/- Copyright (c) 2021 Filippo A. E. Nuccio. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Filippo A. E. Nuccio, Eric Wieser -/ import data.matrix.basic import linear_algebra.tensor_product import ring_theory.tensor_product /-! # Kronecker product of matrices This defines the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product). ## Main definitions * `matrix.kronecker_map`: A generalization of the Kronecker product: given a map `f : α → β → γ` and matrices `A` and `B` with coefficients in `α` and `β`, respectively, it is defined as the matrix with coefficients in `γ` such that `kronecker_map f A B (i₁, i₂) (j₁, j₂) = f (A i₁ j₁) (B i₁ j₂)`. * `matrix.kronecker_map_bilinear`: when `f` is bilinear, so is `kronecker_map f`. ## Specializations * `matrix.kronecker`: An alias of `kronecker_map (*)`. Prefer using the notation. * `matrix.kronecker_bilinear`: `matrix.kronecker` is bilinear * `matrix.kronecker_tmul`: An alias of `kronecker_map (⊗ₜ)`. Prefer using the notation. * `matrix.kronecker_tmul_bilinear`: `matrix.tmul_kronecker` is bilinear ## Notations These require `open_locale kronecker`: * `A ⊗ₖ B` for `kronecker_map (*) A B`. Lemmas about this notation use the token `kronecker`. * `A ⊗ₖₜ B` and `A ⊗ₖₜ[R] B` for `kronecker_map (⊗ₜ) A B`. Lemmas about this notation use the token `kronecker_tmul`. -/ namespace matrix open_locale matrix variables {R α α' β β' γ γ' : Type*} variables {l m n p : Type*} {q r : Type*} {l' m' n' p' : Type*} section kronecker_map /-- Produce a matrix with `f` applied to every pair of elements from `A` and `B`. -/ @[simp] def kronecker_map (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) : matrix (l × n) (m × p) γ | i j := f (A i.1 j.1) (B i.2 j.2) lemma kronecker_map_transpose (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) : kronecker_map f Aᵀ Bᵀ = (kronecker_map f A B)ᵀ := ext $ λ i j, rfl lemma kronecker_map_map_left (f : α' → β → γ) (g : α → α') (A : matrix l m α) (B : matrix n p β) : kronecker_map f (A.map g) B = kronecker_map (λ a b, f (g a) b) A B := ext $ λ i j, rfl lemma kronecker_map_map_right (f : α → β' → γ) (g : β → β') (A : matrix l m α) (B : matrix n p β) : kronecker_map f A (B.map g) = kronecker_map (λ a b, f a (g b)) A B := ext $ λ i j, rfl lemma kronecker_map_map (f : α → β → γ) (g : γ → γ') (A : matrix l m α) (B : matrix n p β) : (kronecker_map f A B).map g = kronecker_map (λ a b, g (f a b)) A B := ext $ λ i j, rfl @[simp] lemma kronecker_map_zero_left [has_zero α] [has_zero γ] (f : α → β → γ) (hf : ∀ b, f 0 b = 0) (B : matrix n p β) : kronecker_map f (0 : matrix l m α) B = 0:= ext $ λ i j,hf _ @[simp] lemma kronecker_map_zero_right [has_zero β] [has_zero γ] (f : α → β → γ) (hf : ∀ a, f a 0 = 0) (A : matrix l m α) : kronecker_map f A (0 : matrix n p β) = 0 := ext $ λ i j, hf _ lemma kronecker_map_add_left [has_add α] [has_add γ] (f : α → β → γ) (hf : ∀ a₁ a₂ b, f (a₁ + a₂) b = f a₁ b + f a₂ b) (A₁ A₂ : matrix l m α) (B : matrix n p β) : kronecker_map f (A₁ + A₂) B = kronecker_map f A₁ B + kronecker_map f A₂ B := ext $ λ i j, hf _ _ _ lemma kronecker_map_add_right [has_add β] [has_add γ] (f : α → β → γ) (hf : ∀ a b₁ b₂, f a (b₁ + b₂) = f a b₁ + f a b₂) (A : matrix l m α) (B₁ B₂ : matrix n p β) : kronecker_map f A (B₁ + B₂) = kronecker_map f A B₁ + kronecker_map f A B₂ := ext $ λ i j, hf _ _ _ lemma kronecker_map_smul_left [has_smul R α] [has_smul R γ] (f : α → β → γ) (r : R) (hf : ∀ a b, f (r • a) b = r • f a b) (A : matrix l m α) (B : matrix n p β) : kronecker_map f (r • A) B = r • kronecker_map f A B := ext $ λ i j, hf _ _ lemma kronecker_map_smul_right [has_smul R β] [has_smul R γ] (f : α → β → γ) (r : R) (hf : ∀ a b, f a (r • b) = r • f a b) (A : matrix l m α) (B : matrix n p β) : kronecker_map f A (r • B) = r • kronecker_map f A B := ext $ λ i j, hf _ _ lemma kronecker_map_diagonal_diagonal [has_zero α] [has_zero β] [has_zero γ] [decidable_eq m] [decidable_eq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (a : m → α) (b : n → β): kronecker_map f (diagonal a) (diagonal b) = diagonal (λ mn, f (a mn.1) (b mn.2)) := begin ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩, simp [diagonal, apply_ite f, ite_and, ite_apply, apply_ite (f (a i₁)), hf₁, hf₂], end @[simp] lemma kronecker_map_one_one [has_zero α] [has_zero β] [has_zero γ] [has_one α] [has_one β] [has_one γ] [decidable_eq m] [decidable_eq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (hf₃ : f 1 1 = 1) : kronecker_map f (1 : matrix m m α) (1 : matrix n n β) = 1 := (kronecker_map_diagonal_diagonal _ hf₁ hf₂ _ _).trans $ by simp only [hf₃, diagonal_one] lemma kronecker_map_reindex (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (en : n ≃ n') (ep : p ≃ p') (M : matrix l m α) (N : matrix n p β) : kronecker_map f (reindex el em M) (reindex en ep N) = reindex (el.prod_congr en) (em.prod_congr ep) (kronecker_map f M N) := by { ext ⟨i, i'⟩ ⟨j, j'⟩, refl } lemma kronecker_map_reindex_left (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (M : matrix l m α) (N : matrix n n' β) : kronecker_map f (matrix.reindex el em M) N = reindex (el.prod_congr (equiv.refl _)) (em.prod_congr (equiv.refl _)) (kronecker_map f M N) := kronecker_map_reindex _ _ _ (equiv.refl _) (equiv.refl _) _ _ lemma kronecker_map_reindex_right (f : α → β → γ) (em : m ≃ m') (en : n ≃ n') (M : matrix l l' α) (N : matrix m n β) : kronecker_map f M (reindex em en N) = reindex ((equiv.refl _).prod_congr em) ((equiv.refl _).prod_congr en) (kronecker_map f M N) := kronecker_map_reindex _ (equiv.refl _) (equiv.refl _) _ _ _ _ lemma kronecker_map_assoc {δ ξ ω ω' : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω') (g' : β → δ → ξ) (A : matrix l m α) (B : matrix n p β) (D : matrix q r δ) (φ : ω ≃ ω') (hφ : ∀ a b d, φ (g (f a b) d) = f' a (g' b d)) : (reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r)).trans (equiv.map_matrix φ) (kronecker_map g (kronecker_map f A B) D) = kronecker_map f' A (kronecker_map g' B D) := ext $ λ i j, hφ _ _ _ lemma kronecker_map_assoc₁ {δ ξ ω : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω) (g' : β → δ → ξ) (A : matrix l m α) (B : matrix n p β) (D : matrix q r δ) (h : ∀ a b d, (g (f a b) d) = f' a (g' b d)) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) (kronecker_map g (kronecker_map f A B) D) = kronecker_map f' A (kronecker_map g' B D) := ext $ λ i j, h _ _ _ /-- When `f` is bilinear then `matrix.kronecker_map f` is also bilinear. -/ @[simps] def kronecker_map_bilinear [comm_semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) : matrix l m α →ₗ[R] matrix n p β →ₗ[R] matrix (l × n) (m × p) γ := linear_map.mk₂ R (kronecker_map (λ r s, f r s)) (kronecker_map_add_left _ $ f.map_add₂) (λ r, kronecker_map_smul_left _ _ $ f.map_smul₂ _) (kronecker_map_add_right _ $ λ a, (f a).map_add) (λ r, kronecker_map_smul_right _ _ $ λ a, (f a).map_smul r) /-- `matrix.kronecker_map_bilinear` commutes with `⬝` if `f` commutes with `*`. This is primarily used with `R = ℕ` to prove `matrix.mul_kronecker_mul`. -/ lemma kronecker_map_bilinear_mul_mul [comm_semiring R] [fintype m] [fintype m'] [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] [non_unital_non_assoc_semiring γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) (h_comm : ∀ a b a' b', f (a * b) (a' * b') = f a a' * f b b') (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' β) (B' : matrix m' n' β) : kronecker_map_bilinear f (A ⬝ B) (A' ⬝ B') = (kronecker_map_bilinear f A A') ⬝ (kronecker_map_bilinear f B B') := begin ext ⟨i, i'⟩ ⟨j, j'⟩, simp only [kronecker_map_bilinear_apply_apply, mul_apply, ← finset.univ_product_univ, finset.sum_product, kronecker_map], simp_rw [f.map_sum, linear_map.sum_apply, linear_map.map_sum, h_comm], end end kronecker_map /-! ### Specialization to `matrix.kronecker_map (*)` -/ section kronecker variables (R) open_locale matrix /-- The Kronecker product. This is just a shorthand for `kronecker_map (*)`. Prefer the notation `⊗ₖ` rather than this definition. -/ @[simp] def kronecker [has_mul α] : matrix l m α → matrix n p α → matrix (l × n) (m × p) α := kronecker_map (*) localized "infix ` ⊗ₖ `:100 := matrix.kronecker_map (*)" in kronecker @[simp] lemma kronecker_apply [has_mul α] (A : matrix l m α) (B : matrix n p α) (i₁ i₂ j₁ j₂) : (A ⊗ₖ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ * B i₂ j₂ := rfl /-- `matrix.kronecker` as a bilinear map. -/ def kronecker_bilinear [comm_semiring R] [semiring α] [algebra R α] : matrix l m α →ₗ[R] matrix n p α →ₗ[R] matrix (l × n) (m × p) α := kronecker_map_bilinear (algebra.lmul R α).to_linear_map /-! What follows is a copy, in order, of every `matrix.kronecker_map` lemma above that has hypotheses which can be filled by properties of `*`. -/ @[simp] lemma zero_kronecker [mul_zero_class α] (B : matrix n p α) : (0 : matrix l m α) ⊗ₖ B = 0 := kronecker_map_zero_left _ zero_mul B @[simp] lemma kronecker_zero [mul_zero_class α] (A : matrix l m α) : A ⊗ₖ (0 : matrix n p α) = 0 := kronecker_map_zero_right _ mul_zero A lemma add_kronecker [distrib α] (A₁ A₂ : matrix l m α) (B : matrix n p α) : (A₁ + A₂) ⊗ₖ B = A₁ ⊗ₖ B + A₂ ⊗ₖ B := kronecker_map_add_left _ add_mul _ _ _ lemma kronecker_add [distrib α] (A : matrix l m α) (B₁ B₂ : matrix n p α) : A ⊗ₖ (B₁ + B₂) = A ⊗ₖ B₁ + A ⊗ₖ B₂ := kronecker_map_add_right _ mul_add _ _ _ lemma smul_kronecker [monoid R] [monoid α] [mul_action R α] [is_scalar_tower R α α] (r : R) (A : matrix l m α) (B : matrix n p α) : (r • A) ⊗ₖ B = r • (A ⊗ₖ B) := kronecker_map_smul_left _ _ (λ _ _, smul_mul_assoc _ _ _) _ _ lemma kronecker_smul [monoid R] [monoid α] [mul_action R α] [smul_comm_class R α α] (r : R) (A : matrix l m α) (B : matrix n p α) : A ⊗ₖ (r • B) = r • (A ⊗ₖ B) := kronecker_map_smul_right _ _ (λ _ _, mul_smul_comm _ _ _) _ _ lemma diagonal_kronecker_diagonal [mul_zero_class α] [decidable_eq m] [decidable_eq n] (a : m → α) (b : n → α): (diagonal a) ⊗ₖ (diagonal b) = diagonal (λ mn, (a mn.1) * (b mn.2)) := kronecker_map_diagonal_diagonal _ zero_mul mul_zero _ _ @[simp] lemma one_kronecker_one [mul_zero_one_class α] [decidable_eq m] [decidable_eq n] : (1 : matrix m m α) ⊗ₖ (1 : matrix n n α) = 1 := kronecker_map_one_one _ zero_mul mul_zero (one_mul _) lemma mul_kronecker_mul [fintype m] [fintype m'] [comm_semiring α] (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' α) (B' : matrix m' n' α) : (A ⬝ B) ⊗ₖ (A' ⬝ B') = (A ⊗ₖ A') ⬝ (B ⊗ₖ B') := kronecker_map_bilinear_mul_mul (algebra.lmul ℕ α).to_linear_map mul_mul_mul_comm A B A' B' @[simp] lemma kronecker_assoc [semigroup α] (A : matrix l m α) (B : matrix n p α) (C : matrix q r α) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) ((A ⊗ₖ B) ⊗ₖ C) = A ⊗ₖ (B ⊗ₖ C) := kronecker_map_assoc₁ _ _ _ _ A B C mul_assoc end kronecker /-! ### Specialization to `matrix.kronecker_map (⊗ₜ)` -/ section kronecker_tmul variables (R) open tensor_product open_locale matrix tensor_product section module variables [comm_semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] variables [module R α] [module R β] [module R γ] /-- The Kronecker tensor product. This is just a shorthand for `kronecker_map (⊗ₜ)`. Prefer the notation `⊗ₖₜ` rather than this definition. -/ @[simp] def kronecker_tmul : matrix l m α → matrix n p β → matrix (l × n) (m × p) (α ⊗[R] β) := kronecker_map (⊗ₜ) localized "infix ` ⊗ₖₜ `:100 := matrix.kronecker_map (⊗ₜ)" in kronecker localized "notation x ` ⊗ₖₜ[`:100 R `] `:0 y:100 := matrix.kronecker_map (tensor_product.tmul R) x y" in kronecker @[simp] lemma kronecker_tmul_apply (A : matrix l m α) (B : matrix n p β) (i₁ i₂ j₁ j₂) : (A ⊗ₖₜ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ ⊗ₜ[R] B i₂ j₂ := rfl /-- `matrix.kronecker` as a bilinear map. -/ def kronecker_tmul_bilinear : matrix l m α →ₗ[R] matrix n p β →ₗ[R] matrix (l × n) (m × p) (α ⊗[R] β) := kronecker_map_bilinear (tensor_product.mk R α β) /-! What follows is a copy, in order, of every `matrix.kronecker_map` lemma above that has hypotheses which can be filled by properties of `⊗ₜ`. -/ @[simp] lemma zero_kronecker_tmul (B : matrix n p β) : (0 : matrix l m α) ⊗ₖₜ[R] B = 0 := kronecker_map_zero_left _ (zero_tmul α) B @[simp] lemma kronecker_tmul_zero (A : matrix l m α) : A ⊗ₖₜ[R] (0 : matrix n p β) = 0 := kronecker_map_zero_right _ (tmul_zero β) A lemma add_kronecker_tmul (A₁ A₂ : matrix l m α) (B : matrix n p α) : (A₁ + A₂) ⊗ₖₜ[R] B = A₁ ⊗ₖₜ B + A₂ ⊗ₖₜ B := kronecker_map_add_left _ add_tmul _ _ _ lemma kronecker_tmul_add (A : matrix l m α) (B₁ B₂ : matrix n p α) : A ⊗ₖₜ[R] (B₁ + B₂) = A ⊗ₖₜ B₁ + A ⊗ₖₜ B₂ := kronecker_map_add_right _ tmul_add _ _ _ lemma smul_kronecker_tmul (r : R) (A : matrix l m α) (B : matrix n p α) : (r • A) ⊗ₖₜ[R] B = r • (A ⊗ₖₜ B) := kronecker_map_smul_left _ _ (λ _ _, smul_tmul' _ _ _) _ _ lemma kronecker_tmul_smul (r : R) (A : matrix l m α) (B : matrix n p α) : A ⊗ₖₜ[R] (r • B) = r • (A ⊗ₖₜ B) := kronecker_map_smul_right _ _ (λ _ _, tmul_smul _ _ _) _ _ lemma diagonal_kronecker_tmul_diagonal [decidable_eq m] [decidable_eq n] (a : m → α) (b : n → α): (diagonal a) ⊗ₖₜ[R] (diagonal b) = diagonal (λ mn, a mn.1 ⊗ₜ b mn.2) := kronecker_map_diagonal_diagonal _ (zero_tmul _) (tmul_zero _) _ _ @[simp] lemma kronecker_tmul_assoc (A : matrix l m α) (B : matrix n p β) (C : matrix q r γ) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) (((A ⊗ₖₜ[R] B) ⊗ₖₜ[R] C).map (tensor_product.assoc _ _ _ _)) = A ⊗ₖₜ[R] (B ⊗ₖₜ[R] C) := ext $ λ i j, assoc_tmul _ _ _ end module section algebra variables [comm_semiring R] [semiring α] [semiring β] [algebra R α] [algebra R β] open_locale kronecker open algebra.tensor_product @[simp] lemma one_kronecker_tmul_one [decidable_eq m] [decidable_eq n] : (1 : matrix m m α) ⊗ₖₜ[R] (1 : matrix n n α) = 1 := kronecker_map_one_one _ (zero_tmul _) (tmul_zero _) rfl lemma mul_kronecker_tmul_mul [fintype m] [fintype m'] (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' β) (B' : matrix m' n' β) : (A ⬝ B) ⊗ₖₜ[R] (A' ⬝ B') = (A ⊗ₖₜ A') ⬝ (B ⊗ₖₜ B') := kronecker_map_bilinear_mul_mul (tensor_product.mk R α β) tmul_mul_tmul A B A' B' end algebra -- insert lemmas specific to `kronecker_tmul` below this line end kronecker_tmul end matrix
747f5644d57fbf496b11ece7809152b29ee6d2c2
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/hott/types/pi.hlean
36568b5c4dc475712580e1992e131cbc915d3c72
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,769
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 open eq equiv is_equiv funext sigma unit bool is_trunc prod 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 -/ /- Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ~ g]. This equivalence, however, is just the combination of [apd10] and function extensionality [funext], and as such, [eq_of_homotopy] Now we show how these things compute. -/ definition apd10_eq_of_homotopy (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h := apd10 (right_inv apd10 h) definition eq_of_homotopy_eta (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p definition eq_of_homotopy_idp (f : Πa, B a) : eq_of_homotopy (λx : A, refl (f x)) = refl f := !eq_of_homotopy_eta /- 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 =[apo011 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 =[apo011 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') =[apo011 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.refl) 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 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 apd end, begin intro h, apply eq_of_homotopy, intro a, esimp, rewrite [left_inv (f1 _)], apply apd 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.refl 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 /- Truncatedness: any dependent product of n-types is an n-type -/ theorem is_trunc_pi (B : A → Type) (n : trunc_index) [H : ∀a, is_trunc n (B a)] : is_trunc n (Πa, B a) := begin revert B H, eapply (trunc_index.rec_on n), {intro B H, fapply is_contr.mk, intro a, apply center, intro f, apply eq_of_homotopy, intro x, apply (center_eq (f x))}, {intro n IH 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 [instance] [priority 500] (n : trunc_index) (f g : Πa, B a) [H : ∀a, is_trunc n (f a = g a)] : is_trunc n (f = g) := begin apply is_trunc_equiv_closed_rev, apply eq_equiv_homotopy end theorem is_trunc_not [instance] (n : trunc_index) (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'), assert 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) := _ /- 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) _ end pi attribute pi.is_trunc_pi [instance] [priority 1520]
d5e2fe9582f03f57226f94c25acc50c52e845b35
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/coe_opt.lean
d424563b6273727174951c6886e3c3f1fc9b1de7
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
204
lean
def f : nat → option nat → nat | a none := a | a (some b) := a + b example (a b : nat) : f a b = a + b := rfl example (a b : nat) : f a b = f a (some b) := rfl example : f 1 (1:nat) = 2 := rfl
680bfd0aac385b0d3ab8354e1cf7e683320700eb
b7b549d2cf38ac9d4e49372b7ad4d37f70449409
/src/LeanLLVM/Alignment.lean
7dc47a07a221ac530e52a522667fbc18c8c0b188
[ "Apache-2.0" ]
permissive
GaloisInc/lean-llvm
7cc196172fe02ff3554edba6cc82f333c30fdc2b
36e2ec604ae22d8ec1b1b66eca0f8887880db6c6
refs/heads/master
1,637,359,020,356
1,629,332,114,000
1,629,402,464,000
146,700,234
29
1
Apache-2.0
1,631,225,695,000
1,535,607,191,000
Lean
UTF-8
Lean
false
false
3,259
lean
import Std.Data.RBMap open Std (RBMap) namespace Std namespace RBNode universe u v variable {α : Type u} {β : α → Type v} section variable (cmp : α → α → Ordering) @[specialize] def upperBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, x, ub => ub | node _ a ky vy b, x, ub => match cmp x ky with | Ordering.lt => upperBound a x (some ⟨ky, vy⟩) | Ordering.gt => upperBound b x ub | Ordering.eq => some ⟨ky, vy⟩ end end RBNode end Std namespace Std namespace RBMap universe u v variable {α : Type u} {β : Type v} {cmp : α → α → Ordering} /- (upperBound k) retrieves the kv pair of the smallest key larger than or equal to `k`, if it exists -/ @[inline] def upperBound : RBMap α β cmp → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.upperBound cmp x none end RBMap end Std namespace LLVM -- An alignment represents a number of bytes that must be a power of 2, -- and is represented via its exponent structure Alignment := (exponent : Nat) -- 1-byte alignment, which is the minimum possible def unaligned : Alignment := ⟨0⟩ -- 2-byte alignment def align2 : Alignment := ⟨1⟩ -- 4-byte alignment def align4 : Alignment := ⟨2⟩ -- 8-byte alignment def align8 : Alignment := ⟨3⟩ -- 16-byte alignment def align16 : Alignment := ⟨4⟩ def maxAlignment (x y: Alignment) : Alignment := ⟨Nat.max x.exponent y.exponent⟩ instance alignment.inh : Inhabited Alignment := ⟨unaligned⟩ partial def lg2aux : Nat → Nat → Nat | r, 0 => r | r, n => lg2aux (r+1) (n/2) def toAlignment (x:Nat) : Option Alignment := let l := lg2aux 0 (x/2); if 2^l = x then some ⟨l⟩ else none -- @padToAlignment x a@ returns the smallest value aligned with @a@ not less than @x@. def padToAlignment (x:Nat) (a:Alignment) := let m : Nat := 2^a.exponent; (x + m - 1)/m * m -- @padDownToAlignment x a@ returns the largest value aligned with @a@ that is not larger than @x@. def padDownToAlignment (x:Nat) (a:Alignment) : Nat := let m : Nat := 2^a.exponent; x/m * m def AlignInfo := RBMap Nat Alignment Ord.compare -- Get alignment for the integer type of the specified bitwidth, -- using LLVM's rules for integer types: "If no match is found, and -- the type sought is an integer type, then the smallest integer type -- that is larger than the bitwidth of the sought type is used. If -- none of the specifications are larger than the bitwidth then the -- largest integer type is used." -- <http://llvm.org/docs/LangRef.html#langref-datalayout> def computeIntegerAlignment (ai:AlignInfo) (k:Nat) : Alignment := match ai.upperBound k with | some ⟨_, a⟩ => a | none => match ai.max with | some ⟨_, a⟩ => a | none => unaligned -- | Get alignment for a vector type of the specified bitwidth, using -- LLVM's rules for vector types: "If no match is found, and the type -- sought is a vector type, then the largest vector type that is -- smaller than the sought vector type will be used as a fall back." -- <http://llvm.org/docs/LangRef.html#langref-datalayout> def computeVectorAlignment (ai:AlignInfo) (k:Nat) : Alignment := match ai.lowerBound k with | some ⟨_, a⟩ => a | none => unaligned end LLVM
1bf01b774c96365ad59e833071080739cca03309
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/04_Quantifiers_and_Equality.org.5.lean
4c32887fa57a4905e70024da3e9220093e8e6093
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
325
lean
/- page 49 -/ import standard variables (A : Type) (r : A → A → Prop) variable refl_r : ∀ x, r x x variable symm_r : ∀ {x y}, r x y → r y x variable trans_r : ∀ {x y z}, r x y → r y z → r x z example (a b c d : A) (Hab : r a b) (Hcb : r c b) (Hcd : r c d) : r a d := trans_r (trans_r Hab (symm_r Hcb)) Hcd
dfa6a7daa89c834481f0e662a4d44b5ae0d0f881
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/pnat/factors.lean
8ec9731487773dbff5b7ce5d1129e69dc7b06725
[ "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
14,415
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import data.pnat.prime import data.multiset.sort import data.int.gcd import algebra.group /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and ℕ+, as we will formalize below. -/ def prime_multiset := multiset nat.primes namespace prime_multiset instance : inhabited prime_multiset := by unfold prime_multiset; apply_instance instance : has_repr prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : canonically_ordered_add_monoid prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : distrib_lattice prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : semilattice_sup_bot prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : has_sub prime_multiset := by { dsimp [prime_multiset], apply_instance } theorem add_sub_of_le {u v : prime_multiset} : u ≤ v → u + (v - u) = v := multiset.add_sub_of_le /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := (p ::ₘ 0) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset → multiset ℕ := λ v, v.map (λ p, (p : ℕ)) instance coe_nat : has_coe prime_multiset (multiset ℕ) := ⟨to_nat_multiset⟩ instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ) := by { unfold_coes, dsimp [to_nat_multiset], apply_instance } theorem coe_nat_injective : function.injective (coe : prime_multiset → multiset ℕ) := multiset.map_injective nat.primes.coe_nat_inj theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ) = (p : ℕ) ::ₘ 0 := rfl theorem coe_nat_prime (v : prime_multiset) (p : ℕ) (h : p ∈ (v : multiset ℕ)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } /-- Converts a `prime_multiset` to a `multiset ℕ+`. -/ def to_pnat_multiset : prime_multiset → multiset ℕ+ := λ v, v.map (λ p, (p : ℕ+)) instance coe_pnat : has_coe prime_multiset (multiset ℕ+) := ⟨to_pnat_multiset⟩ instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ+) := by { unfold_coes, dsimp [to_pnat_multiset], apply_instance } theorem coe_pnat_injective : function.injective (coe : prime_multiset → multiset ℕ+) := multiset.map_injective nat.primes.coe_pnat_inj theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ+) = (p : ℕ+) ::ₘ 0 := rfl theorem coe_pnat_prime (v : prime_multiset) (p : ℕ+) (h : p ∈ (v : multiset ℕ+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } instance coe_multiset_pnat_nat : has_coe (multiset ℕ+) (multiset ℕ) := ⟨λ v, v.map (λ n, (n : ℕ))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset ℕ+)) : (multiset ℕ)) = (v : multiset ℕ) := by { change (v.map (coe : nat.primes → ℕ+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } /-- The product of a `prime_multiset`, as a `ℕ+`. -/ def prod (v : prime_multiset) : ℕ+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : ℕ) = (v : multiset ℕ).prod := begin let h : (v.prod : ℕ) = ((v.map coe).map coe).prod := ((monoid_hom.of coe).map_multiset_prod v.to_pnat_multiset), rw [multiset.map_map] at h, have : (coe : ℕ+ → ℕ) ∘ (coe : nat.primes → ℕ+) = coe := funext (λ p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : ℕ+) := by { change multiset.prod ((p : ℕ+) ::ₘ 0) = (p : ℕ+), rw [multiset.prod_cons, multiset.prod_zero, mul_one] } /-- If a `multiset ℕ` consists only of primes, it can be recast as a `prime_multiset`. -/ def of_nat_multiset (v : multiset ℕ) (h : ∀ (p : ℕ), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ nat.primes nat.prime (λ p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h) : multiset ℕ) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (λ (p : ℕ) (h : p.prime), ((⟨p, h⟩ : nat.primes) : ℕ)) = (λ p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h).prod : ℕ) = (v.prod : ℕ) := by rw[coe_prod, to_of_nat_multiset] /-- If a `multiset ℕ+` consists only of primes, it can be recast as a `prime_multiset`. -/ def of_pnat_multiset (v : multiset ℕ+) (h : ∀ (p : ℕ+), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ+ nat.primes pnat.prime (λ p hp, ⟨(p : ℕ), hp⟩) v h theorem to_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h) : multiset ℕ+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (λ (p : ℕ+) (h : p.prime), ((coe : nat.primes → ℕ+) ⟨p, h⟩)) = (λ p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h).prod : ℕ+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list ℕ) (h : ∀ (p : ℕ), p ∈ l → p.prime) : prime_multiset := of_nat_multiset (l : multiset ℕ) h theorem prod_of_nat_list (l : list ℕ) (h) : ((of_nat_list l h).prod : ℕ) = l.prod := by { have := prod_of_nat_multiset (l : multiset ℕ) h, rw [multiset.coe_prod] at this, exact this } /-- If a `list ℕ+` consists only of primes, it can be recast as a `prime_multiset` with the coercion from lists to multisets. -/ def of_pnat_list (l : list ℕ+) (h : ∀ (p : ℕ+), p ∈ l → p.prime) : prime_multiset := of_pnat_multiset (l : multiset ℕ+) h theorem prod_of_pnat_list (l : list ℕ+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset ℕ+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid ℕ+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := by { dsimp [prod], rw [is_add_monoid_hom.map_add (coe : prime_multiset → multiset ℕ+)], rw [multiset.prod_add] } theorem prod_smul (d : ℕ) (u : prime_multiset) : (d •ℕ u).prod = u.prod ^ d := by { induction d with d ih, refl, rw [succ_nsmul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : ℕ+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : ℕ+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.pos } theorem coe_nat_factor_multiset (n : ℕ+) : ((factor_multiset n) : (multiset ℕ)) = ((nat.factors n) : multiset ℕ) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_injective, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with ⟨l⟩, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes → ℕ), have : ∀ (p : ℕ), p ∈ l' → p.prime := λ p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : ℕ+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid ℕ+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := rfl theorem factor_multiset_mul (n m : ℕ+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : ℕ+) (m : ℕ) : factor_multiset (n ^ m) = m •ℕ (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : ℕ+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : ℕ+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : ℕ+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : ℕ+} : factor_multiset m ≤ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd.intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, prime_multiset.add_sub_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_add_right (le_refl _) } end theorem factor_multiset_le_iff' {m : ℕ+} {v : prime_multiset}: factor_multiset m ≤ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≤ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : ℕ+) : factor_multiset (gcd m n) = (factor_multiset m) ⊓ (factor_multiset n) := begin apply le_antisymm, { apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact inf_le_left, exact inf_le_right} end theorem factor_multiset_lcm (m n : ℕ+) : factor_multiset (lcm m n) = (factor_multiset m) ⊔ (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact le_sup_left, exact le_sup_right}, { apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : ℕ+) (p : nat.primes) (k : ℕ) : (p : ℕ+) ^ k ∣ m ↔ k ≤ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_nsmul, prime_multiset.card_of_prime, mul_one] }, { have : ∀ (m : ℕ), m •ℕ (p ::ₘ 0) = multiset.repeat p m := λ m, by {induction m with m ih, { refl }, rw [succ_nsmul, multiset.repeat_succ, ih], rw[multiset.cons_add, zero_add] }, intros q h, rw [prime_multiset.of_prime, this k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u ⊓ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊓ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u ⊔ v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊔ v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
69b622fdbaddadd4c81d2ffd9e35e38129ddc1b4
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/closed/cartesian.lean
2771bcebae80486e5db3e7eb0933089c9ec01f90
[ "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
16,455
lean
/- Copyright (c) 2020 Bhavik Mehta, Edward Ayers, Thomas Read. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Edward Ayers, Thomas Read -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.constructions.preserve_binary_products import category_theory.closed.monoidal import category_theory.monoidal.of_has_finite_products import category_theory.adjunction import category_theory.epi_mono /-! # Cartesian closed categories Given a category with finite products, the cartesian monoidal structure is provided by the local instance `monoidal_of_has_finite_products`. We define exponentiable objects to be closed objects with respect to this monoidal structure, i.e. `(X × -)` is a left adjoint. We say a category is cartesian closed if every object is exponentiable (equivalently, that the category equipped with the cartesian monoidal structure is closed monoidal). Show that exponential forms a difunctor and define the exponential comparison morphisms. ## TODO Some of the results here are true more generally for closed objects and for closed monoidal categories, and these could be generalised. -/ universes v u u₂ namespace category_theory open category_theory category_theory.category category_theory.limits local attribute [instance] monoidal_of_has_finite_products /-- An object `X` is *exponentiable* if `(X × -)` is a left adjoint. We define this as being `closed` in the cartesian monoidal structure. -/ abbreviation exponentiable {C : Type u} [category.{v} C] [has_finite_products C] (X : C) := closed X /-- If `X` and `Y` are exponentiable then `X ⨯ Y` is. This isn't an instance because it's not usually how we want to construct exponentials, we'll usually prove all objects are exponential uniformly. -/ def binary_product_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] {X Y : C} (hX : exponentiable X) (hY : exponentiable Y) : exponentiable (X ⨯ Y) := { is_adj := begin haveI := hX.is_adj, haveI := hY.is_adj, exact adjunction.left_adjoint_of_nat_iso (monoidal_category.tensor_left_tensor _ _).symm end } /-- The terminal object is always exponentiable. This isn't an instance because most of the time we'll prove cartesian closed for all objects at once, rather than just for this one. -/ def terminal_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] : exponentiable ⊤_C := unit_closed /-- A category `C` is cartesian closed if it has finite products and every object is exponentiable. We define this as `monoidal_closed` with respect to the cartesian monoidal structure. -/ abbreviation cartesian_closed (C : Type u) [category.{v} C] [has_finite_products C] := monoidal_closed C variables {C : Type u} [category.{v} C] (A B : C) {X X' Y Y' Z : C} section exp variables [has_finite_products C] [exponentiable A] /-- This is (-)^A. -/ def exp : C ⥤ C := (@closed.is_adj _ _ _ A _).right /-- The adjunction between A ⨯ - and (-)^A. -/ def exp.adjunction : prod_functor.obj A ⊣ exp A := closed.is_adj.adj /-- The evaluation natural transformation. -/ def ev : exp A ⋙ prod_functor.obj A ⟶ 𝟭 C := closed.is_adj.adj.counit /-- The coevaluation natural transformation. -/ def coev : 𝟭 C ⟶ prod_functor.obj A ⋙ exp A := closed.is_adj.adj.unit notation A ` ⟹ `:20 B:20 := (exp A).obj B notation B ` ^^ `:30 A:30 := (exp A).obj B @[simp, reassoc] lemma ev_coev : limits.prod.map (𝟙 A) ((coev A).app B) ≫ (ev A).app (A ⨯ B) = 𝟙 (A ⨯ B) := adjunction.left_triangle_components (exp.adjunction A) @[simp, reassoc] lemma coev_ev : (coev A).app (A⟹B) ≫ (exp A).map ((ev A).app B) = 𝟙 (A⟹B) := adjunction.right_triangle_components (exp.adjunction A) end exp variables {A} -- Wrap these in a namespace so we don't clash with the core versions. namespace cartesian_closed variables [has_finite_products C] [exponentiable A] /-- Currying in a cartesian closed category. -/ def curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X) := (closed.is_adj.adj.hom_equiv _ _).to_fun /-- Uncurrying in a cartesian closed category. -/ def uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X) := (closed.is_adj.adj.hom_equiv _ _).inv_fun end cartesian_closed open cartesian_closed variables [has_finite_products C] [exponentiable A] @[reassoc] lemma curry_natural_left (f : X ⟶ X') (g : A ⨯ X' ⟶ Y) : curry (limits.prod.map (𝟙 _) f ≫ g) = f ≫ curry g := adjunction.hom_equiv_naturality_left _ _ _ @[reassoc] lemma curry_natural_right (f : A ⨯ X ⟶ Y) (g : Y ⟶ Y') : curry (f ≫ g) = curry f ≫ (exp _).map g := adjunction.hom_equiv_naturality_right _ _ _ @[reassoc] lemma uncurry_natural_right (f : X ⟶ A⟹Y) (g : Y ⟶ Y') : uncurry (f ≫ (exp _).map g) = uncurry f ≫ g := adjunction.hom_equiv_naturality_right_symm _ _ _ @[reassoc] lemma uncurry_natural_left (f : X ⟶ X') (g : X' ⟶ A⟹Y) : uncurry (f ≫ g) = limits.prod.map (𝟙 _) f ≫ uncurry g := adjunction.hom_equiv_naturality_left_symm _ _ _ @[simp] lemma uncurry_curry (f : A ⨯ X ⟶ Y) : uncurry (curry f) = f := (closed.is_adj.adj.hom_equiv _ _).left_inv f @[simp] lemma curry_uncurry (f : X ⟶ A⟹Y) : curry (uncurry f) = f := (closed.is_adj.adj.hom_equiv _ _).right_inv f lemma curry_eq_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) : curry f = g ↔ f = uncurry g := adjunction.hom_equiv_apply_eq _ f g lemma eq_curry_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) : g = curry f ↔ uncurry g = f := adjunction.eq_hom_equiv_apply _ f g -- I don't think these two should be simp. lemma uncurry_eq (g : Y ⟶ A ⟹ X) : uncurry g = limits.prod.map (𝟙 A) g ≫ (ev A).app X := adjunction.hom_equiv_counit _ lemma curry_eq (g : A ⨯ Y ⟶ X) : curry g = (coev A).app Y ≫ (exp A).map g := adjunction.hom_equiv_unit _ lemma uncurry_id_eq_ev (A X : C) [exponentiable A] : uncurry (𝟙 (A ⟹ X)) = (ev A).app X := by rw [uncurry_eq, prod_map_id_id, id_comp] lemma curry_id_eq_coev (A X : C) [exponentiable A] : curry (𝟙 _) = (coev A).app X := by { rw [curry_eq, (exp A).map_id (A ⨯ _)], apply comp_id } lemma curry_injective : function.injective (curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X)) := (closed.is_adj.adj.hom_equiv _ _).injective lemma uncurry_injective : function.injective (uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X)) := (closed.is_adj.adj.hom_equiv _ _).symm.injective /-- Show that the exponential of the terminal object is isomorphic to itself, i.e. `X^1 ≅ X`. The typeclass argument is explicit: any instance can be used. -/ def exp_terminal_iso_self [exponentiable ⊤_C] : (⊤_C ⟹ X) ≅ X := yoneda.ext (⊤_ C ⟹ X) X (λ Y f, (prod.left_unitor Y).inv ≫ uncurry f) (λ Y f, curry ((prod.left_unitor Y).hom ≫ f)) (λ Z g, by rw [curry_eq_iff, iso.hom_inv_id_assoc] ) (λ Z g, by simp) (λ Z W f g, by rw [uncurry_natural_left, prod_left_unitor_inv_naturality_assoc f] ) /-- The internal element which points at the given morphism. -/ def internalize_hom (f : A ⟶ Y) : ⊤_C ⟶ (A ⟹ Y) := curry (limits.prod.fst ≫ f) section pre variables {B} /-- Pre-compose an internal hom with an external hom. -/ def pre (X : C) (f : B ⟶ A) [exponentiable B] : (A⟹X) ⟶ B⟹X := curry (limits.prod.map f (𝟙 _) ≫ (ev A).app X) lemma pre_id (A X : C) [exponentiable A] : pre X (𝟙 A) = 𝟙 (A⟹X) := by { rw [pre, prod_map_id_id, id_comp, ← uncurry_id_eq_ev], simp } -- There's probably a better proof of this somehow /-- Precomposition is contrafunctorial. -/ lemma pre_map [exponentiable B] {D : C} [exponentiable D] (f : A ⟶ B) (g : B ⟶ D) : pre X (f ≫ g) = pre X g ≫ pre X f := begin rw [pre, curry_eq_iff, pre, pre, uncurry_natural_left, uncurry_curry, prod_map_map_assoc, prod_map_comp_id, assoc, ← uncurry_id_eq_ev, ← uncurry_id_eq_ev, ← uncurry_natural_left, curry_natural_right, comp_id, uncurry_natural_right, uncurry_curry], end end pre lemma pre_post_comm [cartesian_closed C] {A B : C} {X Y : Cᵒᵖ} (f : A ⟶ B) (g : X ⟶ Y) : pre A g.unop ≫ (exp Y.unop).map f = (exp X.unop).map f ≫ pre B g.unop := begin erw [← curry_natural_left, eq_curry_iff, uncurry_natural_right, uncurry_curry, prod_map_map_assoc, (ev _).naturality, assoc], refl end /-- The internal hom functor given by the cartesian closed structure. -/ def internal_hom [cartesian_closed C] : C ⥤ Cᵒᵖ ⥤ C := { obj := λ X, { obj := λ Y, Y.unop ⟹ X, map := λ Y Y' f, pre _ f.unop, map_id' := λ Y, pre_id _ _, map_comp' := λ Y Y' Y'' f g, pre_map _ _ }, map := λ A B f, { app := λ X, (exp X.unop).map f, naturality' := λ X Y g, pre_post_comm _ _ }, map_id' := λ X, by { ext, apply functor.map_id }, map_comp' := λ X Y Z f g, by { ext, apply functor.map_comp } } /-- If an initial object `I` exists in a CCC, then `A ⨯ I ≅ I`. -/ @[simps] def zero_mul {I : C} (t : is_initial I) : A ⨯ I ≅ I := { hom := limits.prod.snd, inv := t.to _, hom_inv_id' := begin have: (limits.prod.snd : A ⨯ I ⟶ I) = uncurry (t.to _), rw ← curry_eq_iff, apply t.hom_ext, rw [this, ← uncurry_natural_right, ← eq_curry_iff], apply t.hom_ext, end, inv_hom_id' := t.hom_ext _ _ } /-- If an initial object `0` exists in a CCC, then `0 ⨯ A ≅ 0`. -/ def mul_zero {I : C} (t : is_initial I) : I ⨯ A ≅ I := limits.prod.braiding _ _ ≪≫ zero_mul t /-- If an initial object `0` exists in a CCC then `0^B ≅ 1` for any `B`. -/ def pow_zero {I : C} (t : is_initial I) [cartesian_closed C] : I ⟹ B ≅ ⊤_ C := { hom := default _, inv := curry ((mul_zero t).hom ≫ t.to _), hom_inv_id' := begin rw [← curry_natural_left, curry_eq_iff, ← cancel_epi (mul_zero t).inv], { apply t.hom_ext }, { apply_instance }, { apply_instance } end } -- TODO: Generalise the below to its commutated variants. -- TODO: Define a distributive category, so that zero_mul and friends can be derived from this. /-- In a CCC with binary coproducts, the distribution morphism is an isomorphism. -/ def prod_coprod_distrib [has_binary_coproducts C] [cartesian_closed C] (X Y Z : C) : (Z ⨯ X) ⨿ (Z ⨯ Y) ≅ Z ⨯ (X ⨿ Y) := { hom := coprod.desc (limits.prod.map (𝟙 _) coprod.inl) (limits.prod.map (𝟙 _) coprod.inr), inv := uncurry (coprod.desc (curry coprod.inl) (curry coprod.inr)), hom_inv_id' := begin apply coprod.hom_ext, rw [coprod.inl_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inl_desc, uncurry_curry], rw [coprod.inr_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inr_desc, uncurry_curry], end, inv_hom_id' := begin rw [← uncurry_natural_right, ←eq_curry_iff], apply coprod.hom_ext, rw [coprod.inl_desc_assoc, ←curry_natural_right, coprod.inl_desc, ←curry_natural_left, comp_id], rw [coprod.inr_desc_assoc, ←curry_natural_right, coprod.inr_desc, ←curry_natural_left, comp_id], end } /-- If an initial object `I` exists in a CCC then it is a strict initial object, i.e. any morphism to `I` is an iso. This actually shows a slightly stronger version: any morphism to an initial object from an exponentiable object is an isomorphism. -/ def strict_initial {I : C} (t : is_initial I) (f : A ⟶ I) : is_iso f := begin haveI : mono (limits.prod.lift (𝟙 A) f ≫ (zero_mul t).hom) := mono_comp _ _, rw [zero_mul_hom, prod.lift_snd] at _inst, haveI: split_epi f := ⟨t.to _, t.hom_ext _ _⟩, apply is_iso_of_mono_of_split_epi end instance [has_initial C] (f : A ⟶ ⊥_ C) : is_iso f := strict_initial initial_is_initial _ /-- If an initial object `0` exists in a CCC then every morphism from it is monic. -/ lemma initial_mono {I : C} (B : C) (t : is_initial I) [cartesian_closed C] : mono (t.to B) := ⟨λ B g h _, by { haveI := strict_initial t g, haveI := strict_initial t h, exact eq_of_inv_eq_inv (t.hom_ext _ _) }⟩ instance initial.mono_to [has_initial C] (B : C) [cartesian_closed C] : mono (initial.to B) := initial_mono B initial_is_initial variables {D : Type u₂} [category.{v} D] section functor variables [has_finite_products D] /-- Transport the property of being cartesian closed across an equivalence of categories. Note we didn't require any coherence between the choice of finite products here, since we transport along the `prod_comparison` isomorphism. -/ def cartesian_closed_of_equiv (e : C ≌ D) [h : cartesian_closed C] : cartesian_closed D := { closed := λ X, { is_adj := begin haveI q : exponentiable (e.inverse.obj X) := infer_instance, have : is_left_adjoint (prod_functor.obj (e.inverse.obj X)) := q.is_adj, have : e.functor ⋙ prod_functor.obj X ⋙ e.inverse ≅ prod_functor.obj (e.inverse.obj X), apply nat_iso.of_components _ _, intro Y, { apply as_iso (prod_comparison e.inverse X (e.functor.obj Y)) ≪≫ _, exact ⟨limits.prod.map (𝟙 _) (e.unit_inv.app _), limits.prod.map (𝟙 _) (e.unit.app _), by simpa [←prod_map_id_comp, prod_map_id_id], by simpa [←prod_map_id_comp, prod_map_id_id]⟩, }, { intros Y Z g, simp only [prod_comparison, inv_prod_comparison_map_fst, inv_prod_comparison_map_snd, prod.lift_map, functor.comp_map, prod_functor_obj_map, assoc, comp_id, iso.trans_hom, as_iso_hom], apply prod.hom_ext, { rw [assoc, prod.lift_fst, prod.lift_fst, ←functor.map_comp, limits.prod.map_fst, comp_id], }, { rw [assoc, prod.lift_snd, prod.lift_snd, ←functor.map_comp_assoc, limits.prod.map_snd], simp only [iso.hom_inv_id_app, assoc, equivalence.inv_fun_map, functor.map_comp, comp_id], erw comp_id, }, }, { have : is_left_adjoint (e.functor ⋙ prod_functor.obj X ⋙ e.inverse) := by exactI adjunction.left_adjoint_of_nat_iso this.symm, have : is_left_adjoint (e.inverse ⋙ e.functor ⋙ prod_functor.obj X ⋙ e.inverse) := by exactI adjunction.left_adjoint_of_comp e.inverse _, have : (e.inverse ⋙ e.functor ⋙ prod_functor.obj X ⋙ e.inverse) ⋙ e.functor ≅ prod_functor.obj X, { apply iso_whisker_right e.counit_iso (prod_functor.obj X ⋙ e.inverse ⋙ e.functor) ≪≫ _, change prod_functor.obj X ⋙ e.inverse ⋙ e.functor ≅ prod_functor.obj X, apply iso_whisker_left (prod_functor.obj X) e.counit_iso, }, resetI, apply adjunction.left_adjoint_of_nat_iso this }, end } } variables [cartesian_closed C] [cartesian_closed D] variables (F : C ⥤ D) [preserves_limits_of_shape (discrete walking_pair) F] /-- The exponential comparison map. `F` is a cartesian closed functor if this is an iso for all `A,B`. -/ def exp_comparison (A B : C) : F.obj (A ⟹ B) ⟶ F.obj A ⟹ F.obj B := curry (inv (prod_comparison F A _) ≫ F.map ((ev _).app _)) /-- The exponential comparison map is natural in its left argument. -/ lemma exp_comparison_natural_left (A A' B : C) (f : A' ⟶ A) : exp_comparison F A B ≫ pre (F.obj B) (F.map f) = F.map (pre B f) ≫ exp_comparison F A' B := begin rw [exp_comparison, exp_comparison, ← curry_natural_left, eq_curry_iff, uncurry_natural_left, pre, uncurry_curry, prod_map_map_assoc, curry_eq, prod_map_id_comp, assoc], erw [(ev _).naturality, ev_coev_assoc, ← F.map_id, ← prod_comparison_inv_natural_assoc, ← F.map_id, ← prod_comparison_inv_natural_assoc, ← F.map_comp, ← F.map_comp, pre, curry_eq, prod_map_id_comp, assoc, (ev _).naturality, ev_coev_assoc], refl, end /-- The exponential comparison map is natural in its right argument. -/ lemma exp_comparison_natural_right (A B B' : C) (f : B ⟶ B') : exp_comparison F A B ≫ (exp (F.obj A)).map (F.map f) = F.map ((exp A).map f) ≫ exp_comparison F A B' := by erw [exp_comparison, ← curry_natural_right, curry_eq_iff, exp_comparison, uncurry_natural_left, uncurry_curry, assoc, ← F.map_comp, ← (ev _).naturality, F.map_comp, prod_comparison_inv_natural_assoc, F.map_id] -- TODO: If F has a left adjoint L, then F is cartesian closed if and only if -- L (B ⨯ F A) ⟶ L B ⨯ L F A ⟶ L B ⨯ A -- is an iso for all A ∈ D, B ∈ C. -- Corollary: If F has a left adjoint L which preserves finite products, F is cartesian closed iff -- F is full and faithful. end functor end category_theory
da03a5363d5307b62b6f96ab86f310cea5b0cb23
8f209eb34c0c4b9b6be5e518ebfc767a38bed79c
/code/src/internal/internal_definitions.lean
b39196650bcea6c69ca3ff967a3eba58b940f549
[]
no_license
hediet/masters-thesis
13e3bcacb6227f25f7ec4691fb78cb0363f2dfb5
dc40c14cc4ed073673615412f36b4e386ee7aac9
refs/heads/master
1,680,591,056,302
1,617,710,887,000
1,617,710,887,000
311,762,038
4
0
null
null
null
null
UTF-8
Lean
false
false
5,711
lean
import tactic import ..definitions import data.finset variable [GuardModule] open GuardModule def Result.is_match { α: Type } : Result α → bool | Result.no_match := ff | _ := tt -- ######################## Gdt ######################## -- Simpler definition of 𝒰 that does not need an accumulator def U : Gdt → Φ | (Gdt.rhs _) := Φ.false | (Gdt.branch tr1 tr2) := (U tr1).and (U tr2) | (Gdt.grd (Grd.bang var) tree) := ((Φ.var_is_not_bottom var).and (U tree)) | (Gdt.grd (Grd.tgrd grd) tree) := (Φ.not_tgrd grd) .or (Φ.tgrd_in grd (U tree)) def U'_acc : (Φ → Φ) → Gdt → Φ | acc (Gdt.rhs _) := acc Φ.false | acc (Gdt.branch tr1 tr2) := acc (U'_acc ((U'_acc id tr1).and) tr2) | acc (Gdt.grd (Grd.bang var) tr) := U'_acc (acc ∘ (Φ.var_is_not_bottom var).and) tr | acc (Gdt.grd (Grd.tgrd grd) tr) := acc ( ((Φ.not_tgrd grd)) .or (U'_acc (Φ.tgrd_in grd) tr) ) def U' := U'_acc id def Gdt.mark_all_rhss_inactive: Gdt → Ant bool | (Gdt.rhs rhs) := Ant.rhs tt rhs | (Gdt.branch tr1 tr2) := Ant.branch tr1.mark_all_rhss_inactive tr2.mark_all_rhss_inactive | (Gdt.grd (Grd.tgrd _) tr) := tr.mark_all_rhss_inactive | (Gdt.grd (Grd.bang _) tr) := Ant.diverge tt tr.mark_all_rhss_inactive def Gdt.mark_inactive_rhss : Gdt → Env → Ant bool | (Gdt.rhs rhs) env := Ant.rhs ff rhs | (Gdt.branch tr1 tr2) env := Ant.branch (tr1.mark_inactive_rhss env) ( if (tr1.eval env).is_match then (tr2.mark_all_rhss_inactive) else (tr2.mark_inactive_rhss env) ) | (Gdt.grd (Grd.tgrd grd) tr) env := match tgrd_eval grd env with | none := tr.mark_all_rhss_inactive | some env' := tr.mark_inactive_rhss env' end | (Gdt.grd (Grd.bang var) tr) env := if is_bottom var env then Ant.diverge ff (tr.mark_all_rhss_inactive) else Ant.diverge tt (tr.mark_inactive_rhss env) -- ######################## Ant ######################## def Ant.rhss_list { α: Type }: Ant α → list Rhs | (Ant.rhs a rhs) := [ rhs ] | (Ant.branch tr1 tr2) := Ant.rhss_list tr1 ++ Ant.rhss_list tr2 | (Ant.diverge a tr) := Ant.rhss_list tr def Ant.rhss { α: Type } (ant: Ant α): finset Rhs := ant.rhss_list.to_finset def Ant.disjoint_rhss { α: Type } : Ant α → Prop | (Ant.rhs _ rhs) := true | (Ant.branch tr1 tr2) := tr1.disjoint_rhss ∧ tr2.disjoint_rhss ∧ disjoint tr1.rhss tr2.rhss | (Ant.diverge _ tr) := tr.disjoint_rhss def Ant.map { α β: Type } : (α → β) → Ant α → Ant β | f (Ant.rhs a rhs) := Ant.rhs (f a) rhs | f (Ant.branch tr1 tr2) := (Ant.branch (tr1.map f) (tr2.map f)) | f (Ant.diverge a tr) := (Ant.diverge (f a) (tr.map f)) -- TODO: functor implementieren? f <$> ant def Ant.map_option { α β: Type } : (α → β) → option (Ant α) → option (Ant β) | f (some ant) := some (ant.map f) | f none := none -- TODO: fmap? def Ant.eval_rhss (ant: Ant Φ) (env: Env): Ant bool := ant.map (λ ty, ty.eval env) def Ant.mark_inactive_rhss (ant: Ant Φ) (env: Env) := ant.map (λ ty, !(ty.eval env)) def Ant.inactive_rhss : Ant bool → finset Rhs | (Ant.rhs inactive n) := if inactive then { n } else ∅ | (Ant.diverge inactive tr) := tr.inactive_rhss | (Ant.branch tr1 tr2) := tr1.inactive_rhss ∪ tr2.inactive_rhss inductive Ant.implies: Ant bool → Ant bool → Prop | rhs { a b: bool } { rhs } (h: a → b): Ant.implies (Ant.rhs a rhs) (Ant.rhs b rhs) | branch { a_tr1 a_tr2 b_tr1 b_tr2 } (h1: Ant.implies a_tr1 b_tr1) (h2: Ant.implies a_tr2 b_tr2): Ant.implies (Ant.branch a_tr1 a_tr2) (Ant.branch b_tr1 b_tr2) | diverge { a b: bool } { a_tr b_tr } (h1: Ant.implies a_tr b_tr) (h2: a → b): Ant.implies (Ant.diverge a a_tr) (Ant.diverge b b_tr) infix `⟶`: 50 := Ant.implies def Ant.critical_rhs_sets : Ant bool → finset (finset Rhs) | (Ant.rhs inactive n) := ∅ | (Ant.diverge inactive tr) := tr.critical_rhs_sets ∪ if inactive then ∅ else { tr.rhss } | (Ant.branch tr1 tr2) := tr1.critical_rhs_sets ∪ tr2.critical_rhs_sets def Ant.is_redundant_set (a: Ant bool) (rhss: finset Rhs) := rhss ∩ a.rhss ⊆ a.inactive_rhss ∧ ∀ c ∈ a.critical_rhs_sets, ∃ l ∈ c, l ∉ rhss -- TODO: rcases -- This is a simpler definition of 𝒜 that is semantically equivalent. def A : Gdt → Ant Φ | (Gdt.rhs rhs) := Ant.rhs Φ.true rhs | (Gdt.branch tr1 tr2) := Ant.branch (A tr1) $ (A tr2).map ((U tr1).and) | (Gdt.grd (Grd.bang var) tr) := Ant.diverge (Φ.var_is_bottom var) $ (A tr).map ((Φ.var_is_not_bottom var).and) | (Gdt.grd (Grd.tgrd grd) tr) := (A tr).map (Φ.tgrd_in grd) -- ######################## R ######################## -- (accessible, inaccessible, redundant) structure RhsPartition := mk :: (acc : list Rhs) (inacc : list Rhs) (red : list Rhs) def RhsPartition.rhss (p: RhsPartition) : list Rhs := p.acc ++ p.inacc ++ p.red def RhsPartition.to_triple (p: RhsPartition): (list Rhs × list Rhs × list Rhs) := (p.acc, p.inacc, p.red) /- This definition is much easier to use than ℛ, but almost equal to ℛ. * Associativity of `Ant.map` can be utilized. * RhsPartition is much easier to use than triples. * Ant.branch has no match which would require a case distinction. * This definition can handle any `Ant bool`. -/ def R : Ant bool → RhsPartition | (Ant.rhs can_prove_empty n) := if can_prove_empty then ⟨ [], [], [n] ⟩ else ⟨ [n], [], [] ⟩ | (Ant.diverge can_prove_empty tr) := match R tr, can_prove_empty with | ⟨ [], [], m :: ms ⟩, ff := ⟨ [], [m], ms ⟩ | r, _ := r end | (Ant.branch tr1 tr2) := let r1 := R tr1, r2 := R tr2 in ⟨ r1.acc ++ r2.acc, r1.inacc ++ r2.inacc, r1.red ++ r2.red ⟩
ef35cd6320b165c2cb385e9d3221f60fac011af8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/603.lean
75b1f4a75e79cdb85a1f90b73ca3e66ea9dc7a51
[ "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
224
lean
set_option trace.compiler.ir.result true -- should be tail calls mutual partial def even (a : Nat) : Nat := if a == 0 then 1 else odd (a - 1) partial def odd (a : Nat) : Nat := if a == 0 then 0 else even (a - 1) end
1cc32efb0083a8e9cd048d88ae709fc24db1b363
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/instances/complex.lean
2227f97cae9f6ecbaeaa7a18b50778d4b927692a
[ "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
6,154
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Topology of the complex numbers. -/ import data.complex.basic topology.metric_space.basic topology.instances.real noncomputable theory open filter metric namespace complex -- TODO(Mario): these proofs are all copied from analysis/real. Generalize -- to normed fields instance : metric_space ℂ := { dist := λx y, (x - y).abs, dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, complex.abs_sub _ _, dist_triangle := assume x y z, complex.abs_sub_le _ _ _ } theorem dist_eq (x y : ℂ) : dist x y = (x - y).abs := rfl theorem uniform_continuous_add : uniform_continuous (λp : ℂ × ℂ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ theorem uniform_continuous_neg : uniform_continuous (@has_neg.neg ℂ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [dist_eq] using h⟩ instance : uniform_add_group ℂ := uniform_add_group.mk' uniform_continuous_add uniform_continuous_neg instance : topological_add_group ℂ := by apply_instance lemma uniform_continuous_inv (s : set ℂ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma uniform_continuous_abs : uniform_continuous (abs : ℂ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _)⟩ lemma continuous_abs : continuous (abs : ℂ → ℝ) := uniform_continuous_abs.continuous lemma tendsto_inv {r : ℂ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma continuous_inv' : continuous (λa:{r:ℂ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, (continuous_iff_continuous_at.mp continuous_subtype_val _).comp (tendsto_inv hr) lemma continuous_inv {α} [topological_space α] {f : α → ℂ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℂ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from (continuous_subtype_mk _ hf).comp continuous_inv' lemma uniform_continuous_mul_const {x : ℂ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma uniform_continuous_mul (s : set (ℂ × ℂ)) {r₁ r₂ : ℝ} (r₁0 : 0 < r₁) (r₂0 : 0 < r₂) (H : ∀ x ∈ s, abs (x : ℂ × ℂ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 r₁0 r₂0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma continuous_mul : continuous (λp : ℂ × ℂ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (lt_of_le_of_lt (abs_nonneg _) (lt_add_one _)) (λ x, id)) (mem_nhds_sets (is_open_prod (continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (continuous_abs _ $ is_open_gt' (abs a₂ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) local attribute [semireducible] real.le lemma uniform_continuous_re : uniform_continuous re := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε, ε0, λ _ _, lt_of_le_of_lt (abs_re_le_abs _)⟩) lemma continuous_re : continuous re := uniform_continuous_re.continuous lemma uniform_continuous_im : uniform_continuous im := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε, ε0, λ _ _, lt_of_le_of_lt (abs_im_le_abs _)⟩) lemma continuous_im : continuous im := uniform_continuous_im.continuous lemma uniform_continuous_of_real : uniform_continuous of_real := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε, ε0, λ _ _, by rw [real.dist_eq, complex.dist_eq, of_real_eq_coe, of_real_eq_coe, ← of_real_sub, abs_of_real]; exact id⟩) lemma continuous_of_real : continuous of_real := uniform_continuous_of_real.continuous instance : topological_ring ℂ := { continuous_mul := complex.continuous_mul, ..complex.topological_add_group } instance : topological_semiring ℂ := by apply_instance def real_prod_homeo : homeomorph ℂ (ℝ × ℝ) := { to_equiv := real_prod_equiv, continuous_to_fun := continuous.prod_mk continuous_re continuous_im, continuous_inv_fun := show continuous (λ p : ℝ × ℝ, complex.mk p.1 p.2), by simp only [mk_eq_add_mul_I]; exact continuous_add (continuous_fst.comp continuous_of_real) (continuous_mul (continuous_snd.comp continuous_of_real) continuous_const) } instance : proper_space ℂ := ⟨λx r, begin refine real_prod_homeo.symm.compact_preimage.1 (compact_of_is_closed_subset (compact_prod _ _ (proper_space.compact_ball x.re r) (proper_space.compact_ball x.im r)) (continuous_iff_is_closed.1 real_prod_homeo.symm.continuous _ is_closed_ball) _), exact λ p h, ⟨ le_trans (abs_re_le_abs (⟨p.1, p.2⟩ - x)) h, le_trans (abs_im_le_abs (⟨p.1, p.2⟩ - x)) h⟩ end⟩ end complex
53330d44757b4c95b3a835a789a117d2f720aeb3
4d3f29a7b2eff44af8fd0d3176232e039acb9ee3
/Mathlib/Mathlib/Logic/Basic.lean
0024a536cf6cef247a5289c45eb573ad723226ea
[]
no_license
marijnheule/lamr
5fc5d69d326ff92e321242cfd7f72e78d7f99d7e
28cc4114c7361059bb54f407fa312bf38b48728b
refs/heads/main
1,689,338,013,620
1,630,359,632,000
1,630,359,632,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,934
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.Init.Logic import Mathlib.Function import Mathlib.Tactic.Basic section needs_better_home /- This section contains items that have no direct counterpart from Lean 3 / Mathlib 3. They should probably probably live elsewhere and maybe in some cases should be removed. -/ -- TODO(Jeremy): where is the best place to put these? lemma EqIffBeqTrue [DecidableEq α] {a b : α} : a = b ↔ ((a == b) = true) := ⟨decide_eq_true, of_decide_eq_true⟩ lemma NeqIffBeqFalse [DecidableEq α] {a b : α} : a ≠ b ↔ ((a == b) = false) := ⟨decide_eq_false, of_decide_eq_false⟩ lemma decide_eq_true_iff (p : Prop) [Decidable p] : (decide p = true) ↔ p := ⟨of_decide_eq_true, decide_eq_true⟩ lemma decide_eq_false_iff_not (p : Prop) [Decidable p] : (decide p = false) ↔ ¬ p := ⟨of_decide_eq_false, decide_eq_false⟩ lemma not_not_em (a : Prop) : ¬¬(a ∨ ¬a) := fun H => H (Or.inr fun h => H (Or.inl h)) lemma not_not_not : ¬¬¬a ↔ ¬a := ⟨mt not_not_intro, not_not_intro⟩ lemma or_left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := by rw [← or_assoc, ← or_assoc, @or_comm a b] lemma ExistsUnique.exists {p : α → Prop} : (∃! x, p x) → ∃ x, p x | ⟨x, h, _⟩ => ⟨x, h⟩ lemma Decidable.not_and [Decidable p] [Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := not_and_iff_or_not _ _ @[inline] def Or.by_cases' [Decidable q] (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hq : q then h₂ hq else h₁ (h.resolve_right hq) lemma Exists.nonempty {p : α → Prop} : (∃ x, p x) → Nonempty α | ⟨x, _⟩ => ⟨x⟩ lemma ite_id [h : Decidable c] {α} (t : α) : (if c then t else t) = t := by cases h <;> rfl namespace WellFounded variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop} unsafe def fix'.impl (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := F x fun y _ => impl hwf F y set_option codegen false in @[implementedBy fix'.impl] def fix' (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := hwf.fix F x end WellFounded end needs_better_home -- Below are items ported from mathlib3/src/logic/basic.lean. attribute [local instance] Classical.propDecidable section miscellany variable {α : Type _} {β : Type _} /-- An identity function with its main argument implicit. This will be printed as `hidden` even if it is applied to a large term, so it can be used for elision, as done in the `elide` and `unelide` tactics. -/ @[reducible] def hidden {α : Sort _} {a : α} := a /-- Ex falso, the nondependent eliminator for the `empty` type. -/ def Empty.elim {C : Sort _} : Empty → C := λ e => match e with. instance : Subsingleton Empty := ⟨λa => a.elim⟩ end miscellany /-! ### Declarations about propositional connectives -/ theorem false_ne_true : False ≠ True | h => h.symm ▸ trivial section propositional variable {a b c d : Prop} /-! ### Declarations about `implies` -/ theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ Iff.rfl theorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩ @[simp] lemma eq_iff_iff {p q : Prop} : (p = q) ↔ (p ↔ q) := iff_iff_eq.symm @[simp] theorem imp_self : (a → a) ↔ True := iff_true_intro id theorem imp_intro {α β : Prop} (h : α) : β → α := λ _ => h theorem imp_false : (a → False) ↔ ¬ a := Iff.rfl theorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) := ⟨λ h => ⟨λ ha => (h ha).left, λ ha=> (h ha).right⟩, λ h ha => ⟨h.left ha, h.right ha⟩⟩ @[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) := Iff.intro (λ h ha hb => h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩ => h ha hb) theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies _ _ theorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) := iff_def.trans And.comm theorem imp_true_iff {α : Sort _} : (α → True) ↔ True := iff_true_intro $ λ_ => trivial theorem imp_iff_right (ha : a) : (a → b) ↔ b := ⟨λf => f ha, imp_intro⟩ /-! ### Declarations about `not` -/ /-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with the arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/ def Not.elim {α : Sort _} (H1 : ¬a) (H2 : a) : α := absurd H2 H1 @[reducible] theorem Not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2 theorem not_not_of_not_imp : ¬(a → b) → ¬¬a := mt Not.elim theorem not_of_not_imp {a : Prop} : ¬(a → b) → ¬b := mt imp_intro theorem dec_em (p : Prop) [Decidable p] : p ∨ ¬p := Decidable.em p theorem dec_em' (p : Prop) [Decidable p] : ¬p ∨ p := (dec_em p).swap theorem em (p : Prop) : p ∨ ¬p := Classical.em _ theorem em' (p : Prop) : ¬p ∨ p := (em p).swap theorem or_not {p : Prop} : p ∨ ¬p := em _ section eq_or_ne variable {α : Sort _} (x y : α) theorem Decidable.eq_or_ne [Decidable (x = y)] : x = y ∨ x ≠ y := dec_em $ x = y theorem Decidable.ne_or_eq [Decidable (x = y)] : x ≠ y ∨ x = y := dec_em' $ x = y theorem eq_or_ne : x = y ∨ x ≠ y := em $ x = y theorem ne_or_eq : x ≠ y ∨ x = y := em' $ x = y end eq_or_ne theorem by_contradiction {p} : (¬p → False) → p := Decidable.by_contradiction -- alias by_contradiction ← by_contra theorem by_contra {p} : (¬p → False) → p := Decidable.by_contradiction /- In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely. The `decidable` namespace contains versions of lemmas from the root namespace that explicitly attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs. You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if `classical.choice` appears in the list. -/ --library_note "decidable namespace" /- As mathlib is primarily classical, if the type signature of a `def` or `lemma` does not require any `decidable` instances to state, it is preferable not to introduce any `decidable` instances that are needed in the proof as arguments, but rather to use the `classical` tactic as needed. In the other direction, when `decidable` instances do appear in the type signature, it is better to use explicitly introduced ones rather than allowing Lean to automatically infer classical ones, as these may cause instance mismatch errors later. -/ --library_note "decidable arguments" -- See Note [decidable namespace] protected theorem Decidable.not_not [Decidable a] : ¬¬a ↔ a := Iff.intro Decidable.by_contradiction not_not_intro /-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`. The left-to-right direction, double negation elimination (DNE), is classically true but not constructively. -/ @[simp] theorem not_not : ¬¬a ↔ a := Decidable.not_not theorem of_not_not : ¬¬a → a := by_contra -- See Note [decidable namespace] protected theorem Decidable.of_not_imp [Decidable a] (h : ¬ (a → b)) : a := Decidable.by_contradiction (not_not_of_not_imp h) theorem of_not_imp : ¬ (a → b) → a := Decidable.of_not_imp -- See Note [decidable namespace] protected theorem Decidable.not_imp_symm [Decidable a] (h : ¬a → b) (hb : ¬b) : a := Decidable.by_contradiction $ hb ∘ h theorem Not.decidable_imp_symm [Decidable a] : (¬a → b) → ¬b → a := Decidable.not_imp_symm theorem Not.imp_symm : (¬a → b) → ¬b → a := Not.decidable_imp_symm -- See Note [decidable namespace] protected theorem Decidable.not_imp_comm [Decidable a] [Decidable b] : (¬a → b) ↔ (¬b → a) := ⟨Not.decidable_imp_symm, Not.decidable_imp_symm⟩ theorem not_imp_comm : (¬a → b) ↔ (¬b → a) := Decidable.not_imp_comm @[simp] theorem imp_not_self : (a → ¬a) ↔ ¬a := ⟨λ h ha => h ha ha, λ h _ => h⟩ theorem Decidable.not_imp_self [Decidable a] : (¬a → a) ↔ a := by have := @imp_not_self (¬a); rwa [Decidable.not_not] at this @[simp] theorem not_imp_self : (¬a → a) ↔ a := Decidable.not_imp_self theorem imp.swap : (a → b → c) ↔ (b → a → c) := ⟨Function.swap, Function.swap⟩ theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) := imp.swap /-! ### Declarations about `xor` -/ @[simp] theorem xor_true : xor True = Not := funext $ λ a => by simp [xor] @[simp] theorem xor_false : xor False = id := funext $ λ a => by simp [xor] theorem xor_comm (a b) : xor a b = xor b a := by simp [xor, and_comm, or_comm] -- TODO is_commutative instance @[simp] theorem xor_self (a : Prop) : xor a a = False := by simp [xor] /-! ### Declarations about `and` -/ theorem and_congr_left (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c := And.comm.trans $ (and_congr_right h).trans And.comm theorem and_congr_left' (h : a ↔ b) : a ∧ c ↔ b ∧ c := and_congr h Iff.rfl theorem and_congr_right' (h : b ↔ c) : a ∧ b ↔ a ∧ c := and_congr Iff.rfl h theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := mt And.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt And.right theorem And.imp_left (h : a → b) : a ∧ c → b ∧ c := And.imp h id theorem And.imp_right (h : a → b) : c ∧ a → c ∧ b := And.imp id h lemma And.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := by simp only [And.left_comm, And.comm]; exact Iff.rfl lemma And.rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a := by simp only [And.left_comm, And.comm]; exact Iff.rfl theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ False := Iff.intro (λ h => (h.right) (h.left)) (λ h => h.elim) theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ False := Iff.intro (λ ⟨hna, ha⟩ => hna ha) False.elim theorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a := Iff.intro And.left (λ ha => ⟨ha, h ha⟩) theorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b := Iff.intro And.right (λ hb => ⟨h hb, hb⟩) @[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a ∧ b) ↔ a) ↔ (a → b) := ⟨λ h ha => (h.2 ha).2, and_iff_left_of_imp⟩ @[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a ∧ b) ↔ b) ↔ (b → a) := ⟨λ h ha => (h.2 ha).1, and_iff_right_of_imp⟩ @[simp] lemma iff_self_and {p q : Prop} : (p ↔ p ∧ q) ↔ (p → q) := by rw [@Iff.comm p, and_iff_left_iff_imp] @[simp] lemma iff_and_self {p q : Prop} : (p ↔ q ∧ p) ↔ (p → q) := by rw [and_comm, iff_self_and] @[simp] lemma And.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) := ⟨λ h ha => by simp [ha] at h; exact h, and_congr_right⟩ @[simp] lemma And.congr_left_iff : (a ∧ c ↔ b ∧ c) ↔ c → (a ↔ b) := by simp only [And.comm, ← And.congr_right_iff]; exact Iff.rfl @[simp] lemma and_self_left : a ∧ a ∧ b ↔ a ∧ b := ⟨λ h => ⟨h.1, h.2.2⟩, λ h => ⟨h.1, h.1, h.2⟩⟩ @[simp] lemma and_self_right : (a ∧ b) ∧ b ↔ a ∧ b := ⟨λ h => ⟨h.1.1, h.2⟩, λ h => ⟨⟨h.1, h.2⟩, h.2⟩⟩ /-! ### Declarations about `or` -/ theorem or_congr_left (h : a ↔ b) : a ∨ c ↔ b ∨ c := or_congr h Iff.rfl theorem or_congr_right (h : b ↔ c) : a ∨ b ↔ a ∨ c := or_congr Iff.rfl h theorem or.right_comm : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := by rw [or_assoc, or_assoc, or_comm b] theorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := Or.imp h₂ h₃ h₁ theorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c := Or.imp_left h h₁ theorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b := Or.imp_right h h₁ theorem Or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := Or.elim h ha (λ h₂ => Or.elim h₂ hb hc) theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) := ⟨fun h => ⟨fun ha => h (Or.inl ha), fun hb => h (Or.inr hb)⟩, fun ⟨ha, hb⟩ => Or.rec ha hb⟩ -- See Note [decidable namespace] protected theorem Decidable.or_iff_not_imp_left [Decidable a] : a ∨ b ↔ (¬ a → b) := ⟨Or.resolve_left, λ h => dite _ Or.inl (Or.inr ∘ h)⟩ theorem or_iff_not_imp_left : a ∨ b ↔ (¬ a → b) := Decidable.or_iff_not_imp_left -- See Note [decidable namespace] protected theorem Decidable.or_iff_not_imp_right [Decidable b] : a ∨ b ↔ (¬ b → a) := Or.comm.trans Decidable.or_iff_not_imp_left theorem or_iff_not_imp_right : a ∨ b ↔ (¬ b → a) := Decidable.or_iff_not_imp_right -- See Note [decidable namespace] protected theorem Decidable.not_imp_not [Decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨λ h hb => Decidable.by_contradiction $ λ na => h na hb, mt⟩ theorem not_imp_not : (¬ a → ¬ b) ↔ (b → a) := Decidable.not_imp_not @[simp] theorem or_iff_left_iff_imp : (a ∨ b ↔ a) ↔ (b → a) := ⟨λ h hb => h.1 (Or.inr hb), or_iff_left_of_imp⟩ @[simp] theorem or_iff_right_iff_imp : (a ∨ b ↔ b) ↔ (a → b) := by rw [or_comm, or_iff_left_iff_imp] /-! ### Declarations about distributivity -/ /-- `∧` distributes over `∨` (on the left). -/ theorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := ⟨λ ⟨ha, hbc⟩ => hbc.imp (And.intro ha) (And.intro ha), Or.rec (And.imp_right Or.inl) (And.imp_right Or.inr)⟩ /-- `∧` distributes over `∨` (on the right). -/ theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := (And.comm.trans and_or_distrib_left).trans (or_congr And.comm And.comm) /-- `∨` distributes over `∧` (on the left). -/ theorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := ⟨Or.rec (λha => And.intro (Or.inl ha) (Or.inl ha)) (And.imp Or.inr Or.inr), And.rec $ Or.rec (imp_intro ∘ Or.inl) (Or.imp_right ∘ And.intro)⟩ /-- `∨` distributes over `∧` (on the right). -/ theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := (Or.comm.trans or_and_distrib_left).trans (and_congr Or.comm Or.comm) @[simp] lemma or_self_left : a ∨ a ∨ b ↔ a ∨ b := ⟨λ h => h.elim Or.inl id, λ h => h.elim Or.inl (Or.inr ∘ Or.inr)⟩ @[simp] lemma or_self_right : (a ∨ b) ∨ b ↔ a ∨ b := ⟨λ h => h.elim id Or.inr, λ h => h.elim (Or.inl ∘ Or.inl) Or.inr⟩ /-! Declarations about `iff` -/ theorem iff_of_true (ha : a) (hb : b) : a ↔ b := ⟨λ_ => hb, λ _ => ha⟩ theorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b := ⟨ha.elim, hb.elim⟩ theorem iff_true_left (ha : a) : (a ↔ b) ↔ b := ⟨λ h => h.1 ha, iff_of_true ha⟩ theorem iff_true_right (ha : a) : (b ↔ a) ↔ b := Iff.comm.trans (iff_true_left ha) theorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b := ⟨λ h => mt h.2 ha, iff_of_false ha⟩ theorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b := Iff.comm.trans (iff_false_left ha) @[simp] lemma iff_mpr_iff_true_intro {P : Prop} (h : P) : Iff.mpr (iff_true_intro h) True.intro = h := rfl -- See Note [decidable namespace] protected theorem Decidable.not_or_of_imp [Decidable a] (h : a → b) : ¬ a ∨ b := if ha : a then Or.inr (h ha) else Or.inl ha theorem not_or_of_imp : (a → b) → ¬ a ∨ b := Decidable.not_or_of_imp -- See Note [decidable namespace] protected theorem Decidable.imp_iff_not_or [Decidable a] : (a → b) ↔ (¬ a ∨ b) := ⟨Decidable.not_or_of_imp, Or.neg_resolve_left⟩ theorem imp_iff_not_or : (a → b) ↔ (¬ a ∨ b) := Decidable.imp_iff_not_or -- See Note [decidable namespace] protected theorem Decidable.imp_or_distrib [Decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by simp [Decidable.imp_iff_not_or, Or.comm, Or.left_comm] theorem imp_or_distrib : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := Decidable.imp_or_distrib -- See Note [decidable namespace] protected theorem Decidable.imp_or_distrib' [Decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by (by_cases b) - simp [h] - rw [eq_false h, false_or] exact Iff.symm (or_iff_right_of_imp (λhx x => False.elim (hx x))) theorem imp_or_distrib' : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := Decidable.imp_or_distrib' theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b) | ⟨ha, hb⟩, h => hb $ h ha -- See Note [decidable namespace] protected theorem Decidable.not_imp [Decidable a] : ¬(a → b) ↔ a ∧ ¬b := ⟨λ h => ⟨Decidable.of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩ theorem not_imp : ¬(a → b) ↔ a ∧ ¬b := Decidable.not_imp -- for monotonicity lemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) := λ (h₂ : a → b) => h₁ ∘ h₂ ∘ h₀ -- See Note [decidable namespace] protected theorem Decidable.peirce (a b : Prop) [Decidable a] : ((a → b) → a) → a := if ha : a then λ h => ha else λ h => h ha.elim theorem peirce (a b : Prop) : ((a → b) → a) → a := Decidable.peirce _ _ theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id -- See Note [decidable namespace] protected theorem Decidable.not_iff_not [Decidable a] [Decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) := by rw [@iff_def (¬ a), @iff_def' a]; exact and_congr Decidable.not_imp_not Decidable.not_imp_not theorem not_iff_not : (¬ a ↔ ¬ b) ↔ (a ↔ b) := Decidable.not_iff_not -- See Note [decidable namespace] protected theorem Decidable.not_iff_comm [Decidable a] [Decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) := by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact and_congr Decidable.not_imp_comm imp_not_comm theorem not_iff_comm : (¬ a ↔ b) ↔ (¬ b ↔ a) := Decidable.not_iff_comm -- See Note [decidable namespace] protected theorem Decidable.not_iff : ∀ [Decidable b], ¬ (a ↔ b) ↔ (¬ a ↔ b) := by intro h match h with | isTrue h => simp[h, iff_true] | isFalse h => simp[h, iff_false] theorem not_iff : ¬ (a ↔ b) ↔ (¬ a ↔ b) := Decidable.not_iff -- See Note [decidable namespace] protected theorem Decidable.iff_not_comm [Decidable a] [Decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := by rw [@iff_def a, @iff_def b]; exact and_congr imp_not_comm Decidable.not_imp_comm theorem iff_not_comm : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := Decidable.iff_not_comm -- See Note [decidable namespace] protected theorem Decidable.iff_iff_and_or_not_and_not [Decidable b] : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := by split - intro h; rw [h] (by_cases b) - (exact Or.inl (And.intro h h)) - (exact Or.inr (And.intro h h)) - intro h match h with | Or.inl h => exact Iff.intro (λ _ => h.2) (λ _ => h.1) | Or.inr h => exact Iff.intro (λ a => False.elim $ h.1 a) (λ b => False.elim $ h.2 b) theorem iff_iff_and_or_not_and_not : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := Decidable.iff_iff_and_or_not_and_not lemma Decidable.iff_iff_not_or_and_or_not [Decidable a] [Decidable b] : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := by rw [iff_iff_implies_and_implies a b] simp only [Decidable.imp_iff_not_or, Or.comm] exact Iff.rfl lemma iff_iff_not_or_and_or_not : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := Decidable.iff_iff_not_or_and_or_not -- See Note [decidable namespace] protected theorem Decidable.not_and_not_right [Decidable b] : ¬(a ∧ ¬b) ↔ (a → b) := ⟨λ h ha => h.decidable_imp_symm $ And.intro ha, λ h ⟨ha, hb⟩ => hb $ h ha⟩ theorem not_and_not_right : ¬(a ∧ ¬b) ↔ (a → b) := Decidable.not_and_not_right /-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent. **Important**: this function should be used instead of `rw` on `decidable b`, because the kernel will get stuck reducing the usage of `propext` otherwise, and `dec_trivial` will not work. -/ @[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : Decidable a] : Decidable b := decidable_of_decidable_of_iff D h /-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent. This is the same as `decidable_of_iff` but the iff is flipped. -/ @[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : Decidable b] : Decidable a := decidable_of_decidable_of_iff D h.symm /-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`. (This is sometimes taken as an alternate definition of decidability.) -/ def decidable_of_bool : ∀ (b : Bool) (h : b ↔ a), Decidable a | true, h => isTrue (h.1 rfl) | false, h => isFalse (mt h.2 Bool.ff_ne_tt) /-! ### De Morgan's laws -/ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) | ⟨ha, hb⟩ => Or.elim h (absurd ha) (absurd hb) -- See Note [decidable namespace] protected theorem Decidable.not_and_distrib [Decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h => if ha : a then Or.inr (λ hb => h ⟨ha, hb⟩) else Or.inl ha, not_and_of_not_or_not⟩ -- See Note [decidable namespace] protected theorem Decidable.not_and_distrib' [Decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h => if hb : b then Or.inl (λ ha => h ⟨ha, hb⟩) else Or.inr hb, not_and_of_not_or_not⟩ /-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the disjunction of the negations. -/ theorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := Decidable.not_and_distrib @[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a := not_and.trans imp_not_comm /-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the conjunction of the negations. -/ theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := ⟨λ h => ⟨λ ha => h (Or.inl ha), λ hb => h (Or.inr hb)⟩, λ ⟨h₁, h₂⟩ h => Or.elim h h₁ h₂⟩ -- See Note [decidable namespace] protected theorem Decidable.or_iff_not_and_not [Decidable a] [Decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rw [← not_or_distrib, Decidable.not_not] theorem or_iff_not_and_not : a ∨ b ↔ ¬ (¬a ∧ ¬b) := Decidable.or_iff_not_and_not -- See Note [decidable namespace] protected theorem Decidable.and_iff_not_or_not [Decidable a] [Decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rw [← Decidable.not_and_distrib, Decidable.not_not] theorem and_iff_not_or_not : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := Decidable.and_iff_not_or_not end propositional /-! ### Declarations about equality -/ section equality variable {α : Sort _} {a b : α} @[simp] theorem heq_iff_eq : HEq a b ↔ a = b := ⟨eq_of_heq, heq_of_eq⟩ theorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : HEq hp hq := have : p = q := propext ⟨λ _ => hq, λ _ => hp⟩ by subst q exact HEq.rfl @[simp] lemma eq_rec_constant {α : Sort _} {a a' : α} {β : Sort _} (y : β) (h : a = a') : (@Eq.rec α a (λ α _ => β) y a' h) = y := by cases h exact rfl lemma congr_arg2 {α β γ : Type _} (f : α → β → γ) {x x' : α} {y y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' := by subst hx subst hy exact rfl end equality /-! ### Declarations about quantifiers -/ section quantifiers variable {α : Sort _} {β : Sort _} {p q : α → Prop} {b : Prop} lemma forall_imp (h : ∀ a, p a → q a) : (∀ a, p a) → ∀ a, q a := λ h' a => h a (h' a) lemma forall₂_congr {p q : α → β → Prop} (h : ∀ a b, p a b ↔ q a b) : (∀ a b, p a b) ↔ (∀ a b, q a b) := forall_congr' (λ a => forall_congr' (h a)) lemma forall₃_congr {γ : Sort _} {p q : α → β → γ → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∀ a b c, p a b c) ↔ (∀ a b c, q a b c) := forall_congr' (λ a => forall₂_congr (h a)) lemma forall₄_congr {γ δ : Sort _} {p q : α → β → γ → δ → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∀ a b c d, p a b c d) ↔ (∀ a b c d, q a b c d) := forall_congr' (λ a => forall₃_congr (h a)) lemma Exists.imp (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists_imp_exists h p lemma exists_imp_exists' {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ a, p a → q (f a)) (hp : ∃ a, p a) : ∃ b, q b := Exists.elim hp (λ a hp' => ⟨_, hpq _ hp'⟩) lemma exists₂_congr {p q : α → β → Prop} (h : ∀ a b, p a b ↔ q a b) : (∃ a b, p a b) ↔ (∃ a b, q a b) := exists_congr (λ a => exists_congr (h a)) lemma exists₃_congr {γ : Sort _} {p q : α → β → γ → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∃ a b c, p a b c) ↔ (∃ a b c, q a b c) := exists_congr (λ a => exists₂_congr (h a)) lemma exists₄_congr {γ δ : Sort _} {p q : α → β → γ → δ → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∃ a b c d, p a b c d) ↔ (∃ a b c d, q a b c d) := exists_congr (λ a => exists₃_congr (h a)) @[simp] theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := ⟨λ h x hpx => h ⟨x, hpx⟩, λ h ⟨x, hpx⟩ => h x hpx⟩ /-- Extract an element from a existential statement, using `Classical.choose`. -/ -- This enables projection notation. @[reducible] noncomputable def Exists.choose {p : α → Prop} (P : ∃ a, p a) : α := Classical.choose P /-- Show that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`. -/ lemma Exists.choose_spec {p : α → Prop} (P : ∃ a, p a) : p (P.choose) := Classical.choose_spec P theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x := exists_imp_distrib.2 h @[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x := exists_imp_distrib theorem not.decidable_imp_symm [Decidable a] : (¬a → b) → ¬b → a := Decidable.not_imp_symm theorem not_forall_of_exists_not {p : α → Prop} : (∃ x, ¬ p x) → ¬ ∀ x, p x | ⟨x, hn⟩, h => hn (h x) protected theorem Decidable.not_forall {p : α → Prop} [Decidable (∃ x, ¬ p x)] [∀ x, Decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := ⟨not.decidable_imp_symm $ λ nx x => not.decidable_imp_symm (λ h => ⟨x, h⟩) nx, not_forall_of_exists_not⟩ @[simp] theorem not_forall {p : α → Prop} : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := Decidable.not_forall @[simp] theorem forall_const (α : Sort _) [i : Nonempty α] : (α → b) ↔ b := ⟨i.elim, λ hb x => hb⟩ theorem forall_and_distrib {p q : α → Prop} : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := ⟨λ h => ⟨λ x => (h x).left, λ x => (h x).right⟩, λ ⟨h₁, h₂⟩ x => ⟨h₁ x, h₂ x⟩⟩ @[simp] theorem forall_eq {p : α → Prop} {a' : α} : (∀a, a = a' → p a) ↔ p a' := ⟨λ h => h a' rfl, λ h a e => e.symm ▸ h⟩ @[simp] theorem exists_false : ¬ (∃a:α, False) := fun ⟨a, h⟩ => h @[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} : (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) := ⟨λ ⟨x, hq, hp⟩ => ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩ => ⟨x, hq, hp⟩⟩ @[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} : (∃x, p x ∧ q) ↔ (∃x, p x) ∧ q := by simp [And.comm] @[simp] theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩ @[simp] theorem exists_eq' {a' : α} : ∃ a, a' = a := ⟨_, rfl⟩ @[simp] theorem exists_eq_left {p : α → Prop} {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' := ⟨λ ⟨a, e, h⟩ => e ▸ h, λ h => ⟨_, rfl, h⟩⟩ @[simp] theorem exists_eq_right {p : α → Prop} {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' := (exists_congr $ by exact λ a => And.comm).trans exists_eq_left @[simp] theorem exists_eq_left' {p : α → Prop} {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' := by simp [@eq_comm _ a'] @[simp] theorem exists_apply_eq_apply {α β : Type _} (f : α → β) (a' : α) : ∃ a, f a = f a' := ⟨a', rfl⟩ theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h := @forall_const (q h) p ⟨h⟩ end quantifiers section ite /-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/ lemma apply_dite {α β : Sort _} (f : α → β) (P : Prop) [Decidable P] (x : P → α) (y : ¬ P → α) : f (dite P x y) = dite P (λ h => f (x h)) (λ h => f (y h)) := by by_cases h : P <;> simp[h] /-- A function applied to a `int` is a `ite` of that function applied to each of the branches. -/ lemma apply_ite {α β : Sort _} (f : α → β) (P : Prop) [Decidable P] (x y : α) : f (ite P x y) = ite P (f x) (f y) := apply_dite f P (λ _ => x) (λ _ => y) /-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/ @[simp] lemma dite_not {α : Sort _} (P : Prop) [Decidable P] (x : ¬ P → α) (y : ¬¬ P → α) : dite (¬ P) x y = dite P (λ h => y (not_not_intro h)) x := by by_cases h : P <;> simp[h] /-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/ @[simp] lemma ite_not {α : Sort _} (P : Prop) [Decidable P] (x y : α) : ite (¬ P) x y = ite P y x := dite_not P (λ _ => x) (λ _ => y) end ite
ee5fceb25d6c3a2766b111750637c0c5510e3937
618003631150032a5676f229d13a079ac875ff77
/src/topology/metric_space/premetric_space.lean
658bf105d524526887e1a4d990c6732693bf3dac
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
3,602
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Premetric spaces. Author: Sébastien Gouëzel -/ import topology.metric_space.basic /-! # Premetric spaces Metric spaces are often defined as quotients of spaces endowed with a "distance" function satisfying the triangular inequality, but for which `dist x y = 0` does not imply x = y. We call such a space a premetric space. `dist x y = 0` defines an equivalence relation, and the quotient is canonically a metric space. -/ noncomputable theory universes u v variables {α : Type u} section prio set_option default_priority 100 -- see Note [default priority] class premetric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) end prio namespace premetric section protected lemma dist_nonneg {α : Type u} [premetric_space α] {x y : α} : 0 ≤ dist x y := begin have := calc 0 = dist x x : (premetric_space.dist_self _).symm ... ≤ dist x y + dist y x : premetric_space.dist_triangle _ _ _ ... = dist x y + dist x y : by simp [premetric_space.dist_comm], by linarith end /-- The canonical equivalence relation on a premetric space. -/ def dist_setoid (α : Type u) [premetric_space α] : setoid α := setoid.mk (λx y, dist x y = 0) begin unfold equivalence, repeat { split }, { exact premetric_space.dist_self }, { assume x y h, rwa premetric_space.dist_comm }, { assume x y z hxy hyz, refine le_antisymm _ premetric.dist_nonneg, calc dist x z ≤ dist x y + dist y z : premetric_space.dist_triangle _ _ _ ... = 0 + 0 : by rw [hxy, hyz] ... = 0 : by simp } end local attribute [instance] dist_setoid /-- The canonical quotient of a premetric space, identifying points at distance 0. -/ @[reducible] definition metric_quot (α : Type u) [premetric_space α] : Type* := quotient (premetric.dist_setoid α) instance has_dist_metric_quot {α : Type u} [premetric_space α] : has_dist (metric_quot α) := { dist := quotient.lift₂ (λp q : α, dist p q) begin assume x y x' y' hxx' hyy', have Hxx' : dist x x' = 0 := hxx', have Hyy' : dist y y' = 0 := hyy', have A : dist x y ≤ dist x' y' := calc dist x y ≤ dist x x' + dist x' y : premetric_space.dist_triangle _ _ _ ... = dist x' y : by simp [Hxx'] ... ≤ dist x' y' + dist y' y : premetric_space.dist_triangle _ _ _ ... = dist x' y' : by simp [premetric_space.dist_comm, Hyy'], have B : dist x' y' ≤ dist x y := calc dist x' y' ≤ dist x' x + dist x y' : premetric_space.dist_triangle _ _ _ ... = dist x y' : by simp [premetric_space.dist_comm, Hxx'] ... ≤ dist x y + dist y y' : premetric_space.dist_triangle _ _ _ ... = dist x y : by simp [Hyy'], exact le_antisymm A B end } lemma metric_quot_dist_eq {α : Type u} [premetric_space α] (p q : α) : dist ⟦p⟧ ⟦q⟧ = dist p q := rfl instance metric_space_quot {α : Type u} [premetric_space α] : metric_space (metric_quot α) := { dist_self := begin refine quotient.ind (λy, _), exact premetric_space.dist_self _ end, eq_of_dist_eq_zero := λxc yc, quotient.induction_on₂ xc yc (λx y H, quotient.sound H), dist_comm := λxc yc, quotient.induction_on₂ xc yc (λx y, premetric_space.dist_comm _ _), dist_triangle := λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, premetric_space.dist_triangle _ _ _) } end --section end premetric --namespace
cb288999017b2bf0c160fe6f0d5d4518d00dc044
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/perfection.lean
519d14d808be5869b0f3ee7a2c0777c3b41b1bb9
[ "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,595
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p.pi import algebra.char_p.quotient import algebra.char_p.subring import algebra.ring.pi import analysis.special_functions.pow.nnreal import field_theory.perfect_closure import ring_theory.localization.fraction_ring import ring_theory.subring.basic import ring_theory.valuation.integers /-! # Ring Perfection and Tilt > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define the perfection of a ring of characteristic p, and the tilt of a field given a valuation to `ℝ≥0`. ## TODO Define the valuation on the tilt, and define a characteristic predicate for the tilt. -/ universes u₁ u₂ u₃ u₄ open_locale nnreal /-- The perfection of a monoid `M`, defined to be the projective limit of `M` using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as `{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/ def monoid.perfection (M : Type u₁) [comm_monoid M] (p : ℕ) : submonoid (ℕ → M) := { carrier := { f | ∀ n, f (n + 1) ^ p = f n }, one_mem' := λ n, one_pow _, mul_mem' := λ f g hf hg n, (mul_pow _ _ _).trans $ congr_arg2 _ (hf n) (hg n) } /-- The perfection of a ring `R` with characteristic `p`, as a subsemiring, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def ring.perfection_subsemiring (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] : subsemiring (ℕ → R) := { zero_mem' := λ n, zero_pow $ hp.1.pos, add_mem' := λ f g hf hg n, (frobenius_add R p _ _).trans $ congr_arg2 _ (hf n) (hg n), .. monoid.perfection R p } /-- The perfection of a ring `R` with characteristic `p`, as a subring, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def ring.perfection_subring (R : Type u₁) [comm_ring R] (p : ℕ) [hp : fact p.prime] [char_p R p] : subring (ℕ → R) := (ring.perfection_subsemiring R p).to_subring $ λ n, by simp_rw [← frobenius_def, pi.neg_apply, pi.one_apply, ring_hom.map_neg, ring_hom.map_one] /-- The perfection of a ring `R` with characteristic `p`, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{f : ℕ → R // ∀ n, f (n + 1) ^ p = f n}`. -/ def ring.perfection (R : Type u₁) [comm_semiring R] (p : ℕ) : Type u₁ := {f // ∀ (n : ℕ), (f : ℕ → R) (n + 1) ^ p = f n} namespace perfection variables (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact p.prime] [char_p R p] include hp instance : comm_semiring (ring.perfection R p) := (ring.perfection_subsemiring R p).to_comm_semiring instance : char_p (ring.perfection R p) p := char_p.subsemiring (ℕ → R) p (ring.perfection_subsemiring R p) instance ring (R : Type u₁) [comm_ring R] [char_p R p] : ring (ring.perfection R p) := (ring.perfection_subring R p).to_ring instance comm_ring (R : Type u₁) [comm_ring R] [char_p R p] : comm_ring (ring.perfection R p) := (ring.perfection_subring R p).to_comm_ring instance : inhabited (ring.perfection R p) := ⟨0⟩ /-- The `n`-th coefficient of an element of the perfection. -/ def coeff (n : ℕ) : ring.perfection R p →+* R := { to_fun := λ f, f.1 n, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[ext] lemma ext {f g : ring.perfection R p} (h : ∀ n, coeff R p n f = coeff R p n g) : f = g := subtype.eq $ funext h variables (R p) /-- The `p`-th root of an element of the perfection. -/ def pth_root : ring.perfection R p →+* ring.perfection R p := { to_fun := λ f, ⟨λ n, coeff R p (n + 1) f, λ n, f.2 _⟩, map_one' := rfl, map_mul' := λ f g, rfl, map_zero' := rfl, map_add' := λ f g, rfl } variables {R p} @[simp] lemma coeff_mk (f : ℕ → R) (hf) (n : ℕ) : coeff R p n ⟨f, hf⟩ = f n := rfl lemma coeff_pth_root (f : ring.perfection R p) (n : ℕ) : coeff R p n (pth_root R p f) = coeff R p (n + 1) f := rfl lemma coeff_pow_p (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (f ^ p) = coeff R p n f := by { rw ring_hom.map_pow, exact f.2 n } lemma coeff_pow_p' (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) f ^ p = coeff R p n f := f.2 n lemma coeff_frobenius (f : ring.perfection R p) (n : ℕ) : coeff R p (n + 1) (frobenius _ p f) = coeff R p n f := by apply coeff_pow_p f n -- `coeff_pow_p f n` also works but is slow! lemma coeff_iterate_frobenius (f : ring.perfection R p) (n m : ℕ) : coeff R p (n + m) (frobenius _ p ^[m] f) = coeff R p n f := nat.rec_on m rfl $ λ m ih, by erw [function.iterate_succ_apply', coeff_frobenius, ih] lemma coeff_iterate_frobenius' (f : ring.perfection R p) (n m : ℕ) (hmn : m ≤ n) : coeff R p n (frobenius _ p ^[m] f) = coeff R p (n - m) f := eq.symm $ (coeff_iterate_frobenius _ _ m).symm.trans $ (tsub_add_cancel_of_le hmn).symm ▸ rfl lemma pth_root_frobenius : (pth_root R p).comp (frobenius _ p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, coeff_pth_root, coeff_frobenius] lemma frobenius_pth_root : (frobenius _ p).comp (pth_root R p) = ring_hom.id _ := ring_hom.ext $ λ x, ext $ λ n, by rw [ring_hom.comp_apply, ring_hom.id_apply, ring_hom.map_frobenius, coeff_pth_root, ← ring_hom.map_frobenius, coeff_frobenius] lemma coeff_add_ne_zero {f : ring.perfection R p} {n : ℕ} (hfn : coeff R p n f ≠ 0) (k : ℕ) : coeff R p (n + k) f ≠ 0 := nat.rec_on k hfn $ λ k ih h, ih $ by erw [← coeff_pow_p, ring_hom.map_pow, h, zero_pow hp.1.pos] lemma coeff_ne_zero_of_le {f : ring.perfection R p} {m n : ℕ} (hfm : coeff R p m f ≠ 0) (hmn : m ≤ n) : coeff R p n f ≠ 0 := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in hk.symm ▸ coeff_add_ne_zero hfm k variables (R p) instance perfect_ring : perfect_ring (ring.perfection R p) p := { pth_root' := pth_root R p, frobenius_pth_root' := congr_fun $ congr_arg ring_hom.to_fun $ @frobenius_pth_root R _ p _ _, pth_root_frobenius' := congr_fun $ congr_arg ring_hom.to_fun $ @pth_root_frobenius R _ p _ _ } /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* perfection S p`. -/ @[simps] def lift (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] : (R →+* S) ≃ (R →+* ring.perfection S p) := { to_fun := λ f, { to_fun := λ r, ⟨λ n, f $ _root_.pth_root R p ^[n] r, λ n, by rw [← f.map_pow, function.iterate_succ_apply', pth_root_pow_p]⟩, map_one' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_one _ _).trans f.map_one, map_mul' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_mul _ _ _ _).trans $ f.map_mul _ _, map_zero' := ext $ λ n, (congr_arg f $ ring_hom.iterate_map_zero _ _).trans f.map_zero, map_add' := λ x y, ext $ λ n, (congr_arg f $ ring_hom.iterate_map_add _ _ _ _).trans $ f.map_add _ _ }, inv_fun := ring_hom.comp $ coeff S p 0, left_inv := λ f, ring_hom.ext $ λ r, rfl, right_inv := λ f, ring_hom.ext $ λ r, ext $ λ n, show coeff S p 0 (f (_root_.pth_root R p ^[n] r)) = coeff S p n (f r), by rw [← coeff_iterate_frobenius _ 0 n, zero_add, ← ring_hom.map_iterate_frobenius, right_inverse_pth_root_frobenius.iterate] } lemma hom_ext {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {f g : R →+* ring.perfection S p} (hfg : ∀ x, coeff S p 0 (f x) = coeff S p 0 (g x)) : f = g := (lift p R S).symm.injective $ ring_hom.ext hfg variables {R} {S : Type u₂} [comm_semiring S] [char_p S p] /-- A ring homomorphism `R →+* S` induces `perfection R p →+* perfection S p` -/ @[simps] def map (φ : R →+* S) : ring.perfection R p →+* ring.perfection S p := { to_fun := λ f, ⟨λ n, φ (coeff R p n f), λ n, by rw [← φ.map_pow, coeff_pow_p']⟩, map_one' := subtype.eq $ funext $ λ n, φ.map_one, map_mul' := λ f g, subtype.eq $ funext $ λ n, φ.map_mul _ _, map_zero' := subtype.eq $ funext $ λ n, φ.map_zero, map_add' := λ f g, subtype.eq $ funext $ λ n, φ.map_add _ _ } lemma coeff_map (φ : R →+* S) (f : ring.perfection R p) (n : ℕ) : coeff S p n (map p φ f) = φ (coeff R p n f) := rfl end perfection /-- A perfection map to a ring of characteristic `p` is a map that is isomorphic to its perfection. -/ @[nolint has_nonempty_instance] structure perfection_map (p : ℕ) [fact p.prime] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₂} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* R) : Prop := (injective : ∀ ⦃x y : P⦄, (∀ n, π (pth_root P p ^[n] x) = π (pth_root P p ^[n] y)) → x = y) (surjective : ∀ f : ℕ → R, (∀ n, f (n + 1) ^ p = f n) → ∃ x : P, ∀ n, π (pth_root P p ^[n] x) = f n) namespace perfection_map variables {p : ℕ} [fact p.prime] variables {R : Type u₁} [comm_semiring R] [char_p R p] variables {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] /-- Create a `perfection_map` from an isomorphism to the perfection. -/ @[simps] lemma mk' {f : P →+* R} (g : P ≃+* ring.perfection R p) (hfg : perfection.lift p P R f = g) : perfection_map p f := { injective := λ x y hxy, g.injective $ (ring_hom.ext_iff.1 hfg x).symm.trans $ eq.symm $ (ring_hom.ext_iff.1 hfg y).symm.trans $ perfection.ext $ λ n, (hxy n).symm, surjective := λ y hy, let ⟨x, hx⟩ := g.surjective ⟨y, hy⟩ in ⟨x, λ n, show perfection.coeff R p n (perfection.lift p P R f x) = perfection.coeff R p n ⟨y, hy⟩, by rw [hfg, ← coe_fn_coe_base, hx]⟩ } variables (p R P) /-- The canonical perfection map from the perfection of a ring. -/ lemma of : perfection_map p (perfection.coeff R p 0) := mk' (ring_equiv.refl _) $ (equiv.apply_eq_iff_eq_symm_apply _).2 rfl /-- For a perfect ring, it itself is the perfection. -/ lemma id [perfect_ring R p] : perfection_map p (ring_hom.id R) := { injective := λ x y hxy, hxy 0, surjective := λ f hf, ⟨f 0, λ n, show pth_root R p ^[n] (f 0) = f n, from nat.rec_on n rfl $ λ n ih, injective_pow_p p $ by rw [function.iterate_succ_apply', pth_root_pow_p _, ih, hf]⟩ } variables {p R P} /-- A perfection map induces an isomorphism to the prefection. -/ noncomputable def equiv {π : P →+* R} (m : perfection_map p π) : P ≃+* ring.perfection R p := ring_equiv.of_bijective (perfection.lift p P R π) ⟨λ x y hxy, m.injective $ λ n, (congr_arg (perfection.coeff R p n) hxy : _), λ f, let ⟨x, hx⟩ := m.surjective f.1 f.2 in ⟨x, perfection.ext $ hx⟩⟩ lemma equiv_apply {π : P →+* R} (m : perfection_map p π) (x : P) : m.equiv x = perfection.lift p P R π x := rfl lemma comp_equiv {π : P →+* R} (m : perfection_map p π) (x : P) : perfection.coeff R p 0 (m.equiv x) = π x := rfl lemma comp_equiv' {π : P →+* R} (m : perfection_map p π) : (perfection.coeff R p 0).comp ↑m.equiv = π := ring_hom.ext $ λ x, rfl lemma comp_symm_equiv {π : P →+* R} (m : perfection_map p π) (f : ring.perfection R p) : π (m.equiv.symm f) = perfection.coeff R p 0 f := (m.comp_equiv _).symm.trans $ congr_arg _ $ m.equiv.apply_symm_apply f lemma comp_symm_equiv' {π : P →+* R} (m : perfection_map p π) : π.comp ↑m.equiv.symm = perfection.coeff R p 0 := ring_hom.ext m.comp_symm_equiv variables (p R P) /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* P`, where `P` is any perfection of `S`. -/ @[simps] noncomputable def lift [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] (P : Type u₃) [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) : (R →+* S) ≃ (R →+* P) := { to_fun := λ f, ring_hom.comp ↑m.equiv.symm $ perfection.lift p R S f, inv_fun := λ f, π.comp f, left_inv := λ f, by { simp_rw [← ring_hom.comp_assoc, comp_symm_equiv'], exact (perfection.lift p R S).symm_apply_apply f }, right_inv := λ f, ring_hom.ext $ λ x, m.equiv.injective $ (m.equiv.apply_symm_apply _).trans $ show perfection.lift p R S (π.comp f) x = ring_hom.comp ↑m.equiv f x, from ring_hom.ext_iff.1 ((perfection.lift p R S).apply_eq_iff_eq_symm_apply.2 rfl) _ } variables {R p} lemma hom_ext [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) {f g : R →+* P} (hfg : ∀ x, π (f x) = π (g x)) : f = g := (lift p R S P π m).symm.injective $ ring_hom.ext hfg variables {R P} (p) {S : Type u₂} [comm_semiring S] [char_p S p] variables {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] /-- A ring homomorphism `R →+* S` induces `P →+* Q`, a map of the respective perfections. -/ @[nolint unused_arguments] noncomputable def map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : P →+* Q := lift p P S Q σ n $ φ.comp π lemma comp_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : σ.comp (map p m n φ) = φ.comp π := (lift p P S Q σ n).symm_apply_apply _ lemma map_map {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) (x : P) : σ (map p m n φ x) = φ (π x) := ring_hom.ext_iff.1 (comp_map p m n φ) x -- Why is this slow? lemma map_eq_map (φ : R →+* S) : @map p _ R _ _ _ _ _ _ S _ _ _ _ _ _ _ (of p R) _ (of p S) φ = perfection.map p φ := hom_ext _ (of p S) $ λ f, by rw [map_map, perfection.coeff_map] end perfection_map section perfectoid variables (K : Type u₁) [field K] (v : valuation K ℝ≥0) variables (O : Type u₂) [comm_ring O] [algebra O K] (hv : v.integers O) variables (p : ℕ) include hv /-- `O/(p)` for `O`, ring of integers of `K`. -/ @[nolint unused_arguments has_nonempty_instance] def mod_p := O ⧸ (ideal.span {p} : ideal O) variables [hp : fact p.prime] [hvp : fact (v p ≠ 1)] namespace mod_p instance : comm_ring (mod_p K v O hv p) := ideal.quotient.comm_ring _ include hp hvp instance : char_p (mod_p K v O hv p) p := char_p.quotient O p $ mt hv.one_of_is_unit $ (map_nat_cast (algebra_map O K) p).symm ▸ hvp.1 instance : nontrivial (mod_p K v O hv p) := char_p.nontrivial_of_char_ne_one hp.1.ne_one section classical local attribute [instance] classical.dec omit hp hvp /-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`, a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/ noncomputable def pre_val (x : mod_p K v O hv p) : ℝ≥0 := if x = 0 then 0 else v (algebra_map O K x.out') variables {K v O hv p} lemma pre_val_mk {x : O} (hx : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0) : pre_val K v O hv p (ideal.quotient.mk _ x) = v (algebra_map O K x) := begin obtain ⟨r, hr⟩ := ideal.mem_span_singleton'.1 (ideal.quotient.eq.1 $ quotient.sound' $ @quotient.mk_out' O (ideal.span {p} : ideal O).quotient_rel x), refine (if_neg hx).trans (v.map_eq_of_sub_lt $ lt_of_not_le _), erw [← ring_hom.map_sub, ← hr, hv.le_iff_dvd], exact λ hprx, hx (ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ dvd_of_mul_left_dvd hprx), end lemma pre_val_zero : pre_val K v O hv p 0 = 0 := if_pos rfl lemma pre_val_mul {x y : mod_p K v O hv p} (hxy0 : x * y ≠ 0) : pre_val K v O hv p (x * y) = pre_val K v O hv p x * pre_val K v O hv p y := begin have hx0 : x ≠ 0 := mt (by { rintro rfl, rw zero_mul }) hxy0, have hy0 : y ≠ 0 := mt (by { rintro rfl, rw mul_zero }) hxy0, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_mul at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_mul, v.map_mul] end lemma pre_val_add (x y : mod_p K v O hv p) : pre_val K v O hv p (x + y) ≤ max (pre_val K v O hv p x) (pre_val K v O hv p y) := begin by_cases hx0 : x = 0, { rw [hx0, zero_add], exact le_max_right _ _ }, by_cases hy0 : y = 0, { rw [hy0, add_zero], exact le_max_left _ _ }, by_cases hxy0 : x + y = 0, { rw [hxy0, pre_val_zero], exact zero_le _ }, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, rw ← ring_hom.map_add at hxy0 ⊢, rw [pre_val_mk hx0, pre_val_mk hy0, pre_val_mk hxy0, ring_hom.map_add], exact v.map_add _ _ end lemma v_p_lt_pre_val {x : mod_p K v O hv p} : v p < pre_val K v O hv p x ↔ x ≠ 0 := begin refine ⟨λ h hx, by { rw [hx, pre_val_zero] at h, exact not_lt_zero' h }, λ h, lt_of_not_le $ λ hp, h _⟩, obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, rw [pre_val_mk h, ← map_nat_cast (algebra_map O K) p, hv.le_iff_dvd] at hp, rw [ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton], exact hp end lemma pre_val_eq_zero {x : mod_p K v O hv p} : pre_val K v O hv p x = 0 ↔ x = 0 := ⟨λ hvx, classical.by_contradiction $ λ hx0 : x ≠ 0, by { rw [← v_p_lt_pre_val, hvx] at hx0, exact not_lt_zero' hx0 }, λ hx, hx.symm ▸ pre_val_zero⟩ variables (hv hvp) lemma v_p_lt_val {x : O} : v p < v (algebra_map O K x) ↔ (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := by rw [lt_iff_not_le, not_iff_not, ← map_nat_cast (algebra_map O K) p, hv.le_iff_dvd, ideal.quotient.eq_zero_iff_mem, ideal.mem_span_singleton] open nnreal variables {hv} [hvp] include hp lemma mul_ne_zero_of_pow_p_ne_zero {x y : mod_p K v O hv p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) : x * y ≠ 0 := begin obtain ⟨r, rfl⟩ := ideal.quotient.mk_surjective x, obtain ⟨s, rfl⟩ := ideal.quotient.mk_surjective y, have h1p : (0 : ℝ) < 1 / p := one_div_pos.2 (nat.cast_pos.2 hp.1.pos), rw ← ring_hom.map_mul, rw ← ring_hom.map_pow at hx hy, rw ← v_p_lt_val hv at hx hy ⊢, rw [ring_hom.map_pow, v.map_pow, ← rpow_lt_rpow_iff h1p, ← rpow_nat_cast, ← rpow_mul, mul_one_div_cancel (nat.cast_ne_zero.2 hp.1.ne_zero : (p : ℝ) ≠ 0), rpow_one] at hx hy, rw [ring_hom.map_mul, v.map_mul], refine lt_of_le_of_lt _ (mul_lt_mul₀ hx hy), by_cases hvp : v p = 0, { rw hvp, exact zero_le _ }, replace hvp := zero_lt_iff.2 hvp, conv_lhs { rw ← rpow_one (v p) }, rw ← rpow_add (ne_of_gt hvp), refine rpow_le_rpow_of_exponent_ge hvp (map_nat_cast (algebra_map O K) p ▸ hv.2 _) _, rw [← add_div, div_le_one (nat.cast_pos.2 hp.1.pos : 0 < (p : ℝ))], exact_mod_cast hp.1.two_le end end classical end mod_p /-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/ @[nolint has_nonempty_instance] def pre_tilt := ring.perfection (mod_p K v O hv p) p include hp hvp namespace pre_tilt instance : comm_ring (pre_tilt K v O hv p) := perfection.comm_ring p _ instance : char_p (pre_tilt K v O hv p) p := perfection.char_p (mod_p K v O hv p) p section classical open_locale classical open perfection /-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val_aux (f : pre_tilt K v O hv p) : ℝ≥0 := if h : ∃ n, coeff _ _ n f ≠ 0 then mod_p.pre_val K v O hv p (coeff _ _ (nat.find h) f) ^ (p ^ nat.find h) else 0 variables {K v O hv p} lemma coeff_nat_find_add_ne_zero {f : pre_tilt K v O hv p} {h : ∃ n, coeff _ _ n f ≠ 0} (k : ℕ) : coeff _ _ (nat.find h + k) f ≠ 0 := coeff_add_ne_zero (nat.find_spec h) k lemma val_aux_eq {f : pre_tilt K v O hv p} {n : ℕ} (hfn : coeff _ _ n f ≠ 0) : val_aux K v O hv p f = mod_p.pre_val K v O hv p (coeff _ _ n f) ^ (p ^ n) := begin have h : ∃ n, coeff _ _ n f ≠ 0 := ⟨n, hfn⟩, rw [val_aux, dif_pos h], obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le (nat.find_min' h hfn), induction k with k ih, { refl }, obtain ⟨x, hx⟩ := ideal.quotient.mk_surjective (coeff _ _ (nat.find h + k + 1) f), have h1 : (ideal.quotient.mk _ x : mod_p K v O hv p) ≠ 0 := hx.symm ▸ hfn, have h2 : (ideal.quotient.mk _ (x ^ p) : mod_p K v O hv p) ≠ 0, by { erw [ring_hom.map_pow, hx, ← ring_hom.map_pow, coeff_pow_p], exact coeff_nat_find_add_ne_zero k }, erw [ih (coeff_nat_find_add_ne_zero k), ← hx, ← coeff_pow_p, ring_hom.map_pow, ← hx, ← ring_hom.map_pow, mod_p.pre_val_mk h1, mod_p.pre_val_mk h2, ring_hom.map_pow, v.map_pow, ← pow_mul, pow_succ], refl end lemma val_aux_zero : val_aux K v O hv p 0 = 0 := dif_neg $ λ ⟨n, hn⟩, hn rfl lemma val_aux_one : val_aux K v O hv p 1 = 1 := (val_aux_eq $ show coeff (mod_p K v O hv p) p 0 1 ≠ 0, from one_ne_zero).trans $ by { rw [pow_zero, pow_one, ring_hom.map_one, ← (ideal.quotient.mk _).map_one, mod_p.pre_val_mk, ring_hom.map_one, v.map_one], change (1 : mod_p K v O hv p) ≠ 0, exact one_ne_zero } lemma val_aux_mul (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f * g) = val_aux K v O hv p f * val_aux K v O hv p g := begin by_cases hf : f = 0, { rw [hf, zero_mul, val_aux_zero, zero_mul] }, by_cases hg : g = 0, { rw [hg, mul_zero, val_aux_zero, mul_zero] }, obtain ⟨m, hm⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h), obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h), replace hm := coeff_ne_zero_of_le hm (le_max_left m n), replace hn := coeff_ne_zero_of_le hn (le_max_right m n), have hfg : coeff _ _ (max m n + 1) (f * g) ≠ 0, { rw ring_hom.map_mul, refine mod_p.mul_ne_zero_of_pow_p_ne_zero _ _, { rw [← ring_hom.map_pow, coeff_pow_p f], assumption }, { rw [← ring_hom.map_pow, coeff_pow_p g], assumption } }, rw [val_aux_eq (coeff_add_ne_zero hm 1), val_aux_eq (coeff_add_ne_zero hn 1), val_aux_eq hfg], rw ring_hom.map_mul at hfg ⊢, rw [mod_p.pre_val_mul hfg, mul_pow] end lemma val_aux_add (f g : pre_tilt K v O hv p) : val_aux K v O hv p (f + g) ≤ max (val_aux K v O hv p f) (val_aux K v O hv p g) := begin by_cases hf : f = 0, { rw [hf, zero_add, val_aux_zero, max_eq_right], exact zero_le _ }, by_cases hg : g = 0, { rw [hg, add_zero, val_aux_zero, max_eq_left], exact zero_le _ }, by_cases hfg : f + g = 0, { rw [hfg, val_aux_zero], exact zero_le _ }, replace hf : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf $ perfection.ext h), replace hg : ∃ n, coeff _ _ n g ≠ 0 := not_forall.1 (λ h, hg $ perfection.ext h), replace hfg : ∃ n, coeff _ _ n (f + g) ≠ 0 := not_forall.1 (λ h, hfg $ perfection.ext h), obtain ⟨m, hm⟩ := hf, obtain ⟨n, hn⟩ := hg, obtain ⟨k, hk⟩ := hfg, replace hm := coeff_ne_zero_of_le hm (le_trans (le_max_left m n) (le_max_left _ k)), replace hn := coeff_ne_zero_of_le hn (le_trans (le_max_right m n) (le_max_left _ k)), replace hk := coeff_ne_zero_of_le hk (le_max_right (max m n) k), rw [val_aux_eq hm, val_aux_eq hn, val_aux_eq hk, ring_hom.map_add], cases le_max_iff.1 (mod_p.pre_val_add (coeff _ _ (max (max m n) k) f) (coeff _ _ (max (max m n) k) g)) with h h, { exact le_max_of_le_left (pow_le_pow_of_le_left' h _) }, { exact le_max_of_le_right (pow_le_pow_of_le_left' h _) } end variables (K v O hv p) /-- The valuation `Perfection(O/(p)) → ℝ≥0`. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ noncomputable def val : valuation (pre_tilt K v O hv p) ℝ≥0 := { to_fun := val_aux K v O hv p, map_one' := val_aux_one, map_mul' := val_aux_mul, map_zero' := val_aux_zero, map_add_le_max' := val_aux_add } variables {K v O hv p} lemma map_eq_zero {f : pre_tilt K v O hv p} : val K v O hv p f = 0 ↔ f = 0 := begin by_cases hf0 : f = 0, { rw hf0, exact iff_of_true (valuation.map_zero _) rfl }, obtain ⟨n, hn⟩ : ∃ n, coeff _ _ n f ≠ 0 := not_forall.1 (λ h, hf0 $ perfection.ext h), show val_aux K v O hv p f = 0 ↔ f = 0, refine iff_of_false (λ hvf, hn _) hf0, rw val_aux_eq hn at hvf, replace hvf := pow_eq_zero hvf, rwa mod_p.pre_val_eq_zero at hvf end end classical instance : is_domain (pre_tilt K v O hv p) := begin haveI : nontrivial (pre_tilt K v O hv p) := ⟨(char_p.nontrivial_of_char_ne_one hp.1.ne_one).1⟩, haveI : no_zero_divisors (pre_tilt K v O hv p) := ⟨λ f g hfg, by { simp_rw ← map_eq_zero at hfg ⊢, contrapose! hfg, rw valuation.map_mul, exact mul_ne_zero hfg.1 hfg.2 }⟩, exact no_zero_divisors.to_is_domain _ end end pre_tilt /-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in [scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`, this is implemented as the fraction field of the perfection of `O/(p)`. -/ @[nolint has_nonempty_instance] def tilt := fraction_ring (pre_tilt K v O hv p) namespace tilt noncomputable instance : field (tilt K v O hv p) := fraction_ring.field end tilt end perfectoid
b880be5140ebf1964e6187c909d0b29afc1f8f3f
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/doc/demo/mul_succl.lean
e35857e9412d1b4fcabbb741e54a4dd72073e30d
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
1,653
lean
import tactic using Nat rewrite_set basic add_rewrite add_zerol add_succl eq_id : basic theorem add_assoc (a b c : Nat) : (a + b) + c = a + (b + c) := induction_on a (have (0 + b) + c = 0 + (b + c) : by simp basic) (λ (n : Nat) (iH : (n + b) + c = n + (b + c)), have ((n + 1) + b) + c = (n + 1) + (b + c) : by simp basic) check add_zerol check add_succl check @eq_id -- print environment 1 add_rewrite add_assoc add_comm mul_zeror mul_zerol mul_succr : basic theorem mul_succl_1 (a b : Nat) : (a + 1) * b = a * b + b := induction_on b (have (a + 1) * 0 = a * 0 + 0 : by simp basic) (λ (n : Nat) (iH : (a + 1) * n = a * n + n), have (a + 1) * (n + 1) = a * (n + 1) + (n + 1) : by simp basic) exit rewrite_set first_pass add_rewrite mul_succr eq_id : first_pass rewrite_set sort_add add_rewrite add_assoc add_comm add_left_comm eq_id : sort_add theorem mul_succl_2 (a b : Nat) : (a + 1) * b = a * b + b := induction_on b (have (a + 1) * 0 = a * 0 + 0 : by simp basic) (λ (n : Nat) (iH : (a + 1) * n = a * n + n), have (a + 1) * (n + 1) = a * (n + 1) + (n + 1) : by Then (simp first_pass) (simp sort_add)) exit theorem mul_succl_3 (a b : Nat) : (a + 1) * b = a * b + b := induction_on b (have (a + 1) * 0 = a * 0 + 0 : by simp basic) (λ (n : Nat) (iH : (a + 1) * n = a * n + n), calc (a + 1) * (n + 1) = (a * n + n) + (a + 1) : by simp first_pass ... = (a * n + a) + (n + 1) : by simp sort_add ... = a * (n + 1) + (n + 1) : by simp first_pass)
ad4452cf54b119c501e9527149f5217fa3b267a5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/special_functions/trigonometric/chebyshev.lean
f35d08a9a9f50c0df278b6c3cb2c223fc0441cc0
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,544
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.complex.exponential import data.complex.module import data.polynomial.algebra_map import ring_theory.polynomial.chebyshev /-! # Multiple angle formulas in terms of Chebyshev polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file gives the trigonometric characterizations of Chebyshev polynomials, for both the real (`real.cos`) and complex (`complex.cos`) cosine. -/ namespace polynomial.chebyshev open polynomial variables {R A : Type*} [comm_ring R] [comm_ring A] [algebra R A] @[simp] lemma aeval_T (x : A) (n : ℕ) : aeval x (T R n) = (T A n).eval x := by rw [aeval_def, eval₂_eq_eval_map, map_T] @[simp] lemma aeval_U (x : A) (n : ℕ) : aeval x (U R n) = (U A n).eval x := by rw [aeval_def, eval₂_eq_eval_map, map_U] @[simp] lemma algebra_map_eval_T (x : R) (n : ℕ) : algebra_map R A ((T R n).eval x) = (T A n).eval (algebra_map R A x) := by rw [←aeval_algebra_map_apply_eq_algebra_map_eval, aeval_T] @[simp] lemma algebra_map_eval_U (x : R) (n : ℕ) : algebra_map R A ((U R n).eval x) = (U A n).eval (algebra_map R A x) := by rw [←aeval_algebra_map_apply_eq_algebra_map_eval, aeval_U] @[simp, norm_cast] lemma complex_of_real_eval_T : ∀ x n, ((T ℝ n).eval x : ℂ) = (T ℂ n).eval x := @algebra_map_eval_T ℝ ℂ _ _ _ @[simp, norm_cast] lemma complex_of_real_eval_U : ∀ x n, ((U ℝ n).eval x : ℂ) = (U ℂ n).eval x := @algebra_map_eval_U ℝ ℂ _ _ _ /-! ### Complex versions -/ section complex open complex variable (θ : ℂ) /-- The `n`-th Chebyshev polynomial of the first kind evaluates on `cos θ` to the value `cos (n * θ)`. -/ @[simp] lemma T_complex_cos : ∀ n, (T ℂ n).eval (cos θ) = cos (n * θ) | 0 := by simp only [T_zero, eval_one, nat.cast_zero, zero_mul, cos_zero] | 1 := by simp only [eval_X, one_mul, T_one, nat.cast_one] | (n + 2) := begin simp only [eval_X, eval_one, T_add_two, eval_sub, eval_bit0, nat.cast_succ, eval_mul], rw [T_complex_cos (n + 1), T_complex_cos n], have aux : sin θ * sin θ = 1 - cos θ * cos θ, { rw ← sin_sq_add_cos_sq θ, ring, }, simp only [nat.cast_add, nat.cast_one, add_mul, cos_add, one_mul, sin_add, mul_assoc, aux], ring, end /-- The `n`-th Chebyshev polynomial of the second kind evaluates on `cos θ` to the value `sin ((n + 1) * θ) / sin θ`. -/ @[simp] lemma U_complex_cos (n : ℕ) : (U ℂ n).eval (cos θ) * sin θ = sin ((n + 1) * θ) := begin induction n with d hd, { simp only [U_zero, nat.cast_zero, eval_one, mul_one, zero_add, one_mul] }, { rw U_eq_X_mul_U_add_T, simp only [eval_add, eval_mul, eval_X, T_complex_cos, add_mul, mul_assoc, hd, one_mul], conv_rhs { rw [sin_add, mul_comm] }, push_cast, simp only [add_mul, one_mul] } end end complex /- ### Real versions -/ section real open real variables (θ : ℝ) (n : ℕ) /-- The `n`-th Chebyshev polynomial of the first kind evaluates on `cos θ` to the value `cos (n * θ)`. -/ @[simp] lemma T_real_cos : (T ℝ n).eval (cos θ) = cos (n * θ) := by exact_mod_cast T_complex_cos θ n /-- The `n`-th Chebyshev polynomial of the second kind evaluates on `cos θ` to the value `sin ((n + 1) * θ) / sin θ`. -/ @[simp] lemma U_real_cos : (U ℝ n).eval (cos θ) * sin θ = sin ((n + 1) * θ) := by exact_mod_cast U_complex_cos θ n end real end polynomial.chebyshev
b4683a8ce90c54aa3d66f075a7d30febfb6b194a
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/beginend_bug.lean
9c153e0760c17e38365aaeba284f214e98dbb3d9
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
167
lean
import tools.tactic logic open tactic theorem foo (A : Type) (a b c : A) (Hab : a = b) (Hbc : b = c) : a = c := begin apply eq.trans, apply Hbc, apply Hbc, end
44250e0d4d3216c43891beff231dccbd182aaa91
9cba98daa30c0804090f963f9024147a50292fa0
/scalar.lean
6a6c4b441f4fa042c0d681edb196bf7d7f7451c5
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
351
lean
import ..math.affnKcoord.affnKcoord_std import data.real.basic --configure field here abbreviation scalar := ℝ abbreviation real_scalar := ℝ /- enforce constraint here (and up the stack - but to make it immediately clear when you do something bad) -/ instance : inhabited scalar := by apply_instance instance : field scalar := by apply_instance
4e0c8b4fe35e4b528ec9f40b05e0782382df9b21
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/gcd.lean
85325c2a40eb394ade008d9b946fa2ea66b32482
[]
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,050
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.lattice import Mathlib.algebra.gcd_monoid import Mathlib.PostPort universes u_1 namespace Mathlib /-! # GCD and LCM operations on multisets ## Main definitions - `multiset.gcd` - the greatest common denominator of a `multiset` of elements of a `gcd_monoid` - `multiset.lcm` - the least common multiple of a `multiset` of elements of a `gcd_monoid` ## Implementation notes TODO: simplify with a tactic and `data.multiset.lattice` ## Tags multiset, gcd -/ namespace multiset /-! ### lcm -/ /-- Least common multiple of a multiset -/ def lcm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s : multiset α) : α := fold lcm 1 s @[simp] theorem lcm_zero {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] : lcm 0 = 1 := fold_zero lcm 1 @[simp] theorem lcm_cons {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (s : multiset α) : lcm (a ::ₘ s) = lcm a (lcm s) := fold_cons_left lcm 1 a s @[simp] theorem lcm_singleton {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} : lcm (a ::ₘ 0) = coe_fn normalize a := sorry @[simp] theorem lcm_add {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s₁ : multiset α) (s₂ : multiset α) : lcm (s₁ + s₂) = lcm (lcm s₁) (lcm s₂) := sorry theorem lcm_dvd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : multiset α} {a : α} : lcm s ∣ a ↔ ∀ (b : α), b ∈ s → b ∣ a := sorry theorem dvd_lcm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : multiset α} {a : α} (h : a ∈ s) : a ∣ lcm s := iff.mp lcm_dvd (dvd_refl (lcm s)) a h theorem lcm_mono {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s₁ : multiset α} {s₂ : multiset α} (h : s₁ ⊆ s₂) : lcm s₁ ∣ lcm s₂ := iff.mpr lcm_dvd fun (b : α) (hb : b ∈ s₁) => dvd_lcm (h hb) @[simp] theorem normalize_lcm {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s : multiset α) : coe_fn normalize (lcm s) = lcm s := sorry @[simp] theorem lcm_erase_dup {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] [DecidableEq α] (s : multiset α) : lcm (erase_dup s) = lcm s := sorry @[simp] theorem lcm_ndunion {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) : lcm (ndunion s₁ s₂) = lcm (lcm s₁) (lcm s₂) := sorry @[simp] theorem lcm_union {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) : lcm (s₁ ∪ s₂) = lcm (lcm s₁) (lcm s₂) := sorry @[simp] theorem lcm_ndinsert {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] [DecidableEq α] (a : α) (s : multiset α) : lcm (ndinsert a s) = lcm a (lcm s) := sorry /-! ### gcd -/ /-- Greatest common divisor of a multiset -/ def gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s : multiset α) : α := fold gcd 0 s @[simp] theorem gcd_zero {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] : gcd 0 = 0 := fold_zero gcd 0 @[simp] theorem gcd_cons {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (a : α) (s : multiset α) : gcd (a ::ₘ s) = gcd a (gcd s) := fold_cons_left gcd 0 a s @[simp] theorem gcd_singleton {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {a : α} : gcd (a ::ₘ 0) = coe_fn normalize a := sorry @[simp] theorem gcd_add {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s₁ : multiset α) (s₂ : multiset α) : gcd (s₁ + s₂) = gcd (gcd s₁) (gcd s₂) := sorry theorem dvd_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : multiset α} {a : α} : a ∣ gcd s ↔ ∀ (b : α), b ∈ s → a ∣ b := sorry theorem gcd_dvd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s : multiset α} {a : α} (h : a ∈ s) : gcd s ∣ a := iff.mp dvd_gcd (dvd_refl (gcd s)) a h theorem gcd_mono {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] {s₁ : multiset α} {s₂ : multiset α} (h : s₁ ⊆ s₂) : gcd s₂ ∣ gcd s₁ := iff.mpr dvd_gcd fun (b : α) (hb : b ∈ s₁) => gcd_dvd (h hb) @[simp] theorem normalize_gcd {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s : multiset α) : coe_fn normalize (gcd s) = gcd s := sorry theorem gcd_eq_zero_iff {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] (s : multiset α) : gcd s = 0 ↔ ∀ (x : α), x ∈ s → x = 0 := sorry @[simp] theorem gcd_erase_dup {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] [DecidableEq α] (s : multiset α) : gcd (erase_dup s) = gcd s := sorry @[simp] theorem gcd_ndunion {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) : gcd (ndunion s₁ s₂) = gcd (gcd s₁) (gcd s₂) := sorry @[simp] theorem gcd_union {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) : gcd (s₁ ∪ s₂) = gcd (gcd s₁) (gcd s₂) := sorry @[simp] theorem gcd_ndinsert {α : Type u_1} [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] [DecidableEq α] (a : α) (s : multiset α) : gcd (ndinsert a s) = gcd a (gcd s) := sorry
e25f653ae71053bee4aa03891b8459d234eade0d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/bilinear_form.lean
c297d997a7f2d6e3e264e468b0fd864617ff5a96
[ "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
51,943
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kexing Ying -/ import linear_algebra.dual import linear_algebra.matrix.to_lin /-! # Bilinear form This file defines a bilinear form over a module. Basic ideas such as orthogonality are also introduced, as well as reflexivive, symmetric, non-degenerate and alternating bilinear forms. Adjoints of linear maps with respect to a bilinear form are also introduced. A bilinear form on an R-(semi)module M, is a function from M x M to R, that is linear in both arguments. Comments will typically abbreviate "(semi)module" as just "module", but the definitions should be as general as possible. The result that there exists an orthogonal basis with respect to a symmetric, nondegenerate bilinear form can be found in `quadratic_form.lean` with `exists_orthogonal_basis`. ## Notations Given any term B of type bilin_form, due to a coercion, can use the notation B x y to refer to the function field, ie. B x y = B.bilin x y. In this file we use the following type variables: - `M`, `M'`, ... are modules over the semiring `R`, - `M₁`, `M₁'`, ... are modules over the ring `R₁`, - `M₂`, `M₂'`, ... are modules over the commutative semiring `R₂`, - `M₃`, `M₃'`, ... are modules over the commutative ring `R₃`, - `V`, ... is a vector space over the field `K`. ## References * <https://en.wikipedia.org/wiki/Bilinear_form> ## Tags Bilinear form, -/ open_locale big_operators universes u v w /-- `bilin_form R M` is the type of `R`-bilinear functions `M → M → R`. -/ structure bilin_form (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M] := (bilin : M → M → R) (bilin_add_left : ∀ (x y z : M), bilin (x + y) z = bilin x z + bilin y z) (bilin_smul_left : ∀ (a : R) (x y : M), bilin (a • x) y = a * (bilin x y)) (bilin_add_right : ∀ (x y z : M), bilin x (y + z) = bilin x y + bilin x z) (bilin_smul_right : ∀ (a : R) (x y : M), bilin x (a • y) = a * (bilin x y)) variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] variables {R₁ : Type*} {M₁ : Type*} [ring R₁] [add_comm_group M₁] [module R₁ M₁] variables {R₂ : Type*} {M₂ : Type*} [comm_semiring R₂] [add_comm_monoid M₂] [module R₂ M₂] variables {R₃ : Type*} {M₃ : Type*} [comm_ring R₃] [add_comm_group M₃] [module R₃ M₃] variables {V : Type*} {K : Type*} [field K] [add_comm_group V] [module K V] variables {B : bilin_form R M} {B₁ : bilin_form R₁ M₁} {B₂ : bilin_form R₂ M₂} namespace bilin_form instance : has_coe_to_fun (bilin_form R M) (λ _, M → M → R) := ⟨bilin⟩ initialize_simps_projections bilin_form (bilin -> apply) @[simp] lemma coe_fn_mk (f : M → M → R) (h₁ h₂ h₃ h₄) : (bilin_form.mk f h₁ h₂ h₃ h₄ : M → M → R) = f := rfl lemma coe_fn_congr : Π {x x' y y' : M}, x = x' → y = y' → B x y = B x' y' | _ _ _ _ rfl rfl := rfl @[simp] lemma add_left (x y z : M) : B (x + y) z = B x z + B y z := bilin_add_left B x y z @[simp] lemma smul_left (a : R) (x y : M) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y @[simp] lemma add_right (x y z : M) : B x (y + z) = B x y + B x z := bilin_add_right B x y z @[simp] lemma smul_right (a : R) (x y : M) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y @[simp] lemma zero_left (x : M) : B 0 x = 0 := by { rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul] } @[simp] lemma zero_right (x : M) : B x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, zero_mul] @[simp] lemma neg_left (x y : M₁) : B₁ (-x) y = -(B₁ x y) := by rw [←@neg_one_smul R₁ _ _, smul_left, neg_one_mul] @[simp] lemma neg_right (x y : M₁) : B₁ x (-y) = -(B₁ x y) := by rw [←@neg_one_smul R₁ _ _, smul_right, neg_one_mul] @[simp] lemma sub_left (x y z : M₁) : B₁ (x - y) z = B₁ x z - B₁ y z := by rw [sub_eq_add_neg, sub_eq_add_neg, add_left, neg_left] @[simp] lemma sub_right (x y z : M₁) : B₁ x (y - z) = B₁ x y - B₁ x z := by rw [sub_eq_add_neg, sub_eq_add_neg, add_right, neg_right] variables {D : bilin_form R M} {D₁ : bilin_form R₁ M₁} -- TODO: instantiate `fun_like` lemma coe_injective : function.injective (coe_fn : bilin_form R M → (M → M → R)) := λ B D h, by { cases B, cases D, congr' } @[ext] lemma ext (H : ∀ (x y : M), B x y = D x y) : B = D := coe_injective $ by { funext, exact H _ _ } lemma congr_fun (h : B = D) (x y : M) : B x y = D x y := h ▸ rfl lemma ext_iff : B = D ↔ (∀ x y, B x y = D x y) := ⟨congr_fun, ext⟩ instance : has_zero (bilin_form R M) := { zero := { bilin := λ x y, 0, bilin_add_left := λ x y z, (add_zero 0).symm, bilin_smul_left := λ a x y, (mul_zero a).symm, bilin_add_right := λ x y z, (zero_add 0).symm, bilin_smul_right := λ a x y, (mul_zero a).symm } } @[simp] lemma coe_zero : ⇑(0 : bilin_form R M) = 0 := rfl @[simp] lemma zero_apply (x y : M) : (0 : bilin_form R M) x y = 0 := rfl variables (B D B₁ D₁) instance : has_add (bilin_form R M) := { add := λ B D, { bilin := λ x y, B x y + D x y, bilin_add_left := λ x y z, by rw [add_left, add_left, add_add_add_comm], bilin_smul_left := λ a x y, by rw [smul_left, smul_left, mul_add], bilin_add_right := λ x y z, by rw [add_right, add_right, add_add_add_comm], bilin_smul_right := λ a x y, by rw [smul_right, smul_right, mul_add] } } @[simp] lemma coe_add : ⇑(B + D) = B + D := rfl @[simp] lemma add_apply (x y : M) : (B + D) x y = B x y + D x y := rfl /-- `bilin_form R M` inherits the scalar action by `α` on `R` if this is compatible with multiplication. When `R` itself is commutative, this provides an `R`-action via `algebra.id`. -/ instance {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R] : has_smul α (bilin_form R M) := { smul := λ c B, { bilin := λ x y, c • B x y, bilin_add_left := λ x y z, by { rw [add_left, smul_add] }, bilin_smul_left := λ a x y, by { rw [smul_left, ←mul_smul_comm] }, bilin_add_right := λ x y z, by { rw [add_right, smul_add] }, bilin_smul_right := λ a x y, by { rw [smul_right, ←mul_smul_comm] } } } @[simp] lemma coe_smul {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R] (a : α) (B : bilin_form R M) : ⇑(a • B) = a • B := rfl @[simp] lemma smul_apply {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R] (a : α) (B : bilin_form R M) (x y : M) : (a • B) x y = a • (B x y) := rfl instance : add_comm_monoid (bilin_form R M) := function.injective.add_comm_monoid _ coe_injective coe_zero coe_add (λ n x, coe_smul _ _) instance : has_neg (bilin_form R₁ M₁) := { neg := λ B, { bilin := λ x y, -(B x y), bilin_add_left := λ x y z, by rw [add_left, neg_add], bilin_smul_left := λ a x y, by rw [smul_left, mul_neg], bilin_add_right := λ x y z, by rw [add_right, neg_add], bilin_smul_right := λ a x y, by rw [smul_right, mul_neg] } } @[simp] lemma coe_neg : ⇑(-B₁) = -B₁ := rfl @[simp] lemma neg_apply (x y : M₁) : (-B₁) x y = -(B₁ x y) := rfl instance : has_sub (bilin_form R₁ M₁) := { sub := λ B D, { bilin := λ x y, B x y - D x y, bilin_add_left := λ x y z, by rw [add_left, add_left, add_sub_add_comm], bilin_smul_left := λ a x y, by rw [smul_left, smul_left, mul_sub], bilin_add_right := λ x y z, by rw [add_right, add_right, add_sub_add_comm], bilin_smul_right := λ a x y, by rw [smul_right, smul_right, mul_sub] } } @[simp] lemma coe_sub : ⇑(B₁ - D₁) = B₁ - D₁ := rfl @[simp] lemma sub_apply (x y : M₁) : (B₁ - D₁) x y = B₁ x y - D₁ x y := rfl instance : add_comm_group (bilin_form R₁ M₁) := function.injective.add_comm_group _ coe_injective coe_zero coe_add coe_neg coe_sub (λ n x, coe_smul _ _) (λ n x, coe_smul _ _) instance : inhabited (bilin_form R M) := ⟨0⟩ /-- `coe_fn` as an `add_monoid_hom` -/ def coe_fn_add_monoid_hom : bilin_form R M →+ (M → M → R) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } instance {α} [monoid α] [distrib_mul_action α R] [smul_comm_class α R R] : distrib_mul_action α (bilin_form R M) := function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective coe_smul instance {α} [semiring α] [module α R] [smul_comm_class α R R] : module α (bilin_form R M) := function.injective.module _ coe_fn_add_monoid_hom coe_injective coe_smul section flip variables (R₂) /-- Auxiliary construction for the flip of a bilinear form, obtained by exchanging the left and right arguments. This version is a `linear_map`; it is later upgraded to a `linear_equiv` in `flip_hom`. -/ def flip_hom_aux [algebra R₂ R] : bilin_form R M →ₗ[R₂] bilin_form R M := { to_fun := λ A, { bilin := λ i j, A j i, bilin_add_left := λ x y z, A.bilin_add_right z x y, bilin_smul_left := λ a x y, A.bilin_smul_right a y x, bilin_add_right := λ x y z, A.bilin_add_left y z x, bilin_smul_right := λ a x y, A.bilin_smul_left a y x }, map_add' := λ A₁ A₂, by { ext, simp } , map_smul' := λ c A, by { ext, simp } } variables {R₂} lemma flip_flip_aux [algebra R₂ R] (A : bilin_form R M) : (flip_hom_aux R₂) (flip_hom_aux R₂ A) = A := by { ext A x y, simp [flip_hom_aux] } variables (R₂) /-- The flip of a bilinear form, obtained by exchanging the left and right arguments. This is a less structured version of the equiv which applies to general (noncommutative) rings `R` with a distinguished commutative subring `R₂`; over a commutative ring use `flip`. -/ def flip_hom [algebra R₂ R] : bilin_form R M ≃ₗ[R₂] bilin_form R M := { inv_fun := flip_hom_aux R₂, left_inv := flip_flip_aux, right_inv := flip_flip_aux, .. flip_hom_aux R₂ } variables {R₂} @[simp] lemma flip_apply [algebra R₂ R] (A : bilin_form R M) (x y : M) : flip_hom R₂ A x y = A y x := rfl lemma flip_flip [algebra R₂ R] : (flip_hom R₂).trans (flip_hom R₂) = linear_equiv.refl R₂ (bilin_form R M) := by { ext A x y, simp } /-- The flip of a bilinear form over a ring, obtained by exchanging the left and right arguments, here considered as an `ℕ`-linear equivalence, i.e. an additive equivalence. -/ abbreviation flip' : bilin_form R M ≃ₗ[ℕ] bilin_form R M := flip_hom ℕ /-- The `flip` of a bilinear form over a commutative ring, obtained by exchanging the left and right arguments. -/ abbreviation flip : bilin_form R₂ M₂ ≃ₗ[R₂] bilin_form R₂ M₂ := flip_hom R₂ end flip section to_lin' variables [algebra R₂ R] [module R₂ M] [is_scalar_tower R₂ R M] /-- Auxiliary definition to define `to_lin_hom`; see below. -/ def to_lin_hom_aux₁ (A : bilin_form R M) (x : M) : M →ₗ[R] R := { to_fun := λ y, A x y, map_add' := A.bilin_add_right x, map_smul' := λ c, A.bilin_smul_right c x } /-- Auxiliary definition to define `to_lin_hom`; see below. -/ def to_lin_hom_aux₂ (A : bilin_form R M) : M →ₗ[R₂] M →ₗ[R] R := { to_fun := to_lin_hom_aux₁ A, map_add' := λ x₁ x₂, linear_map.ext $ λ x, by simp only [to_lin_hom_aux₁, linear_map.coe_mk, linear_map.add_apply, add_left], map_smul' := λ c x, linear_map.ext $ begin dsimp [to_lin_hom_aux₁], intros, simp only [← algebra_map_smul R c x, algebra.smul_def, linear_map.coe_mk, linear_map.smul_apply, smul_left] end } variables (R₂) /-- The linear map obtained from a `bilin_form` by fixing the left co-ordinate and evaluating in the right. This is the most general version of the construction; it is `R₂`-linear for some distinguished commutative subsemiring `R₂` of the scalar ring. Over a semiring with no particular distinguished such subsemiring, use `to_lin'`, which is `ℕ`-linear. Over a commutative semiring, use `to_lin`, which is linear. -/ def to_lin_hom : bilin_form R M →ₗ[R₂] M →ₗ[R₂] M →ₗ[R] R := { to_fun := to_lin_hom_aux₂, map_add' := λ A₁ A₂, linear_map.ext $ λ x, begin dsimp only [to_lin_hom_aux₁, to_lin_hom_aux₂], apply linear_map.ext, intros y, simp only [to_lin_hom_aux₂, to_lin_hom_aux₁, linear_map.coe_mk, linear_map.add_apply, add_apply], end , map_smul' := λ c A, begin dsimp [to_lin_hom_aux₁, to_lin_hom_aux₂], apply linear_map.ext, intros x, apply linear_map.ext, intros y, simp only [to_lin_hom_aux₂, to_lin_hom_aux₁, linear_map.coe_mk, linear_map.smul_apply, smul_apply], end } variables {R₂} @[simp] lemma to_lin'_apply (A : bilin_form R M) (x : M) : ⇑(to_lin_hom R₂ A x) = A x := rfl /-- The linear map obtained from a `bilin_form` by fixing the left co-ordinate and evaluating in the right. Over a commutative semiring, use `to_lin`, which is linear rather than `ℕ`-linear. -/ abbreviation to_lin' : bilin_form R M →ₗ[ℕ] M →ₗ[ℕ] M →ₗ[R] R := to_lin_hom ℕ @[simp] lemma sum_left {α} (t : finset α) (g : α → M) (w : M) : B (∑ i in t, g i) w = ∑ i in t, B (g i) w := (bilin_form.to_lin' B).map_sum₂ t g w @[simp] lemma sum_right {α} (t : finset α) (w : M) (g : α → M) : B w (∑ i in t, g i) = ∑ i in t, B w (g i) := (bilin_form.to_lin' B w).map_sum variables (R₂) /-- The linear map obtained from a `bilin_form` by fixing the right co-ordinate and evaluating in the left. This is the most general version of the construction; it is `R₂`-linear for some distinguished commutative subsemiring `R₂` of the scalar ring. Over semiring with no particular distinguished such subsemiring, use `to_lin'_flip`, which is `ℕ`-linear. Over a commutative semiring, use `to_lin_flip`, which is linear. -/ def to_lin_hom_flip : bilin_form R M →ₗ[R₂] M →ₗ[R₂] M →ₗ[R] R := (to_lin_hom R₂).comp (flip_hom R₂).to_linear_map variables {R₂} @[simp] lemma to_lin'_flip_apply (A : bilin_form R M) (x : M) : ⇑(to_lin_hom_flip R₂ A x) = λ y, A y x := rfl /-- The linear map obtained from a `bilin_form` by fixing the right co-ordinate and evaluating in the left. Over a commutative semiring, use `to_lin_flip`, which is linear rather than `ℕ`-linear. -/ abbreviation to_lin'_flip : bilin_form R M →ₗ[ℕ] M →ₗ[ℕ] M →ₗ[R] R := to_lin_hom_flip ℕ end to_lin' end bilin_form section equiv_lin /-- A map with two arguments that is linear in both is a bilinear form. This is an auxiliary definition for the full linear equivalence `linear_map.to_bilin`. -/ def linear_map.to_bilin_aux (f : M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) : bilin_form R₂ M₂ := { bilin := λ x y, f x y, bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z, bilin_smul_left := λ a x y, by rw [linear_map.map_smul, linear_map.smul_apply, smul_eq_mul], bilin_add_right := λ x y z, linear_map.map_add (f x) y z, bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y } /-- Bilinear forms are linearly equivalent to maps with two arguments that are linear in both. -/ def bilin_form.to_lin : bilin_form R₂ M₂ ≃ₗ[R₂] (M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) := { inv_fun := linear_map.to_bilin_aux, left_inv := λ B, by { ext, simp [linear_map.to_bilin_aux] }, right_inv := λ B, by { ext, simp [linear_map.to_bilin_aux] }, .. bilin_form.to_lin_hom R₂ } /-- A map with two arguments that is linear in both is linearly equivalent to bilinear form. -/ def linear_map.to_bilin : (M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) ≃ₗ[R₂] bilin_form R₂ M₂ := bilin_form.to_lin.symm @[simp] lemma linear_map.to_bilin_aux_eq (f : M₂ →ₗ[R₂] M₂ →ₗ[R₂] R₂) : linear_map.to_bilin_aux f = linear_map.to_bilin f := rfl @[simp] lemma linear_map.to_bilin_symm : (linear_map.to_bilin.symm : bilin_form R₂ M₂ ≃ₗ[R₂] _) = bilin_form.to_lin := rfl @[simp] lemma bilin_form.to_lin_symm : (bilin_form.to_lin.symm : _ ≃ₗ[R₂] bilin_form R₂ M₂) = linear_map.to_bilin := linear_map.to_bilin.symm_symm @[simp, norm_cast] lemma bilin_form.to_lin_apply (x : M₂) : ⇑(bilin_form.to_lin B₂ x) = B₂ x := rfl end equiv_lin namespace linear_map variables {R' : Type} [comm_semiring R'] [algebra R' R] [module R' M] [is_scalar_tower R' R M] /-- Apply a linear map on the output of a bilinear form. -/ @[simps] def comp_bilin_form (f : R →ₗ[R'] R') (B : bilin_form R M) : bilin_form R' M := { bilin := λ x y, f (B x y), bilin_add_left := λ x y z, by rw [bilin_form.add_left, map_add], bilin_smul_left := λ r x y, by rw [←smul_one_smul R r (_ : M), bilin_form.smul_left, smul_one_mul r (_ : R), map_smul, smul_eq_mul], bilin_add_right := λ x y z, by rw [bilin_form.add_right, map_add], bilin_smul_right := λ r x y, by rw [←smul_one_smul R r (_ : M), bilin_form.smul_right, smul_one_mul r (_ : R), map_smul, smul_eq_mul] } end linear_map namespace bilin_form section comp variables {M' : Type w} [add_comm_monoid M'] [module R M'] /-- Apply a linear map on the left and right argument of a bilinear form. -/ def comp (B : bilin_form R M') (l r : M →ₗ[R] M') : bilin_form R M := { bilin := λ x y, B (l x) (r y), bilin_add_left := λ x y z, by rw [linear_map.map_add, add_left], bilin_smul_left := λ x y z, by rw [linear_map.map_smul, smul_left], bilin_add_right := λ x y z, by rw [linear_map.map_add, add_right], bilin_smul_right := λ x y z, by rw [linear_map.map_smul, smul_right] } /-- Apply a linear map to the left argument of a bilinear form. -/ def comp_left (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M := B.comp f linear_map.id /-- Apply a linear map to the right argument of a bilinear form. -/ def comp_right (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M := B.comp linear_map.id f lemma comp_comp {M'' : Type*} [add_comm_monoid M''] [module R M''] (B : bilin_form R M'') (l r : M →ₗ[R] M') (l' r' : M' →ₗ[R] M'') : (B.comp l' r').comp l r = B.comp (l'.comp l) (r'.comp r) := rfl @[simp] lemma comp_left_comp_right (B : bilin_form R M) (l r : M →ₗ[R] M) : (B.comp_left l).comp_right r = B.comp l r := rfl @[simp] lemma comp_right_comp_left (B : bilin_form R M) (l r : M →ₗ[R] M) : (B.comp_right r).comp_left l = B.comp l r := rfl @[simp] lemma comp_apply (B : bilin_form R M') (l r : M →ₗ[R] M') (v w) : B.comp l r v w = B (l v) (r w) := rfl @[simp] lemma comp_left_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) : B.comp_left f v w = B (f v) w := rfl @[simp] lemma comp_right_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) : B.comp_right f v w = B v (f w) := rfl @[simp] lemma comp_id_left (B : bilin_form R M) (r : M →ₗ[R] M) : B.comp linear_map.id r = B.comp_right r := by { ext, refl } @[simp] lemma comp_id_right (B : bilin_form R M) (l : M →ₗ[R] M) : B.comp l linear_map.id = B.comp_left l := by { ext, refl } @[simp] lemma comp_left_id (B : bilin_form R M) : B.comp_left linear_map.id = B := by { ext, refl } @[simp] lemma comp_right_id (B : bilin_form R M) : B.comp_right linear_map.id = B := by { ext, refl } -- Shortcut for `comp_id_{left,right}` followed by `comp_{right,left}_id`, -- has to be declared after the former two to get the right priority @[simp] lemma comp_id_id (B : bilin_form R M) : B.comp linear_map.id linear_map.id = B := by { ext, refl } lemma comp_inj (B₁ B₂ : bilin_form R M') {l r : M →ₗ[R] M'} (hₗ : function.surjective l) (hᵣ : function.surjective r) : B₁.comp l r = B₂.comp l r ↔ B₁ = B₂ := begin split; intros h, { -- B₁.comp l r = B₂.comp l r → B₁ = B₂ ext, cases hₗ x with x' hx, subst hx, cases hᵣ y with y' hy, subst hy, rw [←comp_apply, ←comp_apply, h], }, { -- B₁ = B₂ → B₁.comp l r = B₂.comp l r subst h, }, end end comp variables {M₂' M₂'' : Type*} variables [add_comm_monoid M₂'] [add_comm_monoid M₂''] [module R₂ M₂'] [module R₂ M₂''] section congr /-- Apply a linear equivalence on the arguments of a bilinear form. -/ def congr (e : M₂ ≃ₗ[R₂] M₂') : bilin_form R₂ M₂ ≃ₗ[R₂] bilin_form R₂ M₂' := { to_fun := λ B, B.comp e.symm e.symm, inv_fun := λ B, B.comp e e, left_inv := λ B, ext (λ x y, by simp only [comp_apply, linear_equiv.coe_coe, e.symm_apply_apply]), right_inv := λ B, ext (λ x y, by simp only [comp_apply, linear_equiv.coe_coe, e.apply_symm_apply]), map_add' := λ B B', ext (λ x y, by simp only [comp_apply, add_apply]), map_smul' := λ B B', ext (λ x y, by simp [comp_apply, smul_apply]) } @[simp] lemma congr_apply (e : M₂ ≃ₗ[R₂] M₂') (B : bilin_form R₂ M₂) (x y : M₂') : congr e B x y = B (e.symm x) (e.symm y) := rfl @[simp] lemma congr_symm (e : M₂ ≃ₗ[R₂] M₂') : (congr e).symm = congr e.symm := by { ext B x y, simp only [congr_apply, linear_equiv.symm_symm], refl } @[simp] lemma congr_refl : congr (linear_equiv.refl R₂ M₂) = linear_equiv.refl R₂ _ := linear_equiv.ext $ λ B, ext $ λ x y, rfl lemma congr_trans (e : M₂ ≃ₗ[R₂] M₂') (f : M₂' ≃ₗ[R₂] M₂'') : (congr e).trans (congr f) = congr (e.trans f) := rfl lemma congr_congr (e : M₂' ≃ₗ[R₂] M₂'') (f : M₂ ≃ₗ[R₂] M₂') (B : bilin_form R₂ M₂) : congr e (congr f B) = congr (f.trans e) B := rfl lemma congr_comp (e : M₂ ≃ₗ[R₂] M₂') (B : bilin_form R₂ M₂) (l r : M₂'' →ₗ[R₂] M₂') : (congr e B).comp l r = B.comp (linear_map.comp (e.symm : M₂' →ₗ[R₂] M₂) l) (linear_map.comp (e.symm : M₂' →ₗ[R₂] M₂) r) := rfl lemma comp_congr (e : M₂' ≃ₗ[R₂] M₂'') (B : bilin_form R₂ M₂) (l r : M₂' →ₗ[R₂] M₂) : congr e (B.comp l r) = B.comp (l.comp (e.symm : M₂'' →ₗ[R₂] M₂')) (r.comp (e.symm : M₂'' →ₗ[R₂] M₂')) := rfl end congr section lin_mul_lin /-- `lin_mul_lin f g` is the bilinear form mapping `x` and `y` to `f x * g y` -/ def lin_mul_lin (f g : M₂ →ₗ[R₂] R₂) : bilin_form R₂ M₂ := { bilin := λ x y, f x * g y, bilin_add_left := λ x y z, by rw [linear_map.map_add, add_mul], bilin_smul_left := λ x y z, by rw [linear_map.map_smul, smul_eq_mul, mul_assoc], bilin_add_right := λ x y z, by rw [linear_map.map_add, mul_add], bilin_smul_right := λ x y z, by rw [linear_map.map_smul, smul_eq_mul, mul_left_comm] } variables {f g : M₂ →ₗ[R₂] R₂} @[simp] lemma lin_mul_lin_apply (x y) : lin_mul_lin f g x y = f x * g y := rfl @[simp] lemma lin_mul_lin_comp (l r : M₂' →ₗ[R₂] M₂) : (lin_mul_lin f g).comp l r = lin_mul_lin (f.comp l) (g.comp r) := rfl @[simp] lemma lin_mul_lin_comp_left (l : M₂ →ₗ[R₂] M₂) : (lin_mul_lin f g).comp_left l = lin_mul_lin (f.comp l) g := rfl @[simp] lemma lin_mul_lin_comp_right (r : M₂ →ₗ[R₂] M₂) : (lin_mul_lin f g).comp_right r = lin_mul_lin f (g.comp r) := rfl end lin_mul_lin /-- The proposition that two elements of a bilinear form space are orthogonal. For orthogonality of an indexed set of elements, use `bilin_form.is_Ortho`. -/ def is_ortho (B : bilin_form R M) (x y : M) : Prop := B x y = 0 lemma is_ortho_def {B : bilin_form R M} {x y : M} : B.is_ortho x y ↔ B x y = 0 := iff.rfl lemma is_ortho_zero_left (x : M) : is_ortho B (0 : M) x := zero_left x lemma is_ortho_zero_right (x : M) : is_ortho B x (0 : M) := zero_right x lemma ne_zero_of_not_is_ortho_self {B : bilin_form K V} (x : V) (hx₁ : ¬ B.is_ortho x x) : x ≠ 0 := λ hx₂, hx₁ (hx₂.symm ▸ is_ortho_zero_left _) /-- A set of vectors `v` is orthogonal with respect to some bilinear form `B` if and only if for all `i ≠ j`, `B (v i) (v j) = 0`. For orthogonality between two elements, use `bilin_form.is_ortho` -/ def is_Ortho {n : Type w} (B : bilin_form R M) (v : n → M) : Prop := pairwise (B.is_ortho on v) lemma is_Ortho_def {n : Type w} {B : bilin_form R M} {v : n → M} : B.is_Ortho v ↔ ∀ i j : n, i ≠ j → B (v i) (v j) = 0 := iff.rfl section variables {R₄ M₄ : Type*} [ring R₄] [is_domain R₄] variables [add_comm_group M₄] [module R₄ M₄] {G : bilin_form R₄ M₄} @[simp] theorem is_ortho_smul_left {x y : M₄} {a : R₄} (ha : a ≠ 0) : is_ortho G (a • x) y ↔ is_ortho G x y := begin dunfold is_ortho, split; intro H, { rw [smul_left, mul_eq_zero] at H, cases H, { trivial }, { exact H }}, { rw [smul_left, H, mul_zero] }, end @[simp] theorem is_ortho_smul_right {x y : M₄} {a : R₄} (ha : a ≠ 0) : is_ortho G x (a • y) ↔ is_ortho G x y := begin dunfold is_ortho, split; intro H, { rw [smul_right, mul_eq_zero] at H, cases H, { trivial }, { exact H }}, { rw [smul_right, H, mul_zero] }, end /-- A set of orthogonal vectors `v` with respect to some bilinear form `B` is linearly independent if for all `i`, `B (v i) (v i) ≠ 0`. -/ lemma linear_independent_of_is_Ortho {n : Type w} {B : bilin_form K V} {v : n → V} (hv₁ : B.is_Ortho v) (hv₂ : ∀ i, ¬ B.is_ortho (v i) (v i)) : linear_independent K v := begin classical, rw linear_independent_iff', intros s w hs i hi, have : B (s.sum $ λ (i : n), w i • v i) (v i) = 0, { rw [hs, zero_left] }, have hsum : s.sum (λ (j : n), w j * B (v j) (v i)) = w i * B (v i) (v i), { apply finset.sum_eq_single_of_mem i hi, intros j hj hij, rw [is_Ortho_def.1 hv₁ _ _ hij, mul_zero], }, simp_rw [sum_left, smul_left, hsum] at this, exact eq_zero_of_ne_zero_of_mul_right_eq_zero (hv₂ i) this, end end section basis variables {F₂ : bilin_form R₂ M₂} variables {ι : Type*} (b : basis ι R₂ M₂) /-- Two bilinear forms are equal when they are equal on all basis vectors. -/ lemma ext_basis (h : ∀ i j, B₂ (b i) (b j) = F₂ (b i) (b j)) : B₂ = F₂ := to_lin.injective $ b.ext $ λ i, b.ext $ λ j, h i j /-- Write out `B x y` as a sum over `B (b i) (b j)` if `b` is a basis. -/ lemma sum_repr_mul_repr_mul (x y : M₂) : (b.repr x).sum (λ i xi, (b.repr y).sum (λ j yj, xi • yj • B₂ (b i) (b j))) = B₂ x y := begin conv_rhs { rw [← b.total_repr x, ← b.total_repr y] }, simp_rw [finsupp.total_apply, finsupp.sum, sum_left, sum_right, smul_left, smul_right, smul_eq_mul], end end basis /-- The proposition that a bilinear form is reflexive -/ def is_refl (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = 0 → B y x = 0 namespace is_refl variable (H : B.is_refl) lemma eq_zero : ∀ {x y : M}, B x y = 0 → B y x = 0 := λ x y, H x y lemma ortho_comm {x y : M} : is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩ end is_refl /-- The proposition that a bilinear form is symmetric -/ def is_symm (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = B y x namespace is_symm variable (H : B.is_symm) protected lemma eq (x y : M) : B x y = B y x := H x y lemma is_refl : B.is_refl := λ x y H1, H x y ▸ H1 lemma ortho_comm {x y : M} : is_ortho B x y ↔ is_ortho B y x := H.is_refl.ortho_comm end is_symm lemma is_symm_iff_flip' [algebra R₂ R] : B.is_symm ↔ flip_hom R₂ B = B := begin split, { intros h, ext x y, exact h y x }, { intros h x y, conv_lhs { rw ← h }, simp } end /-- The proposition that a bilinear form is alternating -/ def is_alt (B : bilin_form R M) : Prop := ∀ (x : M), B x x = 0 namespace is_alt lemma self_eq_zero (H : B.is_alt) (x : M) : B x x = 0 := H x lemma neg (H : B₁.is_alt) (x y : M₁) : - B₁ x y = B₁ y x := begin have H1 : B₁ (x + y) (x + y) = 0, { exact self_eq_zero H (x + y) }, rw [add_left, add_right, add_right, self_eq_zero H, self_eq_zero H, ring.zero_add, ring.add_zero, add_eq_zero_iff_neg_eq] at H1, exact H1, end lemma is_refl (H : B₁.is_alt) : B₁.is_refl := begin intros x y h, rw [←neg H, h, neg_zero], end lemma ortho_comm (H : B₁.is_alt) {x y : M₁} : is_ortho B₁ x y ↔ is_ortho B₁ y x := H.is_refl.ortho_comm end is_alt section linear_adjoints variables (B) (F : bilin_form R M) variables {M' : Type*} [add_comm_monoid M'] [module R M'] variables (B' : bilin_form R M') (f f' : M →ₗ[R] M') (g g' : M' →ₗ[R] M) /-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of maps between them to be mutually adjoint. -/ def is_adjoint_pair := ∀ ⦃x y⦄, B' (f x) y = B x (g y) variables {B B' B₂ f f' g g'} lemma is_adjoint_pair.eq (h : is_adjoint_pair B B' f g) : ∀ {x y}, B' (f x) y = B x (g y) := h lemma is_adjoint_pair_iff_comp_left_eq_comp_right (f g : module.End R M) : is_adjoint_pair B F f g ↔ F.comp_left f = B.comp_right g := begin split; intros h, { ext x y, rw [comp_left_apply, comp_right_apply], apply h, }, { intros x y, rw [←comp_left_apply, ←comp_right_apply], rw h, }, end lemma is_adjoint_pair_zero : is_adjoint_pair B B' 0 0 := λ x y, by simp only [bilin_form.zero_left, bilin_form.zero_right, linear_map.zero_apply] lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl lemma is_adjoint_pair.add (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B B' f' g') : is_adjoint_pair B B' (f + f') (g + g') := λ x y, by rw [linear_map.add_apply, linear_map.add_apply, add_left, add_right, h, h'] variables {M₁' : Type*} [add_comm_group M₁'] [module R₁ M₁'] variables {B₁' : bilin_form R₁ M₁'} {f₁ f₁' : M₁ →ₗ[R₁] M₁'} {g₁ g₁' : M₁' →ₗ[R₁] M₁} lemma is_adjoint_pair.sub (h : is_adjoint_pair B₁ B₁' f₁ g₁) (h' : is_adjoint_pair B₁ B₁' f₁' g₁') : is_adjoint_pair B₁ B₁' (f₁ - f₁') (g₁ - g₁') := λ x y, by rw [linear_map.sub_apply, linear_map.sub_apply, sub_left, sub_right, h, h'] variables {B₂' : bilin_form R₂ M₂'} {f₂ f₂' : M₂ →ₗ[R₂] M₂'} {g₂ g₂' : M₂' →ₗ[R₂] M₂} lemma is_adjoint_pair.smul (c : R₂) (h : is_adjoint_pair B₂ B₂' f₂ g₂) : is_adjoint_pair B₂ B₂' (c • f₂) (c • g₂) := λ x y, by rw [linear_map.smul_apply, linear_map.smul_apply, smul_left, smul_right, h] variables {M'' : Type*} [add_comm_monoid M''] [module R M''] variables (B'' : bilin_form R M'') lemma is_adjoint_pair.comp {f' : M' →ₗ[R] M''} {g' : M'' →ₗ[R] M'} (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B' B'' f' g') : is_adjoint_pair B B'' (f'.comp f) (g.comp g') := λ x y, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h] lemma is_adjoint_pair.mul {f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') : is_adjoint_pair B B (f * f') (g' * g) := λ x y, by rw [linear_map.mul_apply, linear_map.mul_apply, h, h'] variables (B B' B₁ B₂) (F₂ : bilin_form R₂ M₂) /-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms on the underlying module. In the case that these two forms are identical, this is the usual concept of self adjointness. In the case that one of the forms is the negation of the other, this is the usual concept of skew adjointness. -/ def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B F f f /-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/ def is_pair_self_adjoint_submodule : submodule R₂ (module.End R₂ M₂) := { carrier := { f | is_pair_self_adjoint B₂ F₂ f }, zero_mem' := is_adjoint_pair_zero, add_mem' := λ f g hf hg, hf.add hg, smul_mem' := λ c f h, h.smul c, } @[simp] lemma mem_is_pair_self_adjoint_submodule (f : module.End R₂ M₂) : f ∈ is_pair_self_adjoint_submodule B₂ F₂ ↔ is_pair_self_adjoint B₂ F₂ f := by refl lemma is_pair_self_adjoint_equiv (e : M₂' ≃ₗ[R₂] M₂) (f : module.End R₂ M₂) : is_pair_self_adjoint B₂ F₂ f ↔ is_pair_self_adjoint (B₂.comp ↑e ↑e) (F₂.comp ↑e ↑e) (e.symm.conj f) := begin have hₗ : (F₂.comp ↑e ↑e).comp_left (e.symm.conj f) = (F₂.comp_left f).comp ↑e ↑e := by { ext, simp [linear_equiv.symm_conj_apply], }, have hᵣ : (B₂.comp ↑e ↑e).comp_right (e.symm.conj f) = (B₂.comp_right f).comp ↑e ↑e := by { ext, simp [linear_equiv.conj_apply], }, have he : function.surjective (⇑(↑e : M₂' →ₗ[R₂] M₂) : M₂' → M₂) := e.surjective, show bilin_form.is_adjoint_pair _ _ _ _ ↔ bilin_form.is_adjoint_pair _ _ _ _, rw [is_adjoint_pair_iff_comp_left_eq_comp_right, is_adjoint_pair_iff_comp_left_eq_comp_right, hᵣ, hₗ, comp_inj _ _ he he], end /-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an adjoint for itself. -/ def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f /-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation serves as an adjoint. -/ def is_skew_adjoint (f : module.End R₁ M₁) := is_adjoint_pair B₁ B₁ f (-f) lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R₁ M₁) : B₁.is_skew_adjoint f ↔ is_adjoint_pair (-B₁) B₁ f f := show (∀ x y, B₁ (f x) y = B₁ x ((-f) y)) ↔ ∀ x y, B₁ (f x) y = (-B₁) x (f y), by simp only [linear_map.neg_apply, bilin_form.neg_apply, bilin_form.neg_right] /-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact it is a Jordan subalgebra.) -/ def self_adjoint_submodule := is_pair_self_adjoint_submodule B₂ B₂ @[simp] lemma mem_self_adjoint_submodule (f : module.End R₂ M₂) : f ∈ B₂.self_adjoint_submodule ↔ B₂.is_self_adjoint f := iff.rfl variables (B₃ : bilin_form R₃ M₃) /-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact it is a Lie subalgebra.) -/ def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B₃) B₃ @[simp] lemma mem_skew_adjoint_submodule (f : module.End R₃ M₃) : f ∈ B₃.skew_adjoint_submodule ↔ B₃.is_skew_adjoint f := by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl, } end linear_adjoints end bilin_form namespace bilin_form section orthogonal /-- The orthogonal complement of a submodule `N` with respect to some bilinear form is the set of elements `x` which are orthogonal to all elements of `N`; i.e., for all `y` in `N`, `B x y = 0`. Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a chirality; in addition to this "left" orthogonal complement one could define a "right" orthogonal complement for which, for all `y` in `N`, `B y x = 0`. This variant definition is not currently provided in mathlib. -/ def orthogonal (B : bilin_form R M) (N : submodule R M) : submodule R M := { carrier := { m | ∀ n ∈ N, is_ortho B n m }, zero_mem' := λ x _, is_ortho_zero_right x, add_mem' := λ x y hx hy n hn, by rw [is_ortho, add_right, show B n x = 0, by exact hx n hn, show B n y = 0, by exact hy n hn, zero_add], smul_mem' := λ c x hx n hn, by rw [is_ortho, smul_right, show B n x = 0, by exact hx n hn, mul_zero] } variables {N L : submodule R M} @[simp] lemma mem_orthogonal_iff {N : submodule R M} {m : M} : m ∈ B.orthogonal N ↔ ∀ n ∈ N, is_ortho B n m := iff.rfl lemma orthogonal_le (h : N ≤ L) : B.orthogonal L ≤ B.orthogonal N := λ _ hn l hl, hn l (h hl) lemma le_orthogonal_orthogonal (b : B.is_refl) : N ≤ B.orthogonal (B.orthogonal N) := λ n hn m hm, b _ _ (hm n hn) -- ↓ This lemma only applies in fields as we require `a * b = 0 → a = 0 ∨ b = 0` lemma span_singleton_inf_orthogonal_eq_bot {B : bilin_form K V} {x : V} (hx : ¬ B.is_ortho x x) : (K ∙ x) ⊓ B.orthogonal (K ∙ x) = ⊥ := begin rw ← finset.coe_singleton, refine eq_bot_iff.2 (λ y h, _), rcases mem_span_finset.1 h.1 with ⟨μ, rfl⟩, have := h.2 x _, { rw finset.sum_singleton at this ⊢, suffices hμzero : μ x = 0, { rw [hμzero, zero_smul, submodule.mem_bot] }, change B x (μ x • x) = 0 at this, rw [smul_right] at this, exact or.elim (zero_eq_mul.mp this.symm) id (λ hfalse, false.elim $ hx hfalse) }, { rw submodule.mem_span; exact λ _ hp, hp $ finset.mem_singleton_self _ } end -- ↓ This lemma only applies in fields since we use the `mul_eq_zero` lemma orthogonal_span_singleton_eq_to_lin_ker {B : bilin_form K V} (x : V) : B.orthogonal (K ∙ x) = (bilin_form.to_lin B x).ker := begin ext y, simp_rw [mem_orthogonal_iff, linear_map.mem_ker, submodule.mem_span_singleton ], split, { exact λ h, h x ⟨1, one_smul _ _⟩ }, { rintro h _ ⟨z, rfl⟩, rw [is_ortho, smul_left, mul_eq_zero], exact or.intro_right _ h } end lemma span_singleton_sup_orthogonal_eq_top {B : bilin_form K V} {x : V} (hx : ¬ B.is_ortho x x) : (K ∙ x) ⊔ B.orthogonal (K ∙ x) = ⊤ := begin rw orthogonal_span_singleton_eq_to_lin_ker, exact linear_map.span_singleton_sup_ker_eq_top _ hx, end /-- Given a bilinear form `B` and some `x` such that `B x x ≠ 0`, the span of the singleton of `x` is complement to its orthogonal complement. -/ lemma is_compl_span_singleton_orthogonal {B : bilin_form K V} {x : V} (hx : ¬ B.is_ortho x x) : is_compl (K ∙ x) (B.orthogonal $ K ∙ x) := { disjoint := disjoint_iff.2 $ span_singleton_inf_orthogonal_eq_bot hx, codisjoint := codisjoint_iff.2 $ span_singleton_sup_orthogonal_eq_top hx } end orthogonal /-- The restriction of a bilinear form on a submodule. -/ @[simps apply] def restrict (B : bilin_form R M) (W : submodule R M) : bilin_form R W := { bilin := λ a b, B a b, bilin_add_left := λ _ _ _, add_left _ _ _, bilin_smul_left := λ _ _ _, smul_left _ _ _, bilin_add_right := λ _ _ _, add_right _ _ _, bilin_smul_right := λ _ _ _, smul_right _ _ _} /-- The restriction of a symmetric bilinear form on a submodule is also symmetric. -/ lemma restrict_symm (B : bilin_form R M) (b : B.is_symm) (W : submodule R M) : (B.restrict W).is_symm := λ x y, b x y /-- A nondegenerate bilinear form is a bilinear form such that the only element that is orthogonal to every other element is `0`; i.e., for all nonzero `m` in `M`, there exists `n` in `M` with `B m n ≠ 0`. Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a chirality; in addition to this "left" nondegeneracy condition one could define a "right" nondegeneracy condition that in the situation described, `B n m ≠ 0`. This variant definition is not currently provided in mathlib. In finite dimension either definition implies the other. -/ def nondegenerate (B : bilin_form R M) : Prop := ∀ m : M, (∀ n : M, B m n = 0) → m = 0 section variables (R M) /-- In a non-trivial module, zero is not non-degenerate. -/ lemma not_nondegenerate_zero [nontrivial M] : ¬(0 : bilin_form R M).nondegenerate := let ⟨m, hm⟩ := exists_ne (0 : M) in λ h, hm (h m $ λ n, rfl) end variables {M₂' : Type*} variables [add_comm_monoid M₂'] [module R₂ M₂'] lemma nondegenerate.ne_zero [nontrivial M] {B : bilin_form R M} (h : B.nondegenerate) : B ≠ 0 := λ h0, not_nondegenerate_zero R M $ h0 ▸ h lemma nondegenerate.congr {B : bilin_form R₂ M₂} (e : M₂ ≃ₗ[R₂] M₂') (h : B.nondegenerate) : (congr e B).nondegenerate := λ m hm, (e.symm).map_eq_zero_iff.1 $ h (e.symm m) $ λ n, (congr_arg _ (e.symm_apply_apply n).symm).trans (hm (e n)) @[simp] lemma nondegenerate_congr_iff {B : bilin_form R₂ M₂} (e : M₂ ≃ₗ[R₂] M₂') : (congr e B).nondegenerate ↔ B.nondegenerate := ⟨λ h, begin convert h.congr e.symm, rw [congr_congr, e.self_trans_symm, congr_refl, linear_equiv.refl_apply], end, nondegenerate.congr e⟩ /-- A bilinear form is nondegenerate if and only if it has a trivial kernel. -/ theorem nondegenerate_iff_ker_eq_bot {B : bilin_form R₂ M₂} : B.nondegenerate ↔ B.to_lin.ker = ⊥ := begin rw linear_map.ker_eq_bot', split; intro h, { refine λ m hm, h _ (λ x, _), rw [← to_lin_apply, hm], refl }, { intros m hm, apply h, ext x, exact hm x } end lemma nondegenerate.ker_eq_bot {B : bilin_form R₂ M₂} (h : B.nondegenerate) : B.to_lin.ker = ⊥ := nondegenerate_iff_ker_eq_bot.mp h /-- The restriction of a reflexive bilinear form `B` onto a submodule `W` is nondegenerate if `disjoint W (B.orthogonal W)`. -/ lemma nondegenerate_restrict_of_disjoint_orthogonal (B : bilin_form R₁ M₁) (b : B.is_refl) {W : submodule R₁ M₁} (hW : disjoint W (B.orthogonal W)) : (B.restrict W).nondegenerate := begin rintro ⟨x, hx⟩ b₁, rw [submodule.mk_eq_zero, ← submodule.mem_bot R₁], refine hW.le_bot ⟨hx, λ y hy, _⟩, specialize b₁ ⟨y, hy⟩, rw [restrict_apply, submodule.coe_mk, submodule.coe_mk] at b₁, exact is_ortho_def.mpr (b x y b₁), end /-- An orthogonal basis with respect to a nondegenerate bilinear form has no self-orthogonal elements. -/ lemma is_Ortho.not_is_ortho_basis_self_of_nondegenerate {n : Type w} [nontrivial R] {B : bilin_form R M} {v : basis n R M} (h : B.is_Ortho v) (hB : B.nondegenerate) (i : n) : ¬B.is_ortho (v i) (v i) := begin intro ho, refine v.ne_zero i (hB (v i) $ λ m, _), obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m, rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, sum_right], apply finset.sum_eq_zero, rintros j -, rw smul_right, convert mul_zero _ using 2, obtain rfl | hij := eq_or_ne i j, { exact ho }, { exact h hij }, end /-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is nondegenerate iff the basis has no elements which are self-orthogonal. -/ lemma is_Ortho.nondegenerate_iff_not_is_ortho_basis_self {n : Type w} [nontrivial R] [no_zero_divisors R] (B : bilin_form R M) (v : basis n R M) (hO : B.is_Ortho v) : B.nondegenerate ↔ ∀ i, ¬B.is_ortho (v i) (v i) := begin refine ⟨hO.not_is_ortho_basis_self_of_nondegenerate, λ ho m hB, _⟩, obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m, rw linear_equiv.map_eq_zero_iff, ext i, rw [finsupp.zero_apply], specialize hB (v i), simp_rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, sum_left, smul_left] at hB, rw finset.sum_eq_single i at hB, { exact eq_zero_of_ne_zero_of_mul_right_eq_zero (ho i) hB, }, { intros j hj hij, convert mul_zero _ using 2, exact hO hij, }, { intros hi, convert zero_mul _ using 2, exact finsupp.not_mem_support_iff.mp hi } end section lemma to_lin_restrict_ker_eq_inf_orthogonal (B : bilin_form K V) (W : subspace K V) (b : B.is_refl) : (B.to_lin.dom_restrict W).ker.map W.subtype = (W ⊓ B.orthogonal ⊤ : subspace K V) := begin ext x, split; intro hx, { rcases hx with ⟨⟨x, hx⟩, hker, rfl⟩, erw linear_map.mem_ker at hker, split, { simp [hx] }, { intros y _, rw [is_ortho, b], change (B.to_lin.dom_restrict W) ⟨x, hx⟩ y = 0, rw hker, refl } }, { simp_rw [submodule.mem_map, linear_map.mem_ker], refine ⟨⟨x, hx.1⟩, _, rfl⟩, ext y, change B x y = 0, rw b, exact hx.2 _ submodule.mem_top } end lemma to_lin_restrict_range_dual_annihilator_comap_eq_orthogonal (B : bilin_form K V) (W : subspace K V) : (B.to_lin.dom_restrict W).range.dual_annihilator_comap = B.orthogonal W := begin ext x, split; rw [mem_orthogonal_iff]; intro hx, { intros y hy, rw submodule.mem_dual_annihilator_comap at hx, refine hx (B.to_lin.dom_restrict W ⟨y, hy⟩) ⟨⟨y, hy⟩, rfl⟩ }, { rw submodule.mem_dual_annihilator_comap, rintro _ ⟨⟨w, hw⟩, rfl⟩, exact hx w hw } end variable [finite_dimensional K V] open finite_dimensional lemma finrank_add_finrank_orthogonal {B : bilin_form K V} {W : subspace K V} (b₁ : B.is_refl) : finrank K W + finrank K (B.orthogonal W) = finrank K V + finrank K (W ⊓ B.orthogonal ⊤ : subspace K V) := begin rw [← to_lin_restrict_ker_eq_inf_orthogonal _ _ b₁, ← to_lin_restrict_range_dual_annihilator_comap_eq_orthogonal _ _, finrank_map_subtype_eq], conv_rhs { rw [← @subspace.finrank_add_finrank_dual_annihilator_comap_eq K V _ _ _ _ (B.to_lin.dom_restrict W).range, add_comm, ← add_assoc, add_comm (finrank K ↥((B.to_lin.dom_restrict W).ker)), linear_map.finrank_range_add_finrank_ker] }, end /-- A subspace is complement to its orthogonal complement with respect to some reflexive bilinear form if that bilinear form restricted on to the subspace is nondegenerate. -/ lemma restrict_nondegenerate_of_is_compl_orthogonal {B : bilin_form K V} {W : subspace K V} (b₁ : B.is_refl) (b₂ : (B.restrict W).nondegenerate) : is_compl W (B.orthogonal W) := begin have : W ⊓ B.orthogonal W = ⊥, { rw eq_bot_iff, intros x hx, obtain ⟨hx₁, hx₂⟩ := submodule.mem_inf.1 hx, refine subtype.mk_eq_mk.1 (b₂ ⟨x, hx₁⟩ _), rintro ⟨n, hn⟩, rw [restrict_apply, submodule.coe_mk, submodule.coe_mk, b₁], exact hx₂ n hn }, refine is_compl.of_eq this (eq_top_of_finrank_eq $ (submodule.finrank_le _).antisymm _), conv_rhs { rw ← add_zero (finrank K _) }, rw [← finrank_bot K V, ← this, submodule.dim_sup_add_dim_inf_eq, finrank_add_finrank_orthogonal b₁], exact le_self_add, end /-- A subspace is complement to its orthogonal complement with respect to some reflexive bilinear form if and only if that bilinear form restricted on to the subspace is nondegenerate. -/ theorem restrict_nondegenerate_iff_is_compl_orthogonal {B : bilin_form K V} {W : subspace K V} (b₁ : B.is_refl) : (B.restrict W).nondegenerate ↔ is_compl W (B.orthogonal W) := ⟨λ b₂, restrict_nondegenerate_of_is_compl_orthogonal b₁ b₂, λ h, B.nondegenerate_restrict_of_disjoint_orthogonal b₁ h.1⟩ /-- Given a nondegenerate bilinear form `B` on a finite-dimensional vector space, `B.to_dual` is the linear equivalence between a vector space and its dual with the underlying linear map `B.to_lin`. -/ noncomputable def to_dual (B : bilin_form K V) (b : B.nondegenerate) : V ≃ₗ[K] module.dual K V := B.to_lin.linear_equiv_of_injective (linear_map.ker_eq_bot.mp $ b.ker_eq_bot) subspace.dual_finrank_eq.symm lemma to_dual_def {B : bilin_form K V} (b : B.nondegenerate) {m n : V} : B.to_dual b m n = B m n := rfl section dual_basis variables {ι : Type*} [decidable_eq ι] [fintype ι] /-- The `B`-dual basis `B.dual_basis hB b` to a finite basis `b` satisfies `B (B.dual_basis hB b i) (b j) = B (b i) (B.dual_basis hB b j) = if i = j then 1 else 0`, where `B` is a nondegenerate (symmetric) bilinear form and `b` is a finite basis. -/ noncomputable def dual_basis (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V) : basis ι K V := b.dual_basis.map (B.to_dual hB).symm @[simp] lemma dual_basis_repr_apply (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V) (x i) : (B.dual_basis hB b).repr x i = B x (b i) := by rw [dual_basis, basis.map_repr, linear_equiv.symm_symm, linear_equiv.trans_apply, basis.dual_basis_repr, to_dual_def] lemma apply_dual_basis_left (B : bilin_form K V) (hB : B.nondegenerate) (b : basis ι K V) (i j) : B (B.dual_basis hB b i) (b j) = if j = i then 1 else 0 := by rw [dual_basis, basis.map_apply, basis.coe_dual_basis, ← to_dual_def hB, linear_equiv.apply_symm_apply, basis.coord_apply, basis.repr_self, finsupp.single_apply] lemma apply_dual_basis_right (B : bilin_form K V) (hB : B.nondegenerate) (sym : B.is_symm) (b : basis ι K V) (i j) : B (b i) (B.dual_basis hB b j) = if i = j then 1 else 0 := by rw [sym, apply_dual_basis_left] end dual_basis end /-! We note that we cannot use `bilin_form.restrict_nondegenerate_iff_is_compl_orthogonal` for the lemma below since the below lemma does not require `V` to be finite dimensional. However, `bilin_form.restrict_nondegenerate_iff_is_compl_orthogonal` does not require `B` to be nondegenerate on the whole space. -/ /-- The restriction of a reflexive, non-degenerate bilinear form on the orthogonal complement of the span of a singleton is also non-degenerate. -/ lemma restrict_orthogonal_span_singleton_nondegenerate (B : bilin_form K V) (b₁ : B.nondegenerate) (b₂ : B.is_refl) {x : V} (hx : ¬ B.is_ortho x x) : nondegenerate $ B.restrict $ B.orthogonal (K ∙ x) := begin refine λ m hm, submodule.coe_eq_zero.1 (b₁ m.1 (λ n, _)), have : n ∈ (K ∙ x) ⊔ B.orthogonal (K ∙ x) := (span_singleton_sup_orthogonal_eq_top hx).symm ▸ submodule.mem_top, rcases submodule.mem_sup.1 this with ⟨y, hy, z, hz, rfl⟩, specialize hm ⟨z, hz⟩, rw restrict at hm, erw [add_right, show B m.1 y = 0, by rw b₂; exact m.2 y hy, hm, add_zero] end section linear_adjoints lemma comp_left_injective (B : bilin_form R₁ M₁) (b : B.nondegenerate) : function.injective B.comp_left := λ φ ψ h, begin ext w, refine eq_of_sub_eq_zero (b _ _), intro v, rw [sub_left, ← comp_left_apply, ← comp_left_apply, ← h, sub_self] end lemma is_adjoint_pair_unique_of_nondegenerate (B : bilin_form R₁ M₁) (b : B.nondegenerate) (φ ψ₁ ψ₂ : M₁ →ₗ[R₁] M₁) (hψ₁ : is_adjoint_pair B B ψ₁ φ) (hψ₂ : is_adjoint_pair B B ψ₂ φ) : ψ₁ = ψ₂ := B.comp_left_injective b $ ext $ λ v w, by rw [comp_left_apply, comp_left_apply, hψ₁, hψ₂] variable [finite_dimensional K V] /-- Given bilinear forms `B₁, B₂` where `B₂` is nondegenerate, `symm_comp_of_nondegenerate` is the linear map `B₂.to_lin⁻¹ ∘ B₁.to_lin`. -/ noncomputable def symm_comp_of_nondegenerate (B₁ B₂ : bilin_form K V) (b₂ : B₂.nondegenerate) : V →ₗ[K] V := (B₂.to_dual b₂).symm.to_linear_map.comp B₁.to_lin lemma comp_symm_comp_of_nondegenerate_apply (B₁ : bilin_form K V) {B₂ : bilin_form K V} (b₂ : B₂.nondegenerate) (v : V) : to_lin B₂ (B₁.symm_comp_of_nondegenerate B₂ b₂ v) = to_lin B₁ v := by erw [symm_comp_of_nondegenerate, linear_equiv.apply_symm_apply (B₂.to_dual b₂) _] @[simp] lemma symm_comp_of_nondegenerate_left_apply (B₁ : bilin_form K V) {B₂ : bilin_form K V} (b₂ : B₂.nondegenerate) (v w : V) : B₂ (symm_comp_of_nondegenerate B₁ B₂ b₂ w) v = B₁ w v := begin conv_lhs { rw [← bilin_form.to_lin_apply, comp_symm_comp_of_nondegenerate_apply] }, refl, end /-- Given the nondegenerate bilinear form `B` and the linear map `φ`, `left_adjoint_of_nondegenerate` provides the left adjoint of `φ` with respect to `B`. The lemma proving this property is `bilin_form.is_adjoint_pair_left_adjoint_of_nondegenerate`. -/ noncomputable def left_adjoint_of_nondegenerate (B : bilin_form K V) (b : B.nondegenerate) (φ : V →ₗ[K] V) : V →ₗ[K] V := symm_comp_of_nondegenerate (B.comp_right φ) B b lemma is_adjoint_pair_left_adjoint_of_nondegenerate (B : bilin_form K V) (b : B.nondegenerate) (φ : V →ₗ[K] V) : is_adjoint_pair B B (B.left_adjoint_of_nondegenerate b φ) φ := λ x y, (B.comp_right φ).symm_comp_of_nondegenerate_left_apply b y x /-- Given the nondegenerate bilinear form `B`, the linear map `φ` has a unique left adjoint given by `bilin_form.left_adjoint_of_nondegenerate`. -/ theorem is_adjoint_pair_iff_eq_of_nondegenerate (B : bilin_form K V) (b : B.nondegenerate) (ψ φ : V →ₗ[K] V) : is_adjoint_pair B B ψ φ ↔ ψ = B.left_adjoint_of_nondegenerate b φ := ⟨λ h, B.is_adjoint_pair_unique_of_nondegenerate b φ ψ _ h (is_adjoint_pair_left_adjoint_of_nondegenerate _ _ _), λ h, h.symm ▸ is_adjoint_pair_left_adjoint_of_nondegenerate _ _ _⟩ end linear_adjoints end bilin_form
af6f5d43cdc1b8e2fd1c8bf59085b805f1a869b5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/function/ae_measurable_order.lean
fd40f966cee900bd5a808bcb9e4891d5ccc5b0a3
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,351
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.constructions.borel_space.basic /-! # Measurability criterion for ennreal-valued functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Consider a function `f : α → ℝ≥0∞`. If the level sets `{f < p}` and `{q < f}` have measurable supersets which are disjoint up to measure zero when `p` and `q` are finite numbers satisfying `p < q`, then `f` is almost-everywhere measurable. This is proved in `ennreal.ae_measurable_of_exist_almost_disjoint_supersets`, and deduced from an analogous statement for any target space which is a complete linear dense order, called `measure_theory.ae_measurable_of_exist_almost_disjoint_supersets`. Note that it should be enough to assume that the space is a conditionally complete linear order, but the proof would be more painful. Since our only use for now is for `ℝ≥0∞`, we keep it as simple as possible. -/ open measure_theory set topological_space open_locale classical ennreal nnreal /-- If a function `f : α → β` is such that the level sets `{f < p}` and `{q < f}` have measurable supersets which are disjoint up to measure zero when `p < q`, then `f` is almost-everywhere measurable. It is even enough to have this for `p` and `q` in a countable dense set. -/ theorem measure_theory.ae_measurable_of_exist_almost_disjoint_supersets {α : Type*} {m : measurable_space α} (μ : measure α) {β : Type*} [complete_linear_order β] [densely_ordered β] [topological_space β] [order_topology β] [second_countable_topology β] [measurable_space β] [borel_space β] (s : set β) (s_count : s.countable) (s_dense : dense s) (f : α → β) (h : ∀ (p ∈ s) (q ∈ s), p < q → ∃ u v, measurable_set u ∧ measurable_set v ∧ {x | f x < p} ⊆ u ∧ {x | q < f x} ⊆ v ∧ μ (u ∩ v) = 0) : ae_measurable f μ := begin haveI : encodable s := s_count.to_encodable, have h' : ∀ p q, ∃ u v, measurable_set u ∧ measurable_set v ∧ {x | f x < p} ⊆ u ∧ {x | q < f x} ⊆ v ∧ (p ∈ s → q ∈ s → p < q → μ (u ∩ v) = 0), { assume p q, by_cases H : p ∈ s ∧ q ∈ s ∧ p < q, { rcases h p H.1 q H.2.1 H.2.2 with ⟨u, v, hu, hv, h'u, h'v, hμ⟩, exact ⟨u, v, hu, hv, h'u, h'v, λ ps qs pq, hμ⟩ }, { refine ⟨univ, univ, measurable_set.univ, measurable_set.univ, subset_univ _, subset_univ _, λ ps qs pq, _⟩, simp only [not_and] at H, exact (H ps qs pq).elim } }, choose! u v huv using h', let u' : β → set α := λ p, ⋂ (q ∈ s ∩ Ioi p), u p q, have u'_meas : ∀ i, measurable_set (u' i), { assume i, exact measurable_set.bInter (s_count.mono (inter_subset_left _ _)) (λ b hb, (huv i b).1) }, let f' : α → β := λ x, ⨅ (i : s), piecewise (u' i) (λ x, (i : β)) (λ x, (⊤ : β)) x, have f'_meas : measurable f', { apply measurable_infi, exact λ i, measurable.piecewise (u'_meas i) measurable_const measurable_const }, let t := ⋃ (p : s) (q : s ∩ Ioi p), u' p ∩ v p q, have μt : μ t ≤ 0 := calc μ t ≤ ∑' (p : s) (q : s ∩ Ioi p), μ (u' p ∩ v p q) : begin refine (measure_Union_le _).trans _, apply ennreal.tsum_le_tsum (λ p, _), apply measure_Union_le _, exact (s_count.mono (inter_subset_left _ _)).to_subtype, end ... ≤ ∑' (p : s) (q : s ∩ Ioi p), μ (u p q ∩ v p q) : begin apply ennreal.tsum_le_tsum (λ p, _), refine ennreal.tsum_le_tsum (λ q, measure_mono _), exact inter_subset_inter_left _ (bInter_subset_of_mem q.2) end ... = ∑' (p : s) (q : s ∩ Ioi p), (0 : ℝ≥0∞) : by { congr, ext1 p, congr, ext1 q, exact (huv p q).2.2.2.2 p.2 q.2.1 q.2.2 } ... = 0 : by simp only [tsum_zero], have ff' : ∀ᵐ x ∂μ, f x = f' x, { have : ∀ᵐ x ∂μ, x ∉ t, { have : μ t = 0 := le_antisymm μt bot_le, change μ _ = 0, convert this, ext y, simp only [not_exists, exists_prop, mem_set_of_eq, mem_compl_iff, not_not_mem] }, filter_upwards [this] with x hx, apply (infi_eq_of_forall_ge_of_forall_gt_exists_lt _ _).symm, { assume i, by_cases H : x ∈ u' i, swap, { simp only [H, le_top, not_false_iff, piecewise_eq_of_not_mem] }, simp only [H, piecewise_eq_of_mem], contrapose! hx, obtain ⟨r, ⟨xr, rq⟩, rs⟩ : ∃ r, r ∈ Ioo (i : β) (f x) ∩ s := dense_iff_inter_open.1 s_dense (Ioo i (f x)) is_open_Ioo (nonempty_Ioo.2 hx), have A : x ∈ v i r := (huv i r).2.2.2.1 rq, apply mem_Union.2 ⟨i, _⟩, refine mem_Union.2 ⟨⟨r, ⟨rs, xr⟩⟩, _⟩, exact ⟨H, A⟩ }, { assume q hq, obtain ⟨r, ⟨xr, rq⟩, rs⟩ : ∃ r, r ∈ Ioo (f x) q ∩ s := dense_iff_inter_open.1 s_dense (Ioo (f x) q) is_open_Ioo (nonempty_Ioo.2 hq), refine ⟨⟨r, rs⟩, _⟩, have A : x ∈ u' r := mem_bInter (λ i hi, (huv r i).2.2.1 xr), simp only [A, rq, piecewise_eq_of_mem, subtype.coe_mk] } }, exact ⟨f', f'_meas, ff'⟩, end /-- If a function `f : α → ℝ≥0∞` is such that the level sets `{f < p}` and `{q < f}` have measurable supersets which are disjoint up to measure zero when `p` and `q` are finite numbers satisfying `p < q`, then `f` is almost-everywhere measurable. -/ theorem ennreal.ae_measurable_of_exist_almost_disjoint_supersets {α : Type*} {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) (h : ∀ (p : ℝ≥0) (q : ℝ≥0), p < q → ∃ u v, measurable_set u ∧ measurable_set v ∧ {x | f x < p} ⊆ u ∧ {x | (q : ℝ≥0∞) < f x} ⊆ v ∧ μ (u ∩ v) = 0) : ae_measurable f μ := begin obtain ⟨s, s_count, s_dense, s_zero, s_top⟩ : ∃ s : set ℝ≥0∞, s.countable ∧ dense s ∧ 0 ∉ s ∧ ∞ ∉ s := ennreal.exists_countable_dense_no_zero_top, have I : ∀ x ∈ s, x ≠ ∞ := λ x xs hx, s_top (hx ▸ xs), apply measure_theory.ae_measurable_of_exist_almost_disjoint_supersets μ s s_count s_dense _, rintros p hp q hq hpq, lift p to ℝ≥0 using I p hp, lift q to ℝ≥0 using I q hq, exact h p q (ennreal.coe_lt_coe.1 hpq), end
4c4ed1d533e42f0c2e777e0860d0e18affc351fe
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Leanc.lean
61f1a6935861b8ebd404421e19a9e72b557bde20
[ "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
2,203
lean
import Lean.Compiler.FFI open Lean.Compiler.FFI def main (args : List String) : IO UInt32 := do if args.isEmpty then IO.println "Lean C compiler A simple wrapper around a C compiler. Defaults to `@LEANC_CC@`, which can be overridden with the environment variable `LEAN_CC`. All parameters are passed as-is to the wrapped compiler. Interesting options: * `--print-cflags`: print C compiler flags necessary for building against the Lean runtime and exit * `--print-ldlags`: print C compiler flags necessary for statically linking against the Lean library and exit * Set the `LEANC_GMP` environment variable to a path to `libgmp.a` (or `-l:libgmp.a` on Linux) to link GMP statically. Beware of the licensing consequences since GMP is LGPL." return 1 let root ← match (← IO.getEnv "LEAN_SYSROOT") with | some root => System.FilePath.mk root | none => (← IO.appDir).parent.get! let rootify s := s.replace "ROOT" root.toString let compileOnly := args.contains "-c" let linkStatic := !args.contains "-shared" -- We assume that the CMake variables do not contain escaped spaces let cflags := getCFlags root let mut cflagsInternal := "@LEANC_INTERNAL_FLAGS@".trim.splitOn let mut ldflagsInternal := "@LEANC_INTERNAL_LINKER_FLAGS@".trim.splitOn let ldflags := getLinkerFlags root linkStatic ((← IO.getEnv "LEANC_GMP").getD "-lgmp") for arg in args do match arg with | "--print-cflags" => IO.println <| " ".intercalate (cflags.map rootify |>.toList) return 0 | "--print-ldflags" => IO.println <| " ".intercalate ((cflags ++ ldflags).map rootify |>.toList) return 0 | _ => () let mut cc := "@LEANC_CC@" if let some cc' ← IO.getEnv "LEAN_CC" then cc := cc' -- these are intended for the bundled compiler only cflagsInternal := [] ldflagsInternal := [] cc := rootify cc let args := cflags ++ cflagsInternal ++ args ++ ldflagsInternal ++ ldflags ++ ["-Wno-unused-command-line-argument"] let args := args.filter (!·.isEmpty) |>.map rootify if args.contains "-v" then IO.eprintln s!"{cc} {" ".intercalate args.toList}" let child ← IO.Process.spawn { cmd := cc, args } child.wait
1f9f7f6e4e53b4e00df05e26c18f6029b26304a6
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/field_theory/normal.lean
98248b9ff5101cc602afe2ff492fb3cb53f59e02
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,127
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 field_theory.minpoly import field_theory.splitting_field import field_theory.tower import ring_theory.power_basis /-! # Normal field extensions In this file we define normal field extensions and prove that for a finite extension, being normal is the same as being a splitting field (`normal.of_is_splitting_field` and `normal.exists_is_splitting_field`). ## Main Definitions - `normal F K` where `K` is a field extension of `F`. -/ noncomputable theory open_locale classical open polynomial is_scalar_tower variables (F K : Type*) [field F] [field K] [algebra F K] --TODO(Commelin): refactor normal to extend `is_algebraic`?? /-- Typeclass for normal field extension: `K` is a normal extension of `F` iff the minimal polynomial of every element `x` in `K` splits in `K`, i.e. every conjugate of `x` is in `K`. -/ @[class] def normal : Prop := ∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) instance normal_self : normal F F := λ x, ⟨is_integral_algebra_map, by { rw minpoly.eq_X_sub_C', exact splits_X_sub_C _ }⟩ variables {K} theorem normal.is_integral [h : normal F K] (x : K) : is_integral F x := (h x).1 theorem normal.splits [h : normal F K] (x : K) : splits (algebra_map F K) (minpoly F x) := (h x).2 variables (K) theorem normal.exists_is_splitting_field [normal F K] [finite_dimensional F K] : ∃ p : polynomial F, is_splitting_field F K p := begin obtain ⟨s, hs⟩ := finite_dimensional.exists_is_basis_finset F K, refine ⟨s.prod $ λ x, minpoly F x, splits_prod _ $ λ x hx, normal.splits F x, subalgebra.to_submodule_injective _⟩, rw [algebra.coe_top, eq_top_iff, ← hs.2, submodule.span_le, set.range_subset_iff], refine λ x, algebra.subset_adjoin (multiset.mem_to_finset.mpr $ (mem_roots $ mt (map_eq_zero $ algebra_map F K).1 $ finset.prod_ne_zero_iff.2 $ λ x hx, _).2 _), { exact minpoly.ne_zero (normal.is_integral F x) }, rw [is_root.def, eval_map, ← aeval_def, alg_hom.map_prod], exact finset.prod_eq_zero x.2 (minpoly.aeval _ _) end section normal_tower variables (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma normal.tower_top_of_normal [h : normal F E] : normal K E := begin intros x, cases h x with hx hhx, rw algebra_map_eq F K E at hhx, exact ⟨is_integral_of_is_scalar_tower x hx, polynomial.splits_of_splits_of_dvd (algebra_map K E) (polynomial.map_ne_zero (minpoly.ne_zero hx)) ((polynomial.splits_map_iff (algebra_map F K) (algebra_map K E)).mpr hhx) (minpoly.dvd_map_of_is_scalar_tower F K x)⟩, end variables {F} {E} {E' : Type*} [field E'] [algebra F E'] lemma normal.of_alg_equiv [h : normal F E] (f : E ≃ₐ[F] E') : normal F E' := begin intro x, cases h (f.symm x) with hx hhx, have H := is_integral_alg_hom f.to_alg_hom hx, rw [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_equiv.apply_symm_apply] at H, use H, apply polynomial.splits_of_splits_of_dvd (algebra_map F E') (minpoly.ne_zero hx), { rw ← alg_hom.comp_algebra_map f.to_alg_hom, exact polynomial.splits_comp_of_splits (algebra_map F E) f.to_alg_hom.to_ring_hom hhx }, { apply minpoly.dvd _ _, rw ← add_equiv.map_eq_zero_iff f.symm.to_add_equiv, exact eq.trans (polynomial.aeval_alg_hom_apply f.symm.to_alg_hom x (minpoly F (f.symm x))).symm (minpoly.aeval _ _) }, end lemma alg_equiv.transfer_normal (f : E ≃ₐ[F] E') : normal F E ↔ normal F E' := ⟨λ h, by exactI normal.of_alg_equiv f, λ h, by exactI normal.of_alg_equiv f.symm⟩ lemma normal.of_is_splitting_field {p : polynomial F} [hFEp : is_splitting_field F E p] : normal F E := begin by_cases hp : p = 0, { haveI : is_splitting_field F F p := by { rw hp, exact ⟨splits_zero _, subsingleton.elim _ _⟩ }, exactI (alg_equiv.transfer_normal ((is_splitting_field.alg_equiv F p).trans (is_splitting_field.alg_equiv E p).symm)).mp (normal_self F) }, intro x, haveI hFE : finite_dimensional F E := is_splitting_field.finite_dimensional E p, have Hx : is_integral F x := is_integral_of_noetherian hFE x, refine ⟨Hx, or.inr _⟩, rintros q q_irred ⟨r, hr⟩, let D := adjoin_root q, let pbED := adjoin_root.power_basis q_irred.ne_zero, haveI : finite_dimensional E D := power_basis.finite_dimensional pbED, have findimED : finite_dimensional.findim E D = q.nat_degree := power_basis.findim pbED, letI : algebra F D := ring_hom.to_algebra ((algebra_map E D).comp (algebra_map F E)), haveI : is_scalar_tower F E D := of_algebra_map_eq (λ _, rfl), haveI : finite_dimensional F D := finite_dimensional.trans F E D, suffices : nonempty (D →ₐ[F] E), { cases this with ϕ, rw [←with_bot.coe_one, degree_eq_iff_nat_degree_eq q_irred.ne_zero, ←findimED], have nat_lemma : ∀ a b c : ℕ, a * b = c → c ≤ a → 0 < c → b = 1, { intros a b c h1 h2 h3, nlinarith }, exact nat_lemma _ _ _ (finite_dimensional.findim_mul_findim F E D) (linear_map.findim_le_findim_of_injective (show function.injective ϕ.to_linear_map, from ϕ.to_ring_hom.injective)) finite_dimensional.findim_pos, }, let C := adjoin_root (minpoly F x), have Hx_irred := minpoly.irreducible Hx, letI : algebra C D := ring_hom.to_algebra (adjoin_root.lift (algebra_map F D) (adjoin_root.root q) (by rw [algebra_map_eq F E D, ←eval₂_map, hr, adjoin_root.algebra_map_eq, eval₂_mul, adjoin_root.eval₂_root, zero_mul])), letI : algebra C E := ring_hom.to_algebra (adjoin_root.lift (algebra_map F E) x (minpoly.aeval F x)), haveI : is_scalar_tower F C D := of_algebra_map_eq (λ x, adjoin_root.lift_of.symm), haveI : is_scalar_tower F C E := of_algebra_map_eq (λ x, adjoin_root.lift_of.symm), suffices : nonempty (D →ₐ[C] E), { exact nonempty.map (restrict_base F) this }, let S : set D := ((p.map (algebra_map F E)).roots.map (algebra_map E D)).to_finset, suffices : ⊤ ≤ intermediate_field.adjoin C S, { refine intermediate_field.alg_hom_mk_adjoin_splits' (top_le_iff.mp this) (λ y hy, _), rcases multiset.mem_map.mp (multiset.mem_to_finset.mp hy) with ⟨z, hz1, hz2⟩, have Hz : is_integral F z := is_integral_of_noetherian hFE z, use (show is_integral C y, from is_integral_of_noetherian (finite_dimensional.right F C D) y), apply splits_of_splits_of_dvd (algebra_map C E) (map_ne_zero (minpoly.ne_zero Hz)), { rw [splits_map_iff, ←algebra_map_eq F C E], exact splits_of_splits_of_dvd _ hp hFEp.splits (minpoly.dvd F z (eq.trans (eval₂_eq_eval_map _) ((mem_roots (map_ne_zero hp)).mp hz1))) }, { apply minpoly.dvd, rw [←hz2, aeval_def, eval₂_map, ←algebra_map_eq F C D, algebra_map_eq F E D, ←hom_eval₂, ←aeval_def, minpoly.aeval F z, ring_hom.map_zero] } }, rw [←intermediate_field.to_subalgebra_le_to_subalgebra, intermediate_field.top_to_subalgebra], apply ge_trans (intermediate_field.algebra_adjoin_le_adjoin C S), suffices : (algebra.adjoin C S).res F = (algebra.adjoin E {adjoin_root.root q}).res F, { rw [adjoin_root.adjoin_root_eq_top, subalgebra.res_top, ←@subalgebra.res_top F C] at this, exact top_le_iff.mpr (subalgebra.res_inj F this) }, dsimp only [S], rw [←finset.image_to_finset, finset.coe_image], apply eq.trans (algebra.adjoin_res_eq_adjoin_res F E C D hFEp.adjoin_roots adjoin_root.adjoin_root_eq_top), rw [set.image_singleton, ring_hom.algebra_map_to_algebra, adjoin_root.lift_root] end end normal_tower variables {F} {K} (ϕ ψ : K →ₐ[F] K) (χ ω : K ≃ₐ[F] K) (E : Type*) [field E] [algebra F E] [algebra E K] [is_scalar_tower F E K] /-- Restrict algebra homomorphism to image of normal subfield -/ def alg_hom.restrict_normal_aux [h : normal F E] : (to_alg_hom F E K).range →ₐ[F] (to_alg_hom F E K).range := { to_fun := λ x, ⟨ϕ x, by { suffices : (to_alg_hom F E K).range.map ϕ ≤ _, { exact this ⟨x, subtype.mem x, rfl⟩ }, rintros x ⟨y, ⟨z, -, hy⟩, hx⟩, rw [←hx, ←hy], exact minpoly.mem_range_of_degree_eq_one E _ (or.resolve_left (h z).2 (minpoly.ne_zero (h z).1) (minpoly.irreducible (is_integral_of_is_scalar_tower _ (is_integral_alg_hom ϕ (is_integral_alg_hom _ (h z).1)))) (minpoly.dvd E _ (by rw [aeval_map, aeval_alg_hom, aeval_alg_hom, alg_hom.comp_apply, alg_hom.comp_apply, minpoly.aeval, alg_hom.map_zero, alg_hom.map_zero]))) }⟩, map_zero' := subtype.ext ϕ.map_zero, map_one' := subtype.ext ϕ.map_one, map_add' := λ x y, subtype.ext (ϕ.map_add x y), map_mul' := λ x y, subtype.ext (ϕ.map_mul x y), commutes' := λ x, subtype.ext (ϕ.commutes x) } /-- Restrict algebra homomorphism to normal subfield -/ def alg_hom.restrict_normal [normal F E] : E →ₐ[F] E := ((alg_hom.alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).symm.to_alg_hom.comp (ϕ.restrict_normal_aux E)).comp (alg_hom.alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).to_alg_hom lemma alg_hom.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K (ϕ.restrict_normal E x) = ϕ (algebra_map E K x) := subtype.ext_iff.mp (alg_equiv.apply_symm_apply (alg_hom.alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)) (ϕ.restrict_normal_aux E ⟨is_scalar_tower.to_alg_hom F E K x, ⟨x, ⟨subsemiring.mem_top x, rfl⟩⟩⟩)) lemma alg_hom.restrict_normal_comp [normal F E] : (ϕ.restrict_normal E).comp (ψ.restrict_normal E) = (ϕ.comp ψ).restrict_normal E := alg_hom.ext (λ _, (algebra_map E K).injective (by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes])) /-- Restrict algebra isomorphism to a normal subfield -/ def alg_equiv.restrict_normal [h : normal F E] : E ≃ₐ[F] E := alg_equiv.of_alg_hom (χ.to_alg_hom.restrict_normal E) (χ.symm.to_alg_hom.restrict_normal E) (alg_hom.ext $ λ _, (algebra_map E K).injective (by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes, alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_hom.id_apply, χ.apply_symm_apply])) (alg_hom.ext $ λ _, (algebra_map E K).injective (by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes, alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_hom.id_apply, χ.symm_apply_apply])) lemma alg_equiv.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K (χ.restrict_normal E x) = χ (algebra_map E K x) := χ.to_alg_hom.restrict_normal_commutes E x lemma alg_equiv.restrict_normal_trans [normal F E] : (χ.trans ω).restrict_normal E = (χ.restrict_normal E).trans (ω.restrict_normal E) := alg_equiv.ext (λ _, (algebra_map E K).injective (by simp only [alg_equiv.trans_apply, alg_equiv.restrict_normal_commutes])) /-- Restriction to an normal subfield as a group homomorphism -/ def alg_equiv.restrict_normal_hom [normal F E] : (K ≃ₐ[F] K) →* (E ≃ₐ[F] E) := monoid_hom.mk' (λ χ, χ.restrict_normal E) (λ ω χ, (χ.restrict_normal_trans ω E))
2d696f0ca1a23b91f25217e7f43a401fdf6fb74b
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/nat/cast.lean
d157ec81e821526744f3fb72f6490900d380750b
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,917
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import algebra.ordered_field import data.nat.basic 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 /-- Coercions such as `nat.cast_coe` that go from a concrete structure such as `ℕ` to an arbitrary ring `α` should be set up as follows: ```lean @[priority 900] instance : has_coe_t ℕ α := ⟨...⟩ ``` It needs to be `has_coe_t` instead of `has_coe` because otherwise type-class inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`. The reduced priority is necessary so that it doesn't conflict with instances such as `has_coe_t α (option α)`. For this to work, we reduce the priority of the `coe_base` and `coe_trans` instances because we want the instances for `has_coe_t` to be tried in the following order: 1. `has_coe_t` instances declared in mathlib (such as `has_coe_t α (with_top α)`, etc.) 2. `coe_base`, which contains instances such as `has_coe (fin n) n` 3. `nat.cast_coe : has_coe_t ℕ α` etc. 4. `coe_trans` If `coe_trans` is tried first, then `nat.cast_coe` doesn't get a chance to apply. -/ library_note "coercion into rings" attribute [instance, priority 950] coe_base attribute [instance, priority 500] coe_trans -- see note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℕ α := ⟨nat.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp, norm_cast, priority 500] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl @[simp, norm_cast] theorem cast_ite (P : Prop) [decidable P] (m n : ℕ) : (((ite P m n) : ℕ) : α) = ite P (m : α) (n : α) := by { split_ifs; refl, } end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp, norm_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] /-- `coe : ℕ → α` as an `add_monoid_hom`. -/ def cast_add_monoid_hom (α : Type*) [add_monoid α] [has_one α] : ℕ →+ α := { to_fun := coe, map_add' := cast_add, map_zero' := cast_zero } @[simp] lemma coe_cast_add_monoid_hom [add_monoid α] [has_one α] : (cast_add_monoid_hom α : ℕ → α) = coe := rfl @[simp, norm_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp, norm_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, norm_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, norm_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, norm_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] @[simp] theorem cast_dvd {α : Type*} [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 nat.mul_div_cancel_left _ (nat.pos_iff_ne_zero.2 this), rw [nat.cast_mul, mul_div_cancel_left _ n_nonzero], end /-- `coe : ℕ → α` as a `ring_hom` -/ def cast_ring_hom (α : Type*) [semiring α] : ℕ →+* α := { to_fun := coe, map_one' := cast_one, map_mul' := cast_mul, .. cast_add_monoid_hom α } @[simp] lemma coe_cast_ring_hom [semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl lemma cast_commute [semiring α] (n : ℕ) (x : α) : commute ↑n x := nat.rec_on n (commute.zero_left x) $ λ n ihn, ihn.add_left $ commute.one_left x lemma commute_cast [semiring α] (x : α) (n : ℕ) : commute x n := (n.cast_commute x).symm @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one theorem strict_mono_cast [linear_ordered_semiring α] : strict_mono (coe : ℕ → α) := λ m n h, nat.le_induction (lt_add_of_pos_right _ zero_lt_one) (λ n _ h, lt_add_of_lt_of_pos h zero_lt_one) _ h @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : ℕ} : (m : α) ≤ n ↔ m ≤ n := strict_mono_cast.le_iff_le @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := strict_mono_cast.lt_iff_lt @[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 @[simp, norm_cast] theorem one_lt_cast [linear_ordered_semiring α] {n : ℕ} : 1 < (n : α) ↔ 1 < n := by rw [← cast_one, cast_lt] @[simp, norm_cast] theorem one_le_cast [linear_ordered_semiring α] {n : ℕ} : 1 ≤ (n : α) ↔ 1 ≤ n := by rw [← cast_one, cast_le] @[simp, norm_cast] theorem cast_lt_one [linear_ordered_semiring α] {n : ℕ} : (n : α) < 1 ↔ n = 0 := by rw [← cast_one, cast_lt, lt_succ_iff, le_zero_iff] @[simp, norm_cast] theorem cast_le_one [linear_ordered_semiring α] {n : ℕ} : (n : α) ≤ 1 ↔ n ≤ 1 := by rw [← cast_one, cast_le] @[simp, norm_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, norm_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, norm_cast] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) lemma coe_nat_dvd [comm_semiring α] {m n : ℕ} (h : m ∣ n) : (m : α) ∣ (n : α) := ring_hom.map_dvd (nat.cast_ring_hom α) h alias coe_nat_dvd ← has_dvd.dvd.nat_cast section linear_ordered_field variables [linear_ordered_field α] lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ := inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) := by { rw one_div, exact inv_pos_of_nat } lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) := by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa } lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) := by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa } end linear_ordered_field end nat namespace add_monoid_hom variables {A B : Type*} [add_monoid A] @[ext] lemma ext_nat {f g : ℕ →+ A} (h : f 1 = g 1) : f = g := ext $ λ n, nat.rec_on n (f.map_zero.trans g.map_zero.symm) $ λ n ihn, by simp only [nat.succ_eq_add_one, *, map_add] variables [has_one A] [add_monoid B] [has_one B] lemma eq_nat_cast (f : ℕ →+ A) (h1 : f 1 = 1) : ∀ n : ℕ, f n = n := congr_fun $ show f = nat.cast_add_monoid_hom A, from ext_nat (h1.trans nat.cast_one.symm) lemma map_nat_cast (f : A →+ B) (h1 : f 1 = 1) (n : ℕ) : f n = n := (f.comp (nat.cast_add_monoid_hom A)).eq_nat_cast (by simp [h1]) _ end add_monoid_hom namespace ring_hom variables {R : Type*} {S : Type*} [semiring R] [semiring S] @[simp] lemma eq_nat_cast (f : ℕ →+* R) (n : ℕ) : f n = n := f.to_add_monoid_hom.eq_nat_cast f.map_one n @[simp] lemma map_nat_cast (f : R →+* S) (n : ℕ) : f n = n := (f.comp (nat.cast_ring_hom R)).eq_nat_cast n lemma ext_nat (f g : ℕ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_nat $ f.map_one.trans g.map_one.symm end ring_hom @[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n := ((ring_hom.id ℕ).eq_nat_cast n).symm @[simp] theorem nat.cast_with_bot : ∀ (n : ℕ), @coe ℕ (with_bot ℕ) (@coe_to_lift _ _ nat.cast_coe) n = n | 0 := rfl | (n+1) := by rw [with_bot.coe_add, nat.cast_add, nat.cast_with_bot n]; refl instance nat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℕ →+* R) := ⟨ring_hom.ext_nat⟩ namespace with_top variables {α : Type*} variables [has_zero α] [has_one α] [has_add α] @[simp, norm_cast] lemma coe_nat : ∀(n : nat), ((n : α) : with_top α) = n | 0 := rfl | (n+1) := by { push_cast, rw [coe_nat n] } @[simp] lemma nat_ne_top (n : nat) : (n : with_top α) ≠ ⊤ := by { rw [←coe_nat n], apply coe_ne_top } @[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n := by { rw [←coe_nat n], apply top_ne_coe } lemma add_one_le_of_lt {i n : with_top ℕ} (h : i < n) : i + 1 ≤ n := begin cases n, { exact le_top }, cases i, { exact (not_le_of_lt h le_top).elim }, exact with_top.coe_le_coe.2 (with_top.coe_lt_coe.1 h) end @[elab_as_eliminator] lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ) (h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a := begin have A : ∀n:ℕ, P n := λ n, nat.rec_on n h0 hsuc, cases a, { exact htop A }, { exact A a } end end with_top
9b2b6b9714b9d639d8fc0fe4d3be0091cc71ae3f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/atomic_notation.lean
2bd49db6ff6fe810dea1741331149f9ff172831c
[ "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
113
lean
import logic data.num open num constant f : num → num notation `o`:1 := (10:num) check o + 1 check f o + o + o
ddd63d5d6e94577d78123a60fd5de71e6276b0cd
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/whiskering.lean
0a8f1f8d86079a101ec8567094ca7f631a4d8b8d
[ "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
7,063
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.natural_isomorphism namespace category_theory universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄ section variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] /-- If `α : G ⟶ H` then `whisker_left F α : (F ⋙ G) ⟶ (F ⋙ H)` has components `α.app (F.obj X)`. -/ @[simps] def whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) : (F ⋙ G) ⟶ (F ⋙ H) := { app := λ X, α.app (F.obj X), naturality' := λ X Y f, by rw [functor.comp_map, functor.comp_map, α.naturality] } /-- If `α : G ⟶ H` then `whisker_right α F : (G ⋙ F) ⟶ (G ⋙ F)` has components `F.map (α.app X)`. -/ @[simps] def whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : (G ⋙ F) ⟶ (H ⋙ F) := { app := λ X, F.map (α.app X), naturality' := λ X Y f, by rw [functor.comp_map, functor.comp_map, ←F.map_comp, ←F.map_comp, α.naturality] } variables (C D E) /-- Left-composition gives a functor `(C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E))`. `(whiskering_lift.obj F).obj G` is `F ⋙ G`, and `(whiskering_lift.obj F).map α` is `whisker_left F α`. -/ @[simps] def whiskering_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) := { obj := λ F, { obj := λ G, F ⋙ G, map := λ G H α, whisker_left F α }, map := λ F G τ, { app := λ H, { app := λ c, H.map (τ.app c), naturality' := λ X Y f, begin dsimp, rw [←H.map_comp, ←H.map_comp, ←τ.naturality] end }, naturality' := λ X Y f, begin ext, dsimp, rw [f.naturality] end } } /-- Right-composition gives a functor `(D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E))`. `(whiskering_right.obj H).obj F` is `F ⋙ H`, and `(whiskering_right.obj H).map α` is `whisker_right α H`. -/ @[simps] def whiskering_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) := { obj := λ H, { obj := λ F, F ⋙ H, map := λ _ _ α, whisker_right α H }, map := λ G H τ, { app := λ F, { app := λ c, τ.app (F.obj c), naturality' := λ X Y f, begin dsimp, rw [τ.naturality] end }, naturality' := λ X Y f, begin ext, dsimp, rw [←nat_trans.naturality] end } } variables {C} {D} {E} @[simp] lemma whisker_left_id (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (nat_trans.id G) = nat_trans.id (F.comp G) := rfl @[simp] lemma whisker_left_id' (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (𝟙 G) = 𝟙 (F.comp G) := rfl @[simp] lemma whisker_right_id {G : C ⥤ D} (F : D ⥤ E) : whisker_right (nat_trans.id G) F = nat_trans.id (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_right_id' {G : C ⥤ D} (F : D ⥤ E) : whisker_right (𝟙 G) F = 𝟙 (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_left_comp (F : C ⥤ D) {G H K : D ⥤ E} (α : G ⟶ H) (β : H ⟶ K) : whisker_left F (α ≫ β) = (whisker_left F α) ≫ (whisker_left F β) := rfl @[simp] lemma whisker_right_comp {G H K : C ⥤ D} (α : G ⟶ H) (β : H ⟶ K) (F : D ⥤ E) : whisker_right (α ≫ β) F = (whisker_right α F) ≫ (whisker_right β F) := ((whiskering_right C D E).obj F).map_comp α β /-- If `α : G ≅ H` is a natural isomorphism then `iso_whisker_left F α : (F ⋙ G) ≅ (F ⋙ H)` has components `α.app (F.obj X)`. -/ def iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (F ⋙ G) ≅ (F ⋙ H) := ((whiskering_left C D E).obj F).map_iso α @[simp] lemma iso_whisker_left_hom (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (iso_whisker_left F α).hom = whisker_left F α.hom := rfl @[simp] lemma iso_whisker_left_inv (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (iso_whisker_left F α).inv = whisker_left F α.inv := rfl /-- If `α : G ≅ H` then `iso_whisker_right α F : (G ⋙ F) ≅ (G ⋙ F)` has components `F.map_iso (α.app X)`. -/ def iso_whisker_right {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (G ⋙ F) ≅ (H ⋙ F) := ((whiskering_right C D E).obj F).map_iso α @[simp] lemma iso_whisker_right_hom {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (iso_whisker_right α F).hom = whisker_right α.hom F := rfl @[simp] lemma iso_whisker_right_inv {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (iso_whisker_right α F).inv = whisker_right α.inv F := rfl instance is_iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) [is_iso α] : is_iso (whisker_left F α) := { .. iso_whisker_left F (as_iso α) } instance is_iso_whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) [is_iso α] : is_iso (whisker_right α F) := { .. iso_whisker_right (as_iso α) F } variables {B : Type u₄} [category.{v₄} B] local attribute [elab_simple] whisker_left whisker_right @[simp] lemma whisker_left_twice (F : B ⥤ C) (G : C ⥤ D) {H K : D ⥤ E} (α : H ⟶ K) : whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α := rfl @[simp] lemma whisker_right_twice {H K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟶ K) : whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) := rfl lemma whisker_right_left (F : B ⥤ C) {G H : C ⥤ D} (α : G ⟶ H) (K : D ⥤ E) : whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) := rfl end namespace functor universes u₅ v₅ variables {A : Type u₁} [category.{v₁} A] variables {B : Type u₂} [category.{v₂} B] /-- The left unitor, a natural isomorphism `((𝟭 _) ⋙ F) ≅ F`. -/ @[simps] def left_unitor (F : A ⥤ B) : ((𝟭 A) ⋙ F) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } /-- The right unitor, a natural isomorphism `(F ⋙ (𝟭 B)) ≅ F`. -/ @[simps] def right_unitor (F : A ⥤ B) : (F ⋙ (𝟭 B)) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } variables {C : Type u₃} [category.{v₃} C] variables {D : Type u₄} [category.{v₄} D] /-- The associator for functors, a natural isomorphism `((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H))`. (In fact, `iso.refl _` will work here, but it tends to make Lean slow later, and it's usually best to insert explicit associators.) -/ @[simps] def associator (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) : ((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H)) := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } } lemma triangle (F : A ⥤ B) (G : B ⥤ C) : (associator F (𝟭 B) G).hom ≫ (whisker_left F (left_unitor G).hom) = (whisker_right (right_unitor F).hom G) := by { ext, dsimp, simp } -- See note [dsimp, simp]. variables {E : Type u₅} [category.{v₅} E] variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E) lemma pentagon : (whisker_right (associator F G H).hom K) ≫ (associator F (G ⋙ H) K).hom ≫ (whisker_left F (associator G H K).hom) = ((associator (F ⋙ G) H K).hom ≫ (associator F G (H ⋙ K)).hom) := by { ext, dsimp, simp } end functor end category_theory
b156c769ff910ce60c860dd5f13261f6c8f92e48
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Util/MainM.lean
40c56d6e31c5d6f86025ebaf8bade33a43da6189
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,469
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Util.Log import Lake.Util.Exit import Lake.Util.Error import Lake.Util.Lift namespace Lake /-- The monad in Lake for `main`-like functions. Supports IO, logging, and `exit`. -/ def MainM := EIO ExitCode instance : Monad MainM := inferInstanceAs (Monad (EIO ExitCode)) instance : MonadFinally MainM := inferInstanceAs (MonadFinally (EIO ExitCode)) instance : MonadLift BaseIO MainM := inferInstanceAs (MonadLift BaseIO (EIO ExitCode)) namespace MainM /-! # Basics -/ @[inline] protected def mk (x : EIO ExitCode α) : MainM α := x @[inline] protected def toEIO (self : MainM α) : EIO ExitCode α := self @[inline] protected def toBaseIO (self : MainM α) : BaseIO (Except ExitCode α) := self.toEIO.toBaseIO protected def run (self : MainM α) : BaseIO ExitCode := self.toBaseIO.map fun | Except.ok _ => 0 | Except.error rc => rc /-! # Exits -/ /-- Exit with given return code. -/ protected def exit (rc : ExitCode) : MainM α := MainM.mk <| throw rc instance : MonadExit MainM := ⟨MainM.exit⟩ /-- Try this and catch exits. -/ protected def tryCatchExit (f : ExitCode → MainM α) (self : MainM α) : MainM α := self.toEIO.tryCatch f /-- Try this and catch error codes (i.e., non-zero exits). -/ protected def tryCatchError (f : ExitCode → MainM α) (self : MainM α) : MainM α := self.tryCatchExit fun rc => if rc = 0 then exit 0 else f rc /-- Exit with a generic error code (i.e., 1). -/ protected def failure : MainM α := exit 1 /-- If this exits with an error code (i.e., not 0), perform other. -/ protected def orElse (self : MainM α) (other : Unit → MainM α) : MainM α := self.tryCatchExit fun rc => if rc = 0 then exit 0 else other () instance : Alternative MainM where failure := MainM.failure orElse := MainM.orElse /-! # Logging and IO -/ instance : MonadLog MainM := MonadLog.eio /-- Print out a error line with the given message and then exit with an error code. -/ protected def error (msg : String) (rc : ExitCode := 1) : MainM α := do logError msg exit rc instance : MonadError MainM := ⟨MainM.error⟩ instance : MonadLift IO MainM := ⟨MonadError.runEIO⟩ def runLogIO (x : LogIO α) (verbosity := Verbosity.normal) : MainM α := liftM <| x.run <| MonadLog.eio verbosity instance : MonadLift LogIO MainM := ⟨runLogIO⟩
c29a0c83a77f0af23113d6ac589d3cee7502b5b2
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/AbstractNestedProofs.lean
70bf6602b1653895c61ede65c206d7c129700715
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
2,957
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Closure namespace Lean.Meta namespace AbstractNestedProofs def isNonTrivialProof (e : Expr) : MetaM Bool := do if !(← isProof e) then pure false else e.withApp fun f args => pure $ !f.isAtomic || args.any fun arg => !arg.isAtomic structure Context where baseName : Name structure State where nextIdx : Nat := 1 abbrev M := ReaderT Context $ MonadCacheT ExprStructEq Expr $ StateRefT State MetaM private def mkAuxLemma (e : Expr) : M Expr := do let ctx ← read let s ← get let lemmaName ← mkAuxName (ctx.baseName ++ `proof) s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1 } /- We turn on zeta-expansion to make sure we don't need to perform an expensive `check` step to identify which let-decls can be abstracted. If we design a more efficient test, we can avoid the eager zeta expasion step. It a benchmark created by @selsam, The extra `check` step was a bottleneck. -/ mkAuxDefinitionFor lemmaName e (zeta := true) partial def visit (e : Expr) : M Expr := do if e.isAtomic then pure e else let visitBinders (xs : Array Expr) (k : M Expr) : M Expr := do let localInstances ← getLocalInstances let mut lctx ← getLCtx for x in xs do let xFVarId := x.fvarId! let localDecl ← xFVarId.getDecl let type ← visit localDecl.type let localDecl := localDecl.setType type let localDecl ← match localDecl.value? with | some value => let value ← visit value; pure <| localDecl.setValue value | none => pure localDecl lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl withLCtx lctx localInstances k checkCache { val := e : ExprStructEq } fun _ => do if (← isNonTrivialProof e) then mkAuxLemma e else match e with | .lam .. => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b) (usedLetOnly := false) | .letE .. => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b) (usedLetOnly := false) | .forallE .. => forallTelescope e fun xs b => visitBinders xs do mkForallFVars xs (← visit b) | .mdata _ b => return e.updateMData! (← visit b) | .proj _ _ b => return e.updateProj! (← visit b) | .app .. => e.withApp fun f args => return mkAppN f (← args.mapM visit) | _ => pure e end AbstractNestedProofs /-- Replace proofs nested in `e` with new lemmas. The new lemmas have names of the form `mainDeclName.proof_<idx>` -/ def abstractNestedProofs (mainDeclName : Name) (e : Expr) : MetaM Expr := AbstractNestedProofs.visit e |>.run { baseName := mainDeclName } |>.run |>.run' { nextIdx := 1 } end Lean.Meta
69ebef1161fffc94b47acc5b6d423f22febf89ca
618003631150032a5676f229d13a079ac875ff77
/src/data/complex/module.lean
51e43ad4a86924a49bd22abc19fba3aee690a46c
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
843
lean
/- Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Sébastien Gouëzel -/ import data.complex.basic import ring_theory.algebra /-! This file contains two instance, the fact the ℂ is an ℝ algebra, and an instance to view any complex vector space as a real vector space -/ noncomputable theory namespace complex instance algebra_over_reals : algebra ℝ ℂ := (ring_hom.of coe).to_algebra end complex /- Register as an instance (with low priority) the fact that a complex vector space is also a real vector space. -/ instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E := module.restrict_scalars' ℝ ℂ E attribute [instance, priority 900] module.complex_to_real
0f707979336faa279af645129d481cb57a538bac
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.18.lean
d247026a222de5f38cbacd6f7ae45022b27c9e31
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
205
lean
import standard -- pr2 is semireducible definition pr2 (A : Type) (a b : A) : A := b -- mark pr2 as reducible attribute pr2 [reducible] -- ... -- make it semireducible again attribute pr2 [semireducible]
27f357577044df2b5838d6c02bbb8aa3b5dab93e
0d4c30038160d9c35586ce4dace36fe26a35023b
/src/category_theory/limits/shapes/kernels.lean
5dd8fc630312c5e17f1f622aa36013b53732a103
[ "Apache-2.0" ]
permissive
b-mehta/mathlib
b0c8ec929ec638447e4262f7071570d23db52e14
ce72cde867feabe5bb908cf9e895acc0e11bf1eb
refs/heads/master
1,599,457,264,781
1,586,969,260,000
1,586,969,260,000
220,672,634
0
0
Apache-2.0
1,583,944,480,000
1,573,317,991,000
Lean
UTF-8
Lean
false
false
11,409
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.zero import category_theory.limits.shapes.equalizers /-! # Kernels and cokernels In a category with zero morphisms, the kernel of a morphism `f : X ⟶ Y` is just the equalizer of `f` and `0 : X ⟶ Y`. (Similarly the cokernel is the coequalizer.) We don't yet prove much here, just provide * `kernel : (X ⟶ Y) → C` * `kernel.ι : kernel f ⟶ X` * `kernel.condition : kernel.ι f ≫ f = 0` and * `kernel.lift (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f` (as well as the dual versions) ## Main statements Besides the definition and lifts, * `kernel.ι_zero_is_iso`: a kernel map of a zero morphism is an isomorphism * `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero obect is a kernel map of any monomorphism ## Future work * TODO: images and coimages, and then abelian categories. * TODO: connect this with existing working in the group theory and ring theory libraries. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ universes v u open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables {X Y : C} (f : X ⟶ Y) section variables [has_zero_morphisms.{v} C] /-- A kernel fork is just a fork where the second morphism is a zero morphism. -/ abbreviation kernel_fork := fork f 0 variables {f} @[simp, reassoc] lemma kernel_fork.condition (s : kernel_fork f) : fork.ι s ≫ f = 0 := by erw [fork.condition, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.app_one (s : kernel_fork f) : s.π.app one = 0 := by rw [←fork.app_zero_left, kernel_fork.condition] /-- A morphism `ι` satisfying `ι ≫ f = 0` determines a kernel fork over `f`. -/ abbreviation kernel_fork.of_ι {Z : C} (ι : Z ⟶ X) (w : ι ≫ f = 0) : kernel_fork f := fork.of_ι ι $ by rw [w, has_zero_morphisms.comp_zero] /-- If `s` is a limit kernel fork and `k : W ⟶ X` satisfies ``k ≫ f = 0`, then there is some `l : W ⟶ s.X` sich that `l ≫ fork.ι s = k`. -/ def kernel_fork.is_limit.lift' {s : kernel_fork f} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ kernel_fork.of_ι _ h, hs.fac _ _⟩ end section variables [has_zero_morphisms.{v} C] [has_limit (parallel_pair f 0)] /-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/ abbreviation kernel : C := equalizer f 0 /-- The map from `kernel f` into the source of `f`. -/ abbreviation kernel.ι : kernel f ⟶ X := equalizer.ι f 0 @[simp, reassoc] lemma kernel.condition : kernel.ι f ≫ f = 0 := kernel_fork.condition _ /-- Given any morphism `k : W ⟶ X` satisfying `k ≫ f = 0`, `k` factors through `kernel.ι f` via `kernel.lift : W ⟶ kernel f`. -/ abbreviation kernel.lift {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f := limit.lift (parallel_pair f 0) (kernel_fork.of_ι k h) @[simp, reassoc] lemma kernel.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : kernel.lift f k h ≫ kernel.ι f = k := limit.lift_π _ _ /-- Any morphism `k : W ⟶ X` satisfying `k ≫ f = 0` induces a morphism `l : W ⟶ kernel f` such that `l ≫ kernel.ι f = k`. -/ def kernel.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ kernel f // l ≫ kernel.ι f = k} := ⟨kernel.lift f k h, kernel.lift_ι _ _ _⟩ /-- Every kernel of the zero morphism is an isomorphism -/ def kernel.ι_zero_is_iso [has_limit (parallel_pair (0 : X ⟶ Y) 0)] : is_iso (kernel.ι (0 : X ⟶ Y)) := limit_cone_parallel_pair_self_is_iso _ _ (limit.is_limit _) end section has_zero_object variables [has_zero_object.{v} C] local attribute [instance] has_zero_object.has_zero variables [has_zero_morphisms.{v} C] /-- The morphism from the zero object determines a cone on a kernel diagram -/ def kernel.zero_cone : cone (parallel_pair f 0) := { X := 0, π := { app := λ j, 0 }} /-- The map from the zero object is a kernel of a monomorphism -/ def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_cone f) := fork.is_limit.mk _ (λ s, 0) (λ s, by { erw has_zero_morphisms.zero_comp, convert (@zero_of_comp_mono _ _ _ _ _ _ _ f _ _).symm, exact kernel_fork.condition _ }) (λ _ _ _, has_zero_object.zero_of_to_zero _) /-- The kernel of a monomorphism is isomorphic to the zero object -/ def kernel.of_mono [has_limit (parallel_pair f 0)] [mono f] : kernel f ≅ 0 := functor.map_iso (cones.forget _) $ is_limit.unique_up_to_iso (limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f) /-- The kernel morphism of a monomorphism is a zero morphism -/ lemma kernel.ι_of_mono [has_limit (parallel_pair f 0)] [mono f] : kernel.ι f = 0 := by rw [←category.id_comp (kernel.ι f), ←iso.hom_inv_id (kernel.of_mono f), category.assoc, has_zero_object.zero_of_to_zero (kernel.of_mono f).hom, has_zero_morphisms.zero_comp] end has_zero_object section variables (X) (Y) [has_zero_morphisms.{v} C] /-- The kernel morphism of a zero morphism is an isomorphism -/ def kernel.ι_of_zero [has_limit (parallel_pair (0 : X ⟶ Y) 0)] : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ end section variables [has_zero_morphisms.{v} C] /-- A cokernel cofork is just a cofork where the second morphism is a zero morphism. -/ abbreviation cokernel_cofork := cofork f 0 variables {f} @[simp, reassoc] lemma cokernel_cofork.condition (s : cokernel_cofork f) : f ≫ cofork.π s = 0 := by rw [cofork.condition, has_zero_morphisms.zero_comp] @[simp] lemma cokernel_cofork.app_zero (s : cokernel_cofork f) : s.ι.app zero = 0 := by rw [←cofork.left_app_one, cokernel_cofork.condition] /-- A morphism `π` satisfying `f ≫ π = 0` determines a cokernel cofork on `f`. -/ abbreviation cokernel_cofork.of_π {Z : C} (π : Y ⟶ Z) (w : f ≫ π = 0) : cokernel_cofork f := cofork.of_π π $ by rw [w, has_zero_morphisms.zero_comp] /-- If `s` is a colimit cokernel cofork, then every `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cokernel_cofork.is_limit.desc' {s : cokernel_cofork f} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cokernel_cofork.of_π _ h, hs.fac _ _⟩ end section variables [has_zero_morphisms.{v} C] [has_colimit (parallel_pair f 0)] /-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/ abbreviation cokernel : C := coequalizer f 0 /-- The map from the target of `f` to `cokernel f`. -/ abbreviation cokernel.π : Y ⟶ cokernel f := coequalizer.π f 0 @[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.π f = 0 := cokernel_cofork.condition _ /-- Given any morphism `k : Y ⟶ W` such that `f ≫ k = 0`, `k` factors through `cokernel.π f` via `cokernel.desc : cokernel f ⟶ W`. -/ abbreviation cokernel.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel f ⟶ W := colimit.desc (parallel_pair f 0) (cokernel_cofork.of_π k h) @[simp, reassoc] lemma cokernel.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel.π f ≫ cokernel.desc f k h = k := colimit.ι_desc _ _ /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : cokernel f ⟶ W` such that `cokernel.π f ≫ l = k`. -/ def cokernel.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : cokernel f ⟶ W // cokernel.π f ≫ l = k} := ⟨cokernel.desc f k h, cokernel.π_desc _ _ _⟩ end section has_zero_object variables [has_zero_object.{v} C] local attribute [instance] has_zero_object.has_zero variable [has_zero_morphisms.{v} C] /-- The morphism to the zero object determines a cocone on a cokernel diagram -/ def cokernel.zero_cocone : cocone (parallel_pair f 0) := { X := 0, ι := { app := λ j, 0 } } /-- The morphism to the zero object is a cokernel of an epimorphism -/ def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cocone f) := cofork.is_colimit.mk _ (λ s, 0) (λ s, by { erw has_zero_morphisms.zero_comp, convert (@zero_of_comp_epi _ _ _ _ _ _ f _ _ _).symm, exact cokernel_cofork.condition _ }) (λ _ _ _, has_zero_object.zero_of_from_zero _) /-- The cokernel of an epimorphism is isomorphic to the zero object -/ def cokernel.of_epi [has_colimit (parallel_pair f 0)] [epi f] : cokernel f ≅ 0 := functor.map_iso (cocones.forget _) $ is_colimit.unique_up_to_iso (colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f) /-- The cokernel morphism if an epimorphism is a zero morphism -/ lemma cokernel.π_of_epi [has_colimit (parallel_pair f 0)] [epi f] : cokernel.π f = 0 := by rw [←category.comp_id (cokernel.π f), ←iso.hom_inv_id (cokernel.of_epi f), ←category.assoc, has_zero_object.zero_of_from_zero (cokernel.of_epi f).inv, has_zero_morphisms.comp_zero] end has_zero_object section variables (X) (Y) [has_zero_morphisms.{v} C] /-- The cokernel of a zero morphism is an isomorphism -/ def cokernel.π_of_zero [has_colimit (parallel_pair (0 : X ⟶ Y) 0)] : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ end section has_zero_object variables [has_zero_object.{v} C] local attribute [instance] has_zero_object.has_zero variables [has_zero_morphisms.{v} C] /-- The kernel of the cokernel of an epimorphism is an isomorphism -/ instance kernel.of_cokernel_of_epi [has_colimit (parallel_pair f 0)] [has_limit (parallel_pair (cokernel.π f) 0)] [epi f] : is_iso (kernel.ι (cokernel.π f)) := equalizer.ι_of_self' _ _ $ cokernel.π_of_epi f /-- The cokernel of the kernel of a monomorphism is an isomorphism -/ instance cokernel.of_kernel_of_mono [has_limit (parallel_pair f 0)] [has_colimit (parallel_pair (kernel.ι f) 0)] [mono f] : is_iso (cokernel.π (kernel.ι f)) := coequalizer.π_of_self' _ _ $ kernel.ι_of_mono f end has_zero_object end category_theory.limits namespace category_theory.limits variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 variables [has_zero_morphisms.{v} C] /-- `has_kernels` represents a choice of kernel for every morphism -/ class has_kernels := (has_limit : Π {X Y : C} (f : X ⟶ Y), has_limit (parallel_pair f 0)) /-- `has_cokernels` represents a choice of cokernel for every morphism -/ class has_cokernels := (has_colimit : Π {X Y : C} (f : X ⟶ Y), has_colimit (parallel_pair f 0)) attribute [instance] has_kernels.has_limit has_cokernels.has_colimit /-- Kernels are finite limits, so if `C` has all finite limits, it also has all kernels -/ def has_kernels_of_has_finite_limits [has_finite_limits.{v} C] : has_kernels.{v} C := { has_limit := infer_instance } /-- Cokernels are finite limits, so if `C` has all finite colimits, it also has all cokernels -/ def has_cokernels_of_has_finite_colimits [has_finite_colimits.{v} C] : has_cokernels.{v} C := { has_colimit := infer_instance } end category_theory.limits