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
13eacf6b1ec08433c647a818df5e0d787b72f780
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/complete_boolean_algebra_auto.lean
078a6348af36bffdb83902ff1c3ff3ef9050c8da
[]
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,150
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Theory of complete Boolean algebras. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.complete_lattice import Mathlib.PostPort universes u_1 l u w namespace Mathlib /-- A complete distributive lattice is a bit stronger than the name might suggest; perhaps completely distributive lattice is more descriptive, as this class includes a requirement that the lattice join distribute over *arbitrary* infima, and similarly for the dual. -/ class complete_distrib_lattice (α : Type u_1) extends complete_lattice α where infi_sup_le_sup_Inf : ∀ (a : α) (s : set α), (infi fun (b : α) => infi fun (H : b ∈ s) => a ⊔ b) ≤ a ⊔ Inf s inf_Sup_le_supr_inf : ∀ (a : α) (s : set α), a ⊓ Sup s ≤ supr fun (b : α) => supr fun (H : b ∈ s) => a ⊓ b theorem sup_Inf_eq {α : Type u} [complete_distrib_lattice α] {a : α} {s : set α} : a ⊔ Inf s = infi fun (b : α) => infi fun (H : b ∈ s) => a ⊔ b := le_antisymm (le_infi fun (i : α) => le_infi fun (h : i ∈ s) => sup_le_sup_left (Inf_le h) a) (complete_distrib_lattice.infi_sup_le_sup_Inf a s) theorem Inf_sup_eq {α : Type u} [complete_distrib_lattice α] {b : α} {s : set α} : Inf s ⊔ b = infi fun (a : α) => infi fun (H : a ∈ s) => a ⊔ b := sorry theorem inf_Sup_eq {α : Type u} [complete_distrib_lattice α] {a : α} {s : set α} : a ⊓ Sup s = supr fun (b : α) => supr fun (H : b ∈ s) => a ⊓ b := le_antisymm (complete_distrib_lattice.inf_Sup_le_supr_inf a s) (supr_le fun (i : α) => supr_le fun (h : i ∈ s) => inf_le_inf_left a (le_Sup h)) theorem Sup_inf_eq {α : Type u} [complete_distrib_lattice α] {b : α} {s : set α} : Sup s ⊓ b = supr fun (a : α) => supr fun (H : a ∈ s) => a ⊓ b := sorry theorem Inf_sup_Inf {α : Type u} [complete_distrib_lattice α] {s : set α} {t : set α} : Inf s ⊔ Inf t = infi fun (p : α × α) => infi fun (H : p ∈ set.prod s t) => prod.fst p ⊔ prod.snd p := sorry theorem Sup_inf_Sup {α : Type u} [complete_distrib_lattice α] {s : set α} {t : set α} : Sup s ⊓ Sup t = supr fun (p : α × α) => supr fun (H : p ∈ set.prod s t) => prod.fst p ⊓ prod.snd p := sorry protected instance complete_distrib_lattice.bounded_distrib_lattice {α : Type u} [d : complete_distrib_lattice α] : bounded_distrib_lattice α := bounded_distrib_lattice.mk complete_distrib_lattice.sup complete_distrib_lattice.le complete_distrib_lattice.lt complete_distrib_lattice.le_refl complete_distrib_lattice.le_trans complete_distrib_lattice.le_antisymm complete_distrib_lattice.le_sup_left complete_distrib_lattice.le_sup_right complete_distrib_lattice.sup_le complete_distrib_lattice.inf complete_distrib_lattice.inf_le_left complete_distrib_lattice.inf_le_right complete_distrib_lattice.le_inf sorry complete_distrib_lattice.top complete_distrib_lattice.le_top complete_distrib_lattice.bot complete_distrib_lattice.bot_le /-- A complete boolean algebra is a completely distributive boolean algebra. -/ class complete_boolean_algebra (α : Type u_1) extends boolean_algebra α, complete_distrib_lattice α where theorem compl_infi {α : Type u} {ι : Sort w} [complete_boolean_algebra α] {f : ι → α} : infi fᶜ = supr fun (i : ι) => f iᶜ := le_antisymm (compl_le_of_compl_le (le_infi fun (i : ι) => compl_le_of_compl_le (le_supr (compl ∘ f) i))) (supr_le fun (i : ι) => compl_le_compl (infi_le f i)) theorem compl_supr {α : Type u} {ι : Sort w} [complete_boolean_algebra α] {f : ι → α} : supr fᶜ = infi fun (i : ι) => f iᶜ := sorry theorem compl_Inf {α : Type u} [complete_boolean_algebra α] {s : set α} : Inf sᶜ = supr fun (i : α) => supr fun (H : i ∈ s) => iᶜ := sorry theorem compl_Sup {α : Type u} [complete_boolean_algebra α] {s : set α} : Sup sᶜ = infi fun (i : α) => infi fun (H : i ∈ s) => iᶜ := sorry end Mathlib
537e73cba43e6504df3bddc860a3c33bae52e164
41e069072396dcd54bd9fdadb27cfd35fd07016a
/src/K/marking.lean
1b269344ed6cfbb94b6448704dc172654dedb934
[ "MIT" ]
permissive
semorrison/ModalTab
438ad601bd2631ab9cfe1e61f0d1337a36e2367e
cc94099194a2b69f84eb7a770b7aac711825179f
refs/heads/master
1,585,939,884,891
1,540,961,947,000
1,540,961,947,000
155,500,181
0
0
MIT
1,540,961,175,000
1,540,961,175,000
null
UTF-8
Lean
false
false
10,491
lean
import .semantics data.list.perm open nnf subtype list def pmark (Γ m : list nnf) := ∀ Δ, (∀ δ ∈ Δ, δ ∉ m) → Δ <+ Γ → unsatisfiable (list.diff Γ Δ) @[simp] def mark : nnf → list nnf → list nnf | (nnf.and φ ψ) m := if φ ∈ m ∨ ψ ∈ m then nnf.and φ ψ :: m else m | (nnf.or φ ψ) m := if φ ∈ m ∨ ψ ∈ m then nnf.or φ ψ :: m else m | φ m := m theorem subset_mark : Π {φ Γ}, Γ ⊆ mark φ Γ | (var n) Γ := by dsimp [mark]; reflexivity | (neg n) Γ := by dsimp [mark]; reflexivity | (and φ ψ) Γ := begin dsimp [mark], by_cases φ ∈ Γ ∨ ψ ∈ Γ, {rw if_pos h, apply subset_cons}, {rw if_neg h, reflexivity} end | (or φ ψ) Γ := begin dsimp [mark], by_cases φ ∈ Γ ∨ ψ ∈ Γ, {rw if_pos h, apply subset_cons}, {rw if_neg h, reflexivity} end | (box φ) Γ := by dsimp [mark]; reflexivity | (dia φ) Γ := by dsimp [mark]; reflexivity def pmark_of_closed_and {Γ Δ} (i : and_instance Γ Δ) (m) (h : unsatisfiable Δ) (p : pmark Δ m) : {x // pmark Γ x} := begin cases i with φ ψ hin, split, swap, {exact mark (and φ ψ) m}, { intros Δ' hΔ hsub, by_cases hm : φ ∈ m ∨ ψ ∈ m, -- pos hm { cases hm, -- left hm { have marked : nnf.and φ ψ ∈ mark (nnf.and φ ψ) m, {simp [mem_cons_self, hm] }, have : unsatisfiable (list.diff (φ :: ψ :: list.erase Γ (and φ ψ)) Δ'), {apply p, {intros δ hδ hmem, apply hΔ _ hδ, apply subset_mark hmem}, have : Δ'.erase (and φ ψ) <+ φ :: ψ :: list.erase Γ (and φ ψ), {apply sublist.cons, apply sublist.cons, apply erase_sublist_erase _ hsub}, have hnin: and φ ψ ∉ Δ', {intro, apply hΔ _ a marked}, rw ←erase_of_not_mem hnin, exact this}, intro, intros, intro hsat, have hsat : sat k s (list.diff (φ :: ψ :: list.erase Γ (and φ ψ)) Δ'), {apply sat_subset _ (φ :: (ψ :: list.erase Γ (and φ ψ)).diff Δ'), apply subset_cons_diff, apply sat_subset _ (φ :: ψ :: (list.erase Γ (and φ ψ)).diff Δ'), apply cons_subset_cons, apply subset_cons_diff, have hsatp : and φ ψ ∈ Γ.diff Δ', {apply mem_diff_of_mem hin, intro, apply hΔ _ a marked}, intros x hx, rcases hx with eq₁ | eq₂ | hin', rw eq₁, apply and.left, rw ←sat_of_and, apply hsat _ hsatp, rw eq₂, apply and.right, rw ←sat_of_and, apply hsat _ hsatp, have hsubd : list.diff (list.erase Γ (and φ ψ)) Δ' ⊆ list.diff Γ Δ', {apply subset_of_sublist, apply diff_sublist_of_sublist, apply erase_sublist}, apply hsat, apply hsubd, exact hin'}, apply this, exact hsat }, -- right hm { have marked : nnf.and φ ψ ∈ mark (nnf.and φ ψ) m, { simp [mem_cons_self, hm] }, have : unsatisfiable (list.diff (φ :: ψ :: list.erase Γ (and φ ψ)) Δ'), {apply p, {intros δ hδ hmem, apply hΔ _ hδ, apply subset_mark hmem}, have : Δ'.erase (and φ ψ) <+ φ :: ψ :: list.erase Γ (and φ ψ), {apply sublist.cons, apply sublist.cons, apply erase_sublist_erase, exact hsub}, have hnin: and φ ψ ∉ Δ', {intro, apply hΔ _ a marked}, rw ←erase_of_not_mem hnin, exact this}, intro, intros, intro hsat, have hsat : sat k s (list.diff (φ :: ψ :: list.erase Γ (and φ ψ)) Δ'), {apply sat_subset _ (φ :: (ψ :: list.erase Γ (and φ ψ)).diff Δ'), apply subset_cons_diff, apply sat_subset _ (φ :: ψ :: (list.erase Γ (and φ ψ)).diff Δ'), apply cons_subset_cons, apply subset_cons_diff, have hsatp : and φ ψ ∈ Γ.diff Δ', {apply mem_diff_of_mem hin, intro, apply hΔ _ a marked}, intros x hx, rcases hx with eq₁ | eq₂ | hin', rw eq₁, apply and.left, rw ←sat_of_and, apply hsat _ hsatp, rw eq₂, apply and.right, rw ←sat_of_and, apply hsat _ hsatp, have hsubd : list.diff (list.erase Γ (and φ ψ)) Δ' ⊆ list.diff Γ Δ', {apply subset_of_sublist, apply diff_sublist_of_sublist, apply erase_sublist}, apply hsat, apply hsubd, exact hin'}, apply this, exact hsat } }, -- neg hm { have : unsatisfiable ((φ :: ψ :: list.erase Γ (and φ ψ)).diff $ φ :: ψ :: Δ'.erase (and φ ψ)), {apply p, intros δ hδ hdin, rcases hδ with eq₁ | eq₂ | hmem, {apply hm, left, rw ←eq₁, exact hdin}, {apply hm, right, rw ←eq₂, exact hdin}, {apply hΔ, apply erase_subset _ _ hmem, apply subset_mark hdin}, apply sublist.cons2, apply sublist.cons2, apply erase_sublist_erase _ hsub }, intro, intros, intro hsat, apply this, simp, apply sat_sublist, apply erase_diff_erase_sublist_of_sublist hsub, exact hsat } } end theorem unsat_of_jump {Γ₁ Γ₂ Δ : list nnf} (i : or_instance Δ Γ₁ Γ₂) (m : list nnf) (h₁ : unsatisfiable Γ₁) (h₂ : pmark Γ₁ m) (h₃ : left_prcp i ∉ m) : unsatisfiable Δ := begin cases i with φ ψ hin, have : unsatisfiable ((φ :: list.erase Δ (or φ ψ)).diff [φ]), {apply h₂, intros, cases H, rw H, exact h₃, intro, exact not_mem_nil δ H, apply sublist.cons2, simp}, intro, intros, intro hsat, apply this, apply sat_subset _ Δ _ _ _ hsat, simp [erase_subset] end def pmark_of_jump {Γ₁ Γ₂ Δ : list nnf} (i : or_instance Δ Γ₁ Γ₂) (m : list nnf) (h₁ : unsatisfiable Γ₁) (h₂ : pmark Γ₁ m) (h₃ : left_prcp i ∉ m) : {x // pmark Δ x} := begin cases i with φ ψ hin, split, swap, {exact mark (or φ ψ) m}, { intros Δ' hΔ' hsub, have : unsatisfiable (list.diff (φ :: Δ.erase (or φ ψ)) (φ :: Δ'.erase (or φ ψ))), { apply h₂, intros, intro hmem, rcases H with eq | hin, {apply h₃, simpa [eq] using hmem}, {apply hΔ' δ, apply erase_subset _ _ hin, apply subset_mark hmem}, apply sublist.cons2, apply erase_sublist_erase _ hsub }, intro, intros, intro hsat, apply this st k s, simp, apply sat_sublist, apply erase_diff_erase_sublist_of_sublist, exact hsub, exact hsat } end def pmark_of_closed_or {Γ₁ Γ₂ Δ : list nnf} {m₁ m₂ : list nnf} (i : or_instance Δ Γ₁ Γ₂) (h₁ : unsatisfiable Γ₁) (p₁ : pmark Γ₁ m₁) (h₂ : unsatisfiable Γ₂) (p₂ : pmark Γ₂ m₂) : {x // pmark Δ x} := begin cases i with φ ψ hin, split, swap, {exact mark (or φ ψ) (m₁ ++ m₂)}, { intros Δ' hΔ hsub, by_cases hmφ : φ ∈ m₁, {by_cases hmψ : ψ ∈ m₂, have marked : or φ ψ ∈ mark (or φ ψ) (m₁++m₂), {dsimp [mark], rw if_pos, apply mem_cons_self, left, rw mem_append, left, exact hmφ}, have hnin: or φ ψ ∉ Δ', {intro, apply hΔ _ a marked}, -- both marked { have hl : unsatisfiable (list.diff (φ :: list.erase Δ (or φ ψ)) Δ'), {apply p₁, {intros δ hδ hin, apply hΔ, exact hδ, apply subset_mark, rw mem_append, left, exact hin}, have : Δ'.erase (or φ ψ) <+ φ :: list.erase Δ (or φ ψ), {apply sublist.cons, apply erase_sublist_erase, exact hsub}, rw ←erase_of_not_mem hnin, exact this}, have hr : unsatisfiable (list.diff (ψ :: list.erase Δ (or φ ψ)) Δ'), {apply p₂, {intros δ hδ hin, apply hΔ, exact hδ, apply subset_mark, rw mem_append, right, exact hin}, have : Δ'.erase (or φ ψ) <+ ψ :: list.erase Δ (or φ ψ), {apply sublist.cons, apply erase_sublist_erase, exact hsub}, rw ←erase_of_not_mem hnin, exact this}, intro, intros, intro hsat, have : or φ ψ ∈ list.diff Δ Δ', {apply mem_diff_of_mem hin hnin}, have hforce := hsat _ this, dsimp at hforce, cases hforce with l r, {apply hl st k s, apply sat_subset, apply subset_of_subperm, apply subperm_cons_diff, intros x hx, cases hx, rw hx, exact l, apply hsat, have hsubd : list.diff (list.erase Δ (or φ ψ)) Δ' ⊆ list.diff Δ Δ', {apply subset_of_sublist, apply diff_sublist_of_sublist, apply erase_sublist}, apply hsubd hx}, {apply hr st k s, apply sat_subset, apply subset_of_subperm, apply subperm_cons_diff, intros x hx, cases hx, rw hx, exact r, apply hsat, have hsubd : list.diff (list.erase Δ (or φ ψ)) Δ' ⊆ list.diff Δ Δ', {apply subset_of_sublist, apply diff_sublist_of_sublist, apply erase_sublist}, apply hsubd hx} }, -- marked φ, unmarked ψ { have : unsatisfiable (list.diff (ψ :: Δ.erase (or φ ψ)) (ψ :: Δ'.erase (or φ ψ))), {apply p₂, intros, intro hmem, rcases H with eq | hin, {apply hmψ, rw ←eq, exact hmem}, {apply hΔ δ, apply erase_subset _ _ hin, apply subset_mark, rw mem_append, right, exact hmem}, apply sublist.cons2, apply erase_sublist_erase _ hsub}, intro, intros, intro hsat, apply this st k s, simp, apply sat_sublist, apply erase_diff_erase_sublist_of_sublist hsub, exact hsat } }, -- unmarked φ { have : unsatisfiable (list.diff (φ :: Δ.erase (or φ ψ)) (φ :: Δ'.erase (or φ ψ))), {apply p₁, intros, intro hmem, rcases H with eq | hin, {apply hmφ, rw ←eq, exact hmem}, {apply hΔ δ, apply erase_subset _ _ hin, apply subset_mark, rw mem_append, left, exact hmem}, apply sublist.cons2, apply erase_sublist_erase _ hsub}, intro, intros, intro hsat, apply this st k s, simp, apply sat_sublist, apply erase_diff_erase_sublist_of_sublist hsub, exact hsat } } end theorem modal_pmark {Γ} (h₁ : modal_applicable Γ) (i) (h₂ : i ∈ unmodal Γ ∧ unsatisfiable i): pmark Γ (dia (list.head i) :: rebox (unbox Γ)) := begin intro, intros hδ hsub, intro, intros, intro hsat, have := unmodal_unsat_of_unsat Γ i h₂.1 h₂.2, apply this st k s, apply sat_subset _ _ _ _ _ hsat, intros φ h, apply mem_diff_of_mem, {cases h, rw h, exact unmodal_mem_head Γ i h₂.1, apply rebox_unbox_of_mem, {simp [unbox_iff]}, {exact h}}, {intro, apply hδ, repeat {assumption} } end
c5ce2b2b5448692a8accd5332a02a297a28c82c8
ddf69e0b8ad10bfd251aa1fb492bd92f064768ec
/src/ring_theory/ideal/operations.lean
a0f2f5c6e32bd742389a7720c372ff343d5daf27
[ "Apache-2.0" ]
permissive
MaboroshiChan/mathlib
db1c1982df384a2604b19a5e1f5c6464c7c76de1
7f74e6b35f6bac86b9218250e83441ac3e17264c
refs/heads/master
1,671,993,587,476
1,601,911,102,000
1,601,911,102,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,054
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.nat.choose.sum import data.equiv.ring import algebra.algebra.operations import ring_theory.ideal.basic /-! # More operations on modules and ideals -/ universes u v w x open_locale big_operators namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] instance has_scalar' : has_scalar (ideal R) (submodule R M) := ⟨λ I N, ⨆ r : I, N.map (r.1 • linear_map.id)⟩ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := (le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩ theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := ⟨λ H r hr n hn, H $ smul_mem_smul hr hn, λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩ @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (c:R) n, p n → p (c • n)) : p x := (@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right hri, hs ▸ mul_smul r s m⟩) ⟨0, I.zero_mem, by rw [zero_smul]⟩ (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩) (λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left hyi, by rw [mul_smul, hy]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn) theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := smul_mono h (le_refl N) theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := smul_mono (le_refl I) h variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩) (sup_le (smul_mono_right le_sup_left) (smul_mono_right le_sup_right)) theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩) (sup_le (smul_mono_left le_sup_left) (smul_mono_left le_sup_right)) protected theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) ((zero_smul R t).symm ▸ submodule.zero_mem _) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _) (λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS (λ r hrS, span_induction hnT (λ n hnT, subset_span $ set.mem_bUnion hrS $ set.mem_bUnion hnT $ set.mem_singleton _) ((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _) (λ x y, (smul_add r x y).symm ▸ submodule.add_mem _) (λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _)) ((zero_smul R n).symm ▸ submodule.zero_mem _) (λ r s, (add_smul r s n).symm ▸ submodule.add_mem _) (λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $ span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $ smul_mem_smul (subset_span hrS) (subset_span hnT) variables {M' : Type w} [add_comm_group M'] [module R M'] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f, from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $ smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) end submodule namespace ideal section chinese_remainder variables {R : Type u} [comm_ring R] {ι : Type v} theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R} (hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) : ∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j := begin have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j, { intros j hjs hji, specialize hf i his j hjs hji.symm, rw [eq_top_iff_one, submodule.mem_sup] at hf, rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩, { rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri }, { rw [← hrs, add_sub_cancel'], exact hsj } }, classical, have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j, { choose g hg1 hg2, refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩, { split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem }, { intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } }, rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split, { rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod], apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi }, intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod], refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _, rw quotient.eq_zero_iff_mem, exact hgj j hjs hji end theorem exists_sub_mem [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) : ∃ r : R, ∀ i, r - g i ∈ f i := begin have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j), { have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij), choose φ hφ, existsi λ i, φ i (finset.mem_univ i), exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ }, rcases this with ⟨φ, hφ1, hφ2⟩, use ∑ i, g i * φ i, intros i, rw [← quotient.eq, ring_hom.map_sum], refine eq.trans (finset.sum_eq_single i _ _) _, { intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left (hφ2 j i hji) }, { intros hi, exact (hi $ finset.mem_univ i).elim }, specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1, rw [ring_hom.map_mul, hφ1, mul_one] end def quotient_inf_to_pi_quotient (f : ι → ideal R) : (⨅ i, f i).quotient →+* Π i, (f i).quotient := begin refine quotient.lift (⨅ i, f i) _ _, { convert @@pi.ring_hom (λ i, quotient (f i)) (λ i, ring.to_semiring) ring.to_semiring (λ i, quotient.mk (f i)) }, { intros r hr, rw submodule.mem_infi at hr, ext i, exact quotient.eq_zero_iff_mem.2 (hr i) } end theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : function.bijective (quotient_inf_to_pi_quotient f) := ⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $ (submodule.mem_infi _).2 $ λ i, quotient.eq.1 $ show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl, λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in ⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩ /-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/ noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R) (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : (⨅ i, f i).quotient ≃+* Π i, (f i).quotient := { .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf), .. quotient_inf_to_pi_quotient f } end chinese_remainder section mul_and_radical variables {R : Type u} [comm_ring R] variables {I J K L: ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, ideal.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, ideal.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) := by { unfold span, rw submodule.span_mul_span,} lemma span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : ideal R) := by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton],} theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right hri, J.mul_mem_left hsj⟩ theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) variables (I) theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end lemma mul_eq_bot {R : Type*} [integral_domain R] {I J : ideal R} : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj, let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)), λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩ /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right $ I.mul_mem_left $ nat.add_comm n m ▸ (nat.add_sub_assoc hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right hyni) (λ hmc, I.mul_mem_right $ I.mul_mem_right $ nat.add_sub_cancel' hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, show (r * s)^n ∈ I, from (mul_pow r s n).symm ▸ I.mul_mem_left hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right hrm, (pow_add r m n).symm ▸ J.mul_mem_left hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right hpm) (m.add_mem (m.mul_mem_left hfm) (m.mul_mem_left hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr instance : comm_semiring (ideal R) := submodule.comm_semiring @[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_map_top, submodule.map_id] variables (R) theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ := nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul] variables {R} variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : radical_mul _ _ ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, smul_mem' := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left hx }, .. I.to_add_submonoid.comap (f : R →+ S) } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem {x} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one]; exact (ne_top_iff_one _).1 hK theorem is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, f.map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩ theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw f.map_mul; exact mul_mem_mul (mem_map_of_mem hri) (mem_map_of_mem hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.bUnion_subset $ λ i ⟨r, hri, hfri⟩, set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← f.map_mul]; exact mem_map_of_mem (mul_mem_mul hri hsj)) variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [comm_ring T] {I : ideal T} (f : R →+* S) (g : S →+*T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [comm_ring T] {I : ideal R} (f : R →+* S) (g : S →+*T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose _ _ _ _ (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := congr_fun (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := congr_fun (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f).u_Inf lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I := trans (comap_Inf f s) (by rw infi_image) theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (f.map_pow r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩) theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) := ⟨comap_ne_top f H.left, λ x y h, H.right (show f x * f y ∈ K, by rwa [mem_comap, ring_hom.map_mul] at h)⟩ @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f).monotone_l.map_inf_le _ _ theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem hrni⟩ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f).monotone_u.le_map_sup _ _ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 (le_refl _)) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem hx.left)⟩ theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le)) lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h /-- Correspondence theorem -/ def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le (le_refl _) I.2) le_sup_left, map_rel_iff' := λ I1 I2, ⟨comap_mono, λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H⟩ } /-- The map on ideals induced by a surjective map preserves inclusion. -/ def order_embedding_of_surjective : ideal S ↪o ideal R := (rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _) theorem map_eq_top_or_is_maximal_of_surjective (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine or_iff_not_imp_left.2 (λ ne_top, ⟨λ h, ne_top h, λ J hJ, _⟩), { refine (rel_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.right (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end theorem comap_is_maximal_of_surjective [H : is_maximal K] : is_maximal (comap f K) := begin refine ⟨comap_ne_top _ H.left, λ J hJ, _⟩, suffices : map f J = ⊤, { replace this := congr_arg (comap f) this, rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this, rw eq_top_iff, exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) }, refine H.right (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ)) (λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))), rw [comap_map_of_surjective _ hf, sup_eq_left], exact le_trans (comap_mono bot_le) (le_of_lt hJ) end end surjective lemma mem_quotient_iff_mem (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := begin refine iff.trans (mem_map_iff_of_surjective _ quotient.mk_surjective) _, split, { rintros ⟨x, x_mem, x_eq⟩, simpa using J.add_mem (hIJ (quotient.eq.mp x_eq.symm)) x_mem }, { intro x_mem, exact ⟨x, x_mem, rfl⟩ } end section injective variables (hf : function.injective f) include hf open function lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective section bijective variables (hf : function.bijective f) include hf open function /-- Special case of the correspondence theorem for isomorphic rings -/ def rel_iso_of_bijective : ideal S ≃o ideal R := { to_fun := comap f, inv_fun := map f, left_inv := (rel_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' } lemma comap_le_iff_le_map : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal (H : is_maximal I) : is_maximal (map f I) := by refine or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.left _); calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top end bijective end map_and_comap section is_primary variables {R : Type u} [comm_ring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_primary.to_is_prime (I : ideal R) (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.2 hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary end ideal namespace ring_hom variables {R : Type u} {S : Type v} [comm_ring R] section comm_ring variables [comm_ring S] (f : R →+* S) /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = is_add_group_hom.ker f := rfl lemma ker_eq_comap_bot (f : R →+* S) : f.ker = ideal.comap f ⊥ := rfl lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by rw [submodule.ext'_iff, ker_eq]; exact is_add_group_hom.injective_iff_trivial_ker f lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by rw [submodule.ext'_iff, ker_eq]; exact is_add_group_hom.trivial_ker_iff_eq_zero f /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f := by { rw [mem_ker, f.map_one], exact one_ne_zero } end comm_ring /-- The kernel of a homomorphism to an integral domain is a prime ideal.-/ lemma ker_is_prime [integral_domain S] (f : R →+* S) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ end ring_hom namespace ideal variables {R : Type*} {S : Type*} [comm_ring R] [comm_ring S] lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, refine hx ▸ (mem_map_of_mem _), rw Inf_eq_infi at ⊢ hy, simp at ⊢ hy, intros J hJ, cases (mem_map_iff_of_surjective f hf).1 (hy (map f J) J hJ rfl) with x' hx', have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, ring_hom.map_sub, hx, hx'.right, sub_self y], }, convert J.add_mem this hx'.left, ring, } end theorem map_is_prime_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} [H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) := begin refine ⟨λ h, H.left (eq_top_iff.2 _), λ x y, _⟩, { replace h := congr_arg (comap f) h, rw [comap_map_of_surjective _ hf, comap_top] at h, exact h ▸ sup_le (le_of_eq rfl) hk }, { refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)), rw [← ha, ← hb, ← ring_hom.map_mul, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← ring_hom.map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ f.ker)), ring }, exact (H.right this).imp (λ h, ha ▸ mem_map_of_mem h) (λ h, hb ▸ mem_map_of_mem h) } end theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} (h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical := begin rw [radical_eq_Inf, radical_eq_Inf], have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, convert map_Inf hf this, refine funext (λ j, propext ⟨_, _⟩), { rintros ⟨hj, hj'⟩, haveI : j.is_prime := hj', exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩, map_comap_of_surjective f hf j⟩⟩ }, { rintro ⟨J, ⟨hJ, hJ'⟩⟩, haveI : J.is_prime := hJ.right, refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ }, end section quotient_algebra /-- The ring hom `R/f⁻¹(I) →+* S/I` induced by a ring hom `f : R →+* S` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : I.quotient →+* J.quotient := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) variables {I : ideal R} {J: ideal S} [algebra R S] @[priority 100] instance quotient_algebra : algebra (J.comap (algebra_map R S)).quotient J.quotient := (quotient_map J (algebra_map R S) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective : function.injective (algebra_map (J.comap (algebra_map R S)).quotient J.quotient) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end end quotient_algebra end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] -- It is even a semialgebra. But those aren't in mathlib yet. instance semimodule_submodule : semimodule (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := submodule.smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] variables (f : A →+* B) /-- `lift_of_surjective f hf g hg` is the unique ring homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : A →+* B` is surjective (`hf`), * and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` A . | \ f | \ g | \ v \⌟ B ----> C ∃!φ ``` -/ noncomputable def lift_of_surjective (hf : function.surjective f) (g : A →+* C) (hg : f.ker ≤ g.ker) : B →+* C := { to_fun := λ b, g (classical.some (hf b)), map_one' := begin rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one], exact classical.some_spec (hf 1) end, map_mul' := begin intros x y, rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul], simp only [classical.some_spec (hf _)], end, .. add_monoid_hom.lift_of_surjective f.to_add_monoid_hom hf g.to_add_monoid_hom hg } @[simp] lemma lift_of_surjective_comp_apply (hf : function.surjective f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) : (f.lift_of_surjective hf g hg) (f a) = g a := f.to_add_monoid_hom.lift_of_surjective_comp_apply hf g.to_add_monoid_hom hg a @[simp] lemma lift_of_surjective_comp (hf : function.surjective f) (g : A →+* C) (hg : f.ker ≤ g.ker) : (f.lift_of_surjective hf g hg).comp f = g := by { ext, simp only [comp_apply, lift_of_surjective_comp_apply] } lemma eq_lift_of_surjective (hf : function.surjective f) (g : A →+* C) (hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) : h = (f.lift_of_surjective hf g hg) := begin ext b, rcases hf b with ⟨a, rfl⟩, simp only [← comp_apply, hh, f.lift_of_surjective_comp], end end ring_hom
25ff5adcdb9d64116ddb7225b6d8741bea20840e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/param_binder_update.lean
7f7ebec4ab265b38e2c8f45c2bb1b37fd21d0cac
[ "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,144
lean
section parameter {A : Type*} parameter A -- definition id (a : A) := a parameter {A} definition id₂ (a : A) := a end #check @id #check @id₂ section parameters {A : Type*} {B : Type*} definition foo1 (a : A) (b : B) := a parameters {A} (B) definition foo2 (a : A) (b : B) := a parameters (A) {B} definition foo3 (a : A) (b : B) := a parameters (A) (B) definition foo4 (a : A) (b : B) := a #check @foo1 #check @foo2 #check @foo3 #check @foo4 end #check @foo1 #check @foo2 #check @foo3 #check @foo4 section variables {A : Type*} {B : Type*} definition boo1 (a : A) (b : B) := a variables {A} (B) definition boo2 (a : A) (b : B) := a variables (A) {B} definition boo3 (a : A) (b : B) := a variables (A) (B) definition boo4 (a : A) (b : B) := a #check @boo1 #check @boo2 #check @boo3 #check @boo4 end section variables {A : Type*} {B : Type*} parameter (A) -- ERROR variable (C) -- ERROR variables (C) (D) -- ERROR variables C -- ERROR definition id3 (a : A) := a parameter id3 -- ERROR parameter (C : Type) variables {C} -- ERROR end
20034c43e853a3fc748df1adde9ada218a736ad6
649957717d58c43b5d8d200da34bf374293fe739
/src/tactic/tidy.lean
099a27b0e34dd2c52e558780e00026f3c0f3607c
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
3,181
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import tactic.ext import tactic.auto_cases import tactic.chain import tactic.solve_by_elim import tactic.interactive namespace tactic namespace tidy meta def tidy_attribute : user_attribute := { name := `tidy, descr := "A tactic that should be called by `tidy`." } run_cmd attribute.register ``tidy_attribute meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> pure n.to_string) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail "invalid type for @[tidy] tactic" meta def run_tactics : tactic string := do names ← attribute.get_instances `tidy, first (names.map name_to_tactic) <|> fail "no @[tidy] tactics succeeded" meta def ext1_wrapper : tactic string := do ng ← num_goals, ext1 [] {apply_cfg . new_goals := new_goals.all}, ng' ← num_goals, return $ if ng' > ng then "tactic.ext1 [] {new_goals := tactic.new_goals.all}" else "ext1" meta def default_tactics : list (tactic string) := [ reflexivity >> pure "refl", `[exact dec_trivial] >> pure "exact dec_trivial", propositional_goal >> assumption >> pure "assumption", intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate (ns.map (λ e, e.to_string)))), auto_cases, `[apply_auto_param] >> pure "apply_auto_param", `[dsimp at *] >> pure "dsimp at *", `[simp at *] >> pure "simp at *", ext1_wrapper, fsplit >> pure "fsplit", injections_and_clear >> pure "injections_and_clear", propositional_goal >> (`[solve_by_elim]) >> pure "solve_by_elim", `[unfold_coes] >> pure "unfold_coes", `[unfold_aux] >> pure "unfold_aux", tidy.run_tactics ] meta structure cfg := (trace_result : bool := ff) (trace_result_prefix : string := "/- `tidy` says -/ ") (tactics : list (tactic string) := default_tactics) declare_trace tidy meta def core (cfg : cfg := {}) : tactic (list string) := do results ← chain cfg.tactics, when (cfg.trace_result ∨ is_trace_enabled_for `tidy) $ trace (cfg.trace_result_prefix ++ (", ".intercalate results)), return results end tidy meta def tidy (cfg : tidy.cfg := {}) := tactic.tidy.core cfg >> skip namespace interactive open lean.parser interactive meta def tidy (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) := tactic.tidy { trace_result := trace.is_some, ..cfg } end interactive @[hole_command] meta def tidy_hole_cmd : hole_command := { name := "tidy", descr := "Use `tidy` to complete the goal.", action := λ _, do script ← tidy.core, return [("begin " ++ (", ".intercalate script) ++ " end", "by tidy")] } end tactic
ae6fe56095c3992cbd460182220d6e3c8d4eba35
4727251e0cd73359b15b664c3170e5d754078599
/roadmap/topology/paracompact.lean
a5a4d718bb9bad7d00d4883415258a775984ede9
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,163
lean
/- Copyright (c) 2020 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import ..todo import topology.subset_properties import topology.separation import topology.metric_space.basic /-! A formal roadmap for basic properties of paracompact spaces. It contains the statements that compact spaces and metric spaces are paracompact, and that paracompact t2 spaces are normal, as well as partially formalised proofs. Any contributor should feel welcome to contribute complete proofs. When this happens, we should also consider preserving the current file as an exemplar of a formal roadmap. -/ open set filter universe u namespace roadmap class paracompact_space (X : Type u) [topological_space X] : Prop := (locally_finite_refinement : ∀ {α : Type u} (u : α → set X) (uo : ∀ a, is_open (u a)) (uc : Union u = univ), ∃ {β : Type u} (v : β → set X) (vo : ∀ b, is_open (v b)) (vc : Union v = univ), locally_finite v ∧ ∀ b, ∃ a, v b ⊆ u a) /-- Any open cover of a paracompact space has a locally finite *precise* refinement, that is, one indexed on the same type with each open set contained in the corresponding original one. -/ lemma paracompact_space.precise_refinement {X : Type u} [topological_space X] [paracompact_space X] {α : Type u} (u : α → set X) (uo : ∀ a, is_open (u a)) (uc : Union u = univ) : ∃ v : α → set X, (∀ a, is_open (v a)) ∧ Union v = univ ∧ locally_finite v ∧ (∀ a, v a ⊆ u a) := begin obtain ⟨β, w, wo, wc, lfw, wr⟩ := paracompact_space.locally_finite_refinement u uo uc, choose f hf using wr, refine ⟨λ a, ⋃₀ {s | ∃ b, f b = a ∧ s = w b}, λ a, _, _, _, λ a, _⟩, { apply is_open_sUnion _, rintros t ⟨b, rfl, rfl⟩, apply wo }, { todo }, { todo }, { apply sUnion_subset, rintros t ⟨b, rfl, rfl⟩, apply hf } end lemma paracompact_of_compact {X : Type u} [topological_space X] [compact_space X] : paracompact_space X := begin refine ⟨λ α u uo uc, _⟩, obtain ⟨s, _, sf, sc⟩ := compact_univ.elim_finite_subcover_image (λ a _, uo a) (by rwa [univ_subset_iff, bUnion_univ]), refine ⟨s, λ b, u b.val, λ b, uo b.val, _, _, λ b, ⟨b.val, subset.refl _⟩⟩, { todo }, { intro x, refine ⟨univ, univ_mem, _⟩, todo }, end lemma normal_of_paracompact_t2 {X : Type u} [topological_space X] [t2_space X] [paracompact_space X] : normal_space X := todo /- Similar to the proof of `generalized_tube_lemma`, but different enough not to merge them. Lemma: if `s : set X` is closed and can be separated from any point by open sets, then `s` can also be separated from any closed set by open sets. Apply twice. See * Bourbaki, General Topology, Chapter IX, §4.4 * https://ncatlab.org/nlab/show/paracompact+Hausdorff+spaces+are+normal -/ lemma paracompact_of_metric {X : Type u} [metric_space X] : paracompact_space X := todo /- See Mary Ellen Rudin, A new proof that metric spaces are paracompact. https://www.ams.org/journals/proc/1969-020-02/S0002-9939-1969-0236876-3/S0002-9939-1969-0236876-3.pdf -/ end roadmap
0b1398d0aa7e806846fa255d652497548121c496
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/set_theory/cardinal_ordinal.lean
94e657e03473f8ff0589edfee74dbd068ce12ee8
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,206
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, Floris van Doorn -/ import set_theory.ordinal_arithmetic import tactic.linarith /-! # Cardinals and ordinals Relationships between cardinals and ordinals, properties of cardinals that are proved using ordinals. ## Main definitions * The function `cardinal.aleph'` gives the cardinals listed by their ordinal index, and is the inverse of `cardinal.aleph_idx`. `aleph' n = n`, `aleph' ω = cardinal.omega = ℵ₀`, `aleph' (ω + 1) = ℵ₁`, etc. It is an order isomorphism between ordinals and cardinals. * The function `cardinal.aleph` gives the infinite cardinals listed by their ordinal index. `aleph 0 = cardinal.omega = ℵ₀`, `aleph 1 = ℵ₁` is the first uncountable cardinal, and so on. ## Main Statements * `cardinal.mul_eq_max` and `cardinal.add_eq_max` state that the product (resp. sum) of two infinite cardinals is just their maximum. Several variations around this fact are also given. * `cardinal.mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality. * simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making `simp` able to prove inequalities about numeral cardinals. ## Tags cardinal arithmetic (for infinite cardinals) -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w namespace cardinal section using_ordinals open ordinal theorem ord_is_limit {c} (co : omega ≤ c) : (ord c).is_limit := begin refine ⟨λ h, omega_ne_zero _, λ a, lt_imp_lt_of_le_imp_le _⟩, { rw [← ordinal.le_zero, ord_le] at h, simpa only [card_zero, nonpos_iff_eq_zero] using le_trans co h }, { intro h, rw [ord_le] at h ⊢, rwa [← @add_one_of_omega_le (card a), ← card_succ], rw [← ord_le, ← le_succ_of_is_limit, ord_le], { exact le_trans co h }, { rw ord_omega, exact omega_is_limit } } end /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this definition, we register additionally that this function is an initial segment, i.e., it is order preserving and its range is an initial segment of the ordinals. For the basic function version, see `aleph_idx`. For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @rel_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding.lt_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_rel_embedding.map_rel_iff @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b := aleph_idx.initial_seg.init _ _ /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this version, we register additionally that this function is an order isomorphism between cardinals and ordinals. For the basic function version, see `aleph_idx`. -/ def aleph_idx.rel_iso : @rel_iso cardinal.{u} ordinal.{u} (<) (<) := @rel_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ λ ⟨o, e⟩, begin have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI α r _ h, let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)), apply not_le_of_gt (lt_succ_self s), have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.injective, simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a)) (ordinal.enum r _ (h (succ s))), end @[simp] theorem aleph_idx.rel_iso_coe : (aleph_idx.rel_iso : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.rel_iso⟩ @[simp] theorem mk_cardinal : mk cardinal = univ.{u (u+1)} := by simpa only [card_type, card_univ] using congr_arg card type_cardinal /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. In this version, we register additionally that this function is an order isomorphism between ordinals and cardinals. For the basic function version, see `aleph'`. -/ def aleph'.rel_iso := cardinal.aleph_idx.rel_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. -/ def aleph' : ordinal → cardinal := aleph'.rel_iso @[simp] theorem aleph'.rel_iso_coe : (aleph'.rel_iso : ordinal → cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := aleph'.rel_iso.map_rel_iff @[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c := cardinal.aleph_idx.rel_iso.to_equiv.symm_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o := cardinal.aleph_idx.rel_iso.to_equiv.apply_symm_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by rw [← nonpos_iff_eq_zero, ← aleph'_aleph_idx 0, aleph'_le]; apply ordinal.zero_le @[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ := le_antisymm (cardinal.aleph_idx_le.1 $ by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx]; apply cardinal.lt_succ_self) (cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _) @[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n | 0 := aleph'_zero | (n+1) := show aleph' (ordinal.succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} : aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c := ⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h, λ h, begin rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l], intros x h', rw [← aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ @[simp] theorem aleph'_omega : aleph' ordinal.omega = omega := eq_of_forall_ge_iff $ λ c, begin simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le], exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]), end /-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/ @[simp] def aleph'_equiv : ordinal ≃ cardinal := ⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩ /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o) @[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := aleph'_lt.trans (ordinal.add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ := by rw [aleph, ordinal.add_succ, aleph'_succ]; refl @[simp] theorem aleph_zero : aleph 0 = omega := by simp only [aleph, add_zero, aleph'_omega] theorem omega_le_aleph' {o : ordinal} : omega ≤ aleph' o ↔ ordinal.omega ≤ o := by rw [← aleph'_omega, aleph'_le] theorem omega_le_aleph (o : ordinal) : omega ≤ aleph o := by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord := ord_is_limit $ omega_le_aleph _ theorem exists_aleph {c : cardinal} : omega ≤ c ↔ ∃ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ordinal.omega, by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx]; rwa [← omega_le_aleph', aleph'_aleph_idx]⟩, λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _, λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ordinal.omega /-! ### Properties of `mul` -/ /-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/ theorem mul_eq_self {c : cardinal} (h : omega ≤ c) : c * c = c := begin refine le_antisymm _ (by simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul_left' (one_lt_omega.le.trans h) c), -- the only nontrivial part is `c * c ≤ c`. We prove it inductively. refine acc.rec_on (cardinal.wf.apply c) (λ c _, quotient.induction_on c $ λ α IH ol, _) h, -- consider the minimal well-order `r` on `α` (a type with cardinality `c`). rcases ord_eq α with ⟨r, wo, e⟩, resetI, letI := linear_order_of_STO' r, haveI : is_well_order α (<) := wo, -- Define an order `s` on `α × α` by writing `(a, b) < (c, d)` if `max a b < max c d`, or -- the max are equal and `a < c`, or the max are equal and `a = c` and `b < d`. let g : α × α → α := λ p, max p.1 p.2, let f : α × α ↪ ordinal × (α × α) := ⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), -- this is a well order on `α × α`. haveI : is_well_order _ s := (rel_embedding.preimage _ _).is_well_order, /- it suffices to show that this well order is smaller than `r` if it were larger, then `r` would be a strict prefix of `s`. It would be contained in `β × β` for some `β` of cardinality `< c`. By the inductive assumption, this set has the same cardinality as `β` (or it is finite if `β` is finite), so it is `< c`, which is a contradiction. -/ suffices : type s ≤ type r, {exact card_le_card this}, refine le_of_forall_lt (λ o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _, { have : {q|s q p} ⊆ (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}), { intros q h, simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h, exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit), { exact ⟨(set.embedding_of_subset _ _ this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr punit_equiv_punit), apply @irrefl _ r }, cases lt_or_ge (card (typein (<) (g p)).succ) omega with qo qo, { exact lt_of_lt_of_le (mul_lt_omega qo qo) ol }, { suffices, {exact lt_of_le_of_lt (IH _ this qo) this}, rw ← lt_ord, apply (ord_is_limit ol).2, rw [mk_def, e], apply typein_lt_type } end end using_ordinals /-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum of the cardinalities of `α` and `β`. -/ theorem mul_eq_max {a b : cardinal} (ha : omega ≤ a) (hb : omega ≤ b) : a * b = max a b := le_antisymm (mul_eq_self (le_trans ha (le_max_left a b)) ▸ canonically_ordered_semiring.mul_le_mul (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul_left' (one_lt_omega.le.trans hb) a) (by simpa only [one_mul] using canonically_ordered_semiring.mul_le_mul_right' (one_lt_omega.le.trans ha) b) theorem mul_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a * b < c := lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (mul_lt_omega h h) hc) (λ h, by rw mul_eq_self h; exact max_lt h1 h2) lemma mul_le_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) : a * b ≤ max a b := begin convert canonically_ordered_semiring.mul_le_mul (le_max_left a b) (le_max_right a b), rw [mul_eq_self], refine le_trans h (le_max_left a b) end lemma mul_eq_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) (h' : b ≠ 0) : a * b = max a b := begin apply le_antisymm, apply mul_le_max_of_omega_le_left h, cases le_or_gt omega b with hb hb, rw [mul_eq_max h hb], have : b ≤ a, exact le_trans (le_of_lt hb) h, rw [max_eq_left this], convert canonically_ordered_semiring.mul_le_mul_left' (one_le_iff_ne_zero.mpr h') _, rw [mul_one], end lemma mul_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a := by { rw [mul_eq_max_of_omega_le_left ha hb', max_eq_left hb] } lemma mul_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b := by { rw [mul_comm, mul_eq_left hb ha ha'] } lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a := by { convert canonically_ordered_semiring.mul_le_mul_right' (one_le_iff_ne_zero.mpr h) _, rw [one_mul] } lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b := by { rw [mul_comm], exact le_mul_left h } lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max omega b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { have : a ≠ 0, { rintro rfl, exact not_lt_of_le ha omega_pos }, left, use ha, { rw [← not_lt], intro hb, apply ne_of_gt _ h, refine lt_of_lt_of_le hb (le_mul_left this) }, { rintro rfl, apply this, rw [_root_.mul_zero] at h, subst h }}, right, by_cases h2a : a = 0, { right, exact h2a }, have hb : b ≠ 0, { rintro rfl, apply h2a, rw [mul_zero] at h, subst h }, left, rw [← h, mul_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction, rw [← ne] at h2a, rw [← one_le_iff_ne_zero] at h2a hb, norm_cast at h2a hb h ⊢, apply le_antisymm _ hb, rw [← not_lt], intro h2b, apply ne_of_gt _ h, conv_lhs { rw [← mul_one n] }, rwa [mul_lt_mul_left], apply nat.lt_of_succ_le h2a }, { rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl), { rw [mul_eq_max_of_omega_le_left ha hb, max_eq_left hab] }, all_goals {simp}} end /-! ### Properties of `add` -/ /-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/ theorem add_eq_self {c : cardinal} (h : omega ≤ c) : c + c = c := le_antisymm (by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using canonically_ordered_semiring.mul_le_mul_right' ((nat_lt_omega 2).le.trans h) c) (self_le_add_left c c) /-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum of the cardinalities of `α` and `β`. -/ theorem add_eq_max {a b : cardinal} (ha : omega ≤ a) : a + b = max a b := le_antisymm (add_eq_self (le_trans ha (le_max_left a b)) ▸ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (self_le_add_right _ _) (self_le_add_left _ _) theorem add_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a + b < c := lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (add_lt_omega h h) hc) (λ h, by rw add_eq_self h; exact max_lt h1 h2) lemma eq_of_add_eq_of_omega_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : omega ≤ c) : b = c := begin apply le_antisymm, { rw [← h], apply self_le_add_left }, rw[← not_lt], intro hb, have : a + b < c := add_lt_of_lt hc ha hb, simpa [h, lt_irrefl] using this end lemma add_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) : a + b = a := by { rw [add_eq_max ha, max_eq_left hb] } lemma add_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) : a + b = b := by { rw [add_comm, add_eq_left hb ha] } lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max omega b ≤ a ∨ b = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { left, use ha, rw [← not_lt], intro hb, apply ne_of_gt _ h, exact lt_of_lt_of_le hb (self_le_add_left b a) }, right, rw [← h, add_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢, rw [← add_right_inj, h, add_zero] }, { rintro (⟨h1, h2⟩|h3), rw [add_eq_max h1, max_eq_left h2], rw [h3, add_zero] } end lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max omega a ≤ b ∨ a = 0) := by { rw [add_comm, add_eq_left_iff] } lemma add_one_eq {a : cardinal} (ha : omega ≤ a) : a + 1 = a := have 1 ≤ a, from le_trans (le_of_lt one_lt_omega) ha, add_eq_left ha this protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < omega) : b = c := begin cases le_or_lt omega b with hb hb, { have : a < b := lt_of_lt_of_le ha hb, rw [add_eq_right hb (le_of_lt this), eq_comm] at h, rw [eq_of_add_eq_of_omega_le h this hb] }, { have hc : c < omega, { rw [← not_le], intro hc, apply lt_irrefl omega, apply lt_of_le_of_lt (le_trans hc (self_le_add_left _ a)), rw [← h], apply add_lt_omega ha hb }, rw [lt_omega] at *, rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩, norm_cast at h ⊢, apply add_left_cancel h } end protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < omega) : a = c := by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb } /-! ### Properties about power -/ theorem pow_le {κ μ : cardinal.{u}} (H1 : omega ≤ κ) (H2 : μ < omega) : κ ^ μ ≤ κ := let ⟨n, H3⟩ := lt_omega.1 H2 in H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n (le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero]; from one_lt_omega) H1) (λ n ih, trans_rel_left _ (by { rw [nat.cast_succ, power_add, power_one]; exact canonically_ordered_semiring.mul_le_mul_right' ih _ }) (mul_eq_self H1))) H1) lemma power_self_eq {c : cardinal} (h : omega ≤ c) : c ^ c = 2 ^ c := begin apply le_antisymm, { apply le_trans (power_le_power_right $ le_of_lt $ cantor c), rw [power_mul, mul_eq_self h] }, { convert power_le_power_right (le_trans (le_of_lt $ nat_lt_omega 2) h), apply nat.cast_two.symm } end lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : omega ≤ c) : c ^ (n : cardinal.{u}) ≤ c := pow_le h (nat_lt_omega n) lemma powerlt_omega {c : cardinal} (h : omega ≤ c) : c ^< omega = c := begin apply le_antisymm, { rw [powerlt_le], intro c', rw [lt_omega], rintro ⟨n, rfl⟩, apply power_nat_le h }, convert le_powerlt one_lt_omega, rw [power_one] end lemma powerlt_omega_le (c : cardinal) : c ^< omega ≤ max c omega := begin cases le_or_gt omega c, { rw [powerlt_omega h], apply le_max_left }, rw [powerlt_le], intros c' hc', refine le_trans (le_of_lt $ power_lt_omega h hc') (le_max_right _ _) end /-! ### Computing cardinality of various types -/ theorem mk_list_eq_mk {α : Type u} (H1 : omega ≤ mk α) : mk (list α) = mk α := eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $ calc mk (list α) = sum (λ n : ℕ, mk α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α ... ≤ sum (λ n : ℕ, mk α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_omega n ... = sum (λ n : ulift.{u} ℕ, mk α) : quotient.sound ⟨@sigma_congr_left _ _ (λ _, quotient.out (mk α)) equiv.ulift.symm⟩ ... = omega * mk α : sum_const _ _ ... = max (omega) (mk α) : mul_eq_max (le_refl _) H1 ... = mk α : max_eq_right H1 theorem mk_finset_eq_mk {α : Type u} (h : omega ≤ mk α) : mk (finset α) = mk α := eq.symm $ le_antisymm (mk_le_of_injective (λ x y, finset.singleton_inj.1)) $ calc mk (finset α) ≤ mk (list α) : mk_le_of_surjective list.to_finset_surjective ... = mk α : mk_list_eq_mk h lemma mk_bounded_set_le_of_omega_le (α : Type u) (c : cardinal) (hα : omega ≤ mk α) : mk {t : set α // mk t ≤ c} ≤ mk α ^ c := begin refine le_trans _ (by rw [←add_one_eq hα]), refine quotient.induction_on c _, clear c, intro β, fapply mk_le_of_surjective, { intro f, use sum.inl ⁻¹' range f, refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _, apply mk_range_le }, rintro ⟨s, ⟨g⟩⟩, use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩, apply subtype.eq, ext, split, { rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y, { rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 }, { rw [dif_neg h'] at h, cases h }}, { intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩, use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr', suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this, apply g.2, exact classical.some_spec this } end lemma mk_bounded_set_le (α : Type u) (c : cardinal) : mk {t : set α // mk t ≤ c} ≤ max (mk α) omega ^ c := begin transitivity mk {t : set (ulift.{u} nat ⊕ α) // mk t ≤ c}, { refine ⟨embedding.subtype_map _ _⟩, apply embedding.image, use sum.inr, apply sum.inr.inj, intros s hs, exact le_trans mk_image_le hs }, refine le_trans (mk_bounded_set_le_of_omega_le (ulift.{u} nat ⊕ α) c (self_le_add_right omega (mk α))) _, rw [max_comm, ←add_eq_max]; refl end lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) : mk {t : set α // t ⊆ s ∧ mk t ≤ c} ≤ max (mk s) omega ^ c := begin refine le_trans _ (mk_bounded_set_le s c), refine ⟨embedding.cod_restrict _ _ _⟩, use λ t, coe ⁻¹' t.1, { rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢, refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_coe]; assumption }, rintro ⟨t, h1t, h2t⟩, exact le_trans (mk_preimage_of_injective _ _ subtype.val_injective) h2t end /-! ### Properties of `compl` -/ lemma mk_compl_of_omega_le {α : Type*} (s : set α) (h : omega ≤ #α) (h2 : #s < #α) : #(sᶜ : set α) = #α := by { refine eq_of_add_eq_of_omega_le _ h2 h, exact mk_sum_compl s } lemma mk_compl_finset_of_omega_le {α : Type*} (s : finset α) (h : omega ≤ #α) : #((↑s)ᶜ : set α) = #α := by { apply mk_compl_of_omega_le _ h, exact lt_of_lt_of_le (finset_card_lt_omega s) h } lemma mk_compl_eq_mk_compl_infinite {α : Type*} {s t : set α} (h : omega ≤ #α) (hs : #s < #α) (ht : #t < #α) : #(sᶜ : set α) = #(tᶜ : set α) := by { rw [mk_compl_of_omega_le s h hs, mk_compl_of_omega_le t h ht] } lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} {s : set α} {t : set β} (hα : #α < omega) (h1 : lift.{u (max v w)} (#α) = lift.{v (max u w)} (#β)) (h2 : lift.{u (max v w)} (#s) = lift.{v (max u w)} (#t)) : lift.{u (max v w)} (#(sᶜ : set α)) = lift.{v (max u w)} (#(tᶜ : set β)) := begin have hα' := hα, have h1' := h1, rw [← mk_sum_compl s, ← mk_sum_compl t] at h1, rw [← mk_sum_compl s, add_lt_omega_iff] at hα, lift #s to ℕ using hα.1 with n hn, lift #(sᶜ : set α) to ℕ using hα.2 with m hm, have : #(tᶜ : set β) < omega, { refine lt_of_le_of_lt (mk_subtype_le _) _, rw [← lift_lt, lift_omega, ← h1', ← lift_omega.{u (max v w)}, lift_lt], exact hα' }, lift #(tᶜ : set β) to ℕ using this with k hk, simp [nat_eq_lift_eq_iff] at h2, rw [nat_eq_lift_eq_iff.{v (max u w)}] at h2, simp [h2.symm] at h1 ⊢, norm_cast at h1, simp at h1, exact h1 end lemma mk_compl_eq_mk_compl_finite {α β : Type u} {s : set α} {t : set β} (hα : #α < omega) (h1 : #α = #β) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set β) := by { rw [← lift_inj], apply mk_compl_eq_mk_compl_finite_lift hα; rw [lift_inj]; assumption } lemma mk_compl_eq_mk_compl_finite_same {α : Type*} {s t : set α} (hα : #α < omega) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set α) := mk_compl_eq_mk_compl_finite hα rfl h /-! ### Extending an injection to an equiv -/ theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β) (h : nonempty ((sᶜ : set α) ≃ ((range f)ᶜ : set β))) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin intros, have := h, cases this with g, let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans ((sum_congr (equiv.set.range f f.2) g).trans (set.sum_compl (range f))), refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx] end theorem extend_function_finite {α β : Type*} {s : set α} (f : s ↪ β) (hs : #α < omega) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift hs h], rw [mk_range_eq_lift], exact f.2 end theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin cases (le_or_lt omega (#α)) with hα hα, { apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, cases cardinal.eq.mp (mk_compl_of_omega_le s hα hs) with g2, cases cardinal.eq.mp (mk_compl_of_omega_le (range f) _ _) with g3, { constructor, exact g2.trans (g.trans g3.symm) }, { rw [← lift_le, ← h], refine le_trans _ (lift_le.mpr hα), simp }, rwa [← lift_lt, ← h, mk_range_eq_lift, lift_lt], exact f.2 }, { exact extend_function_finite f hα h } end section bit /-! This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases `simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good enough for practical situations, though. For specific numbers, these inequalities could also be deduced from the corresponding inequalities of natural numbers using `norm_cast`: ``` example : (37 : cardinal) < 42 := by { norm_cast, norm_num } ``` -/ @[simp] lemma bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 := by simp [bit0] @[simp] lemma bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 := by simp [bit1] @[simp] lemma zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a := by { rw ←not_iff_not, simp [bit0], } @[simp] lemma zero_lt_bit1 (a : cardinal) : 0 < bit1 a := lt_of_lt_of_le zero_lt_one (self_le_add_left _ _) @[simp] lemma one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a := ⟨λ h, (zero_lt_bit0 a).mp (lt_of_lt_of_le zero_lt_one h), λ h, le_trans (one_le_iff_pos.mpr h) (self_le_add_left a a)⟩ @[simp] lemma one_le_bit1 (a : cardinal) : 1 ≤ bit1 a := self_le_add_left _ _ theorem bit0_eq_self {c : cardinal} (h : omega ≤ c) : bit0 c = c := add_eq_self h @[simp] theorem bit0_lt_omega {c : cardinal} : bit0 c < omega ↔ c < omega := by simp [bit0, add_lt_omega_iff] @[simp] theorem omega_le_bit0 {c : cardinal} : omega ≤ bit0 c ↔ omega ≤ c := by { rw ← not_iff_not, simp } @[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ omega ≤ c := begin by_cases h : omega ≤ c, { simp only [bit1, bit0_eq_self h, h, eq_self_iff_true, add_one_of_omega_le] }, { simp only [h, iff_false], apply ne_of_gt, rcases lt_omega.1 (not_le.1 h) with ⟨n, rfl⟩, norm_cast, dsimp [bit1, bit0], linarith } end @[simp] theorem bit1_lt_omega {c : cardinal} : bit1 c < omega ↔ c < omega := by simp [bit1, bit0, add_lt_omega_iff, one_lt_omega] @[simp] theorem omega_le_bit1 {c : cardinal} : omega ≤ bit1 c ↔ omega ≤ c := by { rw ← not_iff_not, simp } @[simp] lemma bit0_le_bit0 {a b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb), have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit0_le_bit1 {a b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit1_eq_self_iff.2 hb], }, { rw bit0_eq_self ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb), have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_le_bit1 {a b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b := begin split, { assume h, apply bit0_le_bit1.1 (le_trans (self_le_add_right (bit0 a) 1) h) }, { assume h, calc a + a + 1 ≤ a + b + 1 : add_le_add_right (add_le_add_left h a) 1 ... ≤ b + b + 1 : add_le_add_right (add_le_add_right h b) 1 } end @[simp] lemma bit1_le_bit0 {a b : cardinal} : bit1 a ≤ bit0 b ↔ (a < b ∨ (a ≤ b ∧ omega ≤ a)) := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { simp only [bit1_eq_self_iff.mpr ha, bit0_eq_self hb, ha, and_true], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2, le_of_not_ge I1] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := lt_of_lt_of_le ha hb, have I2 : bit1 a ≤ b := le_trans (le_of_lt (bit1_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp [not_le.mpr ha], } end @[simp] lemma bit0_lt_bit0 {a b : cardinal} : bit0 a < bit0 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_trans ha (le_of_lt h) }, have I2 : ¬ (a < bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := lt_of_lt_of_le ha hb, have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_lt_bit0 {a b : cardinal} : bit1 a < bit0 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit1_eq_self_iff.2 ha, bit0_eq_self hb], }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_lt_bit1 {a b : cardinal} : bit1 a < bit1 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit1_eq_self_iff.2 ha, bit1_eq_self_iff.2 hb], }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit0_lt_bit1 {a b : cardinal} : bit0 a < bit1 b ↔ (a < b ∨ (a ≤ b ∧ a < omega)) := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { simp [bit0_eq_self ha, bit1_eq_self_iff.2 hb, not_lt.mpr ha] }, { rw bit0_eq_self ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2, not_lt.mpr ha] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp only [ha, and_true, nat.bit0_lt_bit1_iff], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } } end lemma one_lt_two : (1 : cardinal) < 2 := -- This strategy works generally to prove inequalities between numerals in `cardinality`. by { norm_cast, norm_num } @[simp] lemma one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a := by simp [← bit1_zero] @[simp] lemma one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a := by simp [← bit1_zero] @[simp] lemma one_le_one : (1 : cardinal) ≤ 1 := le_refl _ end bit end cardinal
3eef316d008fd0bbdf58c2e755fe36353679ba19
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Meta/SynthInstance.lean
c41280f84e37505bde0b4264900f6d8dbb76c0b4
[ "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
26,433
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Leonardo de Moura Type class instance synthesizer using tabled resolution. -/ import Lean.Meta.Basic import Lean.Meta.Instances import Lean.Meta.LevelDefEq import Lean.Meta.AbstractMVars import Lean.Meta.WHNF import Lean.Util.Profile namespace Lean.Meta register_builtin_option synthInstance.maxHeartbeats : Nat := { defValue := 500 descr := "maximum amount of heartbeats per typeclass resolution problem. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit" } register_builtin_option synthInstance.maxSize : Nat := { defValue := 128 descr := "maximum number of instances used to construct a solution in the type class instance synthesis procedure" } namespace SynthInstance def getMaxHeartbeats (opts : Options) : Nat := synthInstance.maxHeartbeats.get opts * 1000 open Std (HashMap) builtin_initialize inferTCGoalsRLAttr : TagAttribute ← registerTagAttribute `inferTCGoalsRL "instruct type class resolution procedure to solve goals from right to left for this instance" def hasInferTCGoalsRLAttribute (env : Environment) (constName : Name) : Bool := inferTCGoalsRLAttr.hasTag env constName structure GeneratorNode where mvar : Expr key : Expr mctx : MetavarContext instances : Array Expr currInstanceIdx : Nat deriving Inhabited structure ConsumerNode where mvar : Expr key : Expr mctx : MetavarContext subgoals : List Expr size : Nat -- instance size so far deriving Inhabited inductive Waiter where | consumerNode : ConsumerNode → Waiter | root : Waiter def Waiter.isRoot : Waiter → Bool | Waiter.consumerNode _ => false | Waiter.root => true /- In tabled resolution, we creating a mapping from goals (e.g., `Coe Nat ?x`) to answers and waiters. Waiters are consumer nodes that are waiting for answers for a particular node. We implement this mapping using a `HashMap` where the keys are normalized expressions. That is, we replace assignable metavariables with auxiliary free variables of the form `_tc.<idx>`. We do not declare these free variables in any local context, and we should view them as "normalized names" for metavariables. For example, the term `f ?m ?m ?n` is normalized as `f _tc.0 _tc.0 _tc.1`. This approach is structural, and we may visit the same goal more than once if the different occurrences are just definitionally equal, but not structurally equal. Remark: a metavariable is assignable only if its depth is equal to the metavar context depth. -/ namespace MkTableKey structure State where nextIdx : Nat := 0 lmap : HashMap MVarId Level := {} emap : HashMap MVarId Expr := {} abbrev M := ReaderT MetavarContext (StateM State) partial def normLevel (u : Level) : M Level := do if !u.hasMVar then pure u else match u with | Level.succ v _ => return u.updateSucc! (← normLevel v) | Level.max v w _ => return u.updateMax! (← normLevel v) (← normLevel w) | Level.imax v w _ => return u.updateIMax! (← normLevel v) (← normLevel w) | Level.mvar mvarId _ => let mctx ← read if !mctx.isLevelAssignable mvarId then pure u else let s ← get match s.lmap.find? mvarId with | some u' => pure u' | none => let u' := mkLevelParam $ Name.mkNum `_tc s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u' } pure u' | u => pure u partial def normExpr (e : Expr) : M Expr := do if !e.hasMVar then pure e else match e with | Expr.const _ us _ => return e.updateConst! (← us.mapM normLevel) | Expr.sort u _ => return e.updateSort! (← normLevel u) | Expr.app f a _ => return e.updateApp! (← normExpr f) (← normExpr a) | Expr.letE _ t v b _ => return e.updateLet! (← normExpr t) (← normExpr v) (← normExpr b) | Expr.forallE _ d b _ => return e.updateForallE! (← normExpr d) (← normExpr b) | Expr.lam _ d b _ => return e.updateLambdaE! (← normExpr d) (← normExpr b) | Expr.mdata _ b _ => return e.updateMData! (← normExpr b) | Expr.proj _ _ b _ => return e.updateProj! (← normExpr b) | Expr.mvar mvarId _ => let mctx ← read if !mctx.isExprAssignable mvarId then pure e else let s ← get match s.emap.find? mvarId with | some e' => pure e' | none => do let e' := mkFVar $ Name.mkNum `_tc s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e' } pure e' | _ => pure e end MkTableKey /- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/ def mkTableKey (mctx : MetavarContext) (e : Expr) : Expr := MkTableKey.normExpr e mctx |>.run' {} structure Answer where result : AbstractMVarsResult resultType : Expr size : Nat instance : Inhabited Answer where default := { result := arbitrary, resultType := arbitrary, size := 0 } structure TableEntry where waiters : Array Waiter answers : Array Answer := #[] structure Context where maxResultSize : Nat maxHeartbeats : Nat /- Remark: the SynthInstance.State is not really an extension of `Meta.State`. The field `postponed` is not needed, and the field `mctx` is misleading since `synthInstance` methods operate over different `MetavarContext`s simultaneously. That being said, we still use `extends` because it makes it simpler to move from `M` to `MetaM`. -/ structure State where result : Option Expr := none generatorStack : Array GeneratorNode := #[] resumeStack : Array (ConsumerNode × Answer) := #[] tableEntries : HashMap Expr TableEntry := {} abbrev SynthM := ReaderT Context $ StateRefT State MetaM def checkMaxHeartbeats : SynthM Unit := do Core.checkMaxHeartbeatsCore "typeclass" `synthInstance.maxHeartbeats (← read).maxHeartbeats @[inline] def mapMetaM (f : forall {α}, MetaM α → MetaM α) {α} : SynthM α → SynthM α := monadMap @f instance : Inhabited (SynthM α) where default := fun _ _ => arbitrary /-- Return globals and locals instances that may unify with `type` -/ def getInstances (type : Expr) : MetaM (Array Expr) := do -- We must retrieve `localInstances` before we use `forallTelescopeReducing` because it will update the set of local instances let localInstances ← getLocalInstances forallTelescopeReducing type fun _ type => do let className? ← isClass? type match className? with | none => throwError "type class instance expected{indentExpr type}" | some className => let globalInstances ← getGlobalInstancesIndex let result ← globalInstances.getUnify type -- Using insertion sort because it is stable and the array `result` should be mostly sorted. -- Most instances have default priority. let result := result.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority let result ← result.mapM fun e => match e.val with | Expr.const constName us _ => return e.val.updateConst! (← us.mapM (fun _ => mkFreshLevelMVar)) | _ => panic! "global instance is not a constant" trace[Meta.synthInstance.globalInstances] "{type}, {result}" let result := localInstances.foldl (init := result) fun (result : Array Expr) linst => if linst.className == className then result.push linst.fvar else result pure result def mkGeneratorNode? (key mvar : Expr) : MetaM (Option GeneratorNode) := do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType let instances ← getInstances mvarType if instances.isEmpty then pure none else let mctx ← getMCtx pure $ some { mvar := mvar, key := key, mctx := mctx, instances := instances, currInstanceIdx := instances.size } /-- Create a new generator node for `mvar` and add `waiter` as its waiter. `key` must be `mkTableKey mctx mvarType`. -/ def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit := withMCtx mctx do trace[Meta.synthInstance.newSubgoal] key match (← mkGeneratorNode? key mvar) with | none => pure () | some node => let entry : TableEntry := { waiters := #[waiter] } modify fun s => { s with generatorStack := s.generatorStack.push node, tableEntries := s.tableEntries.insert key entry } def findEntry? (key : Expr) : SynthM (Option TableEntry) := do return (← get).tableEntries.find? key def getEntry (key : Expr) : SynthM TableEntry := do match (← findEntry? key) with | none => panic! "invalid key at synthInstance" | some entry => pure entry /-- Create a `key` for the goal associated with the given metavariable. That is, we create a key for the type of the metavariable. We must instantiate assigned metavariables before we invoke `mkTableKey`. -/ def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr := withMCtx mctx do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType return mkTableKey mctx mvarType /- See `getSubgoals` and `getSubgoalsAux` We use the parameter `j` to reduce the number of `instantiate*` invocations. It is the same approach we use at `forallTelescope` and `lambdaTelescope`. Given `getSubgoalsAux args j subgoals instVal type`, we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/ structure SubgoalsResult where subgoals : List Expr instVal : Expr instTypeBody : Expr private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) : Array Expr → Nat → List Expr → Expr → Expr → MetaM SubgoalsResult | args, j, subgoals, instVal, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args let mvarType ← mkForallFVars xs d let mvar ← mkFreshExprMVarAt lctx localInsts mvarType let arg := mkAppN mvar xs let instVal := mkApp instVal arg let subgoals := if c.binderInfo.isInstImplicit then mvar::subgoals else subgoals let args := args.push (mkAppN mvar xs) getSubgoalsAux lctx localInsts xs args j subgoals instVal b | args, j, subgoals, instVal, type => do let type := type.instantiateRevRange j args.size args let type ← whnf type if type.isForall then getSubgoalsAux lctx localInsts xs args args.size subgoals instVal type else pure ⟨subgoals, instVal, type⟩ /-- `getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`. The subgoals are in the context of the free variables `xs`, and `(lctx, localInsts)` is the local context and instances before we added the free variables to it. This extra complication is required because 1- We want all metavariables created by `synthInstance` to share the same local context. 2- We want to ensure that applications such as `mvar xs` are higher order patterns. The method `getGoals` create a new metavariable for each parameter of `inst`. For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`. Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these metavariables that are instance implicit arguments, and the expressions: - `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`) - `B (?m_1 xs) ... (?m_n xs)` -/ def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do let instType ← inferType inst let result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType match inst.getAppFn with | Expr.const constName _ _ => let env ← getEnv if hasInferTCGoalsRLAttribute env constName then pure result else pure { result with subgoals := result.subgoals.reverse } | _ => pure result def tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do let mvarType ← inferType mvar let lctx ← getLCtx let localInsts ← getLocalInstances forallTelescopeReducing mvarType fun xs mvarTypeBody => do let ⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst trace[Meta.synthInstance.tryResolve] "{mvarTypeBody} =?= {instTypeBody}" if (← isDefEq mvarTypeBody instTypeBody) then let instVal ← mkLambdaFVars xs instVal if (← isDefEq mvar instVal) then trace[Meta.synthInstance.tryResolve] "success" pure (some ((← getMCtx), subgoals)) else trace[Meta.synthInstance.tryResolve] "failure assigning" pure none else trace[Meta.synthInstance.tryResolve] "failure" pure none /-- Try to synthesize metavariable `mvar` using the instance `inst`. Remark: `mctx` contains `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. A subgoal is created for each instance implicit parameter of `inst`. -/ def tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext × List Expr)) := traceCtx `Meta.synthInstance.tryResolve <| withMCtx mctx <| tryResolveCore mvar inst /-- Assign a precomputed answer to `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/ def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) := withMCtx mctx do let (_, _, val) ← openAbstractMVarsResult answer.result if (← isDefEq mvar val) then pure (some (← getMCtx)) else pure none /-- Move waiters that are waiting for the given answer to the resume stack. -/ def wakeUp (answer : Answer) : Waiter → SynthM Unit | Waiter.root => do if answer.result.paramNames.isEmpty && answer.result.numMVars == 0 then modify fun s => { s with result := answer.result.expr } else let (_, _, answerExpr) ← openAbstractMVarsResult answer.result trace[Meta.synthInstance] "skip answer containing metavariables {answerExpr}" pure () | Waiter.consumerNode cNode => modify fun s => { s with resumeStack := s.resumeStack.push (cNode, answer) } def isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool := oldAnswers.all fun oldAnswer => do -- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer` -- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq) oldAnswer.resultType != answer.resultType private def mkAnswer (cNode : ConsumerNode) : MetaM Answer := withMCtx cNode.mctx do traceM `Meta.synthInstance.newAnswer do m!"size: {cNode.size}, {← inferType cNode.mvar}" let val ← instantiateMVars cNode.mvar trace[Meta.synthInstance.newAnswer] "val: {val}" let result ← abstractMVars val -- assignable metavariables become parameters let resultType ← inferType result.expr pure { result := result, resultType := resultType, size := cNode.size + 1 } /-- Create a new answer after `cNode` resolved all subgoals. That is, `cNode.subgoals == []`. And then, store it in the tabled entries map, and wakeup waiters. -/ def addAnswer (cNode : ConsumerNode) : SynthM Unit := do if cNode.size ≥ (← read).maxResultSize then traceM `Meta.synthInstance.discarded do m!"size: {cNode.size} ≥ {(← read).maxResultSize}, {← inferType cNode.mvar}" return () else let answer ← mkAnswer cNode -- Remark: `answer` does not contain assignable or assigned metavariables. let key := cNode.key let entry ← getEntry key if isNewAnswer entry.answers answer then let newEntry := { entry with answers := entry.answers.push answer } modify fun s => { s with tableEntries := s.tableEntries.insert key newEntry } entry.waiters.forM (wakeUp answer) /-- Process the next subgoal in the given consumer node. -/ def consume (cNode : ConsumerNode) : SynthM Unit := match cNode.subgoals with | [] => addAnswer cNode | mvar::_ => do let waiter := Waiter.consumerNode cNode let key ← mkTableKeyFor cNode.mctx mvar let entry? ← findEntry? key match entry? with | none => newSubgoal cNode.mctx key mvar waiter | some entry => modify fun s => { s with resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack, tableEntries := s.tableEntries.insert key { entry with waiters := entry.waiters.push waiter } } def getTop : SynthM GeneratorNode := do pure (← get).generatorStack.back @[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit := modify fun s => { s with generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f } /-- Try the next instance in the node on the top of the generator stack. -/ def generate : SynthM Unit := do let gNode ← getTop if gNode.currInstanceIdx == 0 then modify fun s => { s with generatorStack := s.generatorStack.pop } else do let key := gNode.key let idx := gNode.currInstanceIdx - 1 let inst := gNode.instances.get! idx let mctx := gNode.mctx let mvar := gNode.mvar trace[Meta.synthInstance.generate] "instance {inst}" modifyTop fun gNode => { gNode with currInstanceIdx := idx } match (← tryResolve mctx mvar inst) with | none => pure () | some (mctx, subgoals) => consume { key := key, mvar := mvar, subgoals := subgoals, mctx := mctx, size := 0 } def getNextToResume : SynthM (ConsumerNode × Answer) := do let s ← get let r := s.resumeStack.back modify fun s => { s with resumeStack := s.resumeStack.pop } pure r /-- Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the next subgoal. -/ def resume : SynthM Unit := do let (cNode, answer) ← getNextToResume match cNode.subgoals with | [] => panic! "resume found no remaining subgoals" | mvar::rest => match (← tryAnswer cNode.mctx mvar answer) with | none => pure () | some mctx => withMCtx mctx <| traceM `Meta.synthInstance.resume do let goal ← inferType cNode.mvar let subgoal ← inferType mvar pure m!"size: {cNode.size + answer.size}, {goal} <== {subgoal}" consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx := mctx, size := cNode.size + answer.size } def step : SynthM Bool := do checkMaxHeartbeats let s ← get if !s.resumeStack.isEmpty then resume pure true else if !s.generatorStack.isEmpty then generate pure true else pure false def getResult : SynthM (Option Expr) := do pure (← get).result partial def synth : SynthM (Option Expr) := do if (← step) then match (← getResult) with | none => synth | some result => pure result else trace[Meta.synthInstance] "failed" pure none def main (type : Expr) (maxResultSize : Nat) : MetaM (Option Expr) := withCurrHeartbeats <| traceCtx `Meta.synthInstance do trace[Meta.synthInstance] "main goal {type}" let mvar ← mkFreshExprMVar type let mctx ← getMCtx let key := mkTableKey mctx type let action : SynthM (Option Expr) := do newSubgoal mctx key mvar Waiter.root synth action.run { maxResultSize := maxResultSize, maxHeartbeats := getMaxHeartbeats (← getOptions) } |>.run' {} end SynthInstance /- Type class parameters can be annotated with `outParam` annotations. Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF `a_i` is an `outParam`. The result is type correct because we reject type class declarations IF it contains a regular parameter X that depends on an `out` parameter Y. Then, we execute type class resolution as usual. If it succeeds, and metavariables ?m_i have been assigned, we try to unify the original type `C a_1 ... a_n` witht the normalized one. -/ private def preprocess (type : Expr) : MetaM Expr := forallTelescopeReducing type fun xs type => do let type ← whnf type mkForallFVars xs type private def preprocessLevels (us : List Level) : MetaM (List Level × Bool) := do let mut r := #[] let mut modified := false for u in us do let u ← instantiateLevelMVars u if u.hasMVar then r := r.push (← mkFreshLevelMVar) modified := true else r := r.push u return (r.toList, modified) private partial def preprocessArgs (type : Expr) (i : Nat) (args : Array Expr) : MetaM (Array Expr) := do if h : i < args.size then let type ← whnf type match type with | Expr.forallE _ d b _ => do let arg := args.get ⟨i, h⟩ let arg ← if isOutParam d then mkFreshExprMVar d else pure arg let args := args.set ⟨i, h⟩ arg preprocessArgs (b.instantiate1 arg) (i+1) args | _ => throwError "type class resolution failed, insufficient number of arguments" -- TODO improve error message else return args private def preprocessOutParam (type : Expr) : MetaM Expr := forallTelescope type fun xs typeBody => do match typeBody.getAppFn with | c@(Expr.const constName us _) => let env ← getEnv if !hasOutParams env constName then /- We treat all universe level parameters as "outParam" -/ let (us, modified) ← preprocessLevels us if modified then let c := mkConst constName us mkForallFVars xs (mkAppN c typeBody.getAppArgs) else return type else do let args := typeBody.getAppArgs let (us, _) ← preprocessLevels us let c := mkConst constName us let cType ← inferType c let args ← preprocessArgs cType 0 args mkForallFVars xs (mkAppN c args) | _ => return type /- Remark: when `maxResultSize? == none`, the configuration option `synthInstance.maxResultSize` is used. Remark: we use a different option for controlling the maximum result size for coercions. -/ def synthInstance? (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (Option Expr) := do profileitM Exception "typeclass inference" (← getOptions) do let opts ← getOptions let maxResultSize := maxResultSize?.getD (synthInstance.maxSize.get opts) let inputConfig ← getConfig withConfig (fun config => { config with isDefEqStuckEx := true, transparency := TransparencyMode.instances, foApprox := true, ctxApprox := true, constApprox := false }) do let type ← instantiateMVars type let type ← preprocess type let s ← get match s.cache.synthInstance.find? type with | some result => pure result | none => let result? ← withNewMCtxDepth do let normType ← preprocessOutParam type trace[Meta.synthInstance] "{type} ==> {normType}" match (← SynthInstance.main normType maxResultSize) with | none => pure none | some result => trace[Meta.synthInstance] "FOUND result {result}" let result ← instantiateMVars result if (← hasAssignableMVar result) then trace[Meta.synthInstance] "Failed has assignable mvar {result.setOption `pp.all true}" pure none else pure (some result) let result? ← match result? with | none => pure none | some result => do trace[Meta.synthInstance] "result {result}" let resultType ← inferType result if (← withConfig (fun _ => inputConfig) <| isDefEq type resultType) then let result ← instantiateMVars result pure (some result) else trace[Meta.synthInstance] "result type{indentExpr resultType}\nis not definitionally equal to{indentExpr type}" pure none if type.hasMVar then pure result? else do modify fun s => { s with cache := { s.cache with synthInstance := s.cache.synthInstance.insert type result? } } pure result? /-- Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if instance cannot be synthesized right now because `type` contains metavariables. -/ def trySynthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (LOption Expr) := do catchInternalId isDefEqStuckExceptionId (toLOptionM <| synthInstance? type maxResultSize?) (fun _ => pure LOption.undef) def synthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM Expr := catchInternalId isDefEqStuckExceptionId (do let result? ← synthInstance? type maxResultSize? match result? with | some result => pure result | none => throwError "failed to synthesize{indentExpr type}") (fun _ => throwError "failed to synthesize{indentExpr type}") private def synthPendingImp (mvarId : MVarId) (maxResultSize? : Option Nat) : MetaM Bool := do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.synthetic => match (← isClass? mvarDecl.type) with | none => pure false | some _ => do let val? ← catchInternalId isDefEqStuckExceptionId (synthInstance? mvarDecl.type maxResultSize?) (fun _ => pure none) match val? with | none => pure false | some val => if (← isExprMVarAssigned mvarId) then pure false else assignExprMVar mvarId val pure true | _ => pure false builtin_initialize synthPendingRef.set (synthPendingImp · none) builtin_initialize registerTraceClass `Meta.synthInstance registerTraceClass `Meta.synthInstance.globalInstances registerTraceClass `Meta.synthInstance.newSubgoal registerTraceClass `Meta.synthInstance.tryResolve registerTraceClass `Meta.synthInstance.resume registerTraceClass `Meta.synthInstance.generate end Lean.Meta
d9814d4bb12e1581b93da5df949bdfae57b9d27f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/star/subalgebra.lean
7356d1122fe090591f35f8a1caef43a0b72de5b2
[ "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
26,787
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Jireh Loreaux -/ import algebra.star.star_alg_hom import algebra.algebra.subalgebra.basic import algebra.star.pointwise import algebra.star.module import ring_theory.adjoin.basic /-! # Star subalgebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A *-subalgebra is a subalgebra of a *-algebra which is closed under *. The centralizer of a *-closed set is a *-subalgebra. -/ universes u v set_option old_structure_cmd true /-- A *-subalgebra is a subalgebra of a *-algebra which is closed under *. -/ structure star_subalgebra (R : Type u) (A : Type v) [comm_semiring R] [star_ring R] [semiring A] [star_ring A] [algebra R A] [star_module R A] extends subalgebra R A : Type v := (star_mem' {a} : a ∈ carrier → star a ∈ carrier) namespace star_subalgebra /-- Forgetting that a *-subalgebra is closed under *. -/ add_decl_doc star_subalgebra.to_subalgebra variables {F R A B C : Type*} [comm_semiring R] [star_ring R] variables [semiring A] [star_ring A] [algebra R A] [star_module R A] variables [semiring B] [star_ring B] [algebra R B] [star_module R B] variables [semiring C] [star_ring C] [algebra R C] [star_module R C] instance : set_like (star_subalgebra R A) A := ⟨star_subalgebra.carrier, λ p q h, by cases p; cases q; congr'⟩ instance : star_mem_class (star_subalgebra R A) A := { star_mem := λ s a, s.star_mem' } instance : subsemiring_class (star_subalgebra R A) A := { add_mem := add_mem', mul_mem := mul_mem', one_mem := one_mem', zero_mem := zero_mem' } instance {R A} [comm_ring R] [star_ring R] [ring A] [star_ring A] [algebra R A] [star_module R A] : subring_class (star_subalgebra R A) A := { neg_mem := λ s a ha, show -a ∈ s.to_subalgebra, from neg_mem ha } -- this uses the `has_star` instance `s` inherits from `star_mem_class (star_subalgebra R A) A` instance (s : star_subalgebra R A) : star_ring s := { star := star, star_involutive := λ r, subtype.ext (star_star r), star_mul := λ r₁ r₂, subtype.ext (star_mul r₁ r₂), star_add := λ r₁ r₂, subtype.ext (star_add r₁ r₂) } instance (s : star_subalgebra R A) : algebra R s := s.to_subalgebra.algebra' instance (s : star_subalgebra R A) : star_module R s := { star_smul := λ r a, subtype.ext (star_smul r a) } @[simp] lemma mem_carrier {s : star_subalgebra R A} {x : A} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[ext] theorem ext {S T : star_subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h @[simp] lemma mem_to_subalgebra {S : star_subalgebra R A} {x} : x ∈ S.to_subalgebra ↔ x ∈ S := iff.rfl @[simp] lemma coe_to_subalgebra (S : star_subalgebra R A) : (S.to_subalgebra : set A) = S := rfl theorem to_subalgebra_injective : function.injective (to_subalgebra : star_subalgebra R A → subalgebra R A) := λ S T h, ext $ λ x, by rw [← mem_to_subalgebra, ← mem_to_subalgebra, h] theorem to_subalgebra_inj {S U : star_subalgebra R A} : S.to_subalgebra = U.to_subalgebra ↔ S = U := to_subalgebra_injective.eq_iff lemma to_subalgebra_le_iff {S₁ S₂ : star_subalgebra R A} : S₁.to_subalgebra ≤ S₂.to_subalgebra ↔ S₁ ≤ S₂ := iff.rfl /-- Copy of a star subalgebra with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : star_subalgebra R A) (s : set A) (hs : s = ↑S) : star_subalgebra R A := { carrier := s, add_mem' := λ _ _, hs.symm ▸ S.add_mem', mul_mem' := λ _ _, hs.symm ▸ S.mul_mem', algebra_map_mem' := hs.symm ▸ S.algebra_map_mem', star_mem' := λ _, hs.symm ▸ S.star_mem' } @[simp] lemma coe_copy (S : star_subalgebra R A) (s : set A) (hs : s = ↑S) : (S.copy s hs : set A) = s := rfl lemma copy_eq (S : star_subalgebra R A) (s : set A) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs variables (S : star_subalgebra R A) theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S := S.algebra_map_mem' r theorem srange_le : (algebra_map R A).srange ≤ S.to_subalgebra.to_subsemiring := λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r theorem range_subset : set.range (algebra_map R A) ⊆ S := λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r theorem range_le : set.range (algebra_map R A) ≤ S := S.range_subset protected theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S := (algebra.smul_def r x).symm ▸ mul_mem (S.algebra_map_mem r) hx /-- Embedding of a subalgebra into the algebra. -/ def subtype : S →⋆ₐ[R] A := by refine_struct { to_fun := (coe : S → A) }; intros; refl @[simp] lemma coe_subtype : (S.subtype : S → A) = coe := rfl lemma subtype_apply (x : S) : S.subtype x = (x : A) := rfl @[simp] lemma to_subalgebra_subtype : S.to_subalgebra.val = S.subtype.to_alg_hom := rfl /-- The inclusion map between `star_subalgebra`s given by `subtype.map id` as a `star_alg_hom`. -/ @[simps] def inclusion {S₁ S₂ : star_subalgebra R A} (h : S₁ ≤ S₂) : S₁ →⋆ₐ[R] S₂ := { to_fun := subtype.map id h, map_one' := rfl, map_mul' := λ x y, rfl, map_zero' := rfl, map_add' := λ x y, rfl, commutes' := λ z, rfl, map_star' := λ x, rfl } lemma inclusion_injective {S₁ S₂ : star_subalgebra R A} (h : S₁ ≤ S₂) : function.injective $ inclusion h := set.inclusion_injective h @[simp] lemma subtype_comp_inclusion {S₁ S₂ : star_subalgebra R A} (h : S₁ ≤ S₂) : S₂.subtype.comp (inclusion h) = S₁.subtype := rfl section map /-- Transport a star subalgebra via a star algebra homomorphism. -/ def map (f : A →⋆ₐ[R] B) (S : star_subalgebra R A) : star_subalgebra R B := { star_mem' := begin rintro _ ⟨a, ha, rfl⟩, exact map_star f a ▸ set.mem_image_of_mem _ (S.star_mem' ha), end, .. S.to_subalgebra.map f.to_alg_hom } lemma map_mono {S₁ S₂ : star_subalgebra R A} {f : A →⋆ₐ[R] B} : S₁ ≤ S₂ → S₁.map f ≤ S₂.map f := set.image_subset f lemma map_injective {f : A →⋆ₐ[R] B} (hf : function.injective f) : function.injective (map f) := λ S₁ S₂ ih, ext $ set.ext_iff.1 $ set.image_injective.2 hf $ set.ext $ set_like.ext_iff.mp ih @[simp] lemma map_id (S : star_subalgebra R A) : S.map (star_alg_hom.id R A) = S := set_like.coe_injective $ set.image_id _ lemma map_map (S : star_subalgebra R A) (g : B →⋆ₐ[R] C) (f : A →⋆ₐ[R] B) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma mem_map {S : star_subalgebra R A} {f : A →⋆ₐ[R] B} {y : B} : y ∈ map f S ↔ ∃ x ∈ S, f x = y := subsemiring.mem_map lemma map_to_subalgebra {S : star_subalgebra R A} {f : A →⋆ₐ[R] B} : (S.map f).to_subalgebra = S.to_subalgebra.map f.to_alg_hom := set_like.coe_injective rfl @[simp] lemma coe_map (S : star_subalgebra R A) (f : A →⋆ₐ[R] B) : (S.map f : set B) = f '' S := rfl /-- Preimage of a star subalgebra under an star algebra homomorphism. -/ def comap (f : A →⋆ₐ[R] B) (S : star_subalgebra R B) : star_subalgebra R A := { star_mem' := λ a ha, show f (star a) ∈ S, from (map_star f a).symm ▸ star_mem ha, .. S.to_subalgebra.comap f.to_alg_hom } theorem map_le_iff_le_comap {S : star_subalgebra R A} {f : A →⋆ₐ[R] B} {U : star_subalgebra R B} : map f S ≤ U ↔ S ≤ comap f U := set.image_subset_iff lemma gc_map_comap (f : A →⋆ₐ[R] B) : galois_connection (map f) (comap f) := λ S U, map_le_iff_le_comap lemma comap_mono {S₁ S₂ : star_subalgebra R B} {f : A →⋆ₐ[R] B} : S₁ ≤ S₂ → S₁.comap f ≤ S₂.comap f := set.preimage_mono lemma comap_injective {f : A →⋆ₐ[R] B} (hf : function.surjective f) : function.injective (comap f) := λ S₁ S₂ h, ext $ λ b, let ⟨x, hx⟩ := hf b in let this := set_like.ext_iff.1 h x in hx ▸ this @[simp] lemma comap_id (S : star_subalgebra R A) : S.comap (star_alg_hom.id R A) = S := set_like.coe_injective $ set.preimage_id lemma comap_comap (S : star_subalgebra R C) (g : B →⋆ₐ[R] C) (f : A →⋆ₐ[R] B) : (S.comap g).comap f = S.comap (g.comp f) := set_like.coe_injective $ set.preimage_preimage @[simp] lemma mem_comap (S : star_subalgebra R B) (f : A →⋆ₐ[R] B) (x : A) : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[simp, norm_cast] lemma coe_comap (S : star_subalgebra R B) (f : A →⋆ₐ[R] B) : (S.comap f : set A) = f ⁻¹' (S : set B) := rfl end map section centralizer variables (R) {A} lemma _root_.set.star_mem_centralizer {a : A} {s : set A} (h : ∀ (a : A), a ∈ s → star a ∈ s) (ha : a ∈ set.centralizer s) : star a ∈ set.centralizer s := λ y hy, by simpa using congr_arg star (ha _ (h _ hy)).symm /-- The centralizer, or commutant, of a *-closed set as star subalgebra. -/ def centralizer (s : set A) (w : ∀ (a : A), a ∈ s → star a ∈ s) : star_subalgebra R A := { star_mem' := λ x, set.star_mem_centralizer w, ..subalgebra.centralizer R s, } @[simp] lemma coe_centralizer (s : set A) (w : ∀ (a : A), a ∈ s → star a ∈ s) : (centralizer R s w : set A) = s.centralizer := rfl lemma mem_centralizer_iff {s : set A} {w} {z : A} : z ∈ centralizer R s w ↔ ∀ g ∈ s, g * z = z * g := iff.rfl lemma centralizer_le (s t : set A) (ws : ∀ (a : A), a ∈ s → star a ∈ s) (wt : ∀ (a : A), a ∈ t → star a ∈ t) (h : s ⊆ t) : centralizer R t wt ≤ centralizer R s ws := set.centralizer_subset h end centralizer end star_subalgebra /-! ### The star closure of a subalgebra -/ namespace subalgebra open_locale pointwise variables {F R A B : Type*} [comm_semiring R] [star_ring R] variables [semiring A] [algebra R A] [star_ring A] [star_module R A] variables [semiring B] [algebra R B] [star_ring B] [star_module R B] /-- The pointwise `star` of a subalgebra is a subalgebra. -/ instance : has_involutive_star (subalgebra R A) := { star := λ S, { carrier := star S.carrier, mul_mem' := λ x y hx hy, begin simp only [set.mem_star, subalgebra.mem_carrier] at *, exact (star_mul x y).symm ▸ mul_mem hy hx, end, one_mem' := set.mem_star.mp ((star_one A).symm ▸ one_mem S : star (1 : A) ∈ S), add_mem' := λ x y hx hy, begin simp only [set.mem_star, subalgebra.mem_carrier] at *, exact (star_add x y).symm ▸ add_mem hx hy, end, zero_mem' := set.mem_star.mp ((star_zero A).symm ▸ zero_mem S : star (0 : A) ∈ S), algebra_map_mem' := λ r, by simpa only [set.mem_star, subalgebra.mem_carrier, ←algebra_map_star_comm] using S.algebra_map_mem (star r) }, star_involutive := λ S, subalgebra.ext $ λ x, ⟨λ hx, (star_star x ▸ hx), λ hx, ((star_star x).symm ▸ hx : star (star x) ∈ S)⟩ } @[simp] lemma mem_star_iff (S : subalgebra R A) (x : A) : x ∈ star S ↔ star x ∈ S := iff.rfl @[simp] lemma star_mem_star_iff (S : subalgebra R A) (x : A) : star x ∈ star S ↔ x ∈ S := by simpa only [star_star] using mem_star_iff S (star x) @[simp] lemma coe_star (S : subalgebra R A) : ((star S : subalgebra R A) : set A) = star S := rfl lemma star_mono : monotone (star : subalgebra R A → subalgebra R A) := λ _ _ h _ hx, h hx variables (R) /-- The star operation on `subalgebra` commutes with `algebra.adjoin`. -/ lemma star_adjoin_comm (s : set A) : star (algebra.adjoin R s) = algebra.adjoin R (star s) := have this : ∀ t : set A, algebra.adjoin R (star t) ≤ star (algebra.adjoin R t), from λ t, algebra.adjoin_le (λ x hx, algebra.subset_adjoin hx), le_antisymm (by simpa only [star_star] using subalgebra.star_mono (this (star s))) (this s) variables {R} /-- The `star_subalgebra` obtained from `S : subalgebra R A` by taking the smallest subalgebra containing both `S` and `star S`. -/ @[simps] def star_closure (S : subalgebra R A) : star_subalgebra R A := { star_mem' := λ a ha, begin simp only [subalgebra.mem_carrier, ←(@algebra.gi R A _ _ _).l_sup_u _ _] at *, rw [←mem_star_iff _ a, star_adjoin_comm], convert ha, simp [set.union_comm], end, .. S ⊔ star S } lemma star_closure_le {S₁ : subalgebra R A} {S₂ : star_subalgebra R A} (h : S₁ ≤ S₂.to_subalgebra) : S₁.star_closure ≤ S₂ := star_subalgebra.to_subalgebra_le_iff.1 $ sup_le h $ λ x hx, (star_star x ▸ star_mem (show star x ∈ S₂, from h $ (S₁.mem_star_iff _).1 hx) : x ∈ S₂) lemma star_closure_le_iff {S₁ : subalgebra R A} {S₂ : star_subalgebra R A} : S₁.star_closure ≤ S₂ ↔ S₁ ≤ S₂.to_subalgebra := ⟨λ h, le_sup_left.trans h, star_closure_le⟩ end subalgebra /-! ### The star subalgebra generated by a set -/ namespace star_subalgebra variables {F R A B : Type*} [comm_semiring R] [star_ring R] variables [semiring A] [algebra R A] [star_ring A] [star_module R A] variables [semiring B] [algebra R B] [star_ring B] [star_module R B] variables (R) /-- The minimal star subalgebra that contains `s`. -/ @[simps] def adjoin (s : set A) : star_subalgebra R A := { star_mem' := λ x hx, by rwa [subalgebra.mem_carrier, ←subalgebra.mem_star_iff, subalgebra.star_adjoin_comm, set.union_star, star_star, set.union_comm], .. (algebra.adjoin R (s ∪ star s)) } lemma adjoin_eq_star_closure_adjoin (s : set A) : adjoin R s = (algebra.adjoin R s).star_closure := to_subalgebra_injective $ show algebra.adjoin R (s ∪ star s) = algebra.adjoin R s ⊔ star (algebra.adjoin R s), from (subalgebra.star_adjoin_comm R s).symm ▸ algebra.adjoin_union s (star s) lemma adjoin_to_subalgebra (s : set A) : (adjoin R s).to_subalgebra = (algebra.adjoin R (s ∪ star s)) := rfl lemma subset_adjoin (s : set A) : s ⊆ adjoin R s := (set.subset_union_left s (star s)).trans algebra.subset_adjoin lemma star_subset_adjoin (s : set A) : star s ⊆ adjoin R s := (set.subset_union_right s (star s)).trans algebra.subset_adjoin lemma self_mem_adjoin_singleton (x : A) : x ∈ adjoin R ({x} : set A) := algebra.subset_adjoin $ set.mem_union_left _ (set.mem_singleton x) lemma star_self_mem_adjoin_singleton (x : A) : star x ∈ adjoin R ({x} : set A) := star_mem $ self_mem_adjoin_singleton R x variables {R} protected lemma gc : galois_connection (adjoin R : set A → star_subalgebra R A) coe := begin intros s S, rw [←to_subalgebra_le_iff, adjoin_to_subalgebra, algebra.adjoin_le_iff, coe_to_subalgebra], exact ⟨λ h, (set.subset_union_left s _).trans h, λ h, set.union_subset h $ λ x hx, star_star x ▸ star_mem (show star x ∈ S, from h hx)⟩, end /-- Galois insertion between `adjoin` and `coe`. -/ protected def gi : galois_insertion (adjoin R : set A → star_subalgebra R A) coe := { choice := λ s hs, (adjoin R s).copy s $ le_antisymm (star_subalgebra.gc.le_u_l s) hs, gc := star_subalgebra.gc, le_l_u := λ S, (star_subalgebra.gc (S : set A) (adjoin R S)).1 $ le_rfl, choice_eq := λ _ _, star_subalgebra.copy_eq _ _ _ } lemma adjoin_le {S : star_subalgebra R A} {s : set A} (hs : s ⊆ S) : adjoin R s ≤ S := star_subalgebra.gc.l_le hs lemma adjoin_le_iff {S : star_subalgebra R A} {s : set A} : adjoin R s ≤ S ↔ s ⊆ S := star_subalgebra.gc _ _ lemma _root_.subalgebra.star_closure_eq_adjoin (S : subalgebra R A) : S.star_closure = adjoin R (S : set A) := le_antisymm (subalgebra.star_closure_le_iff.2 $ subset_adjoin R (S : set A)) (adjoin_le (le_sup_left : S ≤ S ⊔ star S)) /-- If some predicate holds for all `x ∈ (s : set A)` and this predicate is closed under the `algebra_map`, addition, multiplication and star operations, then it holds for `a ∈ adjoin R s`. -/ lemma adjoin_induction {s : set A} {p : A → Prop} {a : A} (h : a ∈ adjoin R s) (Hs : ∀ (x : A), x ∈ s → p x) (Halg : ∀ (r : R), p (algebra_map R A r)) (Hadd : ∀ (x y : A), p x → p y → p (x + y)) (Hmul : ∀ (x y : A), p x → p y → p (x * y)) (Hstar : ∀ (x : A), p x → p (star x)) : p a := algebra.adjoin_induction h (λ x hx, hx.elim (λ hx, Hs x hx) (λ hx, star_star x ▸ Hstar _ (Hs _ hx))) Halg Hadd Hmul lemma adjoin_induction₂ {s : set A} {p : A → A → Prop} {a b : A} (ha : a ∈ adjoin R s) (hb : b ∈ adjoin R s) (Hs : ∀ (x : A), x ∈ s → ∀ (y : A), y ∈ s → p x y) (Halg : ∀ (r₁ r₂ : R), p (algebra_map R A r₁) (algebra_map R A r₂)) (Halg_left : ∀ (r : R) (x : A), x ∈ s → p (algebra_map R A r) x) (Halg_right : ∀ (r : R) (x : A), x ∈ s → p x (algebra_map R A r)) (Hadd_left : ∀ (x₁ x₂ y : A), p x₁ y → p x₂ y → p (x₁ + x₂) y) (Hadd_right : ∀ (x y₁ y₂ : A), p x y₁ → p x y₂ → p x (y₁ + y₂)) (Hmul_left : ∀ (x₁ x₂ y : A), p x₁ y → p x₂ y → p (x₁ * x₂) y) (Hmul_right : ∀ (x y₁ y₂ : A), p x y₁ → p x y₂ → p x (y₁ * y₂)) (Hstar : ∀ (x y : A), p x y → p (star x) (star y)) (Hstar_left : ∀ (x y : A), p x y → p (star x) y) (Hstar_right : ∀ (x y : A), p x y → p x (star y)) : p a b := begin refine algebra.adjoin_induction₂ ha hb (λ x hx y hy, _) Halg (λ r x hx, _) (λ r x hx, _) Hadd_left Hadd_right Hmul_left Hmul_right, { cases hx; cases hy, exacts [Hs x hx y hy, star_star y ▸ Hstar_right _ _ (Hs _ hx _ hy), star_star x ▸ Hstar_left _ _ (Hs _ hx _ hy), star_star x ▸ star_star y ▸ Hstar _ _ (Hs _ hx _ hy)] }, { cases hx, exacts [Halg_left _ _ hx, star_star x ▸ Hstar_right _ _ (Halg_left r _ hx)] }, { cases hx, exacts [Halg_right _ _ hx, star_star x ▸ Hstar_left _ _ (Halg_right r _ hx)] }, end /-- The difference with `star_subalgebra.adjoin_induction` is that this acts on the subtype. -/ lemma adjoin_induction' {s : set A} {p : adjoin R s → Prop} (a : adjoin R s) (Hs : ∀ x (h : x ∈ s), p ⟨x, subset_adjoin R s h⟩) (Halg : ∀ r, p (algebra_map R _ r)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hstar : ∀ x, p x → p (star x)) : p a := subtype.rec_on a $ λ b hb, begin refine exists.elim _ (λ (hb : b ∈ adjoin R s) (hc : p ⟨b, hb⟩), hc), apply adjoin_induction hb, exacts [λ x hx, ⟨subset_adjoin R s hx, Hs x hx⟩, λ r, ⟨star_subalgebra.algebra_map_mem _ r, Halg r⟩, (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨add_mem hx' hy', Hadd _ _ hx hy⟩), (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨mul_mem hx' hy', Hmul _ _ hx hy⟩), λ x hx, exists.elim hx (λ hx' hx, ⟨star_mem hx', Hstar _ hx⟩)] end variables (R) /-- If all elements of `s : set A` commute pairwise and also commute pairwise with elements of `star s`, then `star_subalgebra.adjoin R s` is commutative. See note [reducible non-instances]. -/ @[reducible] def adjoin_comm_semiring_of_comm {s : set A} (hcomm : ∀ (a : A), a ∈ s → ∀ (b : A), b ∈ s → a * b = b * a) (hcomm_star : ∀ (a : A), a ∈ s → ∀ (b : A), b ∈ s → a * star b = star b * a) : comm_semiring (adjoin R s) := { mul_comm := begin rintro ⟨x, hx⟩ ⟨y, hy⟩, ext, simp only [set_like.coe_mk, mul_mem_class.mk_mul_mk], rw [←mem_to_subalgebra, adjoin_to_subalgebra] at hx hy, letI : comm_semiring (algebra.adjoin R (s ∪ star s)) := algebra.adjoin_comm_semiring_of_comm R begin intros a ha b hb, cases ha; cases hb, exacts [hcomm _ ha _ hb, star_star b ▸ hcomm_star _ ha _ hb, star_star a ▸ (hcomm_star _ hb _ ha).symm, by simpa only [star_mul, star_star] using congr_arg star (hcomm _ hb _ ha)], end, exact congr_arg coe (mul_comm (⟨x, hx⟩ : algebra.adjoin R (s ∪ star s)) ⟨y, hy⟩), end, ..(adjoin R s).to_subalgebra.to_semiring } /-- If all elements of `s : set A` commute pairwise and also commute pairwise with elements of `star s`, then `star_subalgebra.adjoin R s` is commutative. See note [reducible non-instances]. -/ @[reducible] def adjoin_comm_ring_of_comm (R : Type u) {A : Type v} [comm_ring R] [star_ring R] [ring A] [algebra R A] [star_ring A] [star_module R A] {s : set A} (hcomm : ∀ (a : A), a ∈ s → ∀ (b : A), b ∈ s → a * b = b * a) (hcomm_star : ∀ (a : A), a ∈ s → ∀ (b : A), b ∈ s → a * star b = star b * a) : comm_ring (adjoin R s) := { ..star_subalgebra.adjoin_comm_semiring_of_comm R hcomm hcomm_star, ..(adjoin R s).to_subalgebra.to_ring } /-- The star subalgebra `star_subalgebra.adjoin R {x}` generated by a single `x : A` is commutative if `x` is normal. -/ instance adjoin_comm_semiring_of_is_star_normal (x : A) [is_star_normal x] : comm_semiring (adjoin R ({x} : set A)) := adjoin_comm_semiring_of_comm R (λ a ha b hb, by { rw [set.mem_singleton_iff] at ha hb, rw [ha, hb] }) (λ a ha b hb, by { rw [set.mem_singleton_iff] at ha hb, simpa only [ha, hb] using (star_comm_self' x).symm }) /-- The star subalgebra `star_subalgebra.adjoin R {x}` generated by a single `x : A` is commutative if `x` is normal. -/ instance adjoin_comm_ring_of_is_star_normal (R : Type u) {A : Type v} [comm_ring R] [star_ring R] [ring A] [algebra R A] [star_ring A] [star_module R A] (x : A) [is_star_normal x] : comm_ring (adjoin R ({x} : set A)) := { mul_comm := mul_comm, ..(adjoin R ({x} : set A)).to_subalgebra.to_ring } /-! ### Complete lattice structure -/ variables {F R A B} instance : complete_lattice (star_subalgebra R A) := galois_insertion.lift_complete_lattice star_subalgebra.gi instance : inhabited (star_subalgebra R A) := ⟨⊤⟩ @[simp] lemma coe_top : (↑(⊤ : star_subalgebra R A) : set A) = set.univ := rfl @[simp] lemma mem_top {x : A} : x ∈ (⊤ : star_subalgebra R A) := set.mem_univ x @[simp] lemma top_to_subalgebra : (⊤ : star_subalgebra R A).to_subalgebra = ⊤ := rfl @[simp] lemma to_subalgebra_eq_top {S : star_subalgebra R A} : S.to_subalgebra = ⊤ ↔ S = ⊤ := star_subalgebra.to_subalgebra_injective.eq_iff' top_to_subalgebra lemma mem_sup_left {S T : star_subalgebra R A} : ∀ {x : A}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : star_subalgebra R A} : ∀ {x : A}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mul_mem_sup {S T : star_subalgebra R A} {x y : A} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T := mul_mem (mem_sup_left hx) (mem_sup_right hy) lemma map_sup (f : A →⋆ₐ[R] B) (S T : star_subalgebra R A) : map f (S ⊔ T) = map f S ⊔ map f T := (star_subalgebra.gc_map_comap f).l_sup @[simp, norm_cast] lemma coe_inf (S T : star_subalgebra R A) : (↑(S ⊓ T) : set A) = S ∩ T := rfl @[simp] lemma mem_inf {S T : star_subalgebra R A} {x : A} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl @[simp] lemma inf_to_subalgebra (S T : star_subalgebra R A) : (S ⊓ T).to_subalgebra = S.to_subalgebra ⊓ T.to_subalgebra := rfl @[simp, norm_cast] lemma coe_Inf (S : set (star_subalgebra R A)) : (↑(Inf S) : set A) = ⋂ s ∈ S, ↑s := Inf_image lemma mem_Inf {S : set (star_subalgebra R A)} {x : A} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := by simp only [← set_like.mem_coe, coe_Inf, set.mem_Inter₂] @[simp] lemma Inf_to_subalgebra (S : set (star_subalgebra R A)) : (Inf S).to_subalgebra = Inf (star_subalgebra.to_subalgebra '' S) := set_like.coe_injective $ by simp @[simp, norm_cast] lemma coe_infi {ι : Sort*} {S : ι → star_subalgebra R A} : (↑(⨅ i, S i) : set A) = ⋂ i, S i := by simp [infi] lemma mem_infi {ι : Sort*} {S : ι → star_subalgebra R A} {x : A} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp] lemma infi_to_subalgebra {ι : Sort*} (S : ι → star_subalgebra R A) : (⨅ i, S i).to_subalgebra = ⨅ i, (S i).to_subalgebra := set_like.coe_injective $ by simp lemma bot_to_subalgebra : (⊥ : star_subalgebra R A).to_subalgebra = ⊥ := by { change algebra.adjoin R (∅ ∪ star ∅) = algebra.adjoin R ∅, simp } theorem mem_bot {x : A} : x ∈ (⊥ : star_subalgebra R A) ↔ x ∈ set.range (algebra_map R A) := by rw [←mem_to_subalgebra, bot_to_subalgebra, algebra.mem_bot] @[simp] theorem coe_bot : ((⊥ : star_subalgebra R A) : set A) = set.range (algebra_map R A) := by simp [set.ext_iff, mem_bot] theorem eq_top_iff {S : star_subalgebra R A} : S = ⊤ ↔ ∀ x : A, x ∈ S := ⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩ end star_subalgebra namespace star_alg_hom open star_subalgebra variables {F R A B : Type*} [comm_semiring R] [star_ring R] variables [semiring A] [algebra R A] [star_ring A] [star_module R A] variables [semiring B] [algebra R B] [star_ring B] variables [hF : star_alg_hom_class F R A B] (f g : F) include hF /-- The equalizer of two star `R`-algebra homomorphisms. -/ def equalizer : star_subalgebra R A := { carrier := {a | f a = g a}, mul_mem' := λ a b (ha : f a = g a) (hb : f b = g b), by rw [set.mem_set_of_eq, map_mul f, map_mul g, ha, hb], add_mem' := λ a b (ha : f a = g a) (hb : f b = g b), by rw [set.mem_set_of_eq, map_add f, map_add g, ha, hb], algebra_map_mem' := λ r, by simp only [set.mem_set_of_eq, alg_hom_class.commutes], star_mem' := λ a (ha : f a = g a), by rw [set.mem_set_of_eq, map_star f, map_star g, ha] } @[simp] lemma mem_equalizer (x : A) : x ∈ star_alg_hom.equalizer f g ↔ f x = g x := iff.rfl lemma adjoin_le_equalizer {s : set A} (h : s.eq_on f g) : adjoin R s ≤ star_alg_hom.equalizer f g := adjoin_le h lemma ext_of_adjoin_eq_top {s : set A} (h : adjoin R s = ⊤) ⦃f g : F⦄ (hs : s.eq_on f g) : f = g := fun_like.ext f g $ λ x, star_alg_hom.adjoin_le_equalizer f g hs $ h.symm ▸ trivial omit hF lemma map_adjoin [star_module R B] (f : A →⋆ₐ[R] B) (s : set A) : map f (adjoin R s) = adjoin R (f '' s) := galois_connection.l_comm_of_u_comm set.image_preimage (gc_map_comap f) star_subalgebra.gc star_subalgebra.gc (λ _, rfl) lemma ext_adjoin {s : set A} [star_alg_hom_class F R (adjoin R s) B] {f g : F} (h : ∀ x : adjoin R s, (x : A) ∈ s → f x = g x) : f = g := begin refine fun_like.ext f g (λ a, adjoin_induction' a (λ x hx, _) (λ r, _) (λ x y hx hy, _) (λ x y hx hy, _) (λ x hx, _)), { exact h ⟨x, subset_adjoin R s hx⟩ hx }, { simp only [alg_hom_class.commutes] }, { rw [map_add, map_add, hx, hy] }, { rw [map_mul, map_mul, hx, hy] }, { rw [map_star, map_star, hx] }, end lemma ext_adjoin_singleton {a : A} [star_alg_hom_class F R (adjoin R ({a} : set A)) B] {f g : F} (h : f ⟨a, self_mem_adjoin_singleton R a⟩ = g ⟨a, self_mem_adjoin_singleton R a⟩) : f = g := ext_adjoin $ λ x hx, (show x = ⟨a, self_mem_adjoin_singleton R a⟩, from subtype.ext $ set.mem_singleton_iff.mp hx).symm ▸ h end star_alg_hom
6f8709d94d8fe015e282a249fac96a1e303e20dc
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/meta/exceptional.lean
f7e4cf020ec9e3d8df2b2a96617e99599a0a70aa
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
1,653
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.monad init.meta.format /- Remark: we use a function that produces a format object as the exception information. Motivation: the formatting object may be big, and we may create it on demand. -/ inductive exceptional (A : Type) | success : A → exceptional | exception : (options → format) → exceptional section open exceptional variables {A : Type} variables [has_to_string A] protected meta_definition exceptional.to_string : exceptional A → string | (success a) := to_string a | (exception .A e) := "Exception: " ++ to_string (e options.mk) attribute [instance] protected meta_definition exceptional.has_to_string : has_to_string (exceptional A) := has_to_string.mk exceptional.to_string end namespace exceptional variables {A B : Type} attribute [inline] protected meta_definition fmap (f : A → B) (e : exceptional A) : exceptional B := exceptional.cases_on e (λ a, success (f a)) (λ f, exception B f) attribute [inline] protected meta_definition bind (e₁ : exceptional A) (e₂ : A → exceptional B) : exceptional B := exceptional.cases_on e₁ (λ a, e₂ a) (λ f, exception B f) attribute [inline] protected meta_definition return (a : A) : exceptional A := success a attribute [inline] meta_definition fail (f : format) : exceptional A := exception A (λ u, f) end exceptional attribute [instance] meta_definition exceptional.is_monad : monad exceptional := monad.mk @exceptional.fmap @exceptional.return @exceptional.bind
4910d2318ed4f244d090cc4f3f18d3b3582bd7ef
ecad13897fdb44984cf1968424224d1750040236
/lean/lean/examples/example06.elab.lean
584dfa5f4b48d6ef352a73a13d0153a1ed4c8904
[]
no_license
MetaBorgCube/sdf3-demo
4899159b1cfb0a95ae3af325035bbba8a1255477
e831606d5b404eba75b087916a1162923143b98a
refs/heads/master
1,609,472,086,310
1,553,380,857,000
1,553,380,857,000
59,577,395
0
0
null
null
null
null
UTF-8
Lean
false
false
34
lean
(a : b) -> (c : d) -> (e : f) -> e
d5be248d6fbbf0f4741882412f66053f95f45b4b
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/polynomial/big_operators.lean
c00093a052bfbe4d8e276712d8ed5e8bcfd571d6
[ "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
6,403
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import data.polynomial.monic import data.polynomial.ring_division import tactic.linarith /-! # Lemmas for the interaction between polynomials and `∑` and `∏`. Recall that `∑` and `∏` are notation for `finset.sum` and `finset.prod` respectively. ## Main results - `polynomial.nat_degree_prod_of_monic` : the degree of a product of monic polynomials is the product of degrees. We prove this only for `[comm_semiring R]`, but it ought to be true for `[semiring R]` and `list.prod`. - `polynomial.nat_degree_prod` : for polynomials over an integral domain, the degree of the product is the sum of degrees. - `polynomial.leading_coeff_prod` : for polynomials over an integral domain, the leading coefficient is the product of leading coefficients. - `polynomial.prod_X_sub_C_coeff_card_pred` carries most of the content for computing the second coefficient of the characteristic polynomial. -/ open finset open_locale big_operators universes u w variables {R : Type u} {ι : Type w} namespace polynomial variable (s : finset ι) section comm_semiring variables [comm_semiring R] (f : ι → polynomial R) lemma nat_degree_prod_le : (∏ i in s, f i).nat_degree ≤ ∑ i in s, (f i).nat_degree := begin classical, induction s using finset.induction with a s ha hs, { simp }, rw [prod_insert ha, sum_insert ha], transitivity (f a).nat_degree + (∏ x in s, f x).nat_degree, apply polynomial.nat_degree_mul_le, linarith, end /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients, provided that this product is nonzero. See `polynomial.leading_coeff_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma leading_coeff_prod' (h : ∏ i in s, (f i).leading_coeff ≠ 0) : (∏ i in s, f i).leading_coeff = ∏ i in s, (f i).leading_coeff := begin classical, revert h, induction s using finset.induction with a s ha hs, { simp }, repeat { rw prod_insert ha }, intro h, rw polynomial.leading_coeff_mul'; { rwa hs, apply right_ne_zero_of_mul h }, end /-- The degree of a product of polynomials is equal to the sum of the degrees, provided that the product of leading coefficients is nonzero. See `polynomial.nat_degree_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma nat_degree_prod' (h : ∏ i in s, (f i).leading_coeff ≠ 0) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := begin classical, revert h, induction s using finset.induction with a s ha hs, { simp }, rw [prod_insert ha, prod_insert ha, sum_insert ha], intro h, rw polynomial.nat_degree_mul', rw hs, apply right_ne_zero_of_mul h, rwa polynomial.leading_coeff_prod', apply right_ne_zero_of_mul h, end lemma nat_degree_prod_of_monic [nontrivial R] (h : ∀ i ∈ s, (f i).monic) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := begin apply nat_degree_prod', suffices : ∏ i in s, (f i).leading_coeff = 1, { rw this, simp }, rw prod_eq_one, intros, apply h, assumption, end lemma coeff_zero_prod : (∏ i in s, f i).coeff 0 = ∏ i in s, (f i).coeff 0 := begin classical, induction s using finset.induction with a s ha hs, { simp only [coeff_one_zero, prod_empty] }, { simp only [ha, hs, mul_coeff_zero, not_false_iff, prod_insert] } end end comm_semiring section comm_ring variables [comm_ring R] open monic -- Eventually this can be generalized with Vieta's formulas -- plus the connection between roots and factorization. lemma prod_X_sub_C_next_coeff [nontrivial R] {s : finset ι} (f : ι → R) : next_coeff ∏ i in s, (X - C (f i)) = -∑ i in s, f i := by { rw next_coeff_prod; { simp [monic_X_sub_C] } } lemma prod_X_sub_C_coeff_card_pred [nontrivial R] (s : finset ι) (f : ι → R) (hs : 0 < s.card) : (∏ i in s, (X - C (f i))).coeff (s.card - 1) = - ∑ i in s, f i := begin convert prod_X_sub_C_next_coeff (by assumption), rw next_coeff, split_ifs, { rw nat_degree_prod_of_monic at h, swap, { intros, apply monic_X_sub_C }, rw sum_eq_zero_iff at h, simp_rw nat_degree_X_sub_C at h, contrapose! h, norm_num, exact multiset.card_pos_iff_exists_mem.mp hs }, congr, rw nat_degree_prod_of_monic; { simp [nat_degree_X_sub_C, monic_X_sub_C] }, end end comm_ring section no_zero_divisors variables [comm_ring R] [no_zero_divisors R] (f : ι → polynomial R) /-- The degree of a product of polynomials is equal to the sum of the degrees. See `polynomial.nat_degree_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma nat_degree_prod [nontrivial R] (h : ∀ i ∈ s, f i ≠ 0) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := begin apply nat_degree_prod', rw prod_ne_zero_iff, intros x hx, simp [h x hx] end lemma nat_degree_multiset_prod [nontrivial R] (s : multiset (polynomial R)) (h : (0 : polynomial R) ∉ s) : nat_degree s.prod = (s.map nat_degree).sum := begin revert h, refine s.induction_on _ _, { simp }, intros p s ih h, rw [multiset.mem_cons, not_or_distrib] at h, have hprod : s.prod ≠ 0 := multiset.prod_ne_zero h.2, rw [multiset.prod_cons, nat_degree_mul (ne.symm h.1) hprod, ih h.2, multiset.map_cons, multiset.sum_cons] end /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is ⊥. -/ lemma degree_prod [nontrivial R] : (∏ i in s, f i).degree = ∑ i in s, (f i).degree := begin classical, induction s using finset.induction with a s ha hs, { simp }, { rw [prod_insert ha, sum_insert ha, degree_mul, hs] }, end /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients. See `polynomial.leading_coeff_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma leading_coeff_prod : (∏ i in s, f i).leading_coeff = ∏ i in s, (f i).leading_coeff := by { rw ← leading_coeff_hom_apply, apply monoid_hom.map_prod } end no_zero_divisors end polynomial
2b47e7aa8d23ee64fad2d13c04a3e1abd2f1cb59
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/analysis/calculus/fderiv.lean
2da793e91ba206714b8086510b264a39634c4dc1
[ "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
112,591
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.tangent_cone import analysis.normed_space.units /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set open_locale topological_space classical noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (𝓝[s] x) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x), { conv in (𝓝[s] x) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (𝓝[s] x) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := begin have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y, { rintros y ⟨c, d, dtop, clim, cdlim⟩, exact tendsto_nhds_unique (h.lim at_top dtop clim cdlim) (h₁.lim at_top dtop clim cdlim) }, have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y, { assume y hy, apply submodule.span_induction hy, { exact λy hy, A y hy }, { simp only [continuous_linear_map.map_zero] }, { simp {contextual := tt} }, { simp {contextual := tt} } }, have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B, have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K := closure_mono this, have : y ∈ closure K := this hy, rwa (is_closed_eq f'.continuous f₁'.continuous).closure_eq at this }, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := unique_diff_within_at.eq (H x hx) h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin split, { assume H, have : tendsto (λ (z : E), z + x) (𝓝 0) (𝓝 (0 + x)), from tendsto_id.add tendsto_const_nhds, rw [zero_add] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel', add_comm z] }, { assume H, have : tendsto (λ (z : E), z - x) (𝓝 x) (𝓝 (x - x)), from tendsto_id.sub tendsto_const_nhds, rw [sub_self] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel'_right] } end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp [mem_closure_iff_nhds_within_ne_bot, ne_bot] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin have : s = univ ∩ s, by simp only [univ_inter], rw [this, ← fderiv_within_univ], exact fderiv_within_inter (mem_nhds_sets hs hx) (unique_diff_on_univ _ (mem_univ _)) end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem filter.eventually_eq.has_strict_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x) (h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x := (h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h theorem filter.eventually_eq.has_fderiv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_eventually_eq (h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply filter.eventually_eq.fderiv_within_eq hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := hL.eq_of_nhds, rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.fderiv_within_eq unique_diff_within_at_univ A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E := fderiv_within_id hxs end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp]protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (𝓝[s] x) ≤ 𝓝[f '' s] (f x) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ 𝓝[t] (f x) : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_within_at.comp' {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = (fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at prod.fst (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at prod.snd (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.add_const c).fderiv_within hxs lemma fderiv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.add_const c).fderiv theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_add c).fderiv_within hxs lemma fderiv_const_add (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := (hf.has_fderiv_at.const_add c).fderiv end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at 𝕜 f x) : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := h.has_fderiv_at.neg.fderiv end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.sub_const c).fderiv_within hxs lemma fderiv_sub_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.sub_const c).fderiv theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_sub c).fderiv_within hxs lemma fderiv_const_sub (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := (hf.has_fderiv_at.const_sub c).fderiv end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section algebra_inverse variables {R :Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R] open normed_ring continuous_linear_map ring /-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/ lemma has_fderiv_at_inverse (x : units R) : has_fderiv_at inverse (- (lmul_right 𝕜 R ↑x⁻¹).comp (lmul_left 𝕜 R ↑x⁻¹)) x := begin have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ (t : R), t) (𝓝 0), { refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _), simp only [normed_field.norm_pow, norm_norm], have h12 : 1 < 2 := by norm_num, convert (asymptotics.is_o_pow_pow h12).comp_tendsto lim_norm_zero, ext, simp }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [has_fderiv_at, has_fderiv_at_filter], convert h_is_o.comp_tendsto h_lim, ext y, simp only [coe_comp', function.comp_app, lmul_right_apply, lmul_left_apply, neg_apply, inverse_unit x, units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul], abel end lemma differentiable_at_inverse (x : units R) : differentiable_at 𝕜 (@inverse R _) x := (has_fderiv_at_inverse x).differentiable_at lemma fderiv_inverse (x : units R) : fderiv 𝕜 (@inverse R _) x = - (lmul_right 𝕜 R ↑x⁻¹).comp (lmul_left 𝕜 R ↑x⁻¹) := (has_fderiv_at_inverse x).fderiv end algebra_inverse section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : closure (range f') = univ) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E), f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F), { assume v hv, apply submodule.span_induction hv, { exact λ w hw, submodule.subset_span (h.maps_to_tangent_cone hw) }, { simp }, { assume w₁ w₂ hw₁ hw₂, rw continuous_linear_map.map_add, exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ }, { assume a w hw, rw continuous_linear_map.map_smul, exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } }, rw [unique_diff_within_at, ← univ_subset_iff], split, show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2, show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc univ ⊆ closure (range f') : univ_subset_iff.2 h' ... = closure (f' '' univ) : by rw image_univ ... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1 ... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : closure_mono (image_closure_subset_closure_image f'.cont) ... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure ... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) : closure_mono (image_subset_iff.mpr B) end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin apply h.unique_diff_within_at hs, have : set.range (e' : E →L[𝕜] F) = univ := e'.to_linear_equiv.to_equiv.range_eq_univ, rw [this, closure_univ] end lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : semimodule.restrict_scalars 𝕜 𝕜' E → semimodule.restrict_scalars 𝕜 𝕜' F} {f' : semimodule.restrict_scalars 𝕜 𝕜' E →L[𝕜'] semimodule.restrict_scalars 𝕜 𝕜' F} {s : set E} {x : E} lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars /-! ### Multiplying by a complex function respects real differentiability Consider two functions `c : E → ℂ` and `f : E → F` where `F` is a complex vector space. If both `c` and `f` are differentiable over `ℝ`, then so is their product. This paragraph proves this statement, in the general version where `ℝ` is replaced by a field `𝕜`, and `ℂ` is replaced by a normed algebra `𝕜'` over `𝕜`. -/ section smul_algebra variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : E → semimodule.restrict_scalars 𝕜 𝕜' F} {f' : E →L[𝕜] semimodule.restrict_scalars 𝕜 𝕜' F} {s : set E} {x : E} {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'} {L : filter E} theorem has_strict_fderiv_at.smul_algebra (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_algebra_right (f x)) x := (is_bounded_bilinear_map_smul_algebra.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul_algebra (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_algebra_right (f x)) s x := (is_bounded_bilinear_map_smul_algebra.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul_algebra (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_algebra_right (f x)) x := (is_bounded_bilinear_map_smul_algebra.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul_algebra (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul_algebra hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul_algebra (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul_algebra hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul_algebra (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul_algebra (hf x hx) @[simp] lemma differentiable.smul_algebra (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul_algebra (hf x) lemma fderiv_within_smul_algebra (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_algebra_right (f x) := (hc.has_fderiv_within_at.smul_algebra hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul_algebra (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_algebra_right (f x) := (hc.has_fderiv_at.smul_algebra hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_algebra_const (hc : has_strict_fderiv_at c c' x) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_algebra_right f) x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_algebra_const (hc : has_fderiv_within_at c c' s x) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_algebra_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_algebra_const (hc : has_fderiv_at c c' x) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : has_fderiv_at (λ y, c y • f) (c'.smul_algebra_right f) x := by simpa only [smul_zero, zero_add] using hc.smul_algebra (has_fderiv_at_const f x) lemma differentiable_within_at.smul_algebra_const (hc : differentiable_within_at 𝕜 c s x) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_algebra_const f).differentiable_within_at lemma differentiable_at.smul_algebra_const (hc : differentiable_at 𝕜 c x) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_algebra_const f).differentiable_at lemma differentiable_on.smul_algebra_const (hc : differentiable_on 𝕜 c s) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_algebra_const f lemma differentiable.smul_algebra_const (hc : differentiable 𝕜 c) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_algebra_const f lemma fderiv_within_smul_algebra_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_algebra_right f := (hc.has_fderiv_within_at.smul_algebra_const f).fderiv_within hxs lemma fderiv_smul_algebra_const (hc : differentiable_at 𝕜 c x) (f : semimodule.restrict_scalars 𝕜 𝕜' F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_algebra_right f := (hc.has_fderiv_at.smul_algebra_const f).fderiv theorem has_strict_fderiv_at.const_smul_algebra (h : has_strict_fderiv_at f f' x) (c : 𝕜') : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : (semimodule.restrict_scalars 𝕜 𝕜' F) →L[𝕜] ((semimodule.restrict_scalars 𝕜 𝕜' F)))) .has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul_algebra (h : has_fderiv_at_filter f f' x L) (c : 𝕜') : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : (semimodule.restrict_scalars 𝕜 𝕜' F) →L[𝕜] ((semimodule.restrict_scalars 𝕜 𝕜' F)))) .has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul_algebra (h : has_fderiv_within_at f f' s x) (c : 𝕜') : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul_algebra c theorem has_fderiv_at.const_smul_algebra (h : has_fderiv_at f f' x) (c : 𝕜') : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul_algebra c lemma differentiable_within_at.const_smul_algebra (h : differentiable_within_at 𝕜 f s x) (c : 𝕜') : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul_algebra c).differentiable_within_at lemma differentiable_at.const_smul_algebra (h : differentiable_at 𝕜 f x) (c : 𝕜') : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul_algebra c).differentiable_at lemma differentiable_on.const_smul_algebra (h : differentiable_on 𝕜 f s) (c : 𝕜') : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul_algebra c lemma differentiable.const_smul_algebra (h : differentiable 𝕜 f) (c : 𝕜') : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul_algebra c lemma fderiv_within_const_smul_algebra (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜') : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul_algebra c).fderiv_within hxs lemma fderiv_const_smul_algebra (h : differentiable_at 𝕜 f x) (c : 𝕜') : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul_algebra c).fderiv end smul_algebra
05c73b5c18887c3ef7dea142e5f81c41dba9c489
510e96af568b060ed5858226ad954c258549f143
/algebra/lattice/fixed_points.lean
9c9a40713bae949a7cd6cca27f0dd69acbd6e172
[]
no_license
Shamrock-Frost/library_dev
cb6d1739237d81e17720118f72ba0a6db8a5906b
0245c71e4931d3aceeacf0aea776454f6ee03c9c
refs/heads/master
1,609,481,034,595
1,500,165,215,000
1,500,165,347,000
97,350,162
0
0
null
1,500,164,969,000
1,500,164,969,000
null
UTF-8
Lean
false
false
4,453
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 Fixed point construction on complete lattices. -/ import .complete_lattice universes u v w variables {α : Type u} {β : Type v} {γ : Type w} lemma ge_of_eq [weak_order α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a namespace lattice section fixedpoint variables [complete_lattice α] {f : α → α} def lfp (f : α → α) : α := Inf {a | f a ≤ a} def gfp (f : α → α) : α := Sup {a | a ≤ f a} lemma lfp_le {a : α} (h : f a ≤ a) : lfp f ≤ a := Inf_le h lemma le_lfp {a : α} (h : ∀b, f b ≤ b → a ≤ b) : a ≤ lfp f := le_Inf h lemma lfp_eq (m : monotone f) : lfp f = f (lfp f) := have f (lfp f) ≤ lfp f, from le_lfp $ assume b, assume h : f b ≤ b, le_trans (m (lfp_le h)) h, le_antisymm (lfp_le (m this)) this lemma lfp_induct {p : α → Prop} (m : monotone f) (step : ∀a, p a → a ≤ lfp f → p (f a)) (sup : ∀s, (∀a∈s, p a) → p (Sup s)) : p (lfp f) := let s := {a | a ≤ lfp f ∧ p a} in have p_s : p (Sup s), from sup s (assume a ⟨_, h⟩, h), have Sup s ≤ lfp f, from le_lfp $ assume a, assume h : f a ≤ a, Sup_le $ assume b ⟨b_le, _⟩, le_trans b_le (lfp_le h), have Sup s = lfp f, from le_antisymm this $ lfp_le $ le_Sup ⟨le_trans (m this) $ ge_of_eq $ lfp_eq m, step _ p_s this⟩, this ▸ p_s lemma monotone_lfp : monotone (@lfp α _) := assume f g, suppose f ≤ g, le_lfp $ assume a, suppose g a ≤ a, lfp_le $ le_trans (‹f ≤ g› a) this lemma le_gfp {a : α} (h : a ≤ f a) : a ≤ gfp f := le_Sup h lemma gfp_le {a : α} (h : ∀b, b ≤ f b → b ≤ a) : gfp f ≤ a := Sup_le h lemma gfp_eq (m : monotone f) : gfp f = f (gfp f) := have gfp f ≤ f (gfp f), from gfp_le $ assume b, assume h : b ≤ f b, le_trans h (m (le_gfp h)), le_antisymm this (le_gfp (m this)) lemma gfp_induct {p : α → Prop} (m : monotone f) (step : ∀a, p a → gfp f ≤ a → p (f a)) (inf : ∀s, (∀a∈s, p a) → p (Inf s)) : p (gfp f) := let s := {a | gfp f ≤ a ∧ p a} in have p_s : p (Inf s), from inf s (assume a ⟨_, h⟩, h), have gfp f ≤ Inf s, from gfp_le $ assume a, assume h : a ≤ f a, le_Inf $ assume b ⟨le_b, _⟩, le_trans (le_gfp h) le_b, have Inf s = gfp f, from le_antisymm (le_gfp $ Inf_le ⟨le_trans (le_of_eq $ gfp_eq m) (m this), step _ p_s this⟩) this, this ▸ p_s lemma monotone_gfp : monotone (@gfp α _) := assume f g, suppose f ≤ g, gfp_le $ assume a, suppose a ≤ f a, le_gfp $ le_trans this (‹f ≤ g› a) end fixedpoint section fixedpoint_eqn variables [complete_lattice α] [complete_lattice β] {f : β → α} {g : α → β} -- Rolling rule lemma lfp_comp (m_f : monotone f) (m_g : monotone g) : lfp (f ∘ g) = f (lfp (g ∘ f)) := le_antisymm (lfp_le $ m_f $ ge_of_eq $ lfp_eq $ monotone_comp m_f m_g) (le_lfp $ assume a fg_le, le_trans (m_f $ lfp_le $ show (g ∘ f) (g a) ≤ g a, from m_g fg_le) fg_le) lemma gfp_comp (m_f : monotone f) (m_g : monotone g) : gfp (f ∘ g) = f (gfp (g ∘ f)) := le_antisymm (gfp_le $ assume a fg_le, le_trans fg_le $ m_f $ le_gfp $ show g a ≤ (g ∘ f) (g a), from m_g fg_le) (le_gfp $ m_f $ le_of_eq $ gfp_eq $ monotone_comp m_f m_g) -- Diagonal rule lemma lfp_lfp {h : α → α → α} (m : ∀⦃a b c d⦄, a ≤ b → c ≤ d → h a c ≤ h b d) : lfp (lfp ∘ h) = lfp (λx, h x x) := let f := lfp (lfp ∘ h) in have f_eq : f = lfp (h f), from lfp_eq $ monotone_comp (assume a b h x, m h (le_refl _)) monotone_lfp, le_antisymm (lfp_le $ lfp_le $ ge_of_eq $ lfp_eq $ assume a b h, m h h) (lfp_le $ ge_of_eq $ calc f = lfp (h f) : f_eq ... = h f (lfp (h f)) : lfp_eq $ assume a b h, m (le_refl _) h ... = h f f : congr_arg (h f) f_eq^.symm) lemma gfp_gfp {h : α → α → α} (m : ∀⦃a b c d⦄, a ≤ b → c ≤ d → h a c ≤ h b d) : gfp (gfp ∘ h) = gfp (λx, h x x) := let f := gfp (gfp ∘ h) in have f_eq : f = gfp (h f), from gfp_eq $ monotone_comp (assume a b h x, m h (le_refl _)) monotone_gfp, le_antisymm (le_gfp $ le_of_eq $ calc f = gfp (h f) : f_eq ... = h f (gfp (h f)) : gfp_eq $ assume a b h, m (le_refl _) h ... = h f f : congr_arg (h f) f_eq^.symm) (le_gfp $ le_gfp $ le_of_eq $ gfp_eq $ assume a b h, m h h) end fixedpoint_eqn end lattice
af6782b97ebffc1292cfc7061b4fb5fbc0f69d76
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/rec4.lean
c490ea648bcb29fcf065783f4c314e7ad3e8b853
[ "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
260
lean
import data.examples.vector open nat vector set_option pp.implicit true set_option pp.notation false definition diag {A : Type*} : Π {n}, vector (vector A n) n → vector A n, diag nil := nil, diag ((a :: va) :: vs) := a :: diag (map tail vs)
cc98ff35f26120e7e80e51f324e6a7cab83b1ef6
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_lean_summary/unnamed_510.lean
8bb90f75eae9a0db9f19cc42143f2d85406150d7
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
173
lean
variables p q : Prop -- BEGIN example (h : false) : p := begin exfalso, -- This changes the goal from `p` to `false`. exact h, -- We close the goal with `h`. end -- END
2c65a9d71c2b6801709958fe8d19b57fbb62c551
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/group_theory/perm/list.lean
6f2ee0a5c85690216cc517828f8f675845337c0b
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,389
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.list.rotate import group_theory.perm.support /-! # Permutations from a list A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. When there are duplicate elements in `l`, how and in what arrangement with respect to the other elements they appear in the list determines the formed permutation. This is because `list.form_perm` is implemented as a product of `equiv.swap`s. That means that presence of a sublist of two adjacent duplicates like `[..., x, x, ...]` will produce the same permutation as if the adjacent duplicates were not present. The `list.form_perm` definition is meant to primarily be used with `nodup l`, so that the resulting permutation is cyclic (if `l` has at least two elements). The presence of duplicates in a particular placement can lead `list.form_perm` to produce a nontrivial permutation that is noncyclic. -/ namespace list variables {α β : Type*} section form_perm variables [decidable_eq α] (l : list α) open equiv equiv.perm /-- A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. -/ def form_perm : equiv.perm α := (zip_with equiv.swap l l.tail).prod @[simp] lemma form_perm_nil : form_perm ([] : list α) = 1 := rfl @[simp] lemma form_perm_singleton (x : α) : form_perm [x] = 1 := rfl @[simp] lemma form_perm_cons_cons (x y : α) (l : list α) : form_perm (x :: y :: l) = swap x y * form_perm (y :: l) := prod_cons lemma form_perm_pair (x y : α) : form_perm [x, y] = swap x y := rfl lemma form_perm_apply_of_not_mem (x : α) (l : list α) (h : x ∉ l) : form_perm l x = x := begin cases l with y l, { simp }, induction l with z l IH generalizing x y, { simp }, { specialize IH x z (mt (mem_cons_of_mem y) h), simp only [not_or_distrib, mem_cons_iff] at h, simp [IH, swap_apply_of_ne_of_ne, h] } end lemma form_perm_apply_mem_of_mem (x : α) (l : list α) (h : x ∈ l) : form_perm l x ∈ l := begin cases l with y l, { simpa }, induction l with z l IH generalizing x y, { simpa using h }, { by_cases hx : x ∈ z :: l, { rw [form_perm_cons_cons, mul_apply, swap_apply_def], split_ifs; simp [IH _ _ hx] }, { replace h : x = y := or.resolve_right h hx, simp [form_perm_apply_of_not_mem _ _ hx, ←h] } } end @[simp] lemma form_perm_cons_concat_apply_last (x y : α) (xs : list α) : form_perm (x :: (xs ++ [y])) y = x := begin induction xs with z xs IH generalizing x y, { simp }, { simp [IH] } end @[simp] lemma form_perm_apply_last (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).last (cons_ne_nil x xs)) = x := begin induction xs using list.reverse_rec_on with xs y IH generalizing x; simp end @[simp] lemma form_perm_apply_nth_le_length (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).nth_le xs.length (by simp)) = x := by rw [nth_le_cons_length, form_perm_apply_last] lemma form_perm_apply_head (x y : α) (xs : list α) (h : nodup (x :: y :: xs)) : form_perm (x :: y :: xs) x = y := by simp [form_perm_apply_of_not_mem _ _ (not_mem_of_nodup_cons h)] lemma form_perm_apply_nth_le_zero (l : list α) (h : nodup l) (hl : 1 < l.length) : form_perm l (l.nth_le 0 (zero_lt_one.trans hl)) = l.nth_le 1 hl := begin rcases l with (_|⟨x, _|⟨y, tl⟩⟩), { simp }, { simp }, { simpa using form_perm_apply_head _ _ _ h } end lemma form_perm_eq_head_iff_eq_last (x y : α) : form_perm (y :: l) x = y ↔ x = last (y :: l) (cons_ne_nil _ _) := iff.trans (by rw form_perm_apply_last) (form_perm (y :: l)).injective.eq_iff lemma zip_with_swap_prod_support' (l l' : list α) : {x | (zip_with swap l l').prod x ≠ x} ≤ l.to_finset ⊔ l'.to_finset := begin simp only [set.sup_eq_union, set.le_eq_subset], induction l with y l hl generalizing l', { simp }, { cases l' with z l', { simp }, { intro x, simp only [set.union_subset_iff, mem_cons_iff, zip_with_cons_cons, foldr, prod_cons, mul_apply], intro hx, by_cases h : x ∈ {x | (zip_with swap l l').prod x ≠ x}, { specialize hl l' h, refine set.mem_union.elim hl (λ hm, _) (λ hm, _); { simp only [finset.coe_insert, set.mem_insert_iff, finset.mem_coe, to_finset_cons, mem_to_finset] at hm ⊢, simp [hm] } }, { simp only [not_not, set.mem_set_of_eq] at h, simp only [h, set.mem_set_of_eq] at hx, rw swap_apply_ne_self_iff at hx, rcases hx with ⟨hyz, rfl|rfl⟩; simp } } } end lemma zip_with_swap_prod_support [fintype α] (l l' : list α) : (zip_with swap l l').prod.support ≤ l.to_finset ⊔ l'.to_finset := begin intros x hx, have hx' : x ∈ {x | (zip_with swap l l').prod x ≠ x} := by simpa using hx, simpa using zip_with_swap_prod_support' _ _ hx' end lemma support_form_perm_le' : {x | form_perm l x ≠ x} ≤ l.to_finset := begin refine (zip_with_swap_prod_support' l l.tail).trans _, simpa [finset.subset_iff] using tail_subset l end lemma support_form_perm_le [fintype α] : support (form_perm l) ≤ l.to_finset := begin intros x hx, have hx' : x ∈ {x | form_perm l x ≠ x} := by simpa using hx, simpa using support_form_perm_le' _ hx' end lemma form_perm_apply_lt (xs : list α) (h : nodup xs) (n : ℕ) (hn : n + 1 < xs.length) : form_perm xs (xs.nth_le n ((nat.lt_succ_self n).trans hn)) = xs.nth_le (n + 1) hn := begin induction n with n IH generalizing xs, { simpa using form_perm_apply_nth_le_zero _ h _ }, { rcases xs with (_|⟨x, _|⟨y, l⟩⟩), { simp }, { simp }, { specialize IH (y :: l) (nodup_of_nodup_cons h) _, { simpa [nat.succ_lt_succ_iff] using hn }, simp only [swap_apply_eq_iff, coe_mul, form_perm_cons_cons, nth_le], generalize_proofs at IH, rw [IH, swap_apply_of_ne_of_ne, nth_le]; { rintro rfl, simpa [nth_le_mem _ _ _] using h } } } end lemma form_perm_apply_nth_le (xs : list α) (h : nodup xs) (n : ℕ) (hn : n < xs.length) : form_perm xs (xs.nth_le n hn) = xs.nth_le ((n + 1) % xs.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases xs with x xs, { simp }, { have : n ≤ xs.length, { refine nat.le_of_lt_succ _, simpa using hn }, rcases this.eq_or_lt with rfl|hn', { simp }, { simp [form_perm_apply_lt, h, nat.mod_eq_of_lt, nat.succ_lt_succ hn'] } } end lemma support_form_perm_of_nodup' (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : {x | form_perm l x ≠ x} = l.to_finset := begin apply le_antisymm, { exact support_form_perm_le' l }, { intros x hx, simp only [finset.mem_coe, mem_to_finset] at hx, obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, rw [set.mem_set_of_eq, form_perm_apply_nth_le _ h], intro H, rw nodup_iff_nth_le_inj at h, specialize h _ _ _ _ H, cases (nat.succ_le_of_lt hn).eq_or_lt with hn' hn', { simp only [←hn', nat.mod_self] at h, refine not_exists.mpr h' _, simpa [←h, eq_comm, length_eq_one] using hn' }, { simpa [nat.mod_eq_of_lt hn'] using h } } end lemma support_form_perm_of_nodup [fintype α] (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : support (form_perm l) = l.to_finset := begin rw ←finset.coe_inj, convert support_form_perm_of_nodup' _ h h', simp [set.ext_iff] end lemma form_perm_rotate_one (l : list α) (h : nodup l) : form_perm (l.rotate 1) = form_perm l := begin have h' : nodup (l.rotate 1), { simpa using h }, by_cases hl : ∀ (x : α), l ≠ [x], { have hl' : ∀ (x : α), l.rotate 1 ≠ [x], { intro, rw [ne.def, rotate_eq_iff], simpa using hl _ }, ext x, by_cases hx : x ∈ l.rotate 1, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ h', nth_le_rotate l, nth_le_rotate l, form_perm_apply_nth_le _ h], simp }, { rw [form_perm_apply_of_not_mem _ _ hx, form_perm_apply_of_not_mem], simpa using hx } }, { push_neg at hl, obtain ⟨x, rfl⟩ := hl, simp } end lemma form_perm_rotate (l : list α) (h : nodup l) (n : ℕ) : form_perm (l.rotate n) = form_perm l := begin induction n with n hn, { simp }, { rw [nat.succ_eq_add_one, ←rotate_rotate, form_perm_rotate_one, hn], rwa is_rotated.nodup_iff, exact is_rotated.forall l n } end lemma form_perm_eq_of_is_rotated {l l' : list α} (hd : nodup l) (h : l ~r l') : form_perm l = form_perm l' := begin obtain ⟨n, rfl⟩ := h, exact (form_perm_rotate l hd n).symm end lemma form_perm_reverse (l : list α) (h : nodup l) : form_perm l.reverse = (form_perm l)⁻¹ := begin -- Let's show `form_perm l` is an inverse to `form_perm l.reverse`. rw [eq_comm, inv_eq_iff_mul_eq_one], ext x, -- We only have to check for `x ∈ l` that `form_perm l (form_perm l.reverse x)` rw [mul_apply, one_apply], by_cases hx : x ∈ l, swap, { rw [form_perm_apply_of_not_mem x l.reverse, form_perm_apply_of_not_mem _ _ hx], simpa using hx }, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem (mem_reverse.mpr hx), rw [form_perm_apply_nth_le l.reverse (nodup_reverse.mpr h), nth_le_reverse', form_perm_apply_nth_le _ h, nth_le_reverse'], { congr, rw [length_reverse, ←nat.succ_le_iff, nat.succ_eq_add_one] at hk, cases hk.eq_or_lt with hk' hk', { simp [←hk'] }, { rw [length_reverse, nat.mod_eq_of_lt hk', tsub_add_eq_add_tsub (nat.le_pred_of_lt hk'), nat.mod_eq_of_lt], { simp }, { rw tsub_add_cancel_of_le, refine tsub_lt_self _ (nat.zero_lt_succ _), all_goals { simpa using (nat.zero_le _).trans_lt hk' } } } }, all_goals { rw [← tsub_add_eq_tsub_tsub, ←length_reverse], refine tsub_lt_self _ (zero_lt_one.trans_le (le_add_right le_rfl)), exact k.zero_le.trans_lt hk } }, end lemma form_perm_pow_apply_nth_le (l : list α) (h : nodup l) (n k : ℕ) (hk : k < l.length) : (form_perm l ^ n) (l.nth_le k hk) = l.nth_le ((k + n) % l.length) (nat.mod_lt _ (k.zero_le.trans_lt hk)) := begin induction n with n hn, { simp [nat.mod_eq_of_lt hk] }, { simp [pow_succ, mul_apply, hn, form_perm_apply_nth_le _ h, nat.succ_eq_add_one, ←nat.add_assoc] } end lemma form_perm_pow_apply_head (x : α) (l : list α) (h : nodup (x :: l)) (n : ℕ) : (form_perm (x :: l) ^ n) x = (x :: l).nth_le (n % (x :: l).length) (nat.mod_lt _ (nat.zero_lt_succ _)) := by { convert form_perm_pow_apply_nth_le _ h n 0 _; simp } lemma form_perm_ext_iff {x y x' y' : α} {l l' : list α} (hd : nodup (x :: y :: l)) (hd' : nodup (x' :: y' :: l')) : form_perm (x :: y :: l) = form_perm (x' :: y' :: l') ↔ (x :: y :: l) ~r (x' :: y' :: l') := begin refine ⟨λ h, _, λ hr, form_perm_eq_of_is_rotated hd hr⟩, rw equiv.perm.ext_iff at h, have hx : x' ∈ (x :: y :: l), { have : x' ∈ {z | form_perm (x :: y :: l) z ≠ z}, { rw [set.mem_set_of_eq, h x', form_perm_apply_head _ _ _ hd'], simp only [mem_cons_iff, nodup_cons] at hd', push_neg at hd', exact hd'.left.left.symm }, simpa using support_form_perm_le' _ this }, obtain ⟨n, hn, hx'⟩ := nth_le_of_mem hx, have hl : (x :: y :: l).length = (x' :: y' :: l').length, { rw [←erase_dup_eq_self.mpr hd, ←erase_dup_eq_self.mpr hd', ←card_to_finset, ←card_to_finset], refine congr_arg finset.card _, rw [←finset.coe_inj, ←support_form_perm_of_nodup' _ hd (by simp), ←support_form_perm_of_nodup' _ hd' (by simp)], simp only [h] }, use n, apply list.ext_le, { rw [length_rotate, hl] }, { intros k hk hk', rw nth_le_rotate, induction k with k IH, { simp_rw [nat.zero_add, nat.mod_eq_of_lt hn], simpa }, { have : k.succ = (k + 1) % (x' :: y' :: l').length, { rw [←nat.succ_eq_add_one, nat.mod_eq_of_lt hk'] }, simp_rw this, rw [←form_perm_apply_nth_le _ hd' k (k.lt_succ_self.trans hk'), ←IH (k.lt_succ_self.trans hk), ←h, form_perm_apply_nth_le _ hd], congr' 1, have h1 : 1 = 1 % (x' :: y' :: l').length := by simp, rw [hl, nat.mod_eq_of_lt hk', h1, ←nat.add_mod, nat.succ_add] } } end lemma form_perm_apply_mem_eq_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = x ↔ length l ≤ 1 := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ hl, hl.nth_le_inj_iff], cases hn : l.length, { exact absurd k.zero_le (hk.trans_le hn.le).not_le }, { rw hn at hk, cases (nat.le_of_lt_succ hk).eq_or_lt with hk' hk', { simp [←hk', nat.succ_le_succ_iff, eq_comm] }, { simpa [nat.mod_eq_of_lt (nat.succ_lt_succ hk'), nat.succ_lt_succ_iff] using k.zero_le.trans_lt hk' } } end lemma form_perm_apply_mem_ne_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x ≠ x ↔ 2 ≤ l.length := begin rw [ne.def, form_perm_apply_mem_eq_self_iff _ hl x hx, not_le], exact ⟨nat.succ_le_of_lt, nat.lt_of_succ_le⟩ end lemma mem_of_form_perm_ne_self (l : list α) (x : α) (h : form_perm l x ≠ x) : x ∈ l := begin suffices : x ∈ {y | form_perm l y ≠ y}, { rw ←mem_to_finset, exact support_form_perm_le' _ this }, simpa using h end lemma form_perm_eq_self_of_not_mem (l : list α) (x : α) (h : x ∉ l) : form_perm l x = x := by_contra (λ H, h $ mem_of_form_perm_ne_self _ _ H) lemma form_perm_eq_one_iff (hl : nodup l) : form_perm l = 1 ↔ l.length ≤ 1 := begin cases l with hd tl, { simp }, { rw ←form_perm_apply_mem_eq_self_iff _ hl hd (mem_cons_self _ _), split, { simp {contextual := tt} }, { intro h, simp only [(hd :: tl).form_perm_apply_mem_eq_self_iff hl hd (mem_cons_self hd tl), add_le_iff_nonpos_left, length, nonpos_iff_eq_zero, length_eq_zero] at h, simp [h] } } end lemma form_perm_eq_form_perm_iff {l l' : list α} (hl : l.nodup) (hl' : l'.nodup) : l.form_perm = l'.form_perm ↔ l ~r l' ∨ l.length ≤ 1 ∧ l'.length ≤ 1 := begin rcases l with (_ | ⟨x, _ | ⟨y, l⟩⟩), { suffices : l'.length ≤ 1 ↔ l' = nil ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero] }, refine ⟨λ h, or.inr h, _⟩, rintro (rfl | h), { simp }, { exact h } }, { suffices : l'.length ≤ 1 ↔ [x] ~r l' ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero, le_rfl] }, refine ⟨λ h, or.inr h, _⟩, rintro (h | h), { simp [←h.perm.length_eq] }, { exact h } }, { rcases l' with (_ | ⟨x', _ | ⟨y', l'⟩⟩), { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, { suffices : ¬ (x :: y :: l) ~r [x'], { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, intro h, simpa using h.perm.length_eq }, { simp [-form_perm_cons_cons, form_perm_ext_iff hl hl'] } } end lemma form_perm_gpow_apply_mem_imp_mem (l : list α) (x : α) (hx : x ∈ l) (n : ℤ) : ((form_perm l) ^ n) x ∈ l := begin by_cases h : (l.form_perm ^ n) x = x, { simpa [h] using hx }, { have : x ∈ {x | (l.form_perm ^ n) x ≠ x} := h, rw ←set_support_apply_mem at this, replace this := set_support_gpow_subset _ _ this, simpa using support_form_perm_le' _ this } end lemma form_perm_pow_length_eq_one_of_nodup (hl : nodup l) : (form_perm l) ^ (length l) = 1 := begin ext x, by_cases hx : x ∈ l, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, simp [form_perm_pow_apply_nth_le _ hl, nat.mod_eq_of_lt hk] }, { have : x ∉ {x | (l.form_perm ^ l.length) x ≠ x}, { intros H, refine hx _, replace H := set_support_gpow_subset l.form_perm l.length H, simpa using support_form_perm_le' _ H }, simpa } end end form_perm end list
35822c18797c27947e5b7acfc2c9d2e12c3ea2a8
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/closed/cartesian.lean
b3ea9b725fd7cd3612c0a55037ae1ab73c9c368e
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
14,099
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.epi_mono import category_theory.limits.shapes.finite_products import category_theory.monoidal.of_has_finite_products import category_theory.limits.preserves.shapes.binary_products import category_theory.adjunction.limits import category_theory.adjunction.mates import category_theory.closed.monoidal /-! # 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₂ noncomputable theory 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) := tensor_closed hX hY /-- 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} variables [has_finite_products C] [exponentiable A] /-- This is (-)^A. -/ abbreviation exp : C ⥤ C := ihom A namespace exp /-- The adjunction between A ⨯ - and (-)^A. -/ abbreviation adjunction : prod.functor.obj A ⊣ exp A := ihom.adjunction A /-- The evaluation natural transformation. -/ abbreviation ev : exp A ⋙ prod.functor.obj A ⟶ 𝟭 C := ihom.ev A /-- The coevaluation natural transformation. -/ abbreviation coev : 𝟭 C ⟶ prod.functor.obj A ⋙ exp A := ihom.coev A notation A ` ⟹ `:20 B:19 := (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) := ihom.ev_coev A B @[simp, reassoc] lemma coev_ev : (coev A).app (A ⟹ B) ≫ (exp A).map ((ev A).app B) = 𝟙 (A ⟹ B) := ihom.coev_ev A B end exp instance : preserves_colimits (prod.functor.obj A) := (ihom.adjunction A).left_adjoint_preserves_colimits variables {A} -- Wrap these in a namespace so we don't clash with the core versions. namespace cartesian_closed /-- Currying in a cartesian closed category. -/ def curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X) := (exp.adjunction A).hom_equiv _ _ /-- Uncurrying in a cartesian closed category. -/ def uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X) := ((exp.adjunction A).hom_equiv _ _).symm @[simp] lemma hom_equiv_apply_eq (f : A ⨯ Y ⟶ X) : (exp.adjunction A).hom_equiv _ _ f = curry f := rfl @[simp] lemma hom_equiv_symm_apply_eq (f : Y ⟶ A ⟹ X) : ((exp.adjunction A).hom_equiv _ _).symm f = uncurry f := rfl @[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 ≫ (exp.ev A).app X := adjunction.hom_equiv_counit _ lemma curry_eq (g : A ⨯ Y ⟶ X) : curry g = (exp.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)) = (exp.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 (𝟙 _) = (exp.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 end cartesian_closed open cartesian_closed /-- 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 ≫ cartesian_closed.uncurry f) (λ Y f, cartesian_closed.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) := cartesian_closed.curry (limits.prod.fst ≫ f) section pre variables {B} /-- Pre-compose an internal hom with an external hom. -/ def pre (f : B ⟶ A) [exponentiable B] : exp A ⟶ exp B := transfer_nat_trans_self (exp.adjunction _) (exp.adjunction _) (prod.functor.map f) lemma prod_map_pre_app_comp_ev (f : B ⟶ A) [exponentiable B] (X : C) : limits.prod.map (𝟙 B) ((pre f).app X) ≫ (exp.ev B).app X = limits.prod.map f (𝟙 (A ⟹ X)) ≫ (exp.ev A).app X := transfer_nat_trans_self_counit _ _ (prod.functor.map f) X lemma uncurry_pre (f : B ⟶ A) [exponentiable B] (X : C) : cartesian_closed.uncurry ((pre f).app X) = limits.prod.map f (𝟙 _) ≫ (exp.ev A).app X := begin rw [uncurry_eq, prod_map_pre_app_comp_ev] end lemma coev_app_comp_pre_app (f : B ⟶ A) [exponentiable B] : (exp.coev A).app X ≫ (pre f).app (A ⨯ X) = (exp.coev B).app X ≫ (exp B).map (limits.prod.map f (𝟙 _)) := unit_transfer_nat_trans_self _ _ (prod.functor.map f) X @[simp] lemma pre_id (A : C) [exponentiable A] : pre (𝟙 A) = 𝟙 _ := by simp [pre] @[simp] lemma pre_map {A₁ A₂ A₃ : C} [exponentiable A₁] [exponentiable A₂] [exponentiable A₃] (f : A₁ ⟶ A₂) (g : A₂ ⟶ A₃) : pre (f ≫ g) = pre g ≫ pre f := by rw [pre, pre, pre, transfer_nat_trans_self_comp, prod.functor.map_comp] end pre /-- The internal hom functor given by the cartesian closed structure. -/ def internal_hom [cartesian_closed C] : Cᵒᵖ ⥤ C ⥤ C := { obj := λ X, exp X.unop, map := λ X Y f, pre f.unop } /-- 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) = cartesian_closed.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 := cartesian_closed.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 := cartesian_closed.uncurry (coprod.desc (cartesian_closed.curry coprod.inl) (cartesian_closed.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. -/ lemma 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 to_initial_is_iso [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 _, begin haveI := strict_initial t g, haveI := strict_initial t h, exact eq_of_inv_eq_inv (t.hom_ext _ _) end⟩ 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)) ≪≫ _, apply prod.map_iso (iso.refl _) (e.unit_iso.app Y).symm }, { intros Y Z g, dsimp [prod_comparison], simp [prod.comp_lift, ← e.inverse.map_comp, ← e.inverse.map_comp_assoc], -- I wonder if it would be a good idea to make `map_comp` a simp lemma the other way round dsimp, simp }, -- See note [dsimp, simp] { 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 } } end functor end category_theory
a15911cb482539848c9f691a217547a65d48d4d1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/shapes/zero_objects.lean
2f8c9f325e6146b40dda436ced2b6c95f9eade21
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,987
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin -/ import category_theory.limits.shapes.terminal /-! # Zero objects A category "has a zero object" if it has an object which is both initial and terminal. Having a zero object provides zero morphisms, as the unique morphisms factoring through the zero object; see `category_theory.limits.shapes.zero_morphisms`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v u v' u' open category_theory open category_theory.category variables {C : Type u} [category.{v} C] variables {D : Type u'} [category.{v'} D] namespace category_theory namespace limits /-- An object `X` in a category is a *zero object* if for every object `Y` there is a unique morphism `to : X → Y` and a unique morphism `from : Y → X`. This is a characteristic predicate for `has_zero_object`. -/ structure is_zero (X : C) : Prop := (unique_to : ∀ Y, nonempty (unique (X ⟶ Y))) (unique_from : ∀ Y, nonempty (unique (Y ⟶ X))) namespace is_zero variables {X Y : C} /-- If `h : is_zero X`, then `h.to Y` is a choice of unique morphism `X → Y`. -/ protected def «to» (h : is_zero X) (Y : C) : X ⟶ Y := @default (X ⟶ Y) $ @unique.inhabited _ $ (h.unique_to Y).some lemma eq_to (h : is_zero X) (f : X ⟶ Y) : f = h.to Y := @unique.eq_default _ (id _) _ lemma to_eq (h : is_zero X) (f : X ⟶ Y) : h.to Y = f := (h.eq_to f).symm /-- If `h : is_zero X`, then `h.from Y` is a choice of unique morphism `Y → X`. -/ protected def «from» (h : is_zero X) (Y : C) : Y ⟶ X := @default (Y ⟶ X) $ @unique.inhabited _ $ (h.unique_from Y).some lemma eq_from (h : is_zero X) (f : Y ⟶ X) : f = h.from Y := @unique.eq_default _ (id _) _ lemma from_eq (h : is_zero X) (f : Y ⟶ X) : h.from Y = f := (h.eq_from f).symm lemma eq_of_src (hX : is_zero X) (f g : X ⟶ Y) : f = g := (hX.eq_to f).trans (hX.eq_to g).symm lemma eq_of_tgt (hX : is_zero X) (f g : Y ⟶ X) : f = g := (hX.eq_from f).trans (hX.eq_from g).symm /-- Any two zero objects are isomorphic. -/ def iso (hX : is_zero X) (hY : is_zero Y) : X ≅ Y := { hom := hX.to Y, inv := hX.from Y, hom_inv_id' := hX.eq_of_src _ _, inv_hom_id' := hY.eq_of_src _ _, } /-- A zero object is in particular initial. -/ protected def is_initial (hX : is_zero X) : is_initial X := @is_initial.of_unique _ _ X $ λ Y, (hX.unique_to Y).some /-- A zero object is in particular terminal. -/ protected def is_terminal (hX : is_zero X) : is_terminal X := @is_terminal.of_unique _ _ X $ λ Y, (hX.unique_from Y).some /-- The (unique) isomorphism between any initial object and the zero object. -/ def iso_is_initial (hX : is_zero X) (hY : is_initial Y) : X ≅ Y := hX.is_initial.unique_up_to_iso hY /-- The (unique) isomorphism between any terminal object and the zero object. -/ def iso_is_terminal (hX : is_zero X) (hY : is_terminal Y) : X ≅ Y := hX.is_terminal.unique_up_to_iso hY lemma of_iso (hY : is_zero Y) (e : X ≅ Y) : is_zero X := begin refine ⟨λ Z, ⟨⟨⟨e.hom ≫ hY.to Z⟩, λ f, _⟩⟩, λ Z, ⟨⟨⟨hY.from Z ≫ e.inv⟩, λ f, _⟩⟩⟩, { rw ← cancel_epi e.inv, apply hY.eq_of_src, }, { rw ← cancel_mono e.hom, apply hY.eq_of_tgt, }, end lemma op (h : is_zero X) : is_zero (opposite.op X) := ⟨λ Y, ⟨⟨⟨(h.from (opposite.unop Y)).op⟩, λ f, quiver.hom.unop_inj (h.eq_of_tgt _ _)⟩⟩, λ Y, ⟨⟨⟨(h.to (opposite.unop Y)).op⟩, λ f, quiver.hom.unop_inj (h.eq_of_src _ _)⟩⟩⟩ lemma unop {X : Cᵒᵖ} (h : is_zero X) : is_zero (opposite.unop X) := ⟨λ Y, ⟨⟨⟨(h.from (opposite.op Y)).unop⟩, λ f, quiver.hom.op_inj (h.eq_of_tgt _ _)⟩⟩, λ Y, ⟨⟨⟨(h.to (opposite.op Y)).unop⟩, λ f, quiver.hom.op_inj (h.eq_of_src _ _)⟩⟩⟩ end is_zero end limits open category_theory.limits lemma iso.is_zero_iff {X Y : C} (e : X ≅ Y) : is_zero X ↔ is_zero Y := ⟨λ h, h.of_iso e.symm, λ h, h.of_iso e⟩ lemma functor.is_zero (F : C ⥤ D) (hF : ∀ X, is_zero (F.obj X)) : is_zero F := begin split; intros G; refine ⟨⟨⟨_⟩, _⟩⟩, { refine { app := λ X, (hF _).to _, naturality' := _ }, intros, exact (hF _).eq_of_src _ _ }, { intro f, ext, apply (hF _).eq_of_src _ _ }, { refine { app := λ X, (hF _).from _, naturality' := _ }, intros, exact (hF _).eq_of_tgt _ _ }, { intro f, ext, apply (hF _).eq_of_tgt _ _ }, end namespace limits variables (C) /-- A category "has a zero object" if it has an object which is both initial and terminal. -/ class has_zero_object : Prop := (zero : ∃ X : C, is_zero X) instance has_zero_object_punit : has_zero_object (discrete punit) := { zero := ⟨⟨⟨⟩⟩, by tidy, by tidy⟩, } section variables [has_zero_object C] /-- Construct a `has_zero C` for a category with a zero object. This can not be a global instance as it will trigger for every `has_zero C` typeclass search. -/ protected def has_zero_object.has_zero : has_zero C := { zero := has_zero_object.zero.some } localized "attribute [instance] category_theory.limits.has_zero_object.has_zero" in zero_object lemma is_zero_zero : is_zero (0 : C) := has_zero_object.zero.some_spec instance has_zero_object_op : has_zero_object Cᵒᵖ := ⟨⟨opposite.op 0, is_zero.op (is_zero_zero C)⟩⟩ end open_locale zero_object lemma has_zero_object_unop [has_zero_object Cᵒᵖ] : has_zero_object C := ⟨⟨opposite.unop 0, is_zero.unop (is_zero_zero Cᵒᵖ)⟩⟩ variables {C} lemma is_zero.has_zero_object {X : C} (hX : is_zero X) : has_zero_object C := ⟨⟨X, hX⟩⟩ /-- Every zero object is isomorphic to *the* zero object. -/ def is_zero.iso_zero [has_zero_object C] {X : C} (hX : is_zero X) : X ≅ 0 := hX.iso (is_zero_zero C) lemma is_zero.obj [has_zero_object D] {F : C ⥤ D} (hF : is_zero F) (X : C) : is_zero (F.obj X) := begin let G : C ⥤ D := (category_theory.functor.const C).obj 0, have hG : is_zero G := functor.is_zero _ (λ X, is_zero_zero _), let e : F ≅ G := hF.iso hG, exact (is_zero_zero _).of_iso (e.app X), end namespace has_zero_object variables [has_zero_object C] /-- There is a unique morphism from the zero object to any object `X`. -/ protected def unique_to (X : C) : unique (0 ⟶ X) := ((is_zero_zero C).unique_to X).some /-- There is a unique morphism from any object `X` to the zero object. -/ protected def unique_from (X : C) : unique (X ⟶ 0) := ((is_zero_zero C).unique_from X).some localized "attribute [instance] category_theory.limits.has_zero_object.unique_to" in zero_object localized "attribute [instance] category_theory.limits.has_zero_object.unique_from" in zero_object @[ext] lemma to_zero_ext {X : C} (f g : X ⟶ 0) : f = g := (is_zero_zero C).eq_of_tgt _ _ @[ext] lemma from_zero_ext {X : C} (f g : 0 ⟶ X) : f = g := (is_zero_zero C).eq_of_src _ _ instance (X : C) : subsingleton (X ≅ 0) := by tidy instance {X : C} (f : 0 ⟶ X) : mono f := { right_cancellation := λ Z g h w, by ext, } instance {X : C} (f : X ⟶ 0) : epi f := { left_cancellation := λ Z g h w, by ext, } instance zero_to_zero_is_iso (f : (0 : C) ⟶ 0) : is_iso f := by convert (show is_iso (𝟙 (0 : C)), by apply_instance) /-- A zero object is in particular initial. -/ def zero_is_initial : is_initial (0 : C) := (is_zero_zero C).is_initial /-- A zero object is in particular terminal. -/ def zero_is_terminal : is_terminal (0 : C) := (is_zero_zero C).is_terminal /-- A zero object is in particular initial. -/ @[priority 10] instance has_initial : has_initial C := has_initial_of_unique 0 /-- A zero object is in particular terminal. -/ @[priority 10] instance has_terminal : has_terminal C := has_terminal_of_unique 0 /-- The (unique) isomorphism between any initial object and the zero object. -/ def zero_iso_is_initial {X : C} (t : is_initial X) : 0 ≅ X := zero_is_initial.unique_up_to_iso t /-- The (unique) isomorphism between any terminal object and the zero object. -/ def zero_iso_is_terminal {X : C} (t : is_terminal X) : 0 ≅ X := zero_is_terminal.unique_up_to_iso t /-- The (unique) isomorphism between the chosen initial object and the chosen zero object. -/ def zero_iso_initial [has_initial C] : 0 ≅ ⊥_ C := zero_is_initial.unique_up_to_iso initial_is_initial /-- The (unique) isomorphism between the chosen terminal object and the chosen zero object. -/ def zero_iso_terminal [has_terminal C] : 0 ≅ ⊤_ C := zero_is_terminal.unique_up_to_iso terminal_is_terminal @[priority 100] instance has_strict_initial : initial_mono_class C := initial_mono_class.of_is_initial zero_is_initial (λ X, category_theory.mono _) end has_zero_object end limits open category_theory.limits open_locale zero_object lemma functor.is_zero_iff [has_zero_object D] (F : C ⥤ D) : is_zero F ↔ ∀ X, is_zero (F.obj X) := ⟨λ hF X, hF.obj X, functor.is_zero _⟩ end category_theory
92daaa0fc2b7df45e5ce70f68d4373f773ac6d9f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/rat/basic.lean
c251ff288ed30f73be78271cee4c4f922a746cf1
[ "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
1,505
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import algebra.field.defs import data.rat.defs /-! # Field Structure on the Rational Numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Summary We put the (discrete) field structure on the type `ℚ` of rational numbers that was defined in `data.rat.defs`. ## Main Definitions - `rat.field` is the field structure on `ℚ`. ## Implementation notes We have to define the field structure in a separate file to avoid cyclic imports: the `field` class contains a map from `ℚ` (see `field`'s docstring for the rationale), so we have a dependency `rat.field → field → rat` that is reflected in the import hierarchy `data.rat.basic → algebra.field.basic → data.rat.defs`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom -/ namespace rat instance : field ℚ := { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), inv := has_inv.inv, rat_cast := id, rat_cast_mk := λ a b h1 h2, (num_div_denom _).symm, qsmul := (*), .. rat.comm_ring, .. rat.comm_group_with_zero} /- Extra instances to short-circuit type class resolution -/ instance : division_ring ℚ := by apply_instance end rat
060b3f4ba2e2e2db1d93f7ab95eb2a56952fa13b
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/init/reserved_notation.hlean
caac2d23e2c4bf802ef48d9bcb7577866462ac61
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
7,680
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.datatypes notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r structure has_zero [class] (A : Type) := (zero : A) structure has_one [class] (A : Type) := (one : A) structure has_add [class] (A : Type) := (add : A → A → A) structure has_mul [class] (A : Type) := (mul : A → A → A) structure has_inv [class] (A : Type) := (inv : A → A) structure has_neg [class] (A : Type) := (neg : A → A) structure has_sub [class] (A : Type) := (sub : A → A → A) structure has_div [class] (A : Type) := (div : A → A → A) structure has_mod [class] (A : Type) := (mod : A → A → A) structure has_dvd.{l} [class] (A : Type.{l}) : Type.{l+1} := (dvd : A → A → Type.{l}) structure has_le.{l} [class] (A : Type.{l}) : Type.{l+1} := (le : A → A → Type.{l}) structure has_lt.{l} [class] (A : Type.{l}) : Type.{l+1} := (lt : A → A → Type.{l}) definition zero [reducible] {A : Type} [s : has_zero A] : A := has_zero.zero A definition one [reducible] {A : Type} [s : has_one A] : A := has_one.one A definition add [reducible] {A : Type} [s : has_add A] : A → A → A := has_add.add definition mul {A : Type} [s : has_mul A] : A → A → A := has_mul.mul definition sub {A : Type} [s : has_sub A] : A → A → A := has_sub.sub definition div {A : Type} [s : has_div A] : A → A → A := has_div.div definition dvd {A : Type} [s : has_dvd A] : A → A → Type := has_dvd.dvd definition mod {A : Type} [s : has_mod A] : A → A → A := has_mod.mod definition neg {A : Type} [s : has_neg A] : A → A := has_neg.neg definition inv {A : Type} [s : has_inv A] : A → A := has_inv.inv definition le {A : Type} [s : has_le A] : A → A → Type := has_le.le definition lt {A : Type} [s : has_lt A] : A → A → Type := has_lt.lt definition ge [reducible] {A : Type} [s : has_le A] (a b : A) : Type := le b a definition gt [reducible] {A : Type} [s : has_lt A] (a b : A) : Type := lt b a definition bit0 [reducible] {A : Type} [s : has_add A] (a : A) : A := add a a definition bit1 [reducible] {A : Type} [s₁ : has_one A] [s₂ : has_add A] (a : A) : A := add (bit0 a) one definition num_has_zero [reducible] [instance] : has_zero num := has_zero.mk num.zero definition num_has_one [reducible] [instance] : has_one num := has_one.mk (num.pos pos_num.one) definition pos_num_has_one [reducible] [instance] : has_one pos_num := has_one.mk (pos_num.one) namespace pos_num open bool definition is_one (a : pos_num) : bool := pos_num.rec_on a tt (λn r, ff) (λn r, ff) definition pred (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, bit0 n) (λn r, bool.rec_on (is_one n) (bit1 r) one) definition size (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, succ r) (λn r, succ r) definition add (a b : pos_num) : pos_num := pos_num.rec_on a succ (λn f b, pos_num.rec_on b (succ (bit1 n)) (λm r, succ (bit1 (f m))) (λm r, bit1 (f m))) (λn f b, pos_num.rec_on b (bit1 n) (λm r, bit1 (f m)) (λm r, bit0 (f m))) b end pos_num definition pos_num_has_add [reducible] [instance] : has_add pos_num := has_add.mk pos_num.add namespace num open pos_num definition add (a b : num) : num := num.rec_on a b (λpa, num.rec_on b (pos pa) (λpb, pos (pos_num.add pa pb))) end num definition num_has_add [reducible] [instance] : has_add num := has_add.mk num.add definition std.priority.default : num := 1000 definition std.priority.max : num := 4294967295 namespace nat protected definition prio := num.add std.priority.default 100 protected definition add (a b : nat) : nat := nat.rec a (λ b₁ r, succ r) b definition of_num (n : num) : nat := num.rec zero (λ n, pos_num.rec (succ zero) (λ n r, nat.add (nat.add r r) (succ zero)) (λ n r, nat.add r r) n) n end nat definition nat_has_zero [reducible] [instance] [priority nat.prio] : has_zero nat := has_zero.mk nat.zero definition nat_has_one [reducible] [instance] [priority nat.prio] : has_one nat := has_one.mk (nat.succ (nat.zero)) definition nat_has_add [reducible] [instance] [priority nat.prio] : has_add nat := has_add.mk nat.add /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ definition std.prec.max : num := 1024 -- the strength of application, identifiers, (, [, etc. definition std.prec.arrow : num := 25 /- The next definition is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ definition std.prec.max_plus := num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ std.prec.max))))))))) /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixr ` ∘ `:60 -- input with \comp reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and type constructors -/ reserve infixr ` ⊎ `:30 reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:100 reserve infix ` ^ `:80 reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:67 /- in the HoTT library we might not always want to overload the following notation, so we put it in namespace algebra -/ infix + := add infix * := mul infix - := sub infix / := div infix ∣ := dvd infix % := mod prefix - := neg namespace algebra postfix ⁻¹ := inv end algebra infix ≤ := le infix ≥ := ge infix < := lt infix > := gt notation [parsing_only] x ` +[`:65 A:0 `] `:0 y:65 := @add A _ x y notation [parsing_only] x ` -[`:65 A:0 `] `:0 y:65 := @sub A _ x y notation [parsing_only] x ` *[`:70 A:0 `] `:0 y:70 := @mul A _ x y notation [parsing_only] x ` /[`:70 A:0 `] `:0 y:70 := @div A _ x y notation [parsing_only] x ` ∣[`:70 A:0 `] `:0 y:70 := @dvd A _ x y notation [parsing_only] x ` %[`:70 A:0 `] `:0 y:70 := @mod A _ x y notation [parsing_only] x ` ≤[`:50 A:0 `] `:0 y:50 := @le A _ x y notation [parsing_only] x ` ≥[`:50 A:0 `] `:0 y:50 := @ge A _ x y notation [parsing_only] x ` <[`:50 A:0 `] `:0 y:50 := @lt A _ x y notation [parsing_only] x ` >[`:50 A:0 `] `:0 y:50 := @gt A _ x y
6fc9f6b955e43767c088f17aba5ceac8dcadc780
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/src/Lean/Elab/Do.lean
c56b0cb4d39bfb0f0a31e2fb7a558fb04002435e
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
70,559
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Elab.BindersUtil import Lean.Elab.PatternVar import Lean.Elab.Quotation.Util import Lean.Parser.Do -- HACK: avoid code explosion until heuristics are improved set_option compiler.reuse false namespace Lean.Elab.Term open Lean.Parser.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == ``Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == ``Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == ``Lean.Parser.Term.do || k == ``Lean.Parser.Term.doSeqIndent || k == ``Lean.Parser.Term.doSeqBracketed || k == ``Lean.Parser.Term.termReturn || k == ``Lean.Parser.Term.termUnless || k == ``Lean.Parser.Term.termTry || k == ``Lean.Parser.Term.termFor /-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/ private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool := let k := letDeclArg.getKind if k == ``Lean.Parser.Term.letPatDecl then false else if k == ``Lean.Parser.Term.letEqnsDecl then true else if k == ``Lean.Parser.Term.letIdDecl then -- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType let binders := letDeclArg[1] binders.getNumArgs > 0 else false /-- Return `true` if the given `letDecl` contains binders. -/ private def letDeclHasBinders (letDecl : Syntax) : Bool := letDeclArgHasBinders letDecl[0] /-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/ private def liftMethodForbiddenBinder (stx : Syntax) : Bool := let k := stx.getKind if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts || k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then -- It is never ok to lift over this kind of binder true -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not else if k == ``Lean.Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Lean.Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``Lean.Parser.Term.doLetArrow then letDeclArgHasBinders stx[2] else false private partial def hasLiftMethod : Syntax → Bool | Syntax.node k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == ``Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr α : Expr expectedType : Expr isPure : Bool -- `true` when it is a pure `do` block. That is, Lean implicitly inserted the `Id` Monad. private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do let u ← getDecLevel type let id := Lean.mkConst ``Id [u] pure { m := id, α := type, expectedType := mkApp id type, isPure := true } private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid 'do' notation, expected type is not available" | some expectedType => let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do match type with | Expr.app m α _ => try let bindInstType ← mkAppM ``Bind #[m] let _ ← Meta.synthInstance bindInstType return some { m := m, α := α, expectedType := expectedType, isPure := false } catch _ => return none | _ => return none let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do match (← extractStep? type) with | some r => return r | none => let typeNew ← whnfCore type if typeNew != type then extract? typeNew else if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available" match (← unfoldDefinition? typeNew) with | some typeNew => extract? typeNew | none => return none match (← extract? expectedType) with | some r => return r | none => mkIdBindFor expectedType namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Name patterns : Syntax rhs : σ deriving Inhabited /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited /- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : NameSet := {} -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code → MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.«break» _ => m!"break {us}" | Code.«continue» _ => m!"continue {us}" | Code.«return» _ v => m!"return {v} {us}" | Code.«match» _ _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec loop : Code → Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.«match» _ _ _ _ alts => alts.any (loop ·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«return» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.«action» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensure_expected_type% "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code → MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl where name : Name params : Array (Name × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.insert ·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.erase ·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← ``(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref) | rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref) | rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← ``(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code → TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.«match» ref g ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (·.insert ·) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := ``((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := ``(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.«match» ref genParam discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternVars pattern <|> Array.map Syntax.getId <$> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternsVars patterns <|> Array.map Syntax.getId <$> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == ``Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `leading_parser "have " >> Term.haveDecl` where ``` haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1][0] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == ``Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == ``Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == ``Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $p:doIfProp then $t else $e) => pure none | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do e ← if eIsSeq then e else `(doSeq|$e:doElem) e ← withRef cond <| match cond with | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e) | _ => `(doElem| if%$i $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1][0], cond := doIf[1][1], thenBranch := doIf[3], elseBranch := doIf[5][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => ``(MProd.mk $elem $tuple)) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == ``Lean.Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(← mkIdentFromRef uvars[0]):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | Kind.regular => true | _ => false structure Context where m : Syntax -- Syntax to reference the monad associated with the do notation. uvars : Array Name kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read let uvarIdents ← ctx.uvars.mapM mkIdentFromRef mkTuple uvarIdents def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u)) | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«continue» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«break» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == ``Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == ``Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action ``(($action : $((←read).m) PUnit)) ``(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == ``Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == ``Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode ``Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == ``Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == ``Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType id arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) ``(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == ``Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do let kind := reassign.getKind if kind == ``Lean.Parser.Term.doReassign then -- doReassign := leading_parser (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensure_type_of% $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then ``(if $cond then $thenBranch else $elseBranch) else let h := optIdent[0] ``(if $h:ident : $cond then $thenBranch else $elseBranch) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(type_of% $(← mkIdentFromRef id)) else `(_) let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => withRef ref <| returnToTerm val | Code.«continue» ref => withRef ref continueToTerm | Code.«break» ref => withRef ref breakToTerm | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | Code.«match» ref genParam discrs optType alts => do let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple (← uvars.mapM mkIdentFromRef) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.«break» u => $u:term := u; break | DoResultBC.«continue» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.«pure» a u => $u:term := u; pure a | DoResultPR.«return» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; pure a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; return a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.«pure» a u => $u:term := u; pure a | DoResultPRBC.«return» a u => $u:term := u; return a | DoResultPRBC.«break» u => $u:term := u; break | DoResultPRBC.«continue» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax m : Syntax -- Syntax representing the monad associated with the do notation. mutableVars : NameSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x def checkNotShadowingMutable (xs : Array Name) : M Unit := do let throwInvalidShadowing (x : Name) : M Unit := throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed" let ctx ← read for x in xs do if ctx.mutableVars.contains x then throwInvalidShadowing x def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Name term : Syntax def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax | stx@(Syntax.node k args) => if liftMethodDelimiter k then return stx else if k == ``Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do if inBinder then throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`" let term := args[1] let term ← expandLiftMethodAux inQuot inBinder term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx) let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder) return Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run [] pure (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == ``Lean.Parser.Term.doLetArrow || kind == ``Lean.Parser.Term.doLet || kind == ``Lean.Parser.Term.doLetRec || kind == ``Lean.Parser.Term.doHave || kind == ``Lean.Parser.Term.doReassign || kind == ``Lean.Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == ``Lean.Parser.Term.doIdDecl then let y := decl[0].getId checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == ``Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == ``Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == ``Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1] let y := doForDecl[0] let ys := doForDecl[2] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do let toStreamFn ← withRef ys ``(toStream) let auxDo ← `(do let mut s := $toStreamFn:ident $ys for $doForDecls:doForDecl,* do match Stream.next? s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let x := doForDecls[0][0] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0][2] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef) if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(for_in% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensure_expected_type% "type mismatch, 'for'" PUnit.unit) | some a => return ensure_expected_type% "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(for_in% $(xs) $uvarsTuple fun $x r => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensure_expected_type% "type mismatch, 'for'" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let genParam := doMatch[1] let discrs := doMatch[2] let optType := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1] let vars ← getPatternsVarsEx patterns.getSepArgs withRef patterns <| checkNotShadowingMutable vars let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref genParam discrs optType alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == ``Lean.Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x.getId] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == ``Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)) else let type := «catch».optType[1] ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular ``(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "'do'-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← expandLiftMethod doElem if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems let k := doElem.getKind if k == ``Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doHave then let var := getDoHaveVar doElem checkNotShadowingMutable #[var] mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == ``Lean.Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == ``Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == ``Lean.Parser.Term.doIf then doIfToCode doElem doElems else if k == ``Lean.Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == ``Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == ``Lean.Parser.Term.doMatch then doMatchToCode doElem doElems else if k == ``Lean.Parser.Term.doTry then doTryToCode doElem doElems else if k == ``Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == ``Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == ``Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == ``Lean.Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Lean.Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == ``Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}" end def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result private partial def ensureArrowNotUsed (stx : Syntax) : MacroM Unit := do /- We expand macros here because we stop the search at nested `do`s So, we also want to stop the search at macros that expand `do ...`. Hopefully this is not a performance bottleneck in practice. -/ let stx ← expandMacros stx stx.getArgs.forM go where go (stx : Syntax) : MacroM Unit := match stx with | Syntax.node k args => do if k == ``Parser.Term.liftMethod || k == ``Parser.Term.doLetArrow || k == ``Parser.Term.doReassignArrow || k == ``Parser.Term.doIfLetBind then Macro.throwErrorAt stx "`←` and `<-` are not allowed in pure `do` blocks, i.e., blocks where Lean implicitly used the `Id` monad" unless k == ``Parser.Term.do do args.forM go | _ => pure () @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? if bindInfo.isPure then liftMacroM <| ensureArrowNotUsed stx let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do] stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem ``Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem ``Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem ``Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem ``Lean.Parser.Term.doReturn end Lean.Elab.Term
79ce26e53797451f4110a9db8ff58a0fd4691c8b
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq8.lean
53c368cf5c08363f662a2dc1f5a763099644d243
[ "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
223
lean
import data.examples.vector open vector definition map {A B C : Type} (f : A → B → C) : Π {n}, vector A n → vector B n → vector C n | map nil nil := nil | map (a :: va) (b :: vb) := f a b :: map va vb
c152cec8204b844813e4513a5456b7955c915930
92b50235facfbc08dfe7f334827d47281471333b
/library/logic/examples/colog88.lean
1532a9ce2570215e0046bd33d89b01dc2fc2df8d
[ "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
2,685
lean
/- Example from "Inductively defined types", from Thierry Coquand and Christine Paulin, COLOG-88. It shows it is inconsistent to allow inductive datatypes such as inductive A : Type := | intro : ((A → Prop) → Prop) → A -/ /- Phi is a positive, but not strictly positive, operator. -/ definition Phi (A : Type) := (A → Prop) → Prop /- If we were allowed to form the inductive type inductive A: Type := | introA : Phi A -> A we would get the following -/ universe l -- The new type A axiom A : Type.{l} -- The constructor axiom introA : Phi A → A -- The eliminator axiom recA : Π {C : A → Type}, (Π (p : Phi A), C (introA p)) → (Π (a : A), C a) -- The "computational rule" axiom recA_comp : Π {C : A → Type} (H : Π (p : Phi A), C (introA p)) (p : Phi A), recA H (introA p) = H p -- The recursor could be used to define matchA definition matchA (a : A) : Phi A := recA (λ p, p) a -- and the computation rule would allows us to define lemma betaA (p : Phi A) : matchA (introA p) = p := !recA_comp -- As in all inductive datatypes, we would be able to prove that constructors are injective. lemma introA_injective : ∀ {p p' : Phi A}, introA p = introA p' → p = p' := λ p p' h, assert aux : matchA (introA p) = matchA (introA p'), by rewrite h, by rewrite [*betaA at aux]; exact aux -- For any type T, there is an injection from T to (T → Prop) definition i {T : Type} : T → (T → Prop) := λ x y, x = y lemma i_injective {T : Type} {a b : T} : i a = i b → a = b := λ h, have e₁ : i a a = i b a, by rewrite [h], have e₂ : (a = a) = (b = a), from e₁, have e₃ : b = a, from eq.subst e₂ rfl, eq.symm e₃ -- Hence, by composition, we get an injection f from (A → Prop) to A definition f : (A → Prop) → A := λ p, introA (i p) lemma f_injective : ∀ {p p' : A → Prop}, f p = f p' → p = p':= λ (p p' : A → Prop) (h : introA (i p) = introA (i p')), i_injective (introA_injective h) /- We are now back to the usual Cantor-Russel paradox. We can define -/ definition P0 (a : A) : Prop := ∃ (P : A → Prop), f P = a ∧ ¬ P a -- i.e., P0 a := codes a set P such that x∉P definition x0 : A := f P0 lemma fP0_eq : f P0 = x0 := rfl lemma not_P0_x0 : ¬ P0 x0 := λ h : P0 x0, obtain (P : A → Prop) (hp : f P = x0 ∧ ¬ P x0), from h, have fp_eq : f P = f P0, from and.elim_left hp, assert p_eq : P = P0, from f_injective fp_eq, have nh : ¬ P0 x0, by rewrite [p_eq at hp]; exact (and.elim_right hp), absurd h nh lemma P0_x0 : P0 x0 := exists.intro P0 (and.intro fP0_eq not_P0_x0) theorem inconsistent : false := absurd P0_x0 not_P0_x0
f429f1f948a719ea33232bbfcaf24205b96399da
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/order/compactly_generated.lean
ae619f00eb100b1dd5436b5979a050841e6d9eb0
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,363
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.finset.order import order.atoms import order.order_iso_nat import order.zorn import tactic.tfae /-! # Compactness properties for complete lattices For complete lattices, there are numerous equivalent ways to express the fact that the relation `>` is well-founded. In this file we define three especially-useful characterisations and provide proofs that they are indeed equivalent to well-foundedness. ## Main definitions * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `complete_lattice.is_compact_element` * `complete_lattice.is_compactly_generated` ## Main results The main result is that the following four conditions are equivalent for a complete lattice: * `well_founded (>)` * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `∀ k, complete_lattice.is_compact_element k` This is demonstrated by means of the following four lemmas: * `complete_lattice.well_founded.is_Sup_finite_compact` * `complete_lattice.is_Sup_finite_compact.is_sup_closed_compact` * `complete_lattice.is_sup_closed_compact.well_founded` * `complete_lattice.is_Sup_finite_compact_iff_all_elements_compact` We also show well-founded lattices are compactly generated (`complete_lattice.compactly_generated_of_well_founded`). ## References - [G. Călugăreanu, *Lattice Concepts of Module Theory*][calugareanu] ## Tags complete lattice, well-founded, compact -/ variables {α : Type*} [complete_lattice α] namespace complete_lattice variables (α) /-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset contains its `Sup`. -/ def is_sup_closed_compact : Prop := ∀ (s : set α) (h : s.nonempty), (∀ a b, a ∈ s → b ∈ s → a ⊔ b ∈ s) → (Sup s) ∈ s /-- A compactness property for a complete lattice is that any subset has a finite subset with the same `Sup`. -/ def is_Sup_finite_compact : Prop := ∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id /-- An element `k` of a complete lattice is said to be compact if any set with `Sup` above `k` has a finite subset with `Sup` above `k`. Such an element is also called "finite" or "S-compact". -/ def is_compact_element {α : Type*} [complete_lattice α] (k : α) := ∀ s : set α, k ≤ Sup s → ∃ t : finset α, ↑t ⊆ s ∧ k ≤ t.sup id /-- An element `k` is compact if and only if any directed set with `Sup` above `k` already got above `k` at some point in the set. -/ theorem is_compact_element_iff_le_of_directed_Sup_le (k : α) : is_compact_element k ↔ ∀ s : set α, s.nonempty → directed_on (≤) s → k ≤ Sup s → ∃ x : α, x ∈ s ∧ k ≤ x := begin classical, split, { by_cases hbot : k = ⊥, -- Any nonempty directed set certainly has sup above ⊥ { rintros _ _ ⟨x, hx⟩ _ _, use x, by simp only [hx, hbot, bot_le, and_self], }, { intros hk s hne hdir hsup, obtain ⟨t, ht⟩ := hk s hsup, -- If t were empty, its sup would be ⊥, which is not above k ≠ ⊥. have tne : t.nonempty, { by_contradiction n, rw [finset.nonempty_iff_ne_empty, not_not] at n, simp only [n, true_and, set.empty_subset, finset.coe_empty, finset.sup_empty, le_bot_iff] at ht, exact absurd ht hbot, }, -- certainly every element of t is below something in s, since ↑t ⊆ s. have t_below_s : ∀ x ∈ t, ∃ y ∈ s, x ≤ y, from λ x hxt, ⟨x, ht.left hxt, by refl⟩, obtain ⟨x, ⟨hxs, hsupx⟩⟩ := finset.sup_le_of_le_directed s hne hdir t t_below_s, exact ⟨x, ⟨hxs, le_trans ht.right hsupx⟩⟩, }, }, { intros hk s hsup, -- Consider the set of finite joins of elements of the (plain) set s. let S : set α := { x | ∃ t : finset α, ↑t ⊆ s ∧ x = t.sup id }, -- S is directed, nonempty, and still has sup above k. have dir_US : directed_on (≤) S, { rintros x ⟨c, hc⟩ y ⟨d, hd⟩, use x ⊔ y, split, { use c ∪ d, split, { simp only [hc.left, hd.left, set.union_subset_iff, finset.coe_union, and_self], }, { simp only [hc.right, hd.right, finset.sup_union], }, }, simp only [and_self, le_sup_left, le_sup_right], }, have sup_S : Sup s ≤ Sup S, { apply Sup_le_Sup, intros x hx, use {x}, simpa only [and_true, id.def, finset.coe_singleton, eq_self_iff_true, finset.sup_singleton, set.singleton_subset_iff], }, have Sne : S.nonempty, { suffices : ⊥ ∈ S, from set.nonempty_of_mem this, use ∅, simp only [set.empty_subset, finset.coe_empty, finset.sup_empty, eq_self_iff_true, and_self], }, -- Now apply the defn of compact and finish. obtain ⟨j, ⟨hjS, hjk⟩⟩ := hk S Sne dir_US (le_trans hsup sup_S), obtain ⟨t, ⟨htS, htsup⟩⟩ := hjS, use t, exact ⟨htS, by rwa ←htsup⟩, }, end /-- A compact element `k` has the property that any directed set lying strictly below `k` has its Sup strictly below `k`. -/ lemma is_compact_element.directed_Sup_lt_of_lt {α : Type*} [complete_lattice α] {k : α} (hk : is_compact_element k) {s : set α} (hemp : s.nonempty) (hdir : directed_on (≤) s) (hbelow : ∀ x ∈ s, x < k) : Sup s < k := begin rw is_compact_element_iff_le_of_directed_Sup_le at hk, by_contradiction, have sSup : Sup s ≤ k, from Sup_le (λ s hs, (hbelow s hs).le), replace sSup : Sup s = k := eq_iff_le_not_lt.mpr ⟨sSup, h⟩, obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le, obtain hxk := hbelow x hxs, exact hxk.ne (hxk.le.antisymm hkx), end lemma finset_sup_compact_of_compact {α β : Type*} [complete_lattice α] {f : β → α} (s : finset β) (h : ∀ x ∈ s, is_compact_element (f x)) : is_compact_element (s.sup f) := begin classical, rw is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, change f with id ∘ f, rw ←finset.sup_finset_image, apply finset.sup_le_of_le_directed d hemp hdir, rintros x hx, obtain ⟨p, ⟨hps, rfl⟩⟩ := finset.mem_image.mp hx, specialize h p hps, rw is_compact_element_iff_le_of_directed_Sup_le at h, specialize h d hemp hdir (le_trans (finset.le_sup hps) hsup), simpa only [exists_prop], end lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) : is_Sup_finite_compact α := begin intros s, let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x }, have hp : p.nonempty, { use [⊥, ∅], simp, }, obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp, use t, simp only [ht₁, ht₂, true_and], apply le_antisymm, { apply Sup_le, intros y hy, classical, have hy' : (insert y t).sup id ∈ p, { use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, }, have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), }, rw ← hm _ hy' hm', simp, }, { rw [← ht₂, finset.sup_id_eq_Sup], exact Sup_le_Sup ht₁, }, end lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) : is_sup_closed_compact α := begin intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h, cases t.eq_empty_or_nonempty with h h, { subst h, rw finset.sup_empty at ht₂, rw ht₂, simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], }, { rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, }, end lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) : well_founded ((>) : α → α → Prop) := begin rw rel_embedding.well_founded_iff_no_descending_seq, rintros ⟨a⟩, suffices : Sup (set.range a) ∈ set.range a, { obtain ⟨n, hn⟩ := set.mem_range.mp this, have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], }, apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, }, apply h (set.range a), { use a 37, apply set.mem_range_self, }, { rintros x y ⟨m, hm⟩ ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply a.to_rel_hom.map_sup, }, end lemma is_Sup_finite_compact_iff_all_elements_compact : is_Sup_finite_compact α ↔ (∀ k : α, is_compact_element k) := begin split, { intros h k s hs, obtain ⟨t, ⟨hts, htsup⟩⟩ := h s, use [t, hts], rwa ←htsup, }, { intros h s, obtain ⟨t, ⟨hts, htsup⟩⟩ := h (Sup s) s (by refl), have : Sup s = t.sup id, { suffices : t.sup id ≤ Sup s, by { apply le_antisymm; assumption }, simp only [id.def, finset.sup_le_iff], intros x hx, apply le_Sup, exact hts hx, }, use [t, hts], assumption, }, end lemma well_founded_characterisations : tfae [well_founded ((>) : α → α → Prop), is_Sup_finite_compact α, is_sup_closed_compact α, ∀ k : α, is_compact_element k] := begin tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, }, tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, }, tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, }, tfae_have : 2 ↔ 4, by { exact is_Sup_finite_compact_iff_all_elements_compact α }, tfae_finish, end lemma well_founded_iff_is_Sup_finite_compact : well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α := (well_founded_characterisations α).out 0 1 lemma is_Sup_finite_compact_iff_is_sup_closed_compact : is_Sup_finite_compact α ↔ is_sup_closed_compact α := (well_founded_characterisations α).out 1 2 lemma is_sup_closed_compact_iff_well_founded : is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) := (well_founded_characterisations α).out 2 0 alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔ _ is_sup_closed_compact.is_Sup_finite_compact alias is_sup_closed_compact_iff_well_founded ↔ _ well_founded.is_sup_closed_compact end complete_lattice /-- A complete lattice is said to be compactly generated if any element is the `Sup` of compact elements. -/ class is_compactly_generated (α : Type*) [complete_lattice α] : Prop := (exists_Sup_eq : ∀ (x : α), ∃ (s : set α), (∀ x ∈ s, complete_lattice.is_compact_element x) ∧ Sup s = x) section variables {α} [is_compactly_generated α] {a b : α} {s : set α} @[simp] lemma Sup_compact_le_eq (b) : Sup {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} = b := begin rcases is_compactly_generated.exists_Sup_eq b with ⟨s, hs, rfl⟩, exact le_antisymm (Sup_le (λ c hc, hc.2)) (Sup_le_Sup (λ c cs, ⟨hs c cs, le_Sup cs⟩)), end @[simp] theorem Sup_compact_eq_top : Sup {a : α | complete_lattice.is_compact_element a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_compact_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_compact_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, complete_lattice.is_compact_element c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_compact_le_eq a, ← Sup_compact_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ /-- This property is sometimes referred to as `α` being upper continuous. -/ theorem inf_Sup_eq_of_directed_on (h : directed_on (≤) s): a ⊓ Sup s = ⨆ b ∈ s, a ⊓ b := le_antisymm (begin rw le_iff_compact_le_imp, by_cases hs : s.nonempty, { intros c hc hcinf, rw le_inf_iff at hcinf, rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le at hc, rcases hc s hs h hcinf.2 with ⟨d, ds, cd⟩, exact (le_inf hcinf.1 cd).trans (le_bsupr d ds) }, { rw set.not_nonempty_iff_eq_empty at hs, simp [hs] } end) supr_inf_le_inf_Sup /-- This property is equivalent to `α` being upper continuous. -/ theorem inf_Sup_eq_supr_inf_sup_finset : a ⊓ Sup s = ⨆ (t : finset α) (H : ↑t ⊆ s), a ⊓ (t.sup id) := le_antisymm (begin rw le_iff_compact_le_imp, intros c hc hcinf, rw le_inf_iff at hcinf, rcases hc s hcinf.2 with ⟨t, ht1, ht2⟩, exact (le_inf hcinf.1 ht2).trans (le_bsupr t ht1), end) (supr_le $ λ t, supr_le $ λ h, inf_le_inf_left _ ((finset.sup_id_eq_Sup t).symm ▸ (Sup_le_Sup h))) theorem complete_lattice.set_independent_iff_finite {s : set α} : complete_lattice.set_independent s ↔ ∀ t : finset α, ↑t ⊆ s → complete_lattice.set_independent (↑t : set α) := ⟨λ hs t ht, hs.mono ht, λ h a ha, begin rw [disjoint_iff, inf_Sup_eq_supr_inf_sup_finset, supr_eq_bot], intro t, rw [supr_eq_bot, finset.sup_id_eq_Sup], intro ht, classical, have h' := (h (insert a t) _ (t.mem_insert_self a)).eq_bot, { rwa [finset.coe_insert, set.insert_diff_self_of_not_mem] at h', exact λ con, ((set.mem_diff a).1 (ht con)).2 (set.mem_singleton a) }, { rw [finset.coe_insert, set.insert_subset], exact ⟨ha, set.subset.trans ht (set.diff_subset _ _)⟩ } end⟩ lemma complete_lattice.set_independent_Union_of_directed {η : Type*} {s : η → set α} (hs : directed (⊆) s) (h : ∀ i, complete_lattice.set_independent (s i)) : complete_lattice.set_independent (⋃ i, s i) := begin by_cases hη : nonempty η, { resetI, rw complete_lattice.set_independent_iff_finite, intros t ht, obtain ⟨I, fi, hI⟩ := set.finite_subset_Union t.finite_to_set ht, obtain ⟨i, hi⟩ := hs.finset_le fi.to_finset, exact (h i).mono (set.subset.trans hI $ set.bUnion_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { rintros a ⟨_, ⟨i, _⟩, _⟩, exfalso, exact hη ⟨i⟩, }, end lemma complete_lattice.independent_sUnion_of_directed {s : set (set α)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, complete_lattice.set_independent a) : complete_lattice.set_independent (⋃₀ s) := by rw set.sUnion_eq_Union; exact complete_lattice.set_independent_Union_of_directed hs.directed_coe (by simpa using h) end namespace complete_lattice lemma compactly_generated_of_well_founded (h : well_founded ((>) : α → α → Prop)) : is_compactly_generated α := begin rw [well_founded_iff_is_Sup_finite_compact, is_Sup_finite_compact_iff_all_elements_compact] at h, -- x is the join of the set of compact elements {x} exact ⟨λ x, ⟨{x}, ⟨λ x _, h x, Sup_singleton⟩⟩⟩, end /-- A compact element `k` has the property that any `b < `k lies below a "maximal element below `k`", which is to say `[⊥, k]` is coatomic. -/ theorem Iic_coatomic_of_compact_element {k : α} (h : is_compact_element k) : is_coatomic (set.Iic k) := ⟨λ ⟨b, hbk⟩, begin by_cases htriv : b = k, { left, ext, simp only [htriv, set.Iic.coe_top, subtype.coe_mk], }, right, rcases zorn.zorn_nonempty_partial_order₀ (set.Iio k) _ b (lt_of_le_of_ne hbk htriv) with ⟨a, a₀, ba, h⟩, { refine ⟨⟨a, le_of_lt a₀⟩, ⟨ne_of_lt a₀, λ c hck, by_contradiction $ λ c₀, _⟩, ba⟩, cases h c.1 (lt_of_le_of_ne c.2 (λ con, c₀ (subtype.ext con))) hck.le, exact lt_irrefl _ hck, }, { intros S SC cC I IS, by_cases hS : S.nonempty, { exact ⟨Sup S, h.directed_Sup_lt_of_lt hS cC.directed_on SC, λ _, le_Sup⟩, }, exact ⟨b, lt_of_le_of_ne hbk htriv, by simp only [set.not_nonempty_iff_eq_empty.mp hS, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩, }, end⟩ lemma coatomic_of_top_compact (h : is_compact_element (⊤ : α)) : is_coatomic α := (@order_iso.Iic_top α _).is_coatomic_iff.mp (Iic_coatomic_of_compact_element h) end complete_lattice section variables [is_modular_lattice α] [is_compactly_generated α] @[priority 100] instance is_atomic_of_is_complemented [is_complemented α] : is_atomic α := ⟨λ b, begin by_cases h : {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} ⊆ {⊥}, { left, rw [← Sup_compact_le_eq b, Sup_eq_bot], exact h }, { rcases set.not_subset.1 h with ⟨c, ⟨hc, hcb⟩, hcbot⟩, right, have hc' := complete_lattice.Iic_coatomic_of_compact_element hc, rw ← is_atomic_iff_is_coatomic at hc', haveI := hc', obtain con | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le (⟨c, le_refl c⟩ : set.Iic c), { exfalso, apply hcbot, simp only [subtype.ext_iff, set.Iic.coe_bot, subtype.coe_mk] at con, exact con }, rw [← subtype.coe_le_coe, subtype.coe_mk] at hac, exact ⟨a, ha.of_is_atom_coe_Iic, hac.trans hcb⟩ }, end⟩ /-- See Lemma 5.1, Călugăreanu -/ @[priority 100] instance is_atomistic_of_is_complemented [is_complemented α] : is_atomistic α := ⟨λ b, ⟨{a | is_atom a ∧ a ≤ b}, begin symmetry, have hle : Sup {a : α | is_atom a ∧ a ≤ b} ≤ b := (Sup_le $ λ _, and.right), apply (lt_or_eq_of_le hle).resolve_left (λ con, _), obtain ⟨c, hc⟩ := exists_is_compl (⟨Sup {a : α | is_atom a ∧ a ≤ b}, hle⟩ : set.Iic b), obtain rfl | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le c, { exact ne_of_lt con (subtype.ext_iff.1 (eq_top_of_is_compl_bot hc)) }, { apply ha.1, rw eq_bot_iff, apply le_trans (le_inf _ hac) hc.1, rw [← subtype.coe_le_coe, subtype.coe_mk], exact le_Sup ⟨ha.of_is_atom_coe_Iic, a.2⟩ } end, λ _, and.left⟩⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem is_complemented_of_Sup_atoms_eq_top (h : Sup {a : α | is_atom a} = ⊤) : is_complemented α := ⟨λ b, begin obtain ⟨s, ⟨s_ind, b_inf_Sup_s, s_atoms⟩, s_max⟩ := zorn.zorn_subset {s : set α | complete_lattice.set_independent s ∧ b ⊓ Sup s = ⊥ ∧ ∀ a ∈ s, is_atom a} _, { refine ⟨Sup s, le_of_eq b_inf_Sup_s, _⟩, rw [← h, Sup_le_iff], intros a ha, rw ← inf_eq_left, refine (eq_bot_or_eq_of_le_atom ha inf_le_left).resolve_left (λ con, ha.1 _), rw [eq_bot_iff, ← con], refine le_inf (le_refl a) ((le_Sup _).trans le_sup_right), rw ← disjoint_iff at *, have a_dis_Sup_s : disjoint a (Sup s) := con.mono_right le_sup_right, rw ← s_max (s ∪ {a}) ⟨λ x hx, _, ⟨_, λ x hx, _⟩⟩ (set.subset_union_left _ _), { exact set.mem_union_right _ (set.mem_singleton _) }, { rw [set.mem_union, set.mem_singleton_iff] at hx, by_cases xa : x = a, { simp only [xa, set.mem_singleton, set.insert_diff_of_mem, set.union_singleton], exact con.mono_right (le_trans (Sup_le_Sup (set.diff_subset s {a})) le_sup_right) }, { have h : (s ∪ {a}) \ {x} = (s \ {x}) ∪ {a}, { simp only [set.union_singleton], rw set.insert_diff_of_not_mem, rw set.mem_singleton_iff, exact ne.symm xa }, rw [h, Sup_union, Sup_singleton], apply (s_ind (hx.resolve_right xa)).disjoint_sup_right_of_disjoint_sup_left (a_dis_Sup_s.mono_right _).symm, rw [← Sup_insert, set.insert_diff_singleton, set.insert_eq_of_mem (hx.resolve_right xa)] } }, { rw [Sup_union, Sup_singleton, ← disjoint_iff], exact b_inf_Sup_s.disjoint_sup_right_of_disjoint_sup_left con.symm }, { rw [set.mem_union, set.mem_singleton_iff] at hx, cases hx, { exact s_atoms x hx }, { rw hx, exact ha } } }, { intros c hc1 hc2, refine ⟨⋃₀ c, ⟨complete_lattice.independent_sUnion_of_directed hc2.directed_on (λ s hs, (hc1 hs).1), _, λ a ha, _⟩, λ _, set.subset_sUnion_of_mem⟩, { rw [Sup_sUnion, ← Sup_image, inf_Sup_eq_of_directed_on, supr_eq_bot], { intro i, rw supr_eq_bot, intro hi, obtain ⟨x, xc, rfl⟩ := (set.mem_image _ _ _).1 hi, exact (hc1 xc).2.1 }, { rw directed_on_image, refine hc2.directed_on.mono (λ s t, Sup_le_Sup) } }, { rcases set.mem_sUnion.1 ha with ⟨s, sc, as⟩, exact (hc1 sc).2.2 a as } } end⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem is_complemented_of_is_atomistic [is_atomistic α] : is_complemented α := is_complemented_of_Sup_atoms_eq_top Sup_atoms_eq_top theorem is_complemented_iff_is_atomistic : is_complemented α ↔ is_atomistic α := begin split; introsI, { exact is_atomistic_of_is_complemented }, { exact is_complemented_of_is_atomistic } end end
4399e36fc761493ac282f0e76f0ae178be5121d4
9a2260f3b7b64ae9c50bf326fdb0387f5ac64683
/src/NITRO/Proto.lean
799fbd481fb512e8f45a7ec83cb16ecbfb75ade2
[ "LicenseRef-scancode-mit-taylor-variant", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
o89/nitro
e8e1c7f3e7baeb7a659f899c605d37b1d3e553a6
c62a67398a89d6e6a2e9da62350adaf5f17cfda9
refs/heads/master
1,670,068,174,264
1,669,086,407,000
1,669,086,407,000
204,147,098
3
5
null
null
null
null
UTF-8
Lean
false
false
1,369
lean
import N2O.Data.BERT import N2O.Network.Default inductive Nitro (α : Type) | init : Nitro α | message : α → List (String × String) → Nitro α | error : String → Nitro α | ping : Nitro α | done : Nitro α def nitroProto (α : Type) [BERT α] : Proto := let readQuery : Term → Option (String × String) := λ t => match t with | Term.tuple [ Term.atom name, Term.string value ] => some (name, value) | _ => none; { ev := Nitro α, nothing := Result.ok, proto := λ p => match p with | Msg.binary input => match Parser.run readTerm input with | Sum.ok (Term.tuple [ Term.atom "pickle", Term.binary target, Term.binary termBin, Term.list linked ]) => match Parser.run readTerm termBin with | Sum.ok term => match BERT.fromTerm term with | Sum.ok v => Nitro.message v (List.filterMap readQuery linked) | Sum.fail s => Nitro.error s | Sum.fail s => Nitro.error s | Sum.ok _ => Nitro.error "unknown term" | Sum.fail s => Nitro.error s | Msg.text "PING" => Nitro.ping | Msg.text "N2O," => Nitro.init | _ => Nitro.error "unknown message" } def ignore {α : Type} [BERT α] : Nitro α → Result := uselessRouter (nitroProto α) def pong := Result.reply (Msg.text "PONG") def Nitro.cx (α : Type) [BERT α] := Cx (nitroProto α)
b7f5cf09332de29c54b40d306e21ae96f875ad6f
a338c3e75cecad4fb8d091bfe505f7399febfd2b
/src/data/list/basic.lean
1ed5747ff4f088dc3a664692c93eeeabf7e27073
[ "Apache-2.0" ]
permissive
bacaimano/mathlib
88eb7911a9054874fba2a2b74ccd0627c90188af
f2edc5a3529d95699b43514d6feb7eb11608723f
refs/heads/master
1,686,410,075,833
1,625,497,070,000
1,625,497,070,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
193,754
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import control.monad.basic import data.nat.basic import order.rel_classes import algebra.group_power.basic /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem cons_ne_self (a : α) (l : list α) : a::l ≠ l := mt (congr_arg length) (nat.succ_ne_self _) theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) @[simp] theorem cons_injective {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := cons_injective.eq_iff theorem exists_cons_of_ne_nil {l : list α} (h : l ≠ nil) : ∃ b L, l = b :: L := by { induction l with c l', contradiction, use [c,l'], } /-! ### mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem _root_.decidable.list.eq_or_ne_mem_of_mem [decidable_eq α] {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := decidable.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} : a ∈ b :: l → a = b ∨ (a ≠ b ∧ a ∈ l) := by classical; exact decidable.list.eq_or_ne_mem_of_mem theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] lemma map_bind (g : β → list γ) (f : α → β) : ∀ l : list α, (list.map f l).bind g = l.bind (λ a, g (f a)) | [] := rfl | (a::l) := by simp only [cons_bind, map_cons, map_bind l] /-! ### length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ @[simp] lemma length_singleton (a : α) : length [a] = 1 := rfl theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ lemma exists_mem_of_ne_nil (l : list α) (h : l ≠ []) : ∃ x, x ∈ l := exists_mem_of_length_pos (length_pos_of_ne_nil h) theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ @[simp] lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end @[simp] lemma length_injective [subsingleton α] : injective (length : list α → ℕ) := length_injective_iff.mpr $ by apply_instance /-! ### set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] := by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] } /-! ### bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. theorem forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : list α}, (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := ball_cons theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /-! ### list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl @[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: l := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_right h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_injective (s : list α) : function.injective (λ t, s ++ t) := λ t₁ t₂, append_left_cancel theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := (append_right_injective s).eq_iff theorem append_left_injective (t : list α) : function.injective (λ s, s ++ t) := λ s₁ s₂, append_right_cancel theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := (append_left_injective t).eq_iff theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /-! ### repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n ↔ n ≠ 0 ∧ b = a | 0 := by simp | (n + 1) := by simp [mem_repeat] theorem eq_of_mem_repeat {a b : α} {n} (h : b ∈ repeat a n) : b = a := (mem_repeat.1 h).2 theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] lemma repeat_left_injective {n : ℕ} (hn : n ≠ 0) : function.injective (λ a : α, repeat a n) := λ a b h, (eq_repeat.1 h).2 _ $ mem_repeat.2 ⟨hn, rfl⟩ lemma repeat_left_inj {a b : α} {n : ℕ} (hn : n ≠ 0) : repeat a n = repeat b n ↔ a = b := (repeat_left_injective hn).eq_iff @[simp] lemma repeat_left_inj' {a b : α} : ∀ {n}, repeat a n = repeat b n ↔ n = 0 ∨ a = b | 0 := by simp | (n + 1) := (repeat_left_inj n.succ_ne_zero).trans $ by simp only [n.succ_ne_zero, false_or] lemma repeat_right_injective (a : α) : function.injective (repeat a) := function.left_inverse.injective (length_repeat a) @[simp] lemma repeat_right_inj {a : α} {n m : ℕ} : repeat a n = repeat a m ↔ n = m := (repeat_right_injective a).eq_iff /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /-! ### bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl -- TODO: duplicate of a lemma in core theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ @[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x := append_nil (f x) /-! ### concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem init_eq_of_concat_eq {a : α} {l₁ l₂ : list α} : concat l₁ a = concat l₂ a → l₁ = l₂ := begin intro h, rw [concat_eq_append, concat_eq_append] at h, exact append_right_cancel h end theorem last_eq_of_concat_eq {a b : α} {l : list α} : concat l a = concat l b → a = b := begin intro h, rw [concat_eq_append, concat_eq_append] at h, exact head_eq_of_cons_eq (append_left_cancel h) end theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by simp theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by simp /-! ### reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] theorem reverse_concat (l : list α) (a : α) : reverse (concat l a) = a :: reverse l := by rw [concat_eq_append, reverse_append, reverse_singleton, singleton_append] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl @[simp] theorem reverse_involutive : involutive (@reverse α) := λ l, reverse_reverse l @[simp] theorem reverse_injective : injective (@reverse α) := reverse_involutive.injective @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff lemma reverse_eq_iff {l l' : list α} : l.reverse = l' ↔ l = l'.reverse := reverse_involutive.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ /-! ### empty -/ attribute [simp] list.empty lemma empty_iff_eq_nil {l : list α} : l.empty ↔ l = [] := list.cases_on l (by simp) (by simp) /-! ### init -/ @[simp] theorem length_init : ∀ (l : list α), length (init l) = length l - 1 | [] := rfl | [a] := rfl | (a :: b :: l) := begin rw init, simp only [add_left_inj, length, succ_add_sub_one], exact length_init (b :: l) end /-! ### last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem init_append_last : ∀ {l : list α} (h : l ≠ []), init l ++ [last l h] = l | [] h := absurd rfl h | [a] h := rfl | (a::b::l) h := begin rw [init, cons_append, last_cons (cons_ne_nil _ _) (cons_ne_nil _ _)], congr, exact init_append_last (cons_ne_nil b l) end theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l | [] h := absurd rfl h | [a] h := or.inl rfl | (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) } lemma last_repeat_succ (a m : ℕ) : (repeat a m.succ).last (ne_nil_of_length_eq_succ (show (repeat a m.succ).length = m.succ, by rw length_repeat)) = a := begin induction m with k IH, { simp }, { simpa only [repeat_succ, last] } end /-! ### last' -/ @[simp] theorem last'_is_none : ∀ {l : list α}, (last' l).is_none ↔ l = [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_none (b::l)] @[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_some (b::l)] theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h | [] x hx := false.elim $ by simpa using hx | [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩ | (a::b::l) x hx := begin rw last' at hx, rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩, use cons_ne_nil _ _, rwa [last_cons] end theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l := let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _ theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l | [] a ha := (option.not_mem_none a ha).elim | [a] _ rfl := rfl | (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] } theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget | [] := by simp [ilast, arbitrary] | [a] := rfl | [a, b] := rfl | [a, b, c] := rfl | (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)] @[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α), last' (l₁ ++ a :: l₂) = last' (a :: l₂) | [] a l₂ := rfl | [b] a l₂ := rfl | (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons] theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []), last' (l₁ ++ l₂) = last' l₂ | [] hl₂ := by contradiction | (b::l₂) _ := last'_append_cons l₁ b l₂ /-! ### head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l | [] h := (option.not_mem_none _ h).elim | (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl } @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem tail_append_singleton_of_ne_nil {a : α} {l : list α} (h : l ≠ nil) : tail (l ++ [a]) = tail l ++ [a] := by { induction l, contradiction, rw [tail,cons_append,tail], } theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l | [] a h := by contradiction | (b::l) a h := by { simp at h, simp [h] } theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l | [] h := by contradiction | (a::l) h := rfl theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := cons_head'_tail (head_mem_head' h) lemma head_mem_self [inhabited α] {l : list α} (h : l ≠ nil) : l.head ∈ l := begin have h' := mem_cons_self l.head l.tail, rwa cons_head_tail h at h', end @[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl lemma tail_append_of_ne_nil (l l' : list α) (h : l ≠ []) : (l ++ l').tail = l.tail ++ l' := begin cases l, { contradiction }, { simp } end /-! ### Induction from the right -/ /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /-- Bidirectional induction principle for lists: if a property holds for the empty list, the singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def bidirectional_rec {C : list α → Sort*} (H0 : C []) (H1 : ∀ (a : α), C [a]) (Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : ∀ l, C l | [] := H0 | [a] := H1 a | (a :: b :: l) := let l' := init (b :: l), b' := last (b :: l) (cons_ne_nil _ _) in have length l' < length (a :: b :: l), by { change _ < length l + 2, simp }, begin rw ←init_append_last (cons_ne_nil b l), have : C l', from bidirectional_rec l', exact Hn a l' b' ‹C l'› end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] } /-- Like `bidirectional_rec`, but with the list parameter placed first. -/ @[elab_as_eliminator] def bidirectional_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (a : α), C [a]) (Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : C l := bidirectional_rec H0 H1 Hn l /-! ### sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact ih.append_right [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff] using h.reverse, λ h, h.append_right l⟩ theorem sublist.append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (hl.append_right _).trans ((append_sublist_append_left _).2 hr) theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (sublist.subset s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, h.subset (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ s.subset @[simp] theorem sublist_nil_iff_eq_nil {l : list α} : l <+ [] ↔ l = [] := ⟨eq_nil_of_sublist_nil, λ H, H ▸ sublist.refl _⟩ theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /-! ### index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp, priority 990] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp, priority 980] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, decidable.by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /-! ### nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ @[simp] theorem nth_eq_none_iff : ∀ {l : list α} {n}, nth l n = none ↔ length l ≤ n := begin intros, split, { intro h, by_contradiction h', have h₂ : ∃ h, l.nth_le n h = l.nth_le n (lt_of_not_ge h') := ⟨lt_of_not_ge h', rfl⟩, rw [← nth_eq_some, h] at h₂, cases h₂ }, { solve_by_elim [nth_len_le] }, end theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm lemma nth_zero (l : list α) : l.nth 0 = l.head' := by cases l; refl lemma nth_injective {α : Type u} {xs : list α} {i j : ℕ} (h₀ : i < xs.length) (h₁ : nodup xs) (h₂ : xs.nth i = xs.nth j) : i = j := begin induction xs with x xs generalizing i j, { cases h₀ }, { cases i; cases j, case nat.zero nat.zero { refl }, case nat.succ nat.succ { congr, cases h₁, apply xs_ih; solve_by_elim [lt_of_succ_lt_succ] }, iterate 2 { dsimp at h₂, cases h₁ with _ _ h h', cases h x _ rfl, rw mem_iff_nth, exact ⟨_, h₂.symm⟩ <|> exact ⟨_, h₂⟩ } }, end @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ /-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as `hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make such a rewrite, with `rw (nth_le_of_eq h)`. -/ lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) : nth_le L i hi = nth_le L' i (h ▸ hi) := by { congr, exact h} @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) : L.nth_le 0 h = L.head := by { cases L, cases h, simp, } lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) : (list.repeat a n).nth_le m h = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma nth_append_right {l₁ l₂ : list α} {n : ℕ} (hn : l₁.length ≤ n) : (l₁ ++ l₂).nth n = l₂.nth (n - l₁.length) := begin by_cases hl : n < (l₁ ++ l₂).length, { rw [nth_le_nth hl, nth_le_nth, nth_le_append_right hn] }, { rw [nth_len_le (le_of_not_lt hl), nth_len_le], rw [not_lt, length_append] at hl, exact nat.le_sub_left_of_add_le hl } end lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] lemma nth_le_cons_length (x : α) (xs : list α) (n : ℕ) (h : n = xs.length) : (x :: xs).nth_le n (by simp [h]) = (x :: xs).last (cons_ne_nil x xs) := begin rw last_eq_nth_le, congr, simp [h] end @[ext] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], } @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma nth_le_reverse' (l : list α) (n : ℕ) (hn : n < l.reverse.length) (hn') : l.reverse.nth_le n hn = l.nth_le (l.length - 1 - n) hn' := begin rw eq_comm, convert nth_le_reverse l.reverse _ _ _ using 1, { simp }, { simpa } end lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) : l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] := begin refine ext_le (by convert h) (λ n h₁ h₂, _), simp only [nth_le_singleton], congr, exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂) end lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma update_nth_nil (n : ℕ) (a : α) : [].update_nth n a = [] := rfl @[simp] lemma update_nth_succ (x : α) (xs : list α) (n : ℕ) (a : α) : (x :: xs).update_nth n.succ a = x :: xs.update_nth n a := rfl lemma update_nth_comm (a b : α) : Π {n m : ℕ} (l : list α) (h : n ≠ m), (l.update_nth n a).update_nth m b = (l.update_nth m b).update_nth n a | _ _ [] _ := by simp | 0 0 (x :: t) h := absurd rfl h | (n + 1) 0 (x :: t) h := by simp [list.update_nth] | 0 (m + 1) (x :: t) h := by simp [list.update_nth] | (n + 1) (m + 1) (x :: t) h := by { simp only [update_nth, true_and, eq_self_iff_true], exact update_nth_comm t (λ h', h $ nat.succ_inj'.mpr h'), } @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl @[simp] lemma insert_nth_succ_nil (n : ℕ) (a : α) : insert_nth (n + 1) a [] = [] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → n ≤ m → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /-! ### map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl theorem map_eq_foldr (f : α → β) (l : list α) : map f l = foldr (λ a bs, f a :: bs) [] l := by induction l; simp * lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /-- A single `list.map` of a composition of functions is equal to composing a `list.map` with another `list.map`, fully applied. This is the reverse direction of `list.map_map`. -/ lemma comp_map (h : β → γ) (g : α → β) (l : list α) : map (h ∘ g) l = map h (map g l) := (map_map _ _ _).symm /-- Composing a `list.map` with another `list.map` is equal to a single `list.map` of composed functions. -/ @[simp] lemma map_comp_map (g : β → γ) (f : α → β) : map g ∘ map f = map (g ∘ f) := by { ext l, rw comp_map } theorem map_filter_eq_foldr (f : α → β) (p : α → Prop) [decidable_pred p] (as : list α) : map f (filter p as) = foldr (λ a bs, if p a then f a :: bs else bs) [] as := by { induction as, { refl }, { simp! [*, apply_ite (map f)] } } lemma last_map (f : α → β) {l : list α} (hl : l ≠ []) : (l.map f).last (mt eq_nil_of_map_eq_nil hl) = f (l.last hl) := begin induction l with l_ih l_tl l_ih, { apply (hl rfl).elim }, { cases l_tl, { simp }, { simpa using l_ih } } end /-! ### map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl @[simp] theorem map₂_flip (f : α → β → γ) : ∀ as bs, map₂ (flip f) bs as = map₂ f as bs | [] [] := rfl | [] (b :: bs) := rfl | (a :: as) [] := rfl | (a :: as) (b :: bs) := by { simp! [map₂_flip], refl } /-! ### take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m) | n 0 := by simp | 0 m := by simp | (succ n) (succ m) := by simp [min_succ_succ, take_repeat] lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] /-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first `i` elements of `l₂` to `l₁`. -/ lemma take_append {l₁ l₂ : list α} (i : ℕ) : take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self] end /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) : nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) := by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ } /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) : nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) := by { simp at hi, rw nth_le_take L _ hi.1 } lemma nth_take {l : list α} {n m : ℕ} (h : m < n) : (l.take n).nth m = l.nth m := begin induction n with n hn generalizing l m, { simp only [nat.nat_zero_eq_zero] at h, exact absurd h (not_lt_of_le m.zero_le) }, { cases l with hd tl, { simp only [take_nil] }, { cases m, { simp only [nth, take] }, { simpa only using hn (nat.lt_of_succ_lt_succ h) } } }, end @[simp] lemma nth_take_of_succ {l : list α} {n : ℕ} : (l.take (n + 1)).nth n = l.nth n := nth_take (nat.lt_succ_self n) lemma take_succ {l : list α} {n : ℕ} : l.take (n + 1) = l.take n ++ (l.nth n).to_list := begin induction l with hd tl hl generalizing n, { simp only [option.to_list, nth, take_nil, append_nil]}, { cases n, { simp only [option.to_list, nth, eq_self_iff_true, and_self, take, nil_append] }, { simp only [hl, cons_append, nth, eq_self_iff_true, and_self, take] } } end @[simp] lemma take_eq_nil_iff {l : list α} {k : ℕ} : l.take k = [] ↔ l = [] ∨ k = 0 := by { cases l; cases k; simp [nat.succ_ne_zero] } lemma init_eq_take (l : list α) : l.init = l.take l.length.pred := begin cases l with x l, { simp [init] }, { induction l with hd tl hl generalizing x, { simp [init], }, { simp [init, hl] } } end lemma init_take {n : ℕ} {l : list α} (h : n < l.length) : (l.take n).init = l.take n.pred := by simp [init_eq_take, min_eq_left_of_lt h, take_take, pred_le] @[simp] lemma drop_eq_nil_of_le {l : list α} {k : ℕ} (h : l.length ≤ k) : l.drop k = [] := by simpa [←length_eq_zero] using nat.sub_eq_zero_of_le h lemma drop_eq_nil_iff_le {l : list α} {k : ℕ} : l.drop k = [] ↔ l.length ≤ k := begin refine ⟨λ h, _, drop_eq_nil_of_le⟩, induction k with k hk generalizing l, { simp only [drop] at h, simp [h] }, { cases l, { simp }, { simp only [drop] at h, simpa [nat.succ_le_succ_iff] using hk h } } end lemma tail_drop (l : list α) (n : ℕ) : (l.drop n).tail = l.drop (n + 1) := begin induction l with hd tl hl generalizing n, { simp }, { cases n, { simp }, { simp [hl] } } end lemma cons_nth_le_drop_succ {l : list α} {n : ℕ} (hn : n < l.length) : l.nth_le n hn :: l.drop (n + 1) = l.drop n := begin induction l with hd tl hl generalizing n, { exact absurd n.zero_le (not_le_of_lt (by simpa using hn)) }, { cases n, { simp }, { simp only [nat.succ_lt_succ_iff, list.length] at hn, simpa [list.nth_le, list.drop] using hl hn } } end theorem drop_nil : ∀ n, drop n [] = ([] : list α) := λ _, drop_eq_nil_of_le (nat.zero_le _) lemma mem_of_mem_drop {α} {n : ℕ} {l : list α} {x : α} (h : x ∈ l.drop n) : x ∈ l := begin induction l generalizing n, case list.nil : n h { simpa using h }, case list.cons : l_hd l_tl l_ih n h { cases n; simp only [mem_cons_iff, drop] at h ⊢, { exact h }, right, apply l_ih h }, end @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_length (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] /-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements up to `i` in `l₂`. -/ lemma drop_append {l₁ l₂ : list α} (i : ℕ) : drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, drop, l₁_ih] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) : nth_le L (i + j) h = nth_le (L.drop i) j begin have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h, rw (take_append_drop i L).symm at h, simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h end := begin have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)], rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right]; simp [A] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) : nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) := by rw nth_le_drop lemma nth_drop (L : list α) (i j : ℕ) : nth (L.drop i) j = nth L (i + j) := begin ext, simp only [nth_eq_some, nth_le_drop', option.mem_def], split; exact λ ⟨h, ha⟩, ⟨by simpa [nat.lt_sub_left_iff_add_lt] using h, ha⟩ end @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] lemma reverse_take {α} {xs : list α} (n : ℕ) (h : n ≤ xs.length) : xs.reverse.take n = (xs.drop (xs.length - n)).reverse := begin induction xs generalizing n; simp only [reverse_cons, drop, reverse_nil, nat.zero_sub, length, take_nil], cases h.lt_or_eq_dec with h' h', { replace h' := le_of_succ_le_succ h', rwa [take_append_of_le_length, xs_ih _ h'], rw [show xs_tl.length + 1 - n = succ (xs_tl.length - n), from _, drop], { rwa [succ_eq_add_one, nat.sub_add_comm] }, { rwa length_reverse } }, { subst h', rw [length, nat.sub_self, drop], suffices : xs_tl.length + 1 = (xs_tl.reverse ++ [xs_hd]).length, by rw [this, take_length, reverse_cons], rw [length_append, length_reverse], refl } end @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /-! ### foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β) (a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) : list.foldl f' (g a) (l.map g) = g (list.foldl f a l) := begin induction l generalizing a, { simp }, { simp [l_ih, h] } end theorem foldr_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β) (a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) : list.foldr f' (g a) (l.map g) = g (list.foldr f a l) := begin induction l generalizing a, { simp }, { simp [l_ih, h] } end theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } lemma injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α} (hl : ∀ f ∈ l, function.injective f) (hf : function.injective f): function.injective (@list.foldl (α → α) (α → α) function.comp f l) := begin induction l generalizing f, { exact hf }, { apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)), apply function.injective.comp hf, apply hl _ (list.mem_cons_self _ _) } end /-- Induction principle for values produced by a `foldr`: if a property holds for the seed element `b : β` and for all incremental `op : α → β → β` performed on the elements `(a : α) ∈ l`. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def foldr_rec_on {C : β → Sort*} (l : list α) (op : α → β → β) (b : β) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op a b)) : C (foldr op b l) := begin induction l with hd tl IH, { exact hb }, { refine hl _ _ hd (mem_cons_self hd tl), refine IH _, intros y hy x hx, exact hl y hy x (mem_cons_of_mem hd hx) } end /-- Induction principle for values produced by a `foldl`: if a property holds for the seed element `b : β` and for all incremental `op : β → α → β` performed on the elements `(a : α) ∈ l`. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def foldl_rec_on {C : β → Sort*} (l : list α) (op : β → α → β) (b : β) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op b a)) : C (foldl op b l) := begin induction l with hd tl IH generalizing b, { exact hb }, { refine IH _ _ _, { intros y hy x hx, exact hl y hy x (mem_cons_of_mem hd hx) }, { exact hl b hb hd (mem_cons_self hd tl) } } end @[simp] lemma foldr_rec_on_nil {C : β → Sort*} (op : α → β → β) (b) (hb : C b) (hl) : foldr_rec_on [] op b hb hl = hb := rfl @[simp] lemma foldr_rec_on_cons {C : β → Sort*} (x : α) (l : list α) (op : α → β → β) (b) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ (x :: l)), C (op a b)) : foldr_rec_on (x :: l) op b hb hl = hl _ (foldr_rec_on l op b hb (λ b hb a ha, hl b hb a (mem_cons_of_mem _ ha))) x (mem_cons_self _ _) := rfl @[simp] lemma foldl_rec_on_nil {C : β → Sort*} (op : β → α → β) (b) (hb : C b) (hl) : foldl_rec_on [] op b hb hl = hb := rfl /- scanl -/ section scanl variables {f : β → α → β} {b : β} {a : α} {l : list α} lemma length_scanl : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] @[simp] lemma scanl_nil (b : β) : scanl f b nil = [b] := rfl @[simp] lemma scanl_cons : scanl f b (a :: l) = [b] ++ scanl f (f b a) l := by simp only [scanl, eq_self_iff_true, singleton_append, and_self] @[simp] lemma nth_zero_scanl : (scanl f b l).nth 0 = some b := begin cases l, { simp only [nth, scanl_nil] }, { simp only [nth, scanl_cons, singleton_append] } end @[simp] lemma nth_le_zero_scanl {h : 0 < (scanl f b l).length} : (scanl f b l).nth_le 0 h = b := begin cases l, { simp only [nth_le, scanl_nil] }, { simp only [nth_le, scanl_cons, singleton_append] } end lemma nth_succ_scanl {i : ℕ} : (scanl f b l).nth (i + 1) = ((scanl f b l).nth i).bind (λ x, (l.nth i).map (λ y, f x y)) := begin induction l with hd tl hl generalizing b i, { symmetry, simp only [option.bind_eq_none', nth, forall_2_true_iff, not_false_iff, option.map_none', scanl_nil, option.not_mem_none, forall_true_iff] }, { simp only [nth, scanl_cons, singleton_append], cases i, { simp only [option.map_some', nth_zero_scanl, nth, option.some_bind'] }, { simp only [hl, nth] } } end lemma nth_le_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} : (scanl f b l).nth_le (i + 1) h = f ((scanl f b l).nth_le i (nat.lt_of_succ_lt h)) (l.nth_le i (nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) := begin induction i with i hi generalizing b l, { cases l, { simp only [length, zero_add, scanl_nil] at h, exact absurd h (lt_irrefl 1) }, { simp only [scanl_cons, singleton_append, nth_le_zero_scanl, nth_le] } }, { cases l, { simp only [length, add_lt_iff_neg_right, scanl_nil] at h, exact absurd h (not_lt_of_lt nat.succ_pos') }, { simp_rw scanl_cons, rw nth_le_append_right _, { simpa only [hi, length, succ_add_sub_one] }, { simp only [length, nat.zero_le, le_add_iff_nonneg_left] } } } end end scanl /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /-! ### mfoldl, mfoldr, mmap -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl theorem mfoldr_eq_foldr (f : α → β → m β) (b l) : mfoldr f b l = foldr (λ a mb, mb >>= f a) (pure b) l := by induction l; simp * attribute [simp] mmap mmap' variables [is_lawful_monad m] theorem mfoldl_eq_foldl (f : β → α → m β) (b l) : mfoldl f b l = foldl (λ mb a, mb >>= λ b, f b a) (pure b) l := begin suffices h : ∀ (mb : m β), (mb >>= λ b, mfoldl f b l) = foldl (λ mb a, mb >>= λ b, f b a) mb l, by simp [←h (pure b)], induction l; intro, { simp }, { simp only [mfoldl, foldl, ←l_ih] with monad_norm } end @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /-! ### prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[to_additive] theorem prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, priority 500] theorem prod_repeat (a : α) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { rw pow_zero, refl }, { rw [list.repeat_succ, list.prod_cons, ih, pow_succ] } end @[simp, priority 500] theorem sum_repeat {α : Type*} [add_monoid α] : ∀ (a : α) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative α) _ @[simp, to_additive] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] /-- If zero is an element of a list `L`, then `list.prod L = 0`. If the domain is a nontrivial monoid with zero with no divisors, then this implication becomes an `iff`, see `list.prod_eq_zero_iff`. -/ theorem prod_eq_zero {M₀ : Type*} [monoid_with_zero M₀] {L : list M₀} (h : (0 : M₀) ∈ L) : L.prod = 0 := begin induction L with a L ihL, { exact absurd h (not_mem_nil _) }, { rw prod_cons, cases (mem_cons_iff _ _ _).1 h with ha hL, exacts [mul_eq_zero_of_left ha.symm _, mul_eq_zero_of_right _ (ihL hL)] } end /-- Product of elements of a list `L` equals zero if and only if `0 ∈ L`. See also `list.prod_eq_zero` for an implication that needs weaker typeclass assumptions. -/ @[simp] theorem prod_eq_zero_iff {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀] [no_zero_divisors M₀] {L : list M₀} : L.prod = 0 ↔ (0 : M₀) ∈ L := begin induction L with a L ihL, { simp }, { rw [prod_cons, mul_eq_zero, ihL, mem_cons_iff, eq_comm] } end theorem prod_ne_zero {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀] [no_zero_divisors M₀] {L : list M₀} (hL : (0 : M₀) ∉ L) : L.prod ≠ 0 := mt prod_eq_zero_iff.1 hL @[to_additive] theorem prod_eq_foldr : l.prod = foldr (*) 1 l := list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α →* β) : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, f.map_one.symm], exact l.foldl_hom _ _ _ 1 f.map_mul } @[to_additive] lemma prod_is_unit [monoid β] : Π {L : list β} (u : ∀ m ∈ L, is_unit m), is_unit L.prod | [] _ := by simp | (h :: t) u := begin simp only [list.prod_cons], exact is_unit.mul (u h (mem_cons_self h t)) (prod_is_unit (λ m mt, u m (mem_cons_of_mem h mt))) end -- `to_additive` chokes on the next few lemmas, so we do them by hand below @[simp] lemma prod_take_mul_prod_drop : ∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], } @[simp] lemma prod_take_succ : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], } /-- A list with product not one must have positive length. -/ lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } lemma prod_update_nth : ∀ (L : list α) (n : ℕ) (a : α), (L.update_nth n a).prod = (L.take n).prod * (if n < L.length then a else 1) * (L.drop (n + 1)).prod | (x::xs) 0 a := by simp [update_nth] | (x::xs) (i+1) a := by simp [update_nth, prod_update_nth xs i a, mul_assoc] | [] _ _ := by simp [update_nth, (nat.zero_le _).not_lt] end monoid section group variables [group α] /-- This is the `list.prod` version of `mul_inv_rev` -/ @[to_additive "This is the `list.sum` version of `add_neg_rev`"] lemma prod_inv_reverse : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).reverse.prod | [] := by simp | (x :: xs) := by simp [prod_inv_reverse xs] /-- A non-commutative variant of `list.prod_reverse` -/ @[to_additive "A non-commutative variant of `list.sum_reverse`"] lemma prod_reverse_noncomm : ∀ (L : list α), L.reverse.prod = (L.map (λ x, x⁻¹)).prod⁻¹ := by simp [prod_inv_reverse] end group section comm_group variables [comm_group α] /-- This is the `list.prod` version of `mul_inv` -/ @[to_additive "This is the `list.sum` version of `add_neg`"] lemma prod_inv : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).prod | [] := by simp | (x :: xs) := by simp [mul_comm, prod_inv xs] end comm_group @[simp] lemma sum_take_add_sum_drop [add_monoid α] : ∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], } @[simp] lemma sum_take_succ [add_monoid α] : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], } lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length) (h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' := begin apply ext_le h (λ i h₁ h₂, _), have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁), rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this, exact add_left_cancel this end lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) : monotone (λ i, (L.take i).sum) := begin apply monotone_of_monotone_nat (λ n, _), by_cases h : n < L.length, { rw sum_take_succ _ _ h, exact le_self_add }, { push_neg at h, simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] } end @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) : 1 ≤ l.prod := begin induction l with hd tl ih, { simp }, rw prod_cons, exact one_le_mul (hl₁ hd (mem_cons_self hd tl)) (ih (λ x h, hl₁ x (mem_cons_of_mem hd h))), end @[to_additive] lemma single_le_prod [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) : ∀ x ∈ l, x ≤ l.prod := begin induction l, { simp }, simp_rw [prod_cons, forall_mem_cons] at ⊢ hl₁, split, { exact le_mul_of_one_le_right' (one_le_prod_of_one_le hl₁.2) }, { exact λ x H, le_mul_of_one_le_of_le hl₁.1 (l_ih hl₁.right x H) }, end @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) (hl₂ : l.prod = 1) : ∀ x ∈ l, x = (1 : α) := λ x hx, le_antisymm (hl₂ ▸ single_le_prod hl₁ _ hx) (hl₁ x hx) lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] (l : list α) : l.sum = 0 ↔ ∀ x ∈ l, x = (0 : α) := ⟨all_zero_of_le_zero_le_of_sum_eq_zero (λ _ _, zero_le _), begin induction l, { simp }, { intro h, rw [sum_cons, add_eq_zero_iff], rw forall_mem_cons at h, exact ⟨h.1, l_ih h.2⟩ }, end⟩ /-- A list with sum not zero must have positive length. -/ lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } /-- If all elements in a list are bounded below by `1`, then the length of the list is bounded by the sum of the elements. -/ lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum := begin induction L with j L IH h, { simp }, rw [sum_cons, length, add_comm], exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi))) end -- Now we tie those lemmas back to their multiplicative versions. attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one /-- A list with positive sum must have positive length. -/ -- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications. lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) : 0 < L.length := length_pos_of_sum_ne_zero L (ne_of_gt h) @[simp, to_additive] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases decidable.list.eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_monoid α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] lemma exists_lt_of_sum_lt [linear_ordered_cancel_add_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [linear_ordered_cancel_add_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end -- Several lemmas about sum/head/tail for `list ℕ`. -- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`. -- We'd like to state this as `L.head * L.tail.prod = L.prod`, -- but because `L.head` relies on an inhabited instances and -- returns a garbage value for the empty list, this is not possible. -- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`, -- and below, restate the lemma just for `ℕ`. @[to_additive] lemma head_mul_tail_prod' [monoid α] (L : list α) : (L.nth 0).get_or_else 1 * L.tail.prod = L.prod := by { cases L, { simp, refl, }, { simp, }, } lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum := by { cases L, { simp, refl, }, { simp, }, } lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L) lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head := by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel] section variables {G : Type*} [comm_group G] attribute [to_additive] alternating_prod @[simp, to_additive] lemma alternating_prod_nil : alternating_prod ([] : list G) = 1 := rfl @[simp, to_additive] lemma alternating_prod_singleton (g : G) : alternating_prod [g] = g := rfl @[simp, to_additive alternating_sum_cons_cons'] lemma alternating_prod_cons_cons (g h : G) (l : list G) : alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) : alternating_sum (g :: h :: l) = g - h + alternating_sum l := by rw [sub_eq_add_neg, alternating_sum] end /-! ### join -/ attribute [simp] join @[simp] theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] @[simp] theorem join_filter_empty_eq_ff [decidable_pred (λ l : list α, l.empty = ff)] : ∀ {L : list (list α)}, join (L.filter (λ l, l.empty = ff)) = L.join | [] := rfl | ([]::L) := by simp [@join_filter_empty_eq_ff L] | ((a::l)::L) := by simp [@join_filter_empty_eq_ff L] @[simp] theorem join_filter_ne_nil [decidable_pred (λ l : list α, l ≠ [])] {L : list (list α)} : join (L.filter (λ l, l ≠ [])) = L.join := by simp [join_filter_empty_eq_ff, ← empty_iff_eq_nil] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end /-! ### lexicographic ordering -/ /-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which `[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`. The definition is given for any relation `r`, not only strict orders. -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem _root_.decidable.list.lex.ne_iff [decidable_eq α] {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { by_cases ab : a = b, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := by classical; exact decidable.list.lex.ne_iff H end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ /-! ### all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /-! ### map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {l : list α} (hx : x ∈ l) : sizeof x < sizeof l := begin induction l with h t ih; cases hx, { rw hx, exact lt_add_of_lt_of_nonneg (lt_one_add _) (nat.zero_le _) }, { exact lt_add_of_pos_of_le (zero_lt_one_add _) (le_of_lt (ih hx)) } end theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_map {p : β → Prop} (g : ∀ b, p b → γ) (f : α → β) (l H) : pmap g (map f l) H = pmap (λ a h, g (f a) h) l (λ a h, H _ (mem_map_of_mem _ h)) := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap @[simp] lemma pmap_eq_nil {p : α → Prop} {f : Π a, p a → β} {l H} : pmap f l H = [] ↔ l = [] := by rw [← length_eq_zero, length_pmap, length_eq_zero] @[simp] lemma attach_eq_nil (l : list α) : l.attach = [] ↔ l = [] := pmap_eq_nil lemma last_pmap {α β : Type*} (p : α → Prop) (f : Π a, p a → β) (l : list α) (hl₁ : ∀ a ∈ l, p a) (hl₂ : l ≠ []) : (l.pmap f hl₁).last (mt list.pmap_eq_nil.1 hl₂) = f (l.last hl₂) (hl₁ _ (list.last_mem hl₂)) := begin induction l with l_hd l_tl l_ih, { apply (hl₂ rfl).elim }, { cases l_tl, { simp }, { apply l_ih } } end lemma nth_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) (n : ℕ) : nth (pmap f l h) n = option.pmap f (nth l n) (λ x H, h x (nth_mem H)) := begin induction l with hd tl hl generalizing n, { simp }, { cases n; simp [hl] } end lemma nth_le_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) {n : ℕ} (hn : n < (pmap f l h).length) : nth_le (pmap f l h) n hn = f (nth_le l n (@length_pmap _ _ p f l h ▸ hn)) (h _ (nth_le_mem l n (@length_pmap _ _ p f l h ▸ hn))) := begin induction l with hd tl hl generalizing n, { simp only [length, pmap] at hn, exact absurd hn (not_lt_of_le n.zero_le) }, { cases n, { simp }, { simpa [hl] } } end /-! ### find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /-! ### lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /-! ### filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl lemma filter_map_append {α β : Type*} (l l' : list α) (f : α → option β) : filter_map f (l ++ l') = filter_map f l ++ filter_map f l' := begin induction l with hd tl hl generalizing l', { simp }, { rw [cons_append, filter_map, filter_map], cases f hd; simp only [filter_map, hl, cons_append, eq_self_iff_true, and_self] } end theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem sublist.map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := filter_map_eq_map f ▸ s.filter_map _ /-! ### reduce_option -/ @[simp] lemma reduce_option_cons_of_some (x : α) (l : list (option α)) : reduce_option (some x :: l) = x :: l.reduce_option := by simp only [reduce_option, filter_map, id.def, eq_self_iff_true, and_self] @[simp] lemma reduce_option_cons_of_none (l : list (option α)) : reduce_option (none :: l) = l.reduce_option := by simp only [reduce_option, filter_map, id.def] @[simp] lemma reduce_option_nil : @reduce_option α [] = [] := rfl @[simp] lemma reduce_option_map {l : list (option α)} {f : α → β} : reduce_option (map (option.map f) l) = map f (reduce_option l) := begin induction l with hd tl hl, { simp only [reduce_option_nil, map_nil] }, { cases hd; simpa only [true_and, option.map_some', map, eq_self_iff_true, reduce_option_cons_of_some] using hl }, end lemma reduce_option_append (l l' : list (option α)) : (l ++ l').reduce_option = l.reduce_option ++ l'.reduce_option := filter_map_append l l' id lemma reduce_option_length_le (l : list (option α)) : l.reduce_option.length ≤ l.length := begin induction l with hd tl hl, { simp only [reduce_option_nil, length] }, { cases hd, { exact nat.le_succ_of_le hl }, { simpa only [length, add_le_add_iff_right, reduce_option_cons_of_some] using hl} } end lemma reduce_option_length_eq_iff {l : list (option α)} : l.reduce_option.length = l.length ↔ ∀ x ∈ l, option.is_some x := begin induction l with hd tl hl, { simp only [forall_const, reduce_option_nil, not_mem_nil, forall_prop_of_false, eq_self_iff_true, length, not_false_iff] }, { cases hd, { simp only [mem_cons_iff, forall_eq_or_imp, bool.coe_sort_ff, false_and, reduce_option_cons_of_none, length, option.is_some_none, iff_false], intro H, have := reduce_option_length_le tl, rw H at this, exact absurd (nat.lt_succ_self _) (not_lt_of_le this) }, { simp only [hl, true_and, mem_cons_iff, forall_eq_or_imp, add_left_inj, bool.coe_sort_tt, length, option.is_some_some, reduce_option_cons_of_some] } } end lemma reduce_option_length_lt_iff {l : list (option α)} : l.reduce_option.length < l.length ↔ none ∈ l := begin rw [(reduce_option_length_le l).lt_iff_ne, ne, reduce_option_length_eq_iff], induction l; simp *, rw [eq_comm, ← option.not_is_some_iff_eq_none, decidable.imp_iff_not_or] end lemma reduce_option_singleton (x : option α) : [x].reduce_option = x.to_list := by cases x; refl lemma reduce_option_concat (l : list (option α)) (x : option α) : (l.concat x).reduce_option = l.reduce_option ++ x.to_list := begin induction l with hd tl hl generalizing x, { cases x; simp [option.to_list] }, { simp only [concat_eq_append, reduce_option_append] at hl, cases hd; simp [hl, reduce_option_append] } end lemma reduce_option_concat_of_some (l : list (option α)) (x : α) : (l.concat (some x)).reduce_option = l.reduce_option.concat x := by simp only [reduce_option_nil, concat_eq_append, reduce_option_append, reduce_option_cons_of_some] lemma reduce_option_mem_iff {l : list (option α)} {x : α} : x ∈ l.reduce_option ↔ (some x) ∈ l := by simp only [reduce_option, id.def, mem_filter_map, exists_eq_right] lemma reduce_option_nth_iff {l : list (option α)} {x : α} : (∃ i, l.nth i = some (some x)) ↔ ∃ i, l.reduce_option.nth i = some x := by rw [←mem_iff_nth, ←mem_iff_nth, reduce_option_mem_iff] /-! ### filter -/ section filter variables {p : α → Prop} [decidable_pred p] theorem filter_eq_foldr (p : α → Prop) [decidable_pred p] (l : list α) : filter p l = foldr (λ a out, if p a then a :: out else out) [] l := by induction l; simp [*, filter] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := (filter_sublist l).subset theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] variable (p) theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := filter_map_eq_filter p ▸ s.filter_map _ theorem map_filter (f : β → α) (l : list β) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter (q) [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter p s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /-! ### count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist _ theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append _ theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := decidable.by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ theorem repeat_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) : repeat a (count a l) = l := eq_of_sublist_of_length_eq (le_count_iff_repeat_sublist.mp (le_refl (count a l))) (eq.trans (length_repeat a (count a l)) h) @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /-! ### prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s @[simp] theorem eq_nil_iff_infix_nil {l : list α} : l <:+: [] ↔ l = [] := ⟨eq_nil_of_infix_nil, λ h, h ▸ infix_refl _⟩ theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s @[simp] theorem eq_nil_iff_prefix_nil {l : list α} : l <+: [] ↔ l = [] := ⟨eq_nil_of_prefix_nil, λ h, h ▸ prefix_refl _⟩ theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s @[simp] theorem eq_nil_iff_suffix_nil {l : list α} : l <:+ [] ↔ l = [] := ⟨eq_nil_of_suffix_nil, λ h, h ▸ suffix_refl _⟩ theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem suffix_cons_iff {x : α} {l₁ l₂ : list α} : l₁ <:+ x :: l₂ ↔ l₁ = x :: l₂ ∨ l₁ <:+ l₂ := begin split, { rintro ⟨⟨hd, tl⟩, hl₃⟩, { exact or.inl hl₃ }, { simp only [cons_append] at hl₃, exact or.inr ⟨_, hl₃.2⟩ } }, { rintro (rfl | hl₁), { exact (x :: l₂).suffix_refl }, { exact hl₁.trans (l₂.suffix_cons _) } } end theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix lemma tail_sublist (l : list α) : l.tail <+ l := sublist_of_suffix (tail_suffix l) theorem tail_subset (l : list α) : tail l ⊆ l := (tail_sublist l).subset theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h lemma prefix_take_le_iff {L : list (list (option α))} {m n : ℕ} (hm : m < L.length) : (take m L) <+: (take n L) ↔ m ≤ n := begin simp only [prefix_iff_eq_take, length_take], induction m with m IH generalizing L n, { simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] }, { cases n, { simp only [nat.nat_zero_eq_zero, nonpos_iff_eq_zero, take, take_nil], split, { cases L, { exact absurd hm (not_lt_of_le m.succ.zero_le) }, { simp only [forall_prop_of_false, not_false_iff, take] } }, { intro h, contradiction } }, { cases L with l ls, { exact absurd hm (not_lt_of_le m.succ.zero_le) }, { simp only [length] at hm, specialize @IH ls n (nat.lt_of_succ_lt_succ hm), simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH, simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take], exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ } } }, end lemma cons_prefix_iff {l l' : list α} {x y : α} : x :: l <+: y :: l' ↔ x = y ∧ l <+: l' := begin split, { rintro ⟨L, hL⟩, simp only [cons_append] at hL, exact ⟨hL.left, ⟨L, hL.right⟩⟩ }, { rintro ⟨rfl, h⟩, rwa [prefix_cons_inj] }, end lemma map_prefix {l l' : list α} (f : α → β) (h : l <+: l') : l.map f <+: l'.map f := begin induction l with hd tl hl generalizing l', { simp only [nil_prefix, map_nil] }, { cases l' with hd' tl', { simpa only using eq_nil_of_prefix_nil h }, { rw cons_prefix_iff at h, simp only [h, prefix_cons_inj, hl, map] } }, end lemma is_prefix.filter_map {l l' : list α} (h : l <+: l') (f : α → option β) : l.filter_map f <+: l'.filter_map f := begin induction l with hd tl hl generalizing l', { simp only [nil_prefix, filter_map_nil] }, { cases l' with hd' tl', { simpa only using eq_nil_of_prefix_nil h }, { rw cons_prefix_iff at h, rw [←@singleton_append _ hd _, ←@singleton_append _ hd' _, filter_map_append, filter_map_append, h.left, prefix_append_right_inj], exact hl h.right } }, end lemma is_prefix.reduce_option {l l' : list (option α)} (h : l <+: l') : l.reduce_option <+: l'.reduce_option := h.filter_map id @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ lemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) := by simp lemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails := by simp @[simp] lemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l) | [] [] := by simp | [] (a::t) := by simp | (a::s) t := by simp [inits_append s t] @[simp] lemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail | [] [] := by simp | [] (a::t) := by simp | (a::s) t := by simp [tails_append s t] -- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'` lemma inits_eq_tails : ∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l) | [] := by simp | (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff] lemma tails_eq_inits : ∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l) | [] := by simp | (a :: l) := by simp [tails_eq_inits l, append_left_inj] lemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) := by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], } lemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) := by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], } lemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) := by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], } lemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) := by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], } instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /-! ### permutations -/ section permutations theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β), (permutations_aux2 t ts r ys f).1 = ys ++ ts | [] f := rfl | (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with | ⟨_, zs⟩, rfl := rfl end @[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) : (permutations_aux2 t ts r [] f).2 = r := rfl @[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α) (f : list α → β) : (permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) :: (permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 := match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with | ⟨_, zs⟩, rfl := rfl end theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) : (permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 := by induction ys generalizing f; simp * theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} : l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts := begin induction ys with y ys ih generalizing l, { simp {contextual := tt} }, { rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]), by funext; simp, mem_cons_iff, ih], split; intro h, { rcases h with e | ⟨l₁, l₂, l0, ye, _⟩, { subst l', exact ⟨[], y::ys, by simp⟩ }, { substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } }, { rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩, { simp [ye] }, { simp at ye, rcases ye with ⟨rfl, rfl⟩, exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } } end theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} : l ∈ (permutations_aux2 t ts [] ys id).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts := by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2 theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) : length (permutations_aux2 t ts [] ys f).2 = length ys := by induction ys generalizing f; simp * theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : foldr (λy r, (permutations_aux2 t ts r y id).2) r L = L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r := by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}] theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} : l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts := have (∃ (a : list α), a ∈ L ∧ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts), from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩, λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩, by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this, or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc] theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r := by simp [foldr_permutations_aux2, (∘), length_permutations_aux2] theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α)) (n) (H : ∀ l ∈ L, length l = n) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r := begin rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)], induction L with l L ih, {simp}, have sum_map : sum (map length L) = n * length L := ih (λ l m, H l (mem_cons_of_mem _ m)), have length_l : length l = n := H _ (mem_cons_self _ _), simp [sum_map, length_l, mul_add, add_comm] end @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl theorem map_permutations_aux2' {α β α' β'} (g : α → α') (g' : β → β') (t : α) (ts ys : list α) (r : list β) (f : list α → β) (f' : list α' → β') (H : ∀ a, g' (f a) = f' (map g a)) : map g' (permutations_aux2 t ts r ys f).2 = (permutations_aux2 (g t) (map g ts) (map g' r) (map g ys) f').2 := begin induction ys generalizing f f'; simp *, apply ys_ih, simp [H], end theorem map_permutations_aux2 {α α'} (g : α → α') (t : α) (ts ys : list α) : map (map g) (permutations_aux2 t ts [] ys id).2 = (permutations_aux2 (g t) (map g ts) [] (map g ys) id).2 := map_permutations_aux2' _ _ _ _ _ _ _ _ (λ _, rfl) theorem map_permutations_aux (f : α → β) : ∀ (ts is : list α), map (map f) (permutations_aux ts is) = permutations_aux (map f ts) (map f is) := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2, rw map at IH2, simp only [foldr_permutations_aux2, map_append, map, map_permutations_aux2, permutations, bind_map, IH1, append_assoc, permutations_aux_cons, cons_bind, ← IH2, map_bind], end theorem map_permutations (f : α → β) (ts : list α) : map (map f) (permutations ts) = permutations (map f ts) := by rw [permutations, permutations, map, map_permutations_aux, map] end permutations /-! ### insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /-! ### erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := (erasep_sublist l).subset theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /-! ### erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp, priority 980] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := (erase_sublist a l).subset theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact sublist.erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /-! ### diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] lemma diff_cons_right (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.diff l₂).erase a := begin induction l₂ with b l₂ ih generalizing l₁ a, { simp_rw [diff_cons, diff_nil] }, { rw [diff_cons, diff_cons, erase_comm, ← diff_cons, ih, ← diff_cons] } end lemma diff_erase (l₁ l₂ : list α) (a : α) : (l₁.diff l₂).erase a = (l₁.erase a).diff l₂ := by rw [← diff_cons_right, diff_cons] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := (diff_sublist _ _).subset theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, (h.erase _).diff_right] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (h.erase b) end diff /-! ### enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : ∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end /-! ### product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /-! ### sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /-! ### disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] := by rw disjoint_comm; exact disjoint_nil_left _ @[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 theorem disjoint_take_drop {l : list α} {m n : ℕ} (hl : l.nodup) (h : m ≤ n) : disjoint (l.take m) (l.drop n) := begin induction l generalizing m n, case list.nil : m n { simp }, case list.cons : x xs xs_ih m n { cases m; cases n; simp only [disjoint_cons_left, mem_cons_iff, disjoint_cons_right, drop, true_or, eq_self_iff_true, not_true, false_and, disjoint_nil_left, take], { cases h }, cases hl with _ _ h₀ h₁, split, { intro h, exact h₀ _ (mem_of_mem_drop h) rfl, }, solve_by_elim [le_of_succ_le_succ] { max_depth := 4 } }, end end disjoint /-! ### union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /-! ### inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h @[simp] lemma inter_reverse {xs ys : list α} : xs.inter ys.reverse = xs.inter ys := by simp only [list.inter, mem_reverse]; congr end inter section choose variables (p : α → Prop) [decidable_pred p] (l : list α) lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose /-! ### map₂_left' -/ section map₂_left' -- The definitional equalities for `map₂_left'` can already be used by the -- simplifie because `map₂_left'` is marked `@[simp]`. @[simp] theorem map₂_left'_nil_right (f : α → option β → γ) (as) : map₂_left' f as [] = (as.map (λ a, f a none), []) := by cases as; refl end map₂_left' /-! ### map₂_right' -/ section map₂_right' variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem map₂_right'_nil_left : map₂_right' f [] bs = (bs.map (f none), []) := by cases bs; refl @[simp] theorem map₂_right'_nil_right : map₂_right' f as [] = ([], as) := rfl @[simp] theorem map₂_right'_nil_cons : map₂_right' f [] (b :: bs) = (f none b :: bs.map (f none), []) := rfl @[simp] theorem map₂_right'_cons_cons : map₂_right' f (a :: as) (b :: bs) = let rec := map₂_right' f as bs in (f (some a) b :: rec.fst, rec.snd) := rfl end map₂_right' /-! ### zip_left' -/ section zip_left' variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_left'_nil_right : zip_left' as ([] : list β) = (as.map (λ a, (a, none)), []) := by cases as; refl @[simp] theorem zip_left'_nil_left : zip_left' ([] : list α) bs = ([], bs) := rfl @[simp] theorem zip_left'_cons_nil : zip_left' (a :: as) ([] : list β) = ((a, none) :: as.map (λ a, (a, none)), []) := rfl @[simp] theorem zip_left'_cons_cons : zip_left' (a :: as) (b :: bs) = let rec := zip_left' as bs in ((a, some b) :: rec.fst, rec.snd) := rfl end zip_left' /-! ### zip_right' -/ section zip_right' variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_right'_nil_left : zip_right' ([] : list α) bs = (bs.map (λ b, (none, b)), []) := by cases bs; refl @[simp] theorem zip_right'_nil_right : zip_right' as ([] : list β) = ([], as) := rfl @[simp] theorem zip_right'_nil_cons : zip_right' ([] : list α) (b :: bs) = ((none, b) :: bs.map (λ b, (none, b)), []) := rfl @[simp] theorem zip_right'_cons_cons : zip_right' (a :: as) (b :: bs) = let rec := zip_right' as bs in ((some a, b) :: rec.fst, rec.snd) := rfl end zip_right' /-! ### map₂_left -/ section map₂_left variables (f : α → option β → γ) (as : list α) -- The definitional equalities for `map₂_left` can already be used by the -- simplifier because `map₂_left` is marked `@[simp]`. @[simp] theorem map₂_left_nil_right : map₂_left f as [] = as.map (λ a, f a none) := by cases as; refl theorem map₂_left_eq_map₂_left' : ∀ as bs, map₂_left f as bs = (map₂_left' f as bs).fst | [] bs := by simp! | (a :: as) [] := by simp! | (a :: as) (b :: bs) := by simp! [*] theorem map₂_left_eq_map₂ : ∀ as bs, length as ≤ length bs → map₂_left f as bs = map₂ (λ a b, f a (some b)) as bs | [] [] h := by simp! | [] (b :: bs) h := by simp! | (a :: as) [] h := by { simp at h, contradiction } | (a :: as) (b :: bs) h := by { simp at h, simp! [*] } end map₂_left /-! ### map₂_right -/ section map₂_right variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem map₂_right_nil_left : map₂_right f [] bs = bs.map (f none) := by cases bs; refl @[simp] theorem map₂_right_nil_right : map₂_right f as [] = [] := rfl @[simp] theorem map₂_right_nil_cons : map₂_right f [] (b :: bs) = f none b :: bs.map (f none) := rfl @[simp] theorem map₂_right_cons_cons : map₂_right f (a :: as) (b :: bs) = f (some a) b :: map₂_right f as bs := rfl theorem map₂_right_eq_map₂_right' : map₂_right f as bs = (map₂_right' f as bs).fst := by simp only [map₂_right, map₂_right', map₂_left_eq_map₂_left'] theorem map₂_right_eq_map₂ (h : length bs ≤ length as) : map₂_right f as bs = map₂ (λ a b, f (some a) b) as bs := begin have : (λ a b, flip f a (some b)) = (flip (λ a b, f (some a) b)) := rfl, simp only [map₂_right, map₂_left_eq_map₂, map₂_flip, *] end end map₂_right /-! ### zip_left -/ section zip_left variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_left_nil_right : zip_left as ([] : list β) = as.map (λ a, (a, none)) := by cases as; refl @[simp] theorem zip_left_nil_left : zip_left ([] : list α) bs = [] := rfl @[simp] theorem zip_left_cons_nil : zip_left (a :: as) ([] : list β) = (a, none) :: as.map (λ a, (a, none)) := rfl @[simp] theorem zip_left_cons_cons : zip_left (a :: as) (b :: bs) = (a, some b) :: zip_left as bs := rfl theorem zip_left_eq_zip_left' : zip_left as bs = (zip_left' as bs).fst := by simp only [zip_left, zip_left', map₂_left_eq_map₂_left'] end zip_left /-! ### zip_right -/ section zip_right variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_right_nil_left : zip_right ([] : list α) bs = bs.map (λ b, (none, b)) := by cases bs; refl @[simp] theorem zip_right_nil_right : zip_right as ([] : list β) = [] := rfl @[simp] theorem zip_right_nil_cons : zip_right ([] : list α) (b :: bs) = (none, b) :: bs.map (λ b, (none, b)) := rfl @[simp] theorem zip_right_cons_cons : zip_right (a :: as) (b :: bs) = (some a, b) :: zip_right as bs := rfl theorem zip_right_eq_zip_right' : zip_right as bs = (zip_right' as bs).fst := by simp only [zip_right, zip_right', map₂_right_eq_map₂_right'] end zip_right /-! ### to_chunks -/ section to_chunks @[simp] theorem to_chunks_nil (n) : @to_chunks α n [] = [] := by cases n; refl theorem to_chunks_aux_eq (n) : ∀ xs i, @to_chunks_aux α n xs i = (xs.take i, (xs.drop i).to_chunks (n+1)) | [] i := by cases i; refl | (x::xs) 0 := by rw [to_chunks_aux, drop, to_chunks]; cases to_chunks_aux n xs n; refl | (x::xs) (i+1) := by rw [to_chunks_aux, to_chunks_aux_eq]; refl theorem to_chunks_eq_cons' (n) : ∀ {xs : list α} (h : xs ≠ []), xs.to_chunks (n+1) = xs.take (n+1) :: (xs.drop (n+1)).to_chunks (n+1) | [] e := (e rfl).elim | (x::xs) _ := by rw [to_chunks, to_chunks_aux_eq]; refl theorem to_chunks_eq_cons : ∀ {n} {xs : list α} (n0 : n ≠ 0) (x0 : xs ≠ []), xs.to_chunks n = xs.take n :: (xs.drop n).to_chunks n | 0 _ e := (e rfl).elim | (n+1) xs _ := to_chunks_eq_cons' _ theorem to_chunks_aux_join {n} : ∀ {xs i l L}, @to_chunks_aux α n xs i = (l, L) → l ++ L.join = xs | [] _ _ _ rfl := rfl | (x::xs) i l L e := begin cases i; [ cases e' : to_chunks_aux n xs n with l L, cases e' : to_chunks_aux n xs i with l L]; { rw [to_chunks_aux, e', to_chunks_aux] at e, cases e, exact (congr_arg (cons x) (to_chunks_aux_join e') : _) } end @[simp] theorem to_chunks_join : ∀ n xs, (@to_chunks α n xs).join = xs | n [] := by cases n; refl | 0 (x::xs) := by simp only [to_chunks, join]; rw append_nil | (n+1) (x::xs) := begin rw to_chunks, cases e : to_chunks_aux n xs n with l L, exact (congr_arg (cons x) (to_chunks_aux_join e) : _), end theorem to_chunks_length_le : ∀ n xs, n ≠ 0 → ∀ l : list α, l ∈ @to_chunks α n xs → l.length ≤ n | 0 _ e _ := (e rfl).elim | (n+1) xs _ l := begin refine (measure_wf length).induction xs _, intros xs IH h, by_cases x0 : xs = [], {subst xs, cases h}, rw to_chunks_eq_cons' _ x0 at h, rcases h with rfl|h, { apply length_take_le }, { refine IH _ _ h, simp only [measure, inv_image, length_drop], exact nat.sub_lt_self (length_pos_iff_ne_nil.2 x0) (succ_pos _) }, end end to_chunks /-! ### Miscellaneous lemmas -/ theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val end list @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm namespace list @[to_additive] theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) : (L.map (g ∘ f)).prod = g ((L.map f).prod) := by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm} theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, r * f b)).sum = r * (L.map f).sum := sum_map_hom L f $ add_monoid_hom.mul_left r theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, f b * r)).sum = (L.map f).sum * r := sum_map_hom L f $ add_monoid_hom.mul_right r universes u v @[simp] theorem mem_map_swap {α : Type u} {β : Type v} (x : α) (y : β) (xs : list (α × β)) : (y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs := begin induction xs with x xs, { simp only [not_mem_nil, map_nil] }, { cases x with a b, simp only [mem_cons_iff, prod.mk.inj_iff, map, prod.swap_prod_mk, prod.exists, xs_ih, and_comm] }, end lemma slice_eq {α} (xs : list α) (n m : ℕ) : slice n m xs = xs.take n ++ xs.drop (n+m) := begin induction n generalizing xs, { simp [slice] }, { cases xs; simp [slice, *, nat.succ_add], } end lemma sizeof_slice_lt {α} [has_sizeof α] (i j : ℕ) (hj : 0 < j) (xs : list α) (hi : i < xs.length) : sizeof (list.slice i j xs) < sizeof xs := begin induction xs generalizing i j, case list.nil : i j h { cases hi }, case list.cons : x xs xs_ih i j h { cases i; simp only [-slice_eq, list.slice], { cases j, cases h, dsimp only [drop], unfold_wf, apply @lt_of_le_of_lt _ _ _ xs.sizeof, { clear_except, induction xs generalizing j; unfold_wf, case list.nil : j { refl }, case list.cons : xs_hd xs_tl xs_ih j { cases j; unfold_wf, refl, transitivity, apply xs_ih, simp }, }, unfold_wf, apply zero_lt_one_add, }, { unfold_wf, apply xs_ih _ _ h, apply lt_of_succ_lt_succ hi, } }, end end list
e1dffcb61066d8ebd26a74defd7b1734cb285188
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/712.lean
24555fc456b50501c52bd6555a9983daf6c0d83a
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
461
lean
reserve infix `~~~`:50 reserve notation `[` a `][` b:10 `]` section local infix `~~~` := eq #print notation ~~~ local infix `~~~`:50 := eq #print notation ~~~ local infix `~~~`:100 := eq infix `~~~`:100 := eq -- FAIL #print notation ~~~ local notation `[` a `][`:10 b:20 `]` := a = b #print notation ][ end notation `[` a `][`:10 b:20 `]` := a = b -- FAIL notation `[` a `][` b `]` := a = b infix `~~~` := eq #print notation ~~~ #print notation ][
550e4f6b7c495631dd56f36a7f24e7246c06dee9
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/category/monad.lean
59329a71a94375099ed11cddc6ba6bf3bc6b6bf7
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
1,052
lean
/- Copyright (c) Luke Nelson and Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Luke Nelson, Jared Roesch, Sebastian Ullrich -/ prelude import init.category.applicative universes u v open function class has_bind (m : Type u → Type v) := (bind : Π {α β : Type u}, m α → (α → m β) → m β) export has_bind (bind) @[inline] def has_bind.and_then {α β : Type u} {m : Type u → Type v} [has_bind m] (x : m α) (y : m β) : m β := do x, y infixl ` >>= `:55 := bind infixl ` >> `:55 := has_bind.and_then class monad (m : Type u → Type v) extends applicative m, has_bind m : Type (max (u+1) v) := (map := λ α β f x, x >>= pure ∘ f) (seq := λ α β f x, f >>= (<$> x)) @[reducible, inline] def return {m : Type u → Type v} [monad m] {α : Type u} : α → m α := pure /- Identical to has_bind.and_then, but it is not inlined. -/ def has_bind.seq {α β : Type u} {m : Type u → Type v} [has_bind m] (x : m α) (y : m β) : m β := do x, y
7c5cf5704cf3b9b32bd9a852fa71fb59d4b8af16
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/smt/default.lean
b2ae27d8500e10e7c75419c67f43cfafec0e82c4
[]
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
344
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.smt.arith import Mathlib.Lean3Lib.smt.array import Mathlib.Lean3Lib.smt.prove namespace Mathlib
5f5e797c66eb533667bfed015d952dfeb31baf35
9028d228ac200bbefe3a711342514dd4e4458bff
/src/group_theory/archimedean.lean
d7fddebb95fc705b88c5987885109c1a91f9ac07
[ "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
3,300
lean
/- Copyright (c) 2020 Heather Macbeth, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Patrick Massot -/ import group_theory.subgroup import algebra.archimedean /-! # Archimedean groups This file proves a few facts about ordered groups which satisfy the `archimedean` property, that is: `class archimedean (α) [ordered_add_comm_monoid α] : Prop :=` `(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n •ℕ y)` They are placed here in a separate file (rather than incorporated as a continuation of `algebra.archimedean`) because they rely on some imports from `group_theory` -- bundled subgroups in particular. The main result is `add_subgroup.cyclic_of_min`: a subgroup of a decidable archimedean abelian group is cyclic, if its set of positive elements has a minimal element. This result is used in this file to deduce `int.subgroup_cyclic`, proving that every subgroup of `ℤ` is cyclic. (There are several other methods one could use to prove this fact, including more purely algebraic methods, but none seem to exist in mathlib as of writing. The closest is `subgroup.is_cyclic`, but that has not been transferred to `add_subgroup`.) The result is also used in `topology.instances.real` as an ingredient in the classification of subgroups of `ℝ`. -/ variables {G : Type*} [decidable_linear_ordered_add_comm_group G] [archimedean G] open decidable_linear_ordered_add_comm_group /-- Given a subgroup `H` of a decidable linearly ordered archimedean abelian group `G`, if there exists a minimal element `a` of `H ∩ G_{>0}` then `H` is generated by `a`. -/ lemma add_subgroup.cyclic_of_min {H : add_subgroup G} {a : G} (ha : is_least {g : G | g ∈ H ∧ 0 < g} a) : H = add_subgroup.closure {a} := begin obtain ⟨⟨a_in, a_pos⟩, a_min⟩ := ha, refine le_antisymm _ (H.closure_le.mpr $ by simp [a_in]), intros g g_in, obtain ⟨k, nonneg, lt⟩ : ∃ k, 0 ≤ g - k •ℤ a ∧ g - k •ℤ a < a := exists_int_smul_near_of_pos' a_pos g, have h_zero : g - k •ℤ a = 0, { by_contra h, have h : a ≤ g - k •ℤ a, { refine a_min ⟨_, _⟩, { exact add_subgroup.sub_mem H g_in (add_subgroup.gsmul_mem H a_in k) }, { exact lt_of_le_of_ne nonneg (ne.symm h) } }, have h' : ¬ (a ≤ g - k •ℤ a) := not_le.mpr lt, contradiction }, simp [sub_eq_zero.mp h_zero, add_subgroup.mem_closure_singleton], end /-- Every subgroup of `ℤ` is cyclic. -/ lemma int.subgroup_cyclic (H : add_subgroup ℤ) : ∃ a, H = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero H with h h, { use 0, rw h, exact add_subgroup.closure_singleton_zero.symm }, let s := {g : ℤ | g ∈ H ∧ 0 < g}, have h_bdd : ∀ g ∈ s, (0 : ℤ) ≤ g := λ _ h, le_of_lt h.2, obtain ⟨g₀, g₀_in, g₀_ne⟩ := h, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℤ, g₁ ∈ H ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, H.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha, ha'⟩ := int.exists_least_of_bdd ⟨(0 : ℤ), h_bdd⟩ ⟨g₁, g₁_in, g₁_pos⟩, exact ⟨a, add_subgroup.cyclic_of_min ⟨ha, ha'⟩⟩, end
2228395362961759a4536e507bedcb95c9ca354d
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/dlist/basic.lean
f9df7ddaa7b6d93c0171a351565bb7a67e1ee711
[ "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
283
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.dlist def dlist.join {α : Type*} : list (dlist α) → dlist α | [] := dlist.empty | (x :: xs) := x ++ dlist.join xs
fc434f7a7fe591ffe9f13ecc33609c5017b663e6
4fa118f6209450d4e8d058790e2967337811b2b5
/src/for_mathlib/uniform_space/uniform_field.lean
17e1c2822396efdf0a3898c6c1024e649d6008e3
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
7,009
lean
/- The goal of this file is to prove the main part of Proposition 7 of Bourbaki GT III 6.8 : The completion hat K of a Hausdorff topological field is a field if the image under the mapping x ↦ x⁻¹ of every Cauchy filter (with respect to the additive uniform structure) which does not have a cluster point at 0 is a Cauchy filter (with respect to the additive uniform structure). Bourbaki does *not* prove this proposition, he refers to the general discussion of extending function defined on a dense subset with values in a complete Hausdorff space. In particular the subtlety about clustering at zero is totally left to readers. All this is very general. The application we have in mind is extension of valuations. In this application K will be equipped with a valuation and the topology on K will be the nonarchimedean topology coming from v. Note that the separated completion of a non-separated topological field is the zero ring, hence the separation assumption is needed. Indeed the kernel of the completion map is the closure of zero which is an ideal. Hence it's either zero (and the field is separated) or the full field, which implies one is sent to zero and the completion ring is trivial. -/ import topology.algebra.uniform_ring import for_mathlib.topological_field import for_mathlib.data.set.basic import for_mathlib.filter noncomputable theory local attribute [instance, priority 0] classical.prop_decidable open filter set_option class.instance_max_depth 100 open set uniform_space uniform_space.completion filter local attribute [instance] topological_add_group.to_uniform_space topological_add_group_is_uniform local notation `𝓝` x:70 := nhds x local notation `𝓤` := uniformity variables {K : Type*} [discrete_field K] [topological_space K] [topological_ring K] variables (K) local notation `hat` := completion def help_tc_search : uniform_space (hat K) := completion.uniform_space K local attribute [instance] help_tc_search def help_tc_search' : separated (hat K) := completion.separated K local attribute [instance] help_tc_search' def help_tc_search'' : complete_space (hat K) := completion.complete_space K local attribute [instance] help_tc_search'' def help_tc_search''' : t1_space (hat K) := t2_space.t1_space local attribute [instance] help_tc_search''' instance [separated K] : nonzero_comm_ring (hat K) := { zero_ne_one := assume h, zero_ne_one $ (uniform_embedding_coe K).inj h, ..completion.comm_ring K } class completable_top_field : Prop := (separated : separated K) (nice : ∀ F : filter K, cauchy F → 𝓝 0 ⊓ F = ⊥ → cauchy (map (λ x, x⁻¹) F)) local attribute [instance] completable_top_field.separated variables [completable_top_field K] [topological_division_ring K] {K} /-- extension of inversion to `hat K` -/ def hat_inv : hat K → hat K := dense_inducing_coe.extend (λ x : K, (coe x⁻¹ : hat K)) lemma continuous_hat_inv {x : hat K} (h : x ≠ 0) : continuous_at hat_inv x := begin haveI : regular_space (hat K) := completion.regular_space K, refine dense_inducing_coe.tendsto_extend _, apply mem_sets_of_superset (compl_singleton_mem_nhds h), intros y y_ne, rw mem_compl_singleton_iff at y_ne, dsimp, apply complete_space.complete, change cauchy (map (coe ∘ (λ (x : K), x⁻¹)) (comap coe (𝓝 y))), rw ← filter.map_map, apply cauchy_map (completion.uniform_continuous_coe K), apply completable_top_field.nice, { apply cauchy_comap, { rw completion.comap_coe_eq_uniformity, exact le_refl _ }, { exact cauchy_nhds }, { exact dense_inducing_coe.comap_nhds_ne_bot } }, { have eq_bot : 𝓝 ↑(0 : K) ⊓ 𝓝 y = ⊥, { by_contradiction h, exact y_ne (eq_of_nhds_ne_bot h).symm }, rw [dense_inducing_coe.nhds_eq_comap (0 : K), ← comap_inf, eq_bot], exact comap_bot }, end lemma hat_inv_extends {x : K} (h : x ≠ 0) : hat_inv (x : hat K) = coe (x⁻¹ : K) := dense_inducing_coe.extend_e_eq _ ((continuous_coe K).continuous_at.comp (topological_division_ring.continuous_inv x h)) lemma hat_inv_is_inv {x : hat K} (x_ne : x ≠ 0) : x*hat_inv x = 1 := begin haveI : t1_space (hat K) := t2_space.t1_space, let f := λ x : hat K, x*hat_inv x, let c := (coe : K → hat K), change f x = 1, have cont : continuous_at f x, { letI : topological_space (hat K × hat K) := prod.topological_space, have : continuous_at (λ y : hat K, ((y, hat_inv y) : hat K × hat K)) x, from continuous_at.prod_mk continuous_id.continuous_at (continuous_hat_inv x_ne), exact (_root_.continuous_mul.continuous_at.comp this : _) }, have clo : x ∈ closure (c '' -{0}), { have := dense_inducing_coe.dense x, rw [← image_univ, show (univ : set K) = {0} ∪ -{0}, from (union_compl_self _).symm, image_union] at this, apply mem_closure_union this, rw image_singleton, exact compl_singleton_mem_nhds x_ne }, have fxclo : f x ∈ closure (f '' (c '' -{0})) := mem_closure_image cont clo, have : f '' (c '' -{0}) ⊆ {1}, { rw image_image, rintros _ ⟨z, z_ne, rfl⟩, rw mem_singleton_iff, rw mem_compl_singleton_iff at z_ne, dsimp [c, f], rw hat_inv_extends z_ne, norm_cast, rw mul_inv_cancel z_ne, norm_cast }, replace fxclo := closure_mono this fxclo, rwa [closure_singleton, mem_singleton_iff] at fxclo end /- The value of `hat_inv` at zero is not really specified, although it's probably zero. Here we explicitly enforce the `inv_zero` axiom. -/ instance completion.has_inv : has_inv (hat K) := ⟨λ x, if x = 0 then 0 else hat_inv x⟩ @[move_cast] lemma coe_inv (x : K) : ((x⁻¹ : K) : hat K)= (x : hat K)⁻¹ := begin by_cases h : x = 0, { rw [h, inv_zero], dsimp [has_inv.inv], norm_cast, simp [if_pos] }, { conv_rhs { dsimp [has_inv.inv] }, norm_cast, rw if_neg, { exact (hat_inv_extends h).symm }, { exact λ H, h (completion.dense_embedding_coe.inj H) } } end instance : discrete_field (hat K) := { zero_ne_one := assume h, discrete_field.zero_ne_one K ((uniform_embedding_coe K).inj h), mul_inv_cancel := λ x x_ne, by { dsimp [has_inv.inv], simp [if_neg x_ne, hat_inv_is_inv x_ne], }, inv_mul_cancel := λ x x_ne, by { dsimp [has_inv.inv], rw [mul_comm, if_neg x_ne, hat_inv_is_inv x_ne] }, inv_zero := show (0 : hat K)⁻¹ = (0 : hat K), by rw_mod_cast inv_zero, has_decidable_eq := by apply_instance, ..completion.has_inv, ..(by apply_instance : comm_ring (hat K)) } instance : topological_division_ring (hat K) := { continuous_inv := begin intros x x_ne, have : {y | y⁻¹ = hat_inv y } ∈ 𝓝 x, { have : -{(0 : hat K)} ⊆ {y : hat K | y⁻¹ = hat_inv y }, { intros y y_ne, rw mem_compl_singleton_iff at y_ne, dsimp [has_inv.inv], rw if_neg y_ne }, exact mem_sets_of_superset (compl_singleton_mem_nhds x_ne) this }, rw continuous_at.congr this, exact continuous_hat_inv x_ne end, ..completion.top_ring_compl }
0b7f8b90f69d2d1ce527a699cb0b3e5109496caf
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/matrix/symmetric.lean
421a3e90d3fc469f3a1e5095be6d66f026723f51
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,118
lean
/- Copyright (c) 2021 Lu-Ming Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lu-Ming Zhang -/ import data.matrix.block /-! # Symmetric matrices This file contains the definition and basic results about symmetric matrices. ## Main definition * `matrix.is_symm `: a matrix `A : matrix n n α` is "symmetric" if `Aᵀ = A`. ## Tags symm, symmetric, matrix -/ variables {α β n m R : Type*} namespace matrix open_locale matrix /-- A matrix `A : matrix n n α` is "symmetric" if `Aᵀ = A`. -/ def is_symm (A : matrix n n α) : Prop := Aᵀ = A lemma is_symm.eq {A : matrix n n α} (h : A.is_symm) : Aᵀ = A := h /-- A version of `matrix.ext_iff` that unfolds the `matrix.transpose`. -/ lemma is_symm.ext_iff {A : matrix n n α} : A.is_symm ↔ ∀ i j, A j i = A i j := matrix.ext_iff.symm /-- A version of `matrix.ext` that unfolds the `matrix.transpose`. -/ @[ext] lemma is_symm.ext {A : matrix n n α} : (∀ i j, A j i = A i j) → A.is_symm := matrix.ext lemma is_symm.apply {A : matrix n n α} (h : A.is_symm) (i j : n) : A j i = A i j := is_symm.ext_iff.1 h i j lemma is_symm_mul_transpose_self [fintype n] [comm_semiring α] (A : matrix n n α) : (A ⬝ Aᵀ).is_symm := transpose_mul _ _ lemma is_symm_transpose_mul_self [fintype n] [comm_semiring α] (A : matrix n n α) : (A ⬝ Aᵀ).is_symm := transpose_mul _ _ lemma is_symm_add_transpose_self [add_comm_semigroup α] (A : matrix n n α) : (A + Aᵀ).is_symm := add_comm _ _ lemma is_symm_transpose_add_self [add_comm_semigroup α] (A : matrix n n α) : (Aᵀ + A).is_symm := add_comm _ _ @[simp] lemma is_symm_zero [has_zero α] : (0 : matrix n n α).is_symm := transpose_zero @[simp] lemma is_symm_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α).is_symm := transpose_one @[simp] lemma is_symm.map {A : matrix n n α} (h : A.is_symm) (f : α → β) : (A.map f).is_symm := transpose_map.symm.trans (h.symm ▸ rfl) @[simp] lemma is_symm.transpose {A : matrix n n α} (h : A.is_symm) : Aᵀ.is_symm := congr_arg _ h @[simp] lemma is_symm.conj_transpose [has_star α] {A : matrix n n α} (h : A.is_symm) : Aᴴ.is_symm := h.transpose.map _ @[simp] lemma is_symm.neg [has_neg α] {A : matrix n n α} (h : A.is_symm) : (-A).is_symm := (transpose_neg _).trans (congr_arg _ h) @[simp] lemma is_symm.add {A B : matrix n n α} [has_add α] (hA : A.is_symm) (hB : B.is_symm) : (A + B).is_symm := (transpose_add _ _).trans (hA.symm ▸ hB.symm ▸ rfl) @[simp] lemma is_symm.sub {A B : matrix n n α} [has_sub α] (hA : A.is_symm) (hB : B.is_symm) : (A - B).is_symm := (transpose_sub _ _).trans (hA.symm ▸ hB.symm ▸ rfl) @[simp] lemma is_symm.smul [has_scalar R α] {A : matrix n n α} (h : A.is_symm) (k : R) : (k • A).is_symm := (transpose_smul _ _).trans (congr_arg _ h) @[simp] lemma is_symm.minor {A : matrix n n α} (h : A.is_symm) (f : m → n) : (A.minor f f).is_symm := (transpose_minor _ _ _).trans (h.symm ▸ rfl) /-- The diagonal matrix `diagonal v` is symmetric. -/ @[simp] lemma is_symm_diagonal [decidable_eq n] [has_zero α] (v : n → α) : (diagonal v).is_symm := diagonal_transpose _ /-- A block matrix `A.from_blocks B C D` is symmetric, if `A` and `D` are symmetric and `Bᵀ = C`. -/ lemma is_symm.from_blocks {A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α} (hA : A.is_symm) (hBC : Bᵀ = C) (hD : D.is_symm) : (A.from_blocks B C D).is_symm := begin have hCB : Cᵀ = B, {rw ← hBC, simp}, unfold matrix.is_symm, rw from_blocks_transpose, congr; assumption end /-- This is the `iff` version of `matrix.is_symm.from_blocks`. -/ lemma is_symm_from_blocks_iff {A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α} : (A.from_blocks B C D).is_symm ↔ A.is_symm ∧ Bᵀ = C ∧ Cᵀ = B ∧ D.is_symm := ⟨λ h, ⟨congr_arg to_blocks₁₁ h, congr_arg to_blocks₂₁ h, congr_arg to_blocks₁₂ h, congr_arg to_blocks₂₂ h⟩, λ ⟨hA, hBC, hCB, hD⟩, is_symm.from_blocks hA hBC hD⟩ end matrix
318bd331cb95fd17ecce3f7066a6b70942e09abf
8ba901cf307a2677c194984e82644023b5d8f5d8
/mm0-lean/x86/x86.lean
a46f43771a2a8abfb04fd46eac6ed248e88d17cf
[ "CC0-1.0" ]
permissive
julian-becker/mm0
af57d3043477e1f17bdedcb29d4099bb8a25f692
79e2755dec1e6ee238e23e3494e84f82b6c138ac
refs/heads/master
1,598,672,691,658
1,572,192,390,000
1,572,192,390,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,743
lean
import x86.bits logic.relation namespace x86 local notation `S` := bitvec.singleton @[reducible] def regnum := bitvec 4 def RAX : regnum := 0 def RCX : regnum := 1 def RDX : regnum := 2 def RSP : regnum := 4 def RBP : regnum := 5 def RSI : regnum := 6 def RDI : regnum := 7 def REX := option (bitvec 4) def REX.to_nat : REX → ℕ | none := 0 | (some r) := r.to_nat def REX.W (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 3) def REX.R (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 2) def REX.X (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 1) def REX.B (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 0) def rex_reg (b : bool) (r : bitvec 3) : regnum := (bitvec.append r (S b) : _) structure scale_index := (scale : bitvec 2) (index : regnum) inductive base | none | rip | reg (reg : regnum) inductive RM : Type | reg : regnum → RM | mem : option scale_index → base → qword → RM def RM.is_mem : RM → Prop | (RM.mem _ _ _) := true | _ := false @[reducible] def Mod := bitvec 2 inductive read_displacement : Mod → qword → list byte → Prop | disp0 : read_displacement 0 0 [] | disp8 (b : byte) : read_displacement 1 (EXTS b) [b] | disp32 (w : word) (l) : w.to_list_byte l → read_displacement 2 (EXTS w) l def read_sib_displacement (mod : Mod) (bbase : regnum) (w : qword) (Base : base) (l : list byte) : Prop := if bbase = RBP ∧ mod = 0 then ∃ b, w = EXTS b ∧ Base = base.none ∧ l = [b] else read_displacement mod w l ∧ Base = base.reg bbase inductive read_SIB (rex : REX) (mod : Mod) : RM → list byte → Prop | mk (b : byte) (bs ix SS) (disp bbase' l) : split_bits b.to_nat [⟨3, bs⟩, ⟨3, ix⟩, ⟨2, SS⟩] → let bbase := rex_reg rex.B bs, index := rex_reg rex.X ix, scaled_index : option scale_index := if index = RSP then none else some ⟨SS, index⟩ in read_sib_displacement mod bbase disp bbase' l → read_SIB (RM.mem scaled_index bbase' disp) (b :: l) inductive read_ModRM (rex : REX) : regnum → RM → list byte → Prop | imm32 (b : byte) (reg_opc : bitvec 3) (i : word) (disp) : split_bits b.to_nat [⟨3, 0b101⟩, ⟨3, reg_opc⟩, ⟨2, 0b00⟩] → i.to_list_byte disp → read_ModRM (rex_reg rex.R reg_opc) (RM.mem none base.rip (EXTS i)) (b :: disp) | reg (b : byte) (rm reg_opc : bitvec 3) : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, 0b11⟩] → read_ModRM (rex_reg rex.R reg_opc) (RM.reg (rex_reg rex.B rm)) [b] | sib (b : byte) (reg_opc : bitvec 3) (mod : Mod) (sib) (l) : split_bits b.to_nat [⟨3, 0b100⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] → read_SIB rex mod sib l → read_ModRM (rex_reg rex.R reg_opc) sib (b :: l) | mem (b : byte) (rm reg_opc : bitvec 3) (mod : Mod) (disp l) : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] → rm ≠ 0b100 → ¬ (rm = 0b101 ∧ mod = 0b00) → read_displacement mod disp l → read_ModRM (rex_reg rex.R reg_opc) (RM.mem none (base.reg (rex_reg rex.B rm)) disp) (b :: l) inductive read_opcode_ModRM (rex : REX) : bitvec 3 → RM → list byte → Prop | mk (rn : regnum) (rm l v b) : read_ModRM rex rn rm l → split_bits rn.to_nat [⟨3, v⟩, ⟨1, b⟩] → read_opcode_ModRM v rm l -- obsolete group 1-4 prefixes omitted inductive read_prefixes : REX → list byte → Prop | nil : read_prefixes none [] | rex (b : byte) (rex) : split_bits b.to_nat [⟨4, rex⟩, ⟨4, 0b0100⟩] → read_prefixes (some rex) [b] @[derive decidable_eq] inductive wsize | Sz8 (have_rex : bool) | Sz16 | Sz32 | Sz64 open wsize def wsize.to_nat : wsize → ℕ | (Sz8 _) := 8 | Sz16 := 16 | Sz32 := 32 | Sz64 := 64 inductive read_imm8 : qword → list byte → Prop | mk (b : byte) : read_imm8 (EXTS b) [b] inductive read_imm16 : qword → list byte → Prop | mk (w : bitvec 16) (l) : bits_to_byte 2 w l → read_imm16 (EXTS w) l inductive read_imm32 : qword → list byte → Prop | mk (w : word) (l) : w.to_list_byte l → read_imm32 (EXTS w) l def read_imm : wsize → qword → list byte → Prop | (Sz8 _) := read_imm8 | Sz16 := read_imm16 | Sz32 := read_imm32 | Sz64 := λ _ _, false def read_full_imm : wsize → qword → list byte → Prop | (Sz8 _) := read_imm8 | Sz16 := read_imm16 | Sz32 := read_imm32 | Sz64 := λ w l, w.to_list_byte l def op_size (have_rex w v : bool) : wsize := if ¬ v then Sz8 have_rex else if w then Sz64 else -- if override then Sz16 else Sz32 def op_size_W (rex : REX) : bool → wsize := op_size rex.is_some rex.W inductive dest_src | Rm_i : RM → qword → dest_src | Rm_r : RM → regnum → dest_src | R_rm : regnum → RM → dest_src open dest_src inductive imm_rm | rm : RM → imm_rm | imm : qword → imm_rm inductive unop | dec | inc | not | neg inductive binop | add | or | adc | sbb | and | sub | xor | cmp | rol | ror | rcl | rcr | shl | shr | tst | sar inductive binop.bits : binop → bitvec 4 → Prop | add : binop.bits binop.add 0x0 | or : binop.bits binop.or 0x1 | adc : binop.bits binop.adc 0x2 | sbb : binop.bits binop.sbb 0x3 | and : binop.bits binop.and 0x4 | sub : binop.bits binop.sub 0x5 | xor : binop.bits binop.xor 0x6 | cmp : binop.bits binop.cmp 0x7 | rol : binop.bits binop.rol 0x8 | ror : binop.bits binop.ror 0x9 | rcl : binop.bits binop.rcl 0xa | rcr : binop.bits binop.rcr 0xb | shl : binop.bits binop.shl 0xc | shr : binop.bits binop.shr 0xd | tst : binop.bits binop.tst 0xe | sar : binop.bits binop.sar 0xf inductive basic_cond | o | b | e | na | s | l | ng inductive basic_cond.bits : basic_cond → bitvec 3 → Prop | o : basic_cond.bits basic_cond.o 0x0 | b : basic_cond.bits basic_cond.b 0x1 | e : basic_cond.bits basic_cond.e 0x2 | na : basic_cond.bits basic_cond.na 0x3 | s : basic_cond.bits basic_cond.s 0x4 | l : basic_cond.bits basic_cond.l 0x6 | ng : basic_cond.bits basic_cond.ng 0x7 inductive cond_code | always | pos : basic_cond → cond_code | neg : basic_cond → cond_code def cond_code.mk : bool → basic_cond → cond_code | ff := cond_code.pos | tt := cond_code.neg inductive cond_code.bits : cond_code → bitvec 4 → Prop | mk (v : bitvec 4) (b c code) : split_bits v.to_nat [⟨3, c⟩, ⟨1, S b⟩] → basic_cond.bits code c → cond_code.bits (cond_code.mk b code) v inductive ast | unop : unop → wsize → RM → ast | binop : binop → wsize → dest_src → ast | mul : wsize → RM → ast | div : wsize → RM → ast | lea : wsize → dest_src → ast | movsx : wsize → dest_src → wsize → ast | movzx : wsize → dest_src → wsize → ast | xchg : wsize → RM → regnum → ast | cmpxchg : wsize → RM → regnum → ast | xadd : wsize → RM → regnum → ast | cmov : cond_code → wsize → dest_src → ast | setcc : cond_code → bool → RM → ast | jump : RM → ast | jcc : cond_code → qword → ast | call : imm_rm → ast | ret : qword → ast | push : imm_rm → ast | pop : RM → ast | leave : ast | cmc | clc | stc -- | int : byte → ast | syscall def ast.mov := ast.cmov cond_code.always inductive decode_hi (v : bool) (sz : wsize) (r : RM) : bool → bitvec 3 → ast → list byte → Prop | test (imm l) : read_imm sz imm l → decode_hi ff 0b000 (ast.binop binop.tst sz (Rm_i r imm)) l | not : decode_hi ff 0b010 (ast.unop unop.not sz r) [] | neg : decode_hi ff 0b011 (ast.unop unop.neg sz r) [] | mul : decode_hi ff 0b100 (ast.mul sz r) [] | div : decode_hi ff 0b110 (ast.div sz r) [] | inc : decode_hi tt 0b000 (ast.unop unop.inc sz r) [] | dec : decode_hi tt 0b001 (ast.unop unop.dec sz r) [] | call : v → decode_hi tt 0b010 (ast.call (imm_rm.rm r)) [] | jump : v → decode_hi tt 0b100 (ast.jump r) [] | push : v → decode_hi tt 0b110 (ast.push (imm_rm.rm r)) [] inductive decode_two (rex : REX) : ast → list byte → Prop | cmov (b : byte) (c reg r l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x4⟩] → let sz := op_size tt rex.W tt in read_ModRM rex reg r l → cond_code.bits code c → decode_two (ast.cmov code sz (R_rm reg r)) (b :: l) | jcc (b : byte) (c imm l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x8⟩] → read_imm32 imm l → cond_code.bits code c → decode_two (ast.jcc code imm) (b :: l) | setcc (b : byte) (c reg r l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x9⟩] → read_ModRM rex reg r l → cond_code.bits code c → decode_two (ast.setcc code rex.is_some r) (b :: l) | cmpxchg (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1011000⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_two (ast.cmpxchg sz r reg) (b :: l) | movsx (b : byte) (v s reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b11⟩, ⟨1, S s⟩, ⟨4, 0xb⟩] → let sz2 := op_size_W rex tt, sz := if v then Sz16 else Sz8 rex.is_some in read_ModRM rex reg r l → decode_two ((if s then ast.movsx else ast.movzx) sz (R_rm reg r) sz2) (b :: l) | xadd (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100000⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_two (ast.xadd sz r reg) (b :: l) | syscall : decode_two ast.syscall [0x05] inductive decode_aux (rex : REX) : ast → list byte → Prop | binop1 (b : byte) (v d opc reg r l op) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S d⟩, ⟨1, 0b0⟩, ⟨3, opc⟩, ⟨2, 0b00⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → let src_dst := if d then R_rm reg r else Rm_r r reg in binop.bits op (EXTZ opc) → decode_aux (ast.binop op sz src_dst) (b :: l) | binop_imm_rax (b : byte) (v opc imm l op) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b10⟩, ⟨3, opc⟩, ⟨2, 0b00⟩] → let sz := op_size_W rex v in binop.bits op (EXTZ opc) → read_imm sz imm l → decode_aux (ast.binop op sz (Rm_i (RM.reg RAX) imm)) (b :: l) | binop_imm (b : byte) (v opc r l1 imm l2 op) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000000⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → read_imm sz imm l2 → binop.bits op (EXTZ opc) → decode_aux (ast.binop op sz (Rm_i r imm)) (b :: l1 ++ l2) | binop_imm8 (opc r l1 imm l2 op) : let sz := op_size_W rex tt in read_opcode_ModRM rex opc r l1 → binop.bits op (EXTZ opc) → read_imm8 imm l2 → decode_aux (ast.binop op sz (Rm_i r imm)) (0x83 :: l1 ++ l2) | binop_hi (b : byte) (v opc r imm op l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100000⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → opc ≠ 6 → binop.bits op (rex_reg tt opc) → read_imm8 imm l2 → decode_aux (ast.binop op sz (Rm_i r imm)) (b :: l1 ++ l2) | binop_hi_reg (b : byte) (v x opc r op l) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S x⟩, ⟨6, 0b110100⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l → opc ≠ 6 → binop.bits op (rex_reg tt opc) → decode_aux (ast.binop op sz (if x then Rm_r r RCX else Rm_i r 1)) (b :: l) | two (a l) : decode_two rex a l → decode_aux a (0x0f :: l) | movsx (reg r l) : read_ModRM rex reg r l → decode_aux (ast.movsx Sz32 (R_rm reg r) Sz64) (0x63 :: l) | mov (b : byte) (v d reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S d⟩, ⟨6, 0b100010⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → let src_dst := if d then R_rm reg r else Rm_r r reg in decode_aux (ast.mov sz src_dst) (b :: l) | mov64 (b : byte) (r v imm l) : split_bits b.to_nat [⟨3, r⟩, ⟨1, S v⟩, ⟨4, 0xb⟩] → let sz := op_size_W rex v in read_full_imm sz imm l → decode_aux (ast.mov sz (Rm_i (RM.reg (rex_reg rex.B r)) imm)) (b :: l) | mov_imm (b : byte) (v opc r imm l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100011⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → read_imm sz imm l2 → decode_aux (ast.mov sz (Rm_i r imm)) (b :: l1 ++ l2) | xchg (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000011⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_aux (ast.xchg sz r reg) (b :: l) | xchg_rax (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b10010⟩] → let sz := op_size tt rex.W tt in decode_aux (ast.xchg sz (RM.reg RAX) (rex_reg rex.B r)) [b] | push_imm (b : byte) (x imm l) : split_bits b.to_nat [⟨1, 0b0⟩, ⟨1, S x⟩, ⟨6, 0b011010⟩] → read_imm (if x then Sz8 ff else Sz32) imm l → decode_aux (ast.push (imm_rm.imm imm)) (b :: l) | push_rm (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b01010⟩] → decode_aux (ast.push (imm_rm.rm (RM.reg (rex_reg rex.B r)))) [b] | pop (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b01011⟩] → decode_aux (ast.pop (RM.reg (rex_reg rex.B r))) [b] | pop_rm (r l) : read_opcode_ModRM rex 0 r l → decode_aux (ast.pop r) (0x8f :: l) | jump (b : byte) (x imm l) : split_bits b.to_nat [⟨1, 0b1⟩, ⟨1, S x⟩, ⟨6, 0b111010⟩] → (if x then read_imm8 imm l else read_imm32 imm l) → decode_aux (ast.jcc cond_code.always imm) (b :: l) | jcc8 (b : byte) (c code imm l) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0b0111⟩] → cond_code.bits code c → read_imm8 imm l → decode_aux (ast.jcc code imm) (b :: l) | call (imm l) : read_imm32 imm l → decode_aux (ast.call (imm_rm.imm imm)) (0xe8 :: l) | ret (b : byte) (v imm l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100001⟩] → (if v then imm = 0 ∧ l = [] else read_imm16 imm l) → decode_aux (ast.ret imm) (b :: l) | leave : decode_aux ast.leave [0xc9] | lea (reg r l) : let sz := op_size tt rex.W tt in read_ModRM rex reg r l → RM.is_mem r → decode_aux (ast.lea sz (R_rm reg r)) (0x8d :: l) | test (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000010⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_aux (ast.binop binop.tst sz (Rm_r r reg)) (b :: l) | test_rax (b : byte) (v imm l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1010100⟩] → let sz := op_size tt rex.W v in read_imm sz imm l → decode_aux (ast.binop binop.tst sz (Rm_i (RM.reg RAX) imm)) (b :: l) | cmc : decode_aux ast.cmc [0xf5] | clc : decode_aux ast.clc [0xf8] | stc : decode_aux ast.stc [0xf9] -- | int (imm) : decode_aux (ast.int imm) [0xcd, imm] | hi (b : byte) (v x opc r a l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b11⟩, ⟨1, S x⟩, ⟨4, 0xf⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → decode_hi v sz r x opc a l2 → decode_aux a (b :: l1 ++ l2) inductive decode : ast → list byte → Prop | mk {rex l1 a l2} : read_prefixes rex l1 → decode_aux rex a l2 → decode a (l1 ++ l2) ---------------------------------------- -- Dynamic semantics ---------------------------------------- structure flags := (CF ZF SF OF : bool) def basic_cond.read : basic_cond → flags → bool | basic_cond.o f := f.OF | basic_cond.b f := f.CF | basic_cond.e f := f.ZF | basic_cond.na f := f.CF || f.ZF | basic_cond.s f := f.SF | basic_cond.l f := f.SF ≠ f.OF | basic_cond.ng f := f.ZF || (f.SF ≠ f.OF) def cond_code.read : cond_code → flags → bool | cond_code.always f := tt | (cond_code.pos c) f := c.read f | (cond_code.neg c) f := bnot $ c.read f structure perm := (isR isW isX : bool) def perm.R : perm := ⟨tt, ff, ff⟩ def perm.W : perm := ⟨ff, tt, ff⟩ def perm.X : perm := ⟨ff, ff, tt⟩ instance : has_add perm := ⟨λ p1 p2, ⟨p1.isR || p2.isR, p1.isW || p2.isW, p1.isX || p2.isX⟩⟩ instance : has_le perm := ⟨λ p1 p2, p1 + p2 = p2⟩ structure mem := (valid : qword → Prop) (mem : ∀ w, valid w → byte) (perm : ∀ w, valid w → perm) structure config := (rip : qword) (regs : regnum → qword) (flags : flags) (mem : mem) def mem.read1 (p : perm) (m : mem) (w : qword) (b : byte) : Prop := ∃ h, b = m.mem w h ∧ p ≤ m.perm w h inductive mem.read' (p : perm) (m : mem) : qword → list byte → Prop | nil (w) : mem.read' w [] | cons {w b l} : m.read1 p w b → mem.read' (w + 1) l → mem.read' w (b :: l) def mem.read (m : mem) : qword → list byte → Prop := m.read' perm.R def mem.readX (m : mem) : qword → list byte → Prop := m.read' (perm.R + perm.X) def mem.set (m : mem) (w : qword) (b : byte) : mem := {mem := λ w' h', if w = w' then b else m.mem w' h', ..m} inductive mem.write1 (m : mem) (w : qword) (b : byte) : mem → Prop | mk (h : m.valid w) : perm.R + perm.W ≤ m.perm w h → mem.write1 (m.set w b) inductive mem.write : mem → qword → list byte → mem → Prop | nil (m w) : mem.write m w [] m | cons {m1 m2 m3 : mem} {w b l} : m1.write1 w b m2 → mem.write m2 (w + 1) l m3 → mem.write m1 w (b :: l) m3 inductive EA | EA_i : qword → EA | EA_r : regnum → EA | EA_m : qword → EA open EA def EA.addr : EA → qword | (EA.EA_m a) := a | _ := 0 def index_ea (k : config) : option scale_index → qword | none := 0 | (some ⟨sc, ix⟩) := (bitvec.shl 1 sc.to_nat) * (k.regs ix) def base.ea (k : config) : base → qword | base.none := 0 | base.rip := k.rip | (base.reg r) := k.regs r def RM.ea (k : config) : RM → EA | (RM.reg r) := EA_r r | (RM.mem ix b d) := EA_m (index_ea k ix + b.ea k + d) def ea_dest (k : config) : dest_src → EA | (Rm_i v _) := v.ea k | (Rm_r v _) := v.ea k | (R_rm r _) := EA_r r def ea_src (k : config) : dest_src → EA | (Rm_i _ v) := EA_i v | (Rm_r _ v) := EA_r v | (R_rm _ v) := v.ea k def imm_rm.ea (k : config) : imm_rm → EA | (imm_rm.rm rm) := rm.ea k | (imm_rm.imm q) := EA_i q def EA.read (k : config) : EA → ∀ sz : wsize, bitvec sz.to_nat → Prop | (EA_i i) sz b := b = EXTZ i | (EA_r r) (Sz8 ff) b := b = EXTZ (if r.nth 2 then (k.regs (r - 4)).ushr 8 else k.regs r) | (EA_r r) sz b := b = EXTZ (k.regs r) | (EA_m a) sz b := ∃ l, k.mem.read a l ∧ bits_to_byte (sz.to_nat / 8) b l def EA.readq (k : config) (ea : EA) (sz : wsize) (q : qword) : Prop := ∃ w, ea.read k sz w ∧ q = EXTZ w def EA.read' (ea : EA) (sz : wsize) : pstate config qword := pstate.assert $ λ k, ea.readq k sz def config.set_reg (k : config) (r : regnum) (v : qword) : config := {regs := λ i, if i = r then v else k.regs i, ..k} def config.write_reg (k : config) (r : regnum) : ∀ sz : wsize, bitvec sz.to_nat → config | (Sz8 have_rex) v := if ¬ have_rex ∧ r.nth 2 then let r' := r - 4 in config.set_reg k r' ((k.regs r').update 8 v) else config.set_reg k r ((k.regs r).update 0 v) | Sz16 v := config.set_reg k r ((k.regs r).update 0 v) | Sz32 v := config.set_reg k r (EXTZ v) | Sz64 v := config.set_reg k r v inductive config.write_mem (k : config) : qword → list byte → config → Prop | mk {a l m'} : k.mem.write a l m' → config.write_mem a l {mem := m', ..k} inductive EA.write (k : config) : EA → ∀ sz : wsize, bitvec sz.to_nat → config → Prop | EA_r (r sz v) : EA.write (EA_r r) sz v (config.write_reg k r sz v) | EA_m (a) (sz : wsize) (v l k') : let n := sz.to_nat / 8 in bits_to_byte n v l → k.write_mem a l k' → EA.write (EA_m a) sz v k' def EA.writeq (k : config) (ea : EA) (sz : wsize) (q : qword) (k' : config) : Prop := ea.write k sz (EXTZ q) k' def EA.write' (ea : EA) (sz : wsize) (q : qword) : pstate config unit := pstate.lift $ λ k _, EA.writeq k ea sz q def write_rip (q : qword) : pstate config unit := pstate.modify $ λ k, {rip := q, ..k} inductive dest_src.read (k : config) (sz : wsize) (ds : dest_src) : EA → qword → qword → Prop | mk (d s) : let ea := ea_dest k ds in ea.readq k sz d → (ea_src k ds).readq k sz s → dest_src.read ea d s def dest_src.read' (sz : wsize) (ds : dest_src) : pstate config (EA × qword × qword) := pstate.assert $ λ k ⟨ea, d, s⟩, dest_src.read k sz ds ea d s def EA.call_dest (k : config) : EA → qword → Prop | (EA_i i) q := q = k.rip + i | (EA_r r) q := q = k.regs r | (EA_m a) q := (EA_m a).read k Sz64 q inductive EA.jump (k : config) : EA → config → Prop | mk (ea : EA) (q) : ea.call_dest k q → EA.jump ea {rip := q, ..k} def write_flags (f : config → flags → flags) : pstate config unit := pstate.lift $ λ k _ k', k' = {flags := f k k.flags, ..k} def MSB (sz : wsize) (w : qword) : bool := w.nth (fin.of_nat (sz.to_nat - 1)) def write_SF_ZF (sz : wsize) (w : qword) : pstate config unit := write_flags $ λ k f, { SF := MSB sz w, ZF := (EXTZ w : bitvec sz.to_nat) = 0, ..f } def write_result_flags (sz : wsize) (w : qword) (c o : bool) : pstate config unit := write_flags (λ k f, {CF := c, OF := o, ..f}) >> write_SF_ZF sz w def erase_flags : pstate config unit := do f ← pstate.any, pstate.modify $ λ s, {flags := f, ..s} def sadd_OV (sz : wsize) (a b : qword) : bool := MSB sz a = MSB sz b ∧ MSB sz (a + b) ≠ MSB sz a def ssub_OV (sz : wsize) (a b : qword) : bool := MSB sz a ≠ MSB sz b ∧ MSB sz (a - b) ≠ MSB sz a def add_carry (sz : wsize) (a b : qword) : qword × bool × bool := (a + b, 2 ^ sz.to_nat ≤ a.to_nat + b.to_nat, sadd_OV sz a b) def sub_borrow (sz : wsize) (a b : qword) : qword × bool × bool := (a - b, a.to_nat < b.to_nat, ssub_OV sz a b) def write_CF_OF_result (sz : wsize) (w : qword) (c o : bool) (ea : EA) : pstate config unit := write_result_flags sz w c o >> ea.write' sz w def write_SF_ZF_result (sz : wsize) (w : qword) (ea : EA) : pstate config unit := write_SF_ZF sz w >> ea.write' sz w def mask_shift : wsize → qword → ℕ | Sz64 w := (EXTZ w : bitvec 6).to_nat | _ w := (EXTZ w : bitvec 5).to_nat def write_binop (sz : wsize) (ea : EA) (a b : qword) : binop → pstate config unit | binop.add := let (w, c, o) := add_carry sz a b in write_CF_OF_result sz w c o ea | binop.sub := let (w, c, o) := sub_borrow sz a b in write_CF_OF_result sz w c o ea | binop.cmp := let (w, c, o) := sub_borrow sz a b in write_result_flags sz w c o | binop.tst := write_result_flags sz (a.and b) ff ff | binop.and := write_CF_OF_result sz (a.and b) ff ff ea | binop.xor := write_CF_OF_result sz (a.xor b) ff ff ea | binop.or := write_CF_OF_result sz (a.or b) ff ff ea | binop.rol := pstate.fail | binop.ror := pstate.fail | binop.rcl := pstate.fail | binop.rcr := pstate.fail | binop.shl := ea.write' sz (a.shl (mask_shift sz b)) >> erase_flags | binop.shr := ea.write' sz (a.ushr (mask_shift sz b)) >> erase_flags | binop.sar := ea.write' sz (a.fill_shr (mask_shift sz b) (MSB sz a)) >> erase_flags | binop.adc := do k ← pstate.get, let result := a + b + EXTZ (S k.flags.CF), let CF := 2 ^ sz.to_nat ≤ a.to_nat + b.to_nat, OF ← pstate.any, write_CF_OF_result sz result CF OF ea | binop.sbb := do k ← pstate.get, let carry : qword := EXTZ (S k.flags.CF), let result := a - (b + carry), let CF := a.to_nat < b.to_nat + carry.to_nat, OF ← pstate.any, write_CF_OF_result sz result CF OF ea def write_unop (sz : wsize) (a : qword) (ea : EA) : unop → pstate config unit | unop.inc := do let (w, _, o) := add_carry sz a 1, write_flags (λ k f, {OF := o, ..f}), write_SF_ZF_result sz w ea | unop.dec := do let (w, _, o) := sub_borrow sz a 1, write_flags (λ k f, {OF := o, ..f}), write_SF_ZF_result sz w ea | unop.not := ea.write' sz a.not | unop.neg := do CF ← pstate.any, write_flags (λ k f, {CF := CF, ..f}), write_SF_ZF_result sz (-a) ea def pop_aux : pstate config qword := do k ← pstate.get, let sp := k.regs RSP, (EA_r RSP).write' Sz64 (sp + 8), (EA_m sp).read' Sz64 def pop (rm : RM) : pstate config unit := do k ← pstate.get, pop_aux >>= (rm.ea k).write' Sz64 def pop_rip : pstate config unit := pop_aux >>= write_rip def push_aux (w : qword) : pstate config unit := do k ← pstate.get, let sp := k.regs RSP - 8, (EA_r RSP).write' Sz64 sp, (EA_m sp).write' Sz64 w def push (i : imm_rm) : pstate config unit := do k ← pstate.get, (i.ea k).read' Sz64 >>= push_aux def push_rip : pstate config unit := do k ← pstate.get, push_aux k.rip def execute : ast → pstate config unit | (ast.unop op sz rm) := do k ← pstate.get, let ea := rm.ea k, w ← ea.read' sz, write_unop sz w ea op | (ast.binop op sz ds) := do (ea, d, s) ← dest_src.read' sz ds, write_binop sz ea d s op | (ast.mul sz r) := do eax ← (EA_r RAX).read' sz, k ← pstate.get, src ← (r.ea k).read' sz, match sz with | (Sz8 _) := (EA_r RAX).write' Sz16 (eax * src) | _ := do let hi := bitvec.of_nat sz.to_nat ((eax.to_nat * src.to_nat).shiftl sz.to_nat), (EA_r RAX).write' sz (eax * src), (EA_r RDX).write' sz (EXTZ hi) end, erase_flags | (ast.div sz r) := do eax ← (EA_r RAX).read' sz, edx ← (EA_r RDX).read' sz, let n := edx.to_nat * (2 ^ sz.to_nat) + eax.to_nat, k ← pstate.get, d ← bitvec.to_nat <$> (r.ea k).read' sz, pstate.assert $ λ _ (_:unit), d ≠ 0 ∧ n / d < 2 ^ sz.to_nat, (EA_r RAX).write' sz (bitvec.of_nat _ (n / d)), (EA_r RDX).write' sz (bitvec.of_nat _ (n % d)), erase_flags | (ast.lea sz ds) := do k ← pstate.get, (ea_dest k ds).write' sz (ea_src k ds).addr | (ast.movsx sz1 ds sz2) := do w ← pstate.assert $ λ k, (ea_src k ds).read k sz1, k ← pstate.get, (ea_dest k ds).write' sz2 (EXTZ (EXTS w : bitvec sz2.to_nat)) | (ast.movzx sz1 ds sz2) := do w ← pstate.assert $ λ k, (ea_src k ds).read k sz1, k ← pstate.get, (ea_dest k ds).write' sz2 (EXTZ w) | (ast.xchg sz r n) := do let src := EA_r n, k ← pstate.get, let dst := r.ea k, val_src ← src.read' sz, val_dst ← dst.read' sz, src.write' sz val_dst, dst.write' sz val_src | (ast.cmpxchg sz r n) := do let src := EA_r n, let acc := EA_r RAX, k ← pstate.get, let dst := r.ea k, val_dst ← dst.read' sz, val_acc ← acc.read' sz, write_binop sz src val_acc val_dst binop.cmp, if val_acc = val_dst then src.read' sz >>= dst.write' sz else acc.write' sz val_dst | (ast.xadd sz r n) := do let src := EA_r n, k ← pstate.get, let dst := r.ea k, val_src ← src.read' sz, val_dst ← dst.read' sz, src.write' sz val_dst, write_binop sz dst val_src val_dst binop.add | (ast.cmov c sz ds) := do k ← pstate.get, when (c.read k.flags) $ (ea_src k ds).read' sz >>= (ea_dest k ds).write' sz | (ast.setcc c b r) := do k ← pstate.get, (r.ea k).write' (Sz8 b) (EXTZ $ S $ c.read k.flags) | (ast.jump rm) := do k ← pstate.get, (rm.ea k).read' Sz64 >>= write_rip | (ast.jcc c i) := do k ← pstate.get, when (c.read k.flags) (write_rip (k.rip + i)) | (ast.call i) := do push_rip, pstate.lift $ λ k _, (i.ea k).jump k | (ast.ret i) := do pop_rip, sp ← (EA_r RSP).read' Sz64, (EA_r RSP).write' Sz64 (sp + i) | (ast.push i) := push i | (ast.pop r) := pop r | ast.leave := do (EA_r RBP).read' Sz64 >>= (EA_r RSP).write' Sz64, pop (RM.reg RBP) | ast.clc := write_flags $ λ _ f, {CF := ff, ..f} | ast.cmc := write_flags $ λ _ f, {CF := bnot f.CF, ..f} | ast.stc := write_flags $ λ _ f, {CF := tt, ..f} -- | (ast.int _) := pstate.fail | ast.syscall := pstate.fail inductive config.step (k : config) : config → Prop | mk {l a k'} : k.mem.readX k.rip l → decode a l → ((do write_rip (k.rip + bitvec.of_nat _ l.length), execute a) k).P () k' → config.step k' inductive config.isIO (k : config) : config → Prop | mk {l k'} : k.mem.readX k.rip l → decode ast.syscall l → ((do let rip := k.rip + bitvec.of_nat _ l.length, write_rip rip, (EA.EA_r RCX).write' Sz64 rip) k).P () k' → config.isIO k' structure kcfg := (input : list byte) (output : list byte) (k : config) inductive config.read_cstr (k : config) (a : qword) : string → Prop | mk {s : string} : (∀ c : char, c ∈ s.to_list → c.1 ≠ 0) → k.mem.read a s.to_cstr → config.read_cstr s inductive read_from_fd (fd : qword) : list byte → list byte → list byte → Prop | other {i buf} : fd ≠ 0 → read_from_fd i buf i | stdin {i' buf} : fd = 0 → (buf = [] → i' = []) → read_from_fd (buf ++ i') buf i' inductive exec_read (i : list byte) (k : config) (fd : qword) (count : ℕ) : list byte → config → qword → Prop | fail {ret} : MSB Sz32 ret → exec_read i k ret | success {i' dat k' ret} : ¬ MSB Sz32 ret → ret.to_nat ≤ count → read_from_fd fd i dat i' → k.write_mem (k.regs RSI) dat k' → exec_read i' k' ret inductive exec_io (i o : list byte) (k : config) : qword → list byte → list byte → config → qword → Prop | _open {pathname fd} : k.read_cstr (k.regs RDI) pathname → let flags := k.regs RSI in flags.to_nat ∈ [0, 0x241] → -- O_RDONLY, or O_WRONLY | O_CREAT | O_TRUNC exec_io 2 i o k fd | _read {buf i' k' ret} : let fd := k.regs RDI, count := (k.regs RDX).to_nat in k.mem.read (k.regs RSI) buf → buf.length = count → exec_read i k fd count i' k' ret → exec_io 0 i' o k' ret -- TODO: write, fstat, mmap inductive config.exit (k : config) : qword → Prop | mk : k.regs RAX = 0x3c → config.exit (k.regs RAX) inductive kcfg.step : kcfg → kcfg → Prop | noio {i o k k'} : config.step k k' → kcfg.step ⟨i, o, k⟩ ⟨i, o, k'⟩ | io {i o k k₁ i' o' k' ret} : config.isIO k k₁ → exec_io i o k₁ (k₁.regs RAX) i' o' k' ret → kcfg.step ⟨i, o, k⟩ ⟨i', o', k'.set_reg RAX ret⟩ def kcfg.steps : kcfg → kcfg → Prop := relation.refl_trans_gen kcfg.step def kcfg.valid (k : kcfg) : Prop := (∃ k', k.step k') ∨ ∃ ret, k.k.exit ret def kcfg.safe (k : kcfg) : Prop := ∀ k', k.steps k' → k'.valid def terminates (k : config) (i o : list byte) := ∀ K', kcfg.steps ⟨i, [], k⟩ K' → ∃ i' o' k' ret, kcfg.steps K' ⟨i', o', k'⟩ ∧ k'.exit ret ∧ (ret = 0 → i' = [] ∧ o' = o) def succeeds (k : config) (i o : list byte) := ∃ i' k', kcfg.steps ⟨i, [], k⟩ ⟨i', o, k'⟩ ∧ k'.exit 0 end x86
5a20f704d500d24e5595c9d55092e1e858e236a7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/preadditive.lean
8f8ab46005f02d19c724d60e6ee4cf8d4cfd17f6
[ "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
9,777
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.additive_functor import category_theory.monoidal.functor /-! # Preadditive monoidal categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A monoidal category is `monoidal_preadditive` if it is preadditive and tensor product of morphisms is linear in both factors. -/ noncomputable theory open_locale classical namespace category_theory open category_theory.limits open category_theory.monoidal_category variables (C : Type*) [category C] [preadditive C] [monoidal_category C] /-- A category is `monoidal_preadditive` if tensoring is additive in both factors. Note we don't `extend preadditive C` here, as `abelian C` already extends it, and we'll need to have both typeclasses sometimes. -/ class monoidal_preadditive : Prop := (tensor_zero' : ∀ {W X Y Z : C} (f : W ⟶ X), f ⊗ (0 : Y ⟶ Z) = 0 . obviously) (zero_tensor' : ∀ {W X Y Z : C} (f : Y ⟶ Z), (0 : W ⟶ X) ⊗ f = 0 . obviously) (tensor_add' : ∀ {W X Y Z : C} (f : W ⟶ X) (g h : Y ⟶ Z), f ⊗ (g + h) = f ⊗ g + f ⊗ h . obviously) (add_tensor' : ∀ {W X Y Z : C} (f g : W ⟶ X) (h : Y ⟶ Z), (f + g) ⊗ h = f ⊗ h + g ⊗ h . obviously) restate_axiom monoidal_preadditive.tensor_zero' restate_axiom monoidal_preadditive.zero_tensor' restate_axiom monoidal_preadditive.tensor_add' restate_axiom monoidal_preadditive.add_tensor' attribute [simp] monoidal_preadditive.tensor_zero monoidal_preadditive.zero_tensor variables {C} [monoidal_preadditive C] local attribute [simp] monoidal_preadditive.tensor_add monoidal_preadditive.add_tensor instance tensor_left_additive (X : C) : (tensor_left X).additive := {} instance tensor_right_additive (X : C) : (tensor_right X).additive := {} instance tensoring_left_additive (X : C) : ((tensoring_left C).obj X).additive := {} instance tensoring_right_additive (X : C) : ((tensoring_right C).obj X).additive := {} /-- A faithful additive monoidal functor to a monoidal preadditive category ensures that the domain is monoidal preadditive. -/ lemma monoidal_preadditive_of_faithful {D} [category D] [preadditive D] [monoidal_category D] (F : monoidal_functor D C) [faithful F.to_functor] [F.to_functor.additive] : monoidal_preadditive D := { tensor_zero' := by { intros, apply F.to_functor.map_injective, simp [F.map_tensor], }, zero_tensor' := by { intros, apply F.to_functor.map_injective, simp [F.map_tensor], }, tensor_add' := begin intros, apply F.to_functor.map_injective, simp only [F.map_tensor, F.to_functor.map_add, preadditive.comp_add, preadditive.add_comp, monoidal_preadditive.tensor_add], end, add_tensor' := begin intros, apply F.to_functor.map_injective, simp only [F.map_tensor, F.to_functor.map_add, preadditive.comp_add, preadditive.add_comp, monoidal_preadditive.add_tensor], end, } open_locale big_operators lemma tensor_sum {P Q R S : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (R ⟶ S)) : f ⊗ ∑ j in s, g j = ∑ j in s, f ⊗ g j := begin rw ←tensor_id_comp_id_tensor, let tQ := (((tensoring_left C).obj Q).map_add_hom : (R ⟶ S) →+ _), change _ ≫ tQ _ = _, rw [tQ.map_sum, preadditive.comp_sum], dsimp [tQ], simp only [tensor_id_comp_id_tensor], end lemma sum_tensor {P Q R S : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (R ⟶ S)) : (∑ j in s, g j) ⊗ f = ∑ j in s, g j ⊗ f := begin rw ←tensor_id_comp_id_tensor, let tQ := (((tensoring_right C).obj P).map_add_hom : (R ⟶ S) →+ _), change tQ _ ≫ _ = _, rw [tQ.map_sum, preadditive.sum_comp], dsimp [tQ], simp only [tensor_id_comp_id_tensor], end variables {C} -- In a closed monoidal category, this would hold because -- `tensor_left X` is a left adjoint and hence preserves all colimits. -- In any case it is true in any preadditive category. instance (X : C) : preserves_finite_biproducts (tensor_left X) := { preserves := λ J _, by exactI { preserves := λ f, { preserves := λ b i, is_bilimit_of_total _ begin dsimp, simp only [←tensor_comp, category.comp_id, ←tensor_sum, ←tensor_id, is_bilimit.total i], end } } } instance (X : C) : preserves_finite_biproducts (tensor_right X) := { preserves := λ J _, by exactI { preserves := λ f, { preserves := λ b i, is_bilimit_of_total _ begin dsimp, simp only [←tensor_comp, category.comp_id, ←sum_tensor, ←tensor_id, is_bilimit.total i], end } } } variables [has_finite_biproducts C] /-- The isomorphism showing how tensor product on the left distributes over direct sums. -/ def left_distributor {J : Type} [fintype J] (X : C) (f : J → C) : X ⊗ (⨁ f) ≅ ⨁ (λ j, X ⊗ f j) := (tensor_left X).map_biproduct f @[simp] lemma left_distributor_hom {J : Type} [fintype J] (X : C) (f : J → C) : (left_distributor X f).hom = ∑ j : J, (𝟙 X ⊗ biproduct.π f j) ≫ biproduct.ι _ j := begin ext, dsimp [tensor_left, left_distributor], simp [preadditive.sum_comp, biproduct.ι_π, comp_dite], end @[simp] lemma left_distributor_inv {J : Type} [fintype J] (X : C) (f : J → C) : (left_distributor X f).inv = ∑ j : J, biproduct.π _ j ≫ (𝟙 X ⊗ biproduct.ι f j) := begin ext, dsimp [tensor_left, left_distributor], simp [preadditive.comp_sum, biproduct.ι_π_assoc, dite_comp], end lemma left_distributor_assoc {J : Type} [fintype J] (X Y : C) (f : J → C) : (as_iso (𝟙 X) ⊗ left_distributor Y f) ≪≫ left_distributor X _ = (α_ X Y (⨁ f)).symm ≪≫ left_distributor (X ⊗ Y) f ≪≫ biproduct.map_iso (λ j, α_ X Y _) := begin ext, simp only [category.comp_id, category.assoc, eq_to_hom_refl, iso.trans_hom, iso.symm_hom, as_iso_hom, comp_zero, comp_dite, preadditive.sum_comp, preadditive.comp_sum, tensor_sum, id_tensor_comp, tensor_iso_hom, left_distributor_hom, biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π, finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero], simp only [←id_tensor_comp, biproduct.ι_π], simp only [id_tensor_comp, tensor_dite, comp_dite], simp only [category.comp_id, comp_zero, monoidal_preadditive.tensor_zero, eq_to_hom_refl, tensor_id, if_true, dif_ctx_congr, finset.sum_congr, finset.mem_univ, finset.sum_dite_eq'], simp only [←tensor_id, associator_naturality, iso.inv_hom_id_assoc], end /-- The isomorphism showing how tensor product on the right distributes over direct sums. -/ def right_distributor {J : Type} [fintype J] (X : C) (f : J → C) : (⨁ f) ⊗ X ≅ ⨁ (λ j, f j ⊗ X) := (tensor_right X).map_biproduct f @[simp] lemma right_distributor_hom {J : Type} [fintype J] (X : C) (f : J → C) : (right_distributor X f).hom = ∑ j : J, (biproduct.π f j ⊗ 𝟙 X) ≫ biproduct.ι _ j := begin ext, dsimp [tensor_right, right_distributor], simp [preadditive.sum_comp, biproduct.ι_π, comp_dite], end @[simp] lemma right_distributor_inv {J : Type} [fintype J] (X : C) (f : J → C) : (right_distributor X f).inv = ∑ j : J, biproduct.π _ j ≫ (biproduct.ι f j ⊗ 𝟙 X) := begin ext, dsimp [tensor_right, right_distributor], simp [preadditive.comp_sum, biproduct.ι_π_assoc, dite_comp], end lemma right_distributor_assoc {J : Type} [fintype J] (X Y : C) (f : J → C) : (right_distributor X f ⊗ as_iso (𝟙 Y)) ≪≫ right_distributor Y _ = α_ (⨁ f) X Y ≪≫ right_distributor (X ⊗ Y) f ≪≫ biproduct.map_iso (λ j, (α_ _ X Y).symm) := begin ext, simp only [category.comp_id, category.assoc, eq_to_hom_refl, iso.symm_hom, iso.trans_hom, as_iso_hom, comp_zero, comp_dite, preadditive.sum_comp, preadditive.comp_sum, sum_tensor, comp_tensor_id, tensor_iso_hom, right_distributor_hom, biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π, finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero, finset.mem_univ, if_true], simp only [←comp_tensor_id, biproduct.ι_π, dite_tensor, comp_dite], simp only [category.comp_id, comp_tensor_id, eq_to_hom_refl, tensor_id, comp_zero, monoidal_preadditive.zero_tensor, if_true, dif_ctx_congr, finset.mem_univ, finset.sum_congr, finset.sum_dite_eq'], simp only [←tensor_id, associator_inv_naturality, iso.hom_inv_id_assoc] end lemma left_distributor_right_distributor_assoc {J : Type*} [fintype J] (X Y : C) (f : J → C) : (left_distributor X f ⊗ as_iso (𝟙 Y)) ≪≫ right_distributor Y _ = α_ X (⨁ f) Y ≪≫ (as_iso (𝟙 X) ⊗ right_distributor Y _) ≪≫ left_distributor X _ ≪≫ biproduct.map_iso (λ j, (α_ _ _ _).symm) := begin ext, simp only [category.comp_id, category.assoc, eq_to_hom_refl, iso.symm_hom, iso.trans_hom, as_iso_hom, comp_zero, comp_dite, preadditive.sum_comp, preadditive.comp_sum, sum_tensor, tensor_sum, comp_tensor_id, tensor_iso_hom, left_distributor_hom, right_distributor_hom, biproduct.map_iso_hom, biproduct.ι_map, biproduct.ι_π, finset.sum_dite_irrel, finset.sum_dite_eq', finset.sum_const_zero, finset.mem_univ, if_true], simp only [←comp_tensor_id, ←id_tensor_comp_assoc, category.assoc, biproduct.ι_π, comp_dite, dite_comp, tensor_dite, dite_tensor], simp only [category.comp_id, category.id_comp, category.assoc, id_tensor_comp, comp_zero, zero_comp, monoidal_preadditive.tensor_zero, monoidal_preadditive.zero_tensor, comp_tensor_id, eq_to_hom_refl, tensor_id, if_true, dif_ctx_congr, finset.sum_congr, finset.mem_univ, finset.sum_dite_eq'], simp only [associator_inv_naturality, iso.hom_inv_id_assoc] end end category_theory
10f8e9bc434567f1fbffba14e0999b49ca374692
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fintype/small.lean
f56a2ef40b2ad2e0ecfe0c2e784c2f166f2b9c9e
[ "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
495
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 data.fintype.card import logic.small.basic /-! # All finite types are small. That is, any `α` with `[fintype α]` is equivalent to a type in any universe. -/ universes w v @[priority 100] instance small_of_fintype (α : Type v) [fintype α] : small.{w} α := begin rw small_congr (fintype.equiv_fin α), apply_instance, end
c19e7774421f5e60542642f5a807d95fe5a3b099
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/05_Interacting_with_Lean.org.6.lean
0d857f09efaaa5991175cebdbf43201b87bc8955
[]
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
232
lean
/- page 66 -/ import standard import standard algebra.ordered_ring open nat algebra -- BEGIN check and.intro check and.elim check or.intro_left check or.intro_right check or.elim check eq.refl check eq.symm check eq.trans -- END
553451886ed05c4e2f61b0801eab65610cf1d7cc
59aed81a2ce7741e690907fc374be338f4f88b6f
/src/math-888/lec-13.lean
0f2f8ea16d4ef41e0e7b55c3629c6674978d56c4
[]
no_license
agusakov/math-688-lean
c84d5e1423eb208a0281135f0214b91b30d0ef48
67dc27ebff55a74c6b5a1c469ba04e7981d2e550
refs/heads/main
1,679,699,340,788
1,616,602,782,000
1,616,602,782,000
332,894,454
0
0
null
null
null
null
UTF-8
Lean
false
false
2,237
lean
/- 9 Mar 2020 -/ -- Cayley graphs import data.fintype.basic import data.sym2 import data.set.finite import group_theory.subgroup import linear_algebra.matrix import data.rel open finset universes u v @[ext] structure digraph (V : Type u) := (adj : V → V → Prop) -- for labelled edges, do `V → V → set S` or w/e (loopless : irreflexive adj . obviously) @[ext] structure labelled_digraph (V : Type u) (α : Type*) := (adj : V → V → set α) --(loopless : irreflexive adj . obviously) /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def digraph.from_rel {V : Type u} (r : V → V → Prop) : digraph V := { adj := λ a b, (a ≠ b) ∧ r a b, loopless := λ a ⟨hn, _⟩, hn rfl } open_locale big_operators matrix open finset matrix digraph variables {α : Type u} [fintype α] variables (R : Type v) [semiring R] variables (Γ : digraph α) (R) [decidable_rel Γ.adj] /-- `adj_matrix G R` is the matrix `A` such that `A i j = (1 : R)` if `i` and `j` are adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/ def adj_matrix : matrix α α R | i j := if (Γ.adj i j) then 1 else 0 variables {G : Type u} [add_comm_group G] [fintype G] /- Let `(G, +)` be a finite abelian group. Let `S` be a generating set of `G` such that `S = -S`, i.e. if `g ∈ S` then `-g ∈ S`, and `0 ∉ S`. The Cayley graph of `G` w.r.t. `S` is the graph `Γ` whose vertex set is `G` and where, if `x, y ∈ G`, `Γ.adj x y` if `x - y ∈ S`. -/ -- for `S` we have -- `finset G` -- if `g ∈ S` then `-g ∈ S` -- need hypothesis that says that `subgroup.closure S = ⊤` -- `0 ∉ S` -- `adj` is defined as -- λ a b, a - b ∈ S def cayley_graph (S : set G) (h : add_subgroup.closure S = ⊤) (h2 : (0 : G) ∉ S) (h4 : ∀ (g ∈ S), -g ∈ S) : digraph G := { adj := λ a b, a - b ∈ S, loopless := begin intros x h3, simp at h3, apply h2, exact h3, end } def labelled_cayley_graph (S : set G) [decidable_pred S] (h : add_subgroup.closure S = ⊤) (h2 : (0 : G) ∉ S) (h4 : ∀ (g ∈ S), -g ∈ S) : labelled_digraph G S := { adj := λ a b, if h3 : (a - b) ∈ S then {⟨a - b, h3⟩} else ∅}
f8450a40f15057621043293a1696ae294aacad0e
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/algebra/monoid_algebra.lean
99421db1bef0499570532f09c54633368c7d8d0e
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
28,875
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, Yury G. Kudryashov, Scott Morrison -/ import algebra.algebra.basic /-! # Monoid algebras When the domain of a `finsupp` has a multiplicative or additive structure, we can define a convolution product. To mathematicians this structure is known as the "monoid algebra", i.e. the finite formal linear combinations over a given semiring of elements of the monoid. The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses. In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G` in the same way, and then define the convolution product on these. When the domain is additive, this is used to define polynomials: ``` polynomial α := add_monoid_algebra ℕ α mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α ``` When the domain is multiplicative, e.g. a group, this will be used to define the group ring. ## Implementation note Unfortunately because additive and multiplicative structures both appear in both cases, it doesn't appear to be possible to make much use of `to_additive`, and we just settle for saying everything twice. Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale classical big_operators open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def monoid_algebra : Type (max u₁ u₂) := G →₀ k end namespace monoid_algebra variables {k G} local attribute [reducible] monoid_algebra section variables [semiring k] [monoid G] /-- The product of `f g : monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x * y = a`. (Think of the group ring of a group.) -/ instance : has_mul (monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl lemma mul_apply (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma mul_apply_antidiagonal (f g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) : mul_apply f g x ... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm ... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 : (finset.sum_filter _ _).symm ... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 : sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl) ... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _) $ λ p hps hp, begin simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢, by_cases h1 : f p.1 = 0, { rw [h1, zero_mul] }, { rw [hp hps h1, mul_zero] } end end section variables [semiring k] [monoid G] lemma support_mul (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `1` and zero elsewhere. -/ instance : has_one (monoid_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_algebra k G) = single 1 1 := rfl -- TODO: the simplifier unfolds 0 in the instance proof! protected lemma zero_mul (f : monoid_algebra k G) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] protected lemma mul_zero (f : monoid_algebra k G) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : monoid_algebra k G) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : monoid_algebra k G) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] instance : semiring (monoid_algebra k G) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := monoid_algebra.zero_mul, mul_zero := monoid_algebra.mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } @[simp] lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) @[simp] lemma single_pow {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n) | 0 := rfl | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : G →* monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by rw [single_mul_single, one_mul] } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma mul_single_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) = ite (a₁ * x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_one_apply (f : monoid_algebra k G) (r : k) (x : G) : (f * single 1 r) x = f x * r := f.mul_single_apply_aux $ λ a, by rw [mul_one] lemma single_mul_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr' with g s, split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_one_mul_apply (f : monoid_algebra k G) (r : k) (x : G) : (single 1 r * f) x = r * f x := f.single_mul_apply_aux $ λ a, by rw [one_mul] end instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [mul_comm] end, .. monoid_algebra.semiring } instance [ring k] : has_neg (monoid_algebra k G) := by apply_instance instance [ring k] [monoid G] : ring (monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. monoid_algebra.semiring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) := { mul_comm := mul_comm, .. monoid_algebra.ring} instance {R : Type*} [semiring R] [semiring k] [semimodule R k] : has_scalar R (monoid_algebra k G) := finsupp.has_scalar instance {R : Type*} [semiring R] [semiring k] [semimodule R k] : semimodule R (monoid_algebra k G) := finsupp.semimodule G k lemma single_one_comm [comm_semiring k] [monoid G] (r : k) (f : monoid_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } /-- As a preliminary to defining the `k`-algebra structure on `monoid_algebra k G`, we define the underlying ring homomorphism. In fact, we do this in more generality, providing the ring homomorphism `k →+* monoid_algebra A G` given any ring homomorphism `k →+* A`. -/ def algebra_map' {A : Type*} [semiring k] [semiring A] (f : k →+* A) [monoid G] : k →+* monoid_algebra A G := { to_fun := λ x, single 1 (f x), map_one' := by { simp, refl }, map_mul' := λ x y, by rw [single_mul_single, one_mul, f.map_mul], map_zero' := by rw [f.map_zero, single_zero], map_add' := λ x y, by rw [f.map_add, single_add], } /-- The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`. In particular this provides the instance `algebra k (monoid_algebra k G)`. -/ instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : algebra k (monoid_algebra A G) := { smul_def' := λ r a, by { ext x, dsimp [algebra_map'], rw single_one_mul_apply, rw algebra.smul_def'', }, commutes' := λ r f, show single 1 (algebra_map k A r) * f = f * single 1 (algebra_map k A r), by { ext, rw [single_one_mul_apply, mul_single_one_apply, algebra.commutes], }, ..algebra_map' (algebra_map k A) } @[simp] lemma coe_algebra_map {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : (algebra_map k (monoid_algebra A G) : k → monoid_algebra A G) = single 1 ∘ (algebra_map k A) := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = (algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) b * of k G a := by simp lemma single_algebra_map_eq_algebra_map_mul_of {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] (a : G) (b : k) : single a (algebra_map k A b) = (algebra_map k (monoid_algebra A G) : k → monoid_algebra A G) b * of A G a := by simp instance [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) := finsupp.comap_distrib_mul_action_self section lift variables (k G) [comm_semiring k] [monoid G] (A : Type u₃) [semiring A] [algebra k A] /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (G →* A) ≃ (monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : monoid_algebra k G →* A).comp (of k G), to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a), map_one' := by { rw [one_def, sum_single_index, one_smul, F.map_one], apply zero_smul }, map_mul' := λ f g, begin rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index], work_on_goal 1 { intros, rw zero_smul, }, work_on_goal 1 { intros, rw add_smul, }, refine finset.sum_congr rfl (λ a ha, _), simp only, rw [finsupp.mul_sum, finsupp.sum_sum_index], work_on_goal 1 { intros, rw zero_smul, }, work_on_goal 1 { intros, rw add_smul, }, refine finset.sum_congr rfl (λ a' ha', _), simp only, rw [sum_single_index, F.map_mul, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm], apply zero_smul, end, map_zero' := sum_zero_index, map_add' := λ f g, begin rw [sum_add_index], { intros, rw zero_smul, }, { intros, rw add_smul, }, end, commutes' := λ r, begin rw [coe_algebra_map, sum_single_index, F.map_one, algebra.smul_def, mul_one, algebra.id.map_eq_self], apply zero_smul end, }, left_inv := λ f, begin ext x, simp [sum_single_index] end, right_inv := λ F, begin ext f, conv_rhs { rw ← f.sum_single }, simp [← F.map_smul, finsupp.sum, ← F.map_sum] end } variables {k G A} lemma lift_apply (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F a) := rfl @[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] A) (x : G) : (lift k G A).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* A) (x) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* A) (a b) : lift k G A F (single a b) = b • F a := by rw [single_eq_algebra_map_mul_of, ← algebra.smul_def, alg_hom.map_smul, lift_of] lemma lift_unique' (F : monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ -- @[ext] -- FIXME I would really like to make this an `ext` lemma, but it seems to cause `ext` to loop. lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := (lift k G A).symm.injective $ monoid_hom.ext h end lift section variables (k) /-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/ def group_smul.linear_map [group G] [comm_ring k] (V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) : (semimodule.restrict_scalars k (monoid_algebra k G) V) →ₗ[k] (semimodule.restrict_scalars k (monoid_algebra k G) V) := { to_fun := λ v, (single g (1 : k) • v : V), map_add' := λ x y, smul_add (single g (1 : k)) x y, map_smul' := λ c x, by simp only [semimodule.restrict_scalars_smul_def, coe_algebra_map, ←mul_smul, single_one_comm], }. @[simp] lemma group_smul.linear_map_apply [group G] [comm_ring k] (V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) (v : V) : (group_smul.linear_map k V g) v = (single g (1 : k) • v : V) := rfl section variables {k} variables [group G] [comm_ring k] {V : Type u₃} {gV : add_comm_group V} {mV : module (monoid_algebra k G) V} {W : Type u₃} {gW : add_comm_group W} {mW : module (monoid_algebra k G) W} (f : (semimodule.restrict_scalars k (monoid_algebra k G) V) →ₗ[k] (semimodule.restrict_scalars k (monoid_algebra k G) W)) (h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W)) include h /-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/ def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W := { to_fun := f, map_add' := λ v v', by simp, map_smul' := λ c v, begin apply finsupp.induction c, { simp, }, { intros g r c' nm nz w, rw [add_smul, linear_map.map_add, w, add_smul, add_left_inj, single_eq_algebra_map_mul_of, ←smul_smul, ←smul_smul], erw [f.map_smul, h g v], refl, } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, prod_insert has, prod_insert has] section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] @[simp] lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y * x⁻¹) * r := f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm @[simp] lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) : (single x r * f) y = r * f (x⁻¹ * y) := f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm lemma mul_apply_left (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) := calc (f * g) x = sum f (λ a b, (single a b * g) x) : by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single] ... = _ : by simp only [single_mul_apply, finsupp.sum] -- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`. lemma mul_apply_right (f g : monoid_algebra k G) (x : G) : (f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) := calc (f * g) x = sum g (λ a b, (f * single a b) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end end monoid_algebra section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the additive monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def add_monoid_algebra := G →₀ k end namespace add_monoid_algebra variables {k G} local attribute [reducible] add_monoid_algebra section variables [semiring k] [add_monoid G] /-- The product of `f g : add_monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the additive monoid of monomial exponents.) -/ instance : has_mul (add_monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def {f g : add_monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl lemma mul_apply (f g : add_monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma support_mul (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `0` and zero elsewhere. -/ instance : has_one (add_monoid_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 := rfl -- TODO: the simplifier unfolds 0 in the instance proof! protected lemma zero_mul (f : add_monoid_algebra k G) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] protected lemma mul_zero (f : add_monoid_algebra k G) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : add_monoid_algebra k G) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : add_monoid_algebra k G) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] instance : semiring (add_monoid_algebra k G) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := add_monoid_algebra.zero_mul, mul_zero := add_monoid_algebra.mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : add_monoid_algebra k G) * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by { rw [single_mul_single, one_mul], refl } } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma mul_single_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ + a₂ = z) (b₁ * b₂) 0) = ite (a₁ + x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_zero_apply (f : add_monoid_algebra k G) (r : k) (x : G) : (f * single 0 r) x = f x * r := f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero] lemma single_mul_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x + a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x + a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr' with g s, split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_zero_mul_apply (f : add_monoid_algebra k G) (r : k) (x : G) : (single 0 r * f) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] end instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. add_monoid_algebra.semiring } instance [ring k] : has_neg (add_monoid_algebra k G) := by apply_instance instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. add_monoid_algebra.semiring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) := { mul_comm := mul_comm, .. add_monoid_algebra.ring} variables {R : Type*} instance [semiring R] [semiring k] [semimodule R k] : has_scalar R (add_monoid_algebra k G) := finsupp.has_scalar instance [semiring R] [semiring k] [semimodule R k] : semimodule R (add_monoid_algebra k G) := finsupp.semimodule G k /-- As a preliminary to defining the `k`-algebra structure on `add_monoid_algebra k G`, we define the underlying ring homomorphism. In fact, we do this in more generality, providing the ring homomorphism `R →+* add_monoid_algebra k G` given any ring homomorphism `R →+* k`. -/ def algebra_map' [semiring R] [semiring k] (f : R →+* k) [add_monoid G] : R →+* add_monoid_algebra k G := { to_fun := λ x, single 0 (f x), map_one' := by { simp, refl }, map_mul' := λ x y, by rw [single_mul_single, zero_add, f.map_mul], map_zero' := by rw [f.map_zero, single_zero], map_add' := λ x y, by rw [f.map_add, single_add], } /-- The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`. In particular this provides the instance `algebra k (add_monoid_algebra k G)`. -/ instance [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : algebra R (add_monoid_algebra k G) := { smul_def' := λ r a, by { ext x, dsimp [algebra_map'], rw single_zero_mul_apply, rw algebra.smul_def'', }, commutes' := λ r f, show single 0 (algebra_map R k r) * f = f * single 0 (algebra_map R k r), by { ext, rw [single_zero_mul_apply, mul_single_zero_apply, algebra.commutes], }, ..algebra_map' (algebra_map R k) } @[simp] lemma coe_algebra_map [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : (algebra_map R (add_monoid_algebra k G) : R → add_monoid_algebra k G) = single 0 ∘ (algebra_map R k) := rfl /-- Any monoid homomorphism `multiplicative G →* A` can be lifted to an algebra homomorphism `add_monoid_algebra k G →ₐ[k] A`. -/ def lift [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] : (multiplicative G →* A) ≃ (add_monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, ((f : add_monoid_algebra k G →+* A) : add_monoid_algebra k G →* A).comp (of k G), to_fun := λ F, { -- The proofs here are almost identical to `monoid_algebra.lift`, but use `erw` instead of `rw` -- to unfold `multiplicative` to_fun := λ f, f.sum (λ a b, b • F a), map_one' := by { rw [one_def, sum_single_index, one_smul], erw [F.map_one], apply zero_smul }, map_mul' := λ f g, begin rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index], work_on_goal 1 { intros, rw zero_smul, }, work_on_goal 1 { intros, rw add_smul, }, refine finset.sum_congr rfl (λ a ha, _), simp only, rw [finsupp.mul_sum, finsupp.sum_sum_index], work_on_goal 1 { intros, rw zero_smul, }, work_on_goal 1 { intros, rw add_smul, }, refine finset.sum_congr rfl (λ a' ha', _), simp only, rw [sum_single_index], erw [F.map_mul], rw [algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm], apply zero_smul, end, map_zero' := sum_zero_index, map_add' := λ f g, begin rw [sum_add_index], { intros, rw zero_smul, }, { intros, rw add_smul, }, end, commutes' := λ r, begin rw [coe_algebra_map, sum_single_index], erw [F.map_one], rw [algebra.smul_def, mul_one, algebra.id.map_eq_self], apply zero_smul end, }, left_inv := λ f, begin ext x, simp [sum_single_index] end, right_inv := λ F, begin ext f, conv_rhs { rw ← f.sum_single }, simp [← F.map_smul, finsupp.sum, ← F.map_sum] end } -- It is hard to state the equivalent of `distrib_mul_action G (monoid_algebra k G)` -- because we've never discussed actions of additive groups. lemma alg_hom_ext {A : Type u₃} [comm_semiring k] [add_monoid G] [semiring A] [algebra k A] ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) : φ₁ = φ₂ := lift.symm.injective $ by {ext, apply h} lemma alg_hom_ext_iff {A : Type u₃} [comm_semiring k] [add_monoid G] [semiring A] [algebra k A] ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ : (∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ := ⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩ universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] end add_monoid_algebra
8984ee852f531cb02329ca226d1cbe120664ac90
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/module/linear_map.lean
a96c8a0fda49b68c103202c709b92ed79d96484a
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
21,110
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen -/ import algebra.group.hom import algebra.module.basic import algebra.group_action_hom /-! # Linear maps and linear equivalences In this file we define * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`module`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `linear_equiv R M ₂`, `M ≃ₗ[R] M₂`: an invertible linear map ## Tags linear map, linear equiv, linear equivalences, linear isomorphism, linear isomorphic -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A map `f` between modules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between modules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] extends add_hom M M₂, M →[R] M₂ end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom /-- The `mul_action_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_mul_action_hom infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [module R M] [module R M₂] /-- The `distrib_mul_action_hom` underlying a `linear_map`. -/ def to_distrib_mul_action_hom (f : M →ₗ[R] M₂) : distrib_mul_action_hom R M M₂ := { map_zero' := zero_smul R (0 : M) ▸ zero_smul R (f.to_fun 0) ▸ f.map_smul' 0 0, ..f } instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [module R M] [module R M₂] variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} theorem coe_injective : injective (λ f : M →ₗ[R] M₂, show M → M₂, from f) := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] lemma mk_coe (f : M →ₗ[R] M₂) (h₁ h₂) : (linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) = f := ext $ λ _, rfl variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := f.to_distrib_mul_action_hom.map_zero @[simp] lemma map_eq_zero_iff (h : function.injective f) {x : M} : f x = 0 ↔ x = 0 := ⟨λ w, by { apply h, simp [w], }, λ w, by { subst w, simp, }⟩ variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [module S M] [has_scalar R M₂] [module S M₂] := (map_smul : ∀ (f : M →ₗ[S] M₂) (c : R) (x : M), f (c • x) = c • f x) variables {M M₂} @[priority 100] instance is_scalar_tower.compatible_smul {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [module S M] [is_scalar_tower R S M] [has_scalar R M₂] [module S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ f c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (f x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [module S M] [has_scalar R M₂] [module S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) (c : R) (x : M) : f (c • x) = c • f x := compatible_smul.map_smul f c x instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ⇑f.to_add_monoid_hom = f := rfl section restrict_scalars variables (R) [semiring S] [module S M] [module S M₂] [compatible_smul M M₂ R S] /-- If `M` and `M₂` are both `R`-modules and `S`-modules and `R`-module structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ @[simps] def restrict_scalars (f : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul_of_tower } lemma restrict_scalars_injective : function.injective (restrict_scalars R : (M →ₗ[S] M₂) → (M →ₗ[R] M₂)) := λ f g h, ext (linear_map.congr_fun h : _) @[simp] lemma restrict_scalars_inj (f g : M →ₗ[S] M₂) : f.restrict_scalars R = g.restrict_scalars R ↔ f = g := (restrict_scalars_injective R).eq_iff end restrict_scalars variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `R`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₗ[R] M} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smul, g.map_smul, h] theorem ext_ring_iff {f g : R →ₗ[R] M} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ end section variables {module_M : module R M} {module_M₂ : module R M₂} {module_M₃ : module R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[simp, norm_cast] lemma coe_comp : (f.comp g : M → M₃) = f ∘ g := rfl @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl end /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [module R M] [module R M₂] (f : M →ₗ[R] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, λ a b, by { rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂] }⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {module_M : module R M} {module_M₂ : module R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f } instance compatible_smul.int_module {S : Type*} [semiring S] [module S M] [module S M₂] : compatible_smul M M₂ ℤ S := ⟨λ f c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simp [add_smul, ih] }, case hn : n ih { simp [sub_smul, ih] } end⟩ instance compatible_smul.units {R S : Type*} [monoid R] [mul_action R M] [mul_action R M₂] [semiring S] [module S M] [module S M₂] [compatible_smul M M₂ R S] : compatible_smul M M₂ (units R) S := ⟨λ f c x, (compatible_smul.map_smul f (c : R) x : _)⟩ end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [module R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [module R M] [module R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `linear_map.endomorphism_semiring` and algebra structure `module.endomorphism_algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℕ`-linear map. -/ def add_monoid_hom.to_nat_linear_map [add_comm_monoid M] [add_comm_monoid M₂] (f : M →+ M₂) : M →ₗ[ℕ] M₂ := ⟨f, f.map_add, f.map_nat_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ @[simp] lemma add_monoid_hom.coe_to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : ⇑f.to_int_linear_map = f := rfl /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } @[simp] lemma add_monoid_hom.coe_to_rat_linear_map [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) : ⇑f.to_rat_linear_map = f := rfl /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] extends M →ₗ[R] M₂, M ≃+ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_add_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables {M₄ : Type*} variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [module R M] [module R M₂] [module R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_mk {to_fun inv_fun map_add map_smul left_inv right_inv } : ⇑(⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) = to_fun := rfl -- This exists for compatibility, previously `≃ₗ[R]` extended `≃` instead of `≃+`. @[nolint doc_blame] def to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂ := λ f, f.to_add_equiv.to_equiv lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[simp] lemma to_equiv_inj {e₁ e₂ : M ≃ₗ[R] M₂} : e₁.to_equiv = e₂.to_equiv ↔ e₁ = e₂ := to_equiv_injective.eq_iff lemma to_linear_map_injective : function.injective (coe : (M ≃ₗ[R] M₂) → (M →ₗ[R] M₂)) := λ e₁ e₂ H, to_equiv_injective $ equiv.ext $ linear_map.congr_fun H @[simp, norm_cast] lemma to_linear_map_inj {e₁ e₂ : M ≃ₗ[R] M₂} : (e₁ : M →ₗ[R] M₂) = e₂ ↔ e₁ = e₂ := to_linear_map_injective.eq_iff end section variables {module_M : module R M} {module_M₂ : module R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma to_linear_map_eq_coe : e.to_linear_map = ↑e := rfl @[simp, norm_cast] theorem coe_coe : ⇑(e : M →ₗ[R] M₂) = e := rfl @[simp] lemma coe_to_equiv : ⇑e.to_equiv = e := rfl @[simp] lemma coe_to_linear_map : ⇑e.to_linear_map = e := rfl @[simp] lemma to_fun_eq_coe : e.to_fun = e := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := to_equiv_injective (equiv.ext h) protected lemma congr_arg : Π {x x' : M}, x = x' → e x = e x' | _ _ rfl := rfl protected lemma congr_fun (h : e = e') (x : M) : e x = e' x := h ▸ rfl lemma ext_iff : e = e' ↔ ∀ x, e x = e' x := ⟨λ h x, h ▸ rfl, ext⟩ end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [module R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [module R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- See Note [custom simps projection] -/ def simps.symm_apply [module R M] [module R M₂] (e : M ≃ₗ[R] M₂) : M₂ → M := e.symm initialize_simps_projections linear_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm : e.inv_fun = e.symm := rfl variables {module_M₃ : module R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl /-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/ lemma to_add_monoid_hom_commutes : e.to_linear_map.to_add_monoid_hom = e.to_add_equiv.to_add_monoid_hom := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := to_equiv_injective e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := to_equiv_injective e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] lemma refl_symm [module R M] : (refl R M).symm = linear_equiv.refl R M := rfl @[simp] lemma trans_symm [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) : f.trans f.symm = linear_equiv.refl R M := by { ext x, simp } @[simp] lemma symm_trans [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) : f.symm.trans f = linear_equiv.refl R M₂ := by { ext x, simp } @[simp, norm_cast] lemma refl_to_linear_map [module R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [module R M] [module R M₂] [module R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M →ₗ[R] M₃) := rfl @[simp] lemma mk_coe (h₁ h₂ f h₃ h₄) : (linear_equiv.mk e h₁ h₂ f h₃ h₄ : M ≃ₗ[R] M₂) = e := ext $ λ _, rfl @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } lemma symm_bijective [module R M] [module R M₂] : function.bijective (symm : (M ≃ₗ[R] M₂) → (M₂ ≃ₗ[R] M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (f h₁ h₂ h₃ h₄) : (linear_equiv.mk f h₁ h₂ ⇑e h₃ h₄ : M₂ ≃ₗ[R] M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] theorem symm_mk (f h₁ h₂ h₃ h₄) : (⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₗ[R] M₂).symm = { to_fun := f, inv_fun := e, ..(⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₗ[R] M₂).symm } := rfl protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end /-- An involutive linear map is a linear equivalence. -/ def of_involutive [module R M] (f : M →ₗ[R] M) (hf : involutive f) : M ≃ₗ[R] M := { .. f, .. hf.to_equiv f } @[simp] lemma coe_of_involutive [module R M] (f : M →ₗ[R] M) (hf : involutive f) : ⇑(of_involutive f hf) = f := rfl section restrict_scalars variables (R) [module R M] [module R M₂] [semiring S] [module S M] [module S M₂] [linear_map.compatible_smul M M₂ R S] /-- If `M` and `M₂` are both `R`-semimodules and `S`-semimodules and `R`-semimodule structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear equivalence from `M` to `M₂` is also an `R`-linear equivalence. See also `linear_map.restrict_scalars`. -/ @[simps] def restrict_scalars (f : M ≃ₗ[S] M₂) : M ≃ₗ[R] M₂ := { to_fun := f, inv_fun := f.symm, left_inv := f.left_inv, right_inv := f.right_inv, .. f.to_linear_map.restrict_scalars R } lemma restrict_scalars_injective : function.injective (restrict_scalars R : (M ≃ₗ[S] M₂) → (M ≃ₗ[R] M₂)) := λ f g h, ext (linear_equiv.congr_fun h : _) @[simp] lemma restrict_scalars_inj (f g : M ≃ₗ[S] M₂) : f.restrict_scalars R = g.restrict_scalars R ↔ f = g := (restrict_scalars_injective R).eq_iff end restrict_scalars end add_comm_monoid end linear_equiv
73fc636d2d9d5122e2163261172d58802c73598d
1437b3495ef9020d5413178aa33c0a625f15f15f
/data/real/nnreal.lean
a8f78fb4b3f042db4f8d116dc62de03a39696da0
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,838
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import data.real.basic order.lattice section discrete_field @[simp] lemma inv_eq_zero {α} [discrete_field α] (a : α) : a⁻¹ = 0 ↔ a = 0 := classical.by_cases (assume : a = 0, by simp [*])(assume : a ≠ 0, by simp [*, inv_ne_zero]) end discrete_field noncomputable theory open lattice local attribute [instance] classical.prop_decidable def nnreal := {r : ℝ // 0 ≤ r} local notation ` ℝ≥0 ` := nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝ≥0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ @[simp] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp] protected lemma coe_sub (r₁ r₂ : ℝ≥0) (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma zero_div (r : ℝ≥0) : 0 / r = 0 := nnreal.eq (zero_div _) @[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := @nnreal.eq_iff r 0 instance : comm_semiring ℝ≥0 := begin refine { zero := 0, add := (+), one := 1, mul := (*), ..}; { intros; apply nnreal.eq; simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib, add_comm_monoid.zero] } end instance : is_semiring_hom (coe : ℝ≥0 → ℝ) := by refine_struct {..}; intros; refl lemma sum_coe {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.sum f) = s.sum (λa, (f a : ℝ)) := eq.symm $ finset.sum_hom _ lemma prod_coe {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.prod f) = s.prod (λa, (f a : ℝ)) := eq.symm $ finset.prod_hom _ lemma smul_coe (r : ℝ≥0) : ∀n, ↑(add_monoid.smul n r) = add_monoid.smul n (r:ℝ) | 0 := rfl | (n + 1) := by simp [add_monoid.add_smul, smul_coe n] @[simp] protected lemma coe_nat_cast : ∀(n : ℕ), (↑(↑n : ℝ≥0) : ℝ) = n | 0 := rfl | (n + 1) := by simp [coe_nat_cast n] instance : decidable_linear_order ℝ≥0 := { le := (≤), lt := λa b, (a : ℝ) < b, lt_iff_le_not_le := assume a b, @lt_iff_le_not_le ℝ _ a b, le_refl := assume a, le_refl (a : ℝ), le_trans := assume a b c, @le_trans ℝ _ a b c, le_antisymm := assume a b hab hba, nnreal.eq $ le_antisymm hab hba, le_total := assume a b, le_total (a : ℝ) b, decidable_le := λa b, by apply_instance } protected lemma coe_le {r₁ r₂ : ℝ≥0} : r₁ ≤ r₂ ↔ (r₁ : ℝ) ≤ r₂ := iff.rfl protected lemma coe_lt {r₁ r₂ : ℝ≥0} : r₁ < r₂ ↔ (r₁ : ℝ) < r₂ := iff.rfl protected lemma coe_pos {r : ℝ≥0} : 0 < r ↔ (0 : ℝ) < r := iff.rfl instance : canonically_ordered_monoid ℝ≥0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.decidable_linear_order} instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := zero_le, .. nnreal.decidable_linear_order } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.lattice.order_bot, .. nnreal.lattice.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.lattice.order_bot, .. nnreal.lattice.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c, mul_le_mul_of_nonneg_left := assume a b c, @mul_le_mul_of_nonneg_left ℝ _ a b c, mul_le_mul_of_nonneg_right := assume a b c, @mul_le_mul_of_nonneg_right ℝ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_lt_one := @zero_lt_one ℝ _, .. nnreal.decidable_linear_order, .. nnreal.canonically_ordered_monoid, .. nnreal.comm_semiring } instance : canonically_ordered_comm_semiring ℝ≥0 := { zero_ne_one := assume h, @zero_ne_one ℝ _ $ congr_arg subtype.val $ h, mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp, .. nnreal.linear_ordered_semiring, .. nnreal.canonically_ordered_monoid, .. nnreal.comm_semiring } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_left_of_le $ hb _ $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb _ $ hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : has_Sup ℝ≥0 := ⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s), begin by_cases h : s = ∅, { simp [h, set.image_empty, real.Sup_empty] }, rcases set.ne_empty_iff_exists_mem.1 h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝ≥0 := ⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s), begin by_cases h : s = ∅, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (by simp [h]) (assume r ⟨q, _, eq⟩, eq ▸ q.2) end⟩⟩ lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝ≥0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h _ hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h _ hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice.lattice_of_decidable_linear_order, .. nnreal.lattice.order_bot } instance : archimedean nnreal := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (add_monoid.smul n y : nnreal), by simp [*, smul_coe]⟩ ⟩ lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end lemma lt_iff_exists_rat_btwn (a b : nnreal) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end section of_real @[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt, lt_irrefl] @[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 := by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r)) lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 := of_real_eq_zero.2 @[simp] lemma of_real_coe {r : nnreal} : nnreal.of_real r = r := nnreal.eq $ by simp [nnreal.of_real] @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) : nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p := by simp [nnreal.coe_le, nnreal.of_real, hp] @[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} : nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt, nnreal.of_real, lt_irrefl] lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans (and_iff_left h) @[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p := nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := (of_real_add hr hp).symm lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p := nnreal.coe_le.2 $ max_le_max h $ le_refl _ lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p := nnreal.coe_le.2 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe end of_real section mul lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end end mul section sub lemma sub_eq_zero {r p : nnreal} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le] using h @[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [nnreal.coe_le, nnreal.coe_le, nnreal.coe_sub _ _ h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le, nnreal.coe_le, sub_eq_zero h] end lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] @[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a := nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub _ _ h, sub_add_cancel] end sub section inv lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl @[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero @[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 := by rw [← nnreal.eq_iff, nnreal.coe_inv, nnreal.coe_zero, inv_eq_zero, ← nnreal.coe_zero, nnreal.eq_iff] @[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r := by simp [zero_lt_iff_ne_zero] @[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 := nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h @[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 := by rw [mul_comm, inv_mul_cancel h] @[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq inv_inv' @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_if_le_inv {a b r : nnreal} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [nnreal.coe_lt, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) end inv end nnreal
1efc8dd84464f1b4d47b6060ec7e34169d108545
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/normed_space/extend.lean
238d700112bfd3dd792ddf9d964ebf83dd0a2e58
[ "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
6,818
lean
/- Copyright (c) 2020 Ruben Van de Velde. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ruben Van de Velde -/ import data.complex.is_R_or_C /-! # Extending a continuous `ℝ`-linear map to a continuous `𝕜`-linear map In this file we provide a way to extend a continuous `ℝ`-linear map to a continuous `𝕜`-linear map in a way that bounds the norm by the norm of the original map, when `𝕜` is either `ℝ` (the extension is trivial) or `ℂ`. We formulate the extension uniformly, by assuming `is_R_or_C 𝕜`. We motivate the form of the extension as follows. Note that `fc : F →ₗ[𝕜] 𝕜` is determined fully by `Re fc`: for all `x : F`, `fc (I • x) = I * fc x`, so `Im (fc x) = -Re (fc (I • x))`. Therefore, given an `fr : F →ₗ[ℝ] ℝ`, we define `fc x = fr x - fr (I • x) * I`. ## Main definitions * `linear_map.extend_to_𝕜` * `continuous_linear_map.extend_to_𝕜` ## Implementation details For convenience, the main definitions above operate in terms of `restrict_scalars ℝ 𝕜 F`. Alternate forms which operate on `[is_scalar_tower ℝ 𝕜 F]` instead are provided with a primed name. -/ open is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] {F : Type*} [semi_normed_group F] [semi_normed_space 𝕜 F] local notation `abs𝕜` := @is_R_or_C.abs 𝕜 _ /-- Extend `fr : F →ₗ[ℝ] ℝ` to `F →ₗ[𝕜] 𝕜` in a way that will also be continuous and have its norm bounded by `∥fr∥` if `fr` is continuous. -/ noncomputable def linear_map.extend_to_𝕜' [module ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →ₗ[ℝ] ℝ) : F →ₗ[𝕜] 𝕜 := begin let fc : F → 𝕜 := λ x, (fr x : 𝕜) - (I : 𝕜) * (fr ((I : 𝕜) • x)), have add : ∀ x y : F, fc (x + y) = fc x + fc y, { assume x y, simp only [fc], unfold_coes, simp only [smul_add, ring_hom.map_add, ring_hom.to_fun_eq_coe, linear_map.to_fun_eq_coe, linear_map.map_add], rw mul_add, abel, }, have A : ∀ (c : ℝ) (x : F), (fr ((c : 𝕜) • x) : 𝕜) = (c : 𝕜) * (fr x : 𝕜), { assume c x, rw [← of_real_mul], congr' 1, rw [is_R_or_C.of_real_alg, smul_assoc, fr.map_smul, algebra.id.smul_eq_mul, one_smul] }, have smul_ℝ : ∀ (c : ℝ) (x : F), fc ((c : 𝕜) • x) = (c : 𝕜) * fc x, { assume c x, simp only [fc, A], rw A c x, rw [smul_smul, mul_comm I (c : 𝕜), ← smul_smul, A, mul_sub], ring }, have smul_I : ∀ x : F, fc ((I : 𝕜) • x) = (I : 𝕜) * fc x, { assume x, simp only [fc], cases @I_mul_I_ax 𝕜 _ with h h, { simp [h] }, rw [mul_sub, ← mul_assoc, smul_smul, h], simp only [neg_mul_eq_neg_mul_symm, linear_map.map_neg, one_mul, one_smul, mul_neg_eq_neg_mul_symm, of_real_neg, neg_smul, sub_neg_eq_add, add_comm] }, have smul_𝕜 : ∀ (c : 𝕜) (x : F), fc (c • x) = c • fc x, { assume c x, rw [← re_add_im c, add_smul, add_smul, add, smul_ℝ, ← smul_smul, smul_ℝ, smul_I, ← mul_assoc], refl }, exact { to_fun := fc, map_add' := add, map_smul' := smul_𝕜 } end lemma linear_map.extend_to_𝕜'_apply [module ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →ₗ[ℝ] ℝ) (x : F) : fr.extend_to_𝕜' x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl /-- The norm of the extension is bounded by `∥fr∥`. -/ lemma norm_bound [semi_normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →L[ℝ] ℝ) (x : F) : ∥(fr.to_linear_map.extend_to_𝕜' x : 𝕜)∥ ≤ ∥fr∥ * ∥x∥ := begin let lm : F →ₗ[𝕜] 𝕜 := fr.to_linear_map.extend_to_𝕜', -- We aim to find a `t : 𝕜` such that -- * `lm (t • x) = fr (t • x)` (so `lm (t • x) = t * lm x ∈ ℝ`) -- * `∥lm x∥ = ∥lm (t • x)∥` (so `t.abs` must be 1) -- If `lm x ≠ 0`, `(lm x)⁻¹` satisfies the first requirement, and after normalizing, it -- satisfies the second. -- (If `lm x = 0`, the goal is trivial.) classical, by_cases h : lm x = 0, { rw [h, norm_zero], apply mul_nonneg; exact norm_nonneg _ }, let fx := (lm x)⁻¹, let t := fx / (abs𝕜 fx : 𝕜), have ht : abs𝕜 t = 1, by field_simp [abs_of_real, of_real_inv, is_R_or_C.abs_inv, is_R_or_C.abs_div, is_R_or_C.abs_abs, h], have h1 : (fr (t • x) : 𝕜) = lm (t • x), { apply ext, { simp only [lm, of_real_re, linear_map.extend_to_𝕜'_apply, mul_re, I_re, of_real_im, zero_mul, add_monoid_hom.map_sub, sub_zero, mul_zero], refl }, { symmetry, calc im (lm (t • x)) = im (t * lm x) : by rw [lm.map_smul, smul_eq_mul] ... = im ((lm x)⁻¹ / (abs𝕜 (lm x)⁻¹) * lm x) : rfl ... = im (1 / (abs𝕜 (lm x)⁻¹ : 𝕜)) : by rw [div_mul_eq_mul_div, inv_mul_cancel h] ... = 0 : by rw [← of_real_one, ← of_real_div, of_real_im] ... = im (fr (t • x) : 𝕜) : by rw [of_real_im] } }, calc ∥lm x∥ = abs𝕜 t * ∥lm x∥ : by rw [ht, one_mul] ... = ∥t * lm x∥ : by rw [← norm_eq_abs, normed_field.norm_mul] ... = ∥lm (t • x)∥ : by rw [←smul_eq_mul, lm.map_smul] ... = ∥(fr (t • x) : 𝕜)∥ : by rw h1 ... = ∥fr (t • x)∥ : by rw [norm_eq_abs, abs_of_real, norm_eq_abs, abs_to_real] ... ≤ ∥fr∥ * ∥t • x∥ : continuous_linear_map.le_op_norm _ _ ... = ∥fr∥ * (∥t∥ * ∥x∥) : by rw norm_smul ... ≤ ∥fr∥ * ∥x∥ : by rw [norm_eq_abs, ht, one_mul] end /-- Extend `fr : F →L[ℝ] ℝ` to `F →L[𝕜] 𝕜`. -/ noncomputable def continuous_linear_map.extend_to_𝕜' [semi_normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →L[ℝ] ℝ) : F →L[𝕜] 𝕜 := linear_map.mk_continuous _ (∥fr∥) (norm_bound _) lemma continuous_linear_map.extend_to_𝕜'_apply [semi_normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →L[ℝ] ℝ) (x : F) : fr.extend_to_𝕜' x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl /-- Extend `fr : restrict_scalars ℝ 𝕜 F →ₗ[ℝ] ℝ` to `F →ₗ[𝕜] 𝕜`. -/ noncomputable def linear_map.extend_to_𝕜 (fr : (restrict_scalars ℝ 𝕜 F) →ₗ[ℝ] ℝ) : F →ₗ[𝕜] 𝕜 := fr.extend_to_𝕜' lemma linear_map.extend_to_𝕜_apply (fr : (restrict_scalars ℝ 𝕜 F) →ₗ[ℝ] ℝ) (x : F) : fr.extend_to_𝕜 x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl /-- Extend `fr : restrict_scalars ℝ 𝕜 F →L[ℝ] ℝ` to `F →L[𝕜] 𝕜`. -/ noncomputable def continuous_linear_map.extend_to_𝕜 (fr : (restrict_scalars ℝ 𝕜 F) →L[ℝ] ℝ) : F →L[𝕜] 𝕜 := fr.extend_to_𝕜' lemma continuous_linear_map.extend_to_𝕜_apply (fr : (restrict_scalars ℝ 𝕜 F) →L[ℝ] ℝ) (x : F) : fr.extend_to_𝕜 x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl
5e2a8985a69e255ee6feebb520cf99a4d6ecb37e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/witt_vector/structure_polynomial.lean
6773d3916808df1f9af548f05ad651c66bac77a5
[ "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
18,392
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.matrix.notation import field_theory.mv_polynomial import field_theory.finite.polynomial import number_theory.basic import ring_theory.witt_vector.witt_polynomial /-! # Witt structure polynomials In this file we prove the main theorem that makes the whole theory of Witt vectors work. Briefly, consider a polynomial `Φ : mv_polynomial idx ℤ` over the integers, with polynomials variables indexed by an arbitrary type `idx`. Then there exists a unique family of polynomials `φ : ℕ → mv_polynomial (idx × ℕ) Φ` such that for all `n : ℕ` we have (`witt_structure_int_exists_unique`) ``` bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℤ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. N.b.: As far as we know, these polynomials do not have a name in the literature, so we have decided to call them the “Witt structure polynomials”. See `witt_structure_int`. ## Special cases With the main result of this file in place, we apply it to certain special polynomials. For example, by taking `Φ = X tt + X ff` resp. `Φ = X tt * X ff` we obtain families of polynomials `witt_add` resp. `witt_mul` (with type `ℕ → mv_polynomial (bool × ℕ) ℤ`) that will be used in later files to define the addition and multiplication on the ring of Witt vectors. ## Outline of the proof The proof of `witt_structure_int_exists_unique` is rather technical, and takes up most of this file. We start by proving the analogous version for polynomials with rational coefficients, instead of integer coefficients. In this case, the solution is rather easy, since the Witt polynomials form a faithful change of coordinates in the polynomial ring `mv_polynomial ℕ ℚ`. We therefore obtain a family of polynomials `witt_structure_rat Φ` for every `Φ : mv_polynomial idx ℚ`. If `Φ` has integer coefficients, then the polynomials `witt_structure_rat Φ n` do so as well. Proving this claim is the essential core of this file, and culminates in `map_witt_structure_int`, which proves that upon mapping the coefficients of `witt_structure_int Φ n` from the integers to the rationals, one obtains `witt_structure_rat Φ n`. Ultimately, the proof of `map_witt_structure_int` relies on ``` dvd_sub_pow_of_dvd_sub {R : Type*} [comm_ring R] {p : ℕ} {a b : R} : (p : R) ∣ a - b → ∀ (k : ℕ), (p : R) ^ (k + 1) ∣ a ^ p ^ k - b ^ p ^ k ``` ## Main results * `witt_structure_rat Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` associated with `Φ : mv_polynomial idx ℚ` and satisfying the property explained above. * `witt_structure_rat_prop`: the proof that `witt_structure_rat` indeed satisfies the property. * `witt_structure_int Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℤ` associated with `Φ : mv_polynomial idx ℤ` and satisfying the property explained above. * `map_witt_structure_int`: the proof that the integral polynomials `with_structure_int Φ` are equal to `witt_structure_rat Φ` when mapped to polynomials with rational coefficients. * `witt_structure_int_prop`: the proof that `witt_structure_int` indeed satisfies the property. * Five families of polynomials that will be used to define the ring structure on the ring of Witt vectors: - `witt_vector.witt_zero` - `witt_vector.witt_one` - `witt_vector.witt_add` - `witt_vector.witt_mul` - `witt_vector.witt_neg` (We also define `witt_vector.witt_sub`, and later we will prove that it describes subtraction, which is defined as `λ a b, a + -b`. See `witt_vector.sub_coeff` for this proof.) -/ open mv_polynomial open set open finset (range) open finsupp (single) -- This lemma reduces a bundled morphism to a "mere" function, -- and consequently the simplifier cannot use a lot of powerful simp-lemmas. -- We disable this locally, and probably it should be disabled globally in mathlib. local attribute [-simp] coe_eval₂_hom variables {p : ℕ} {R : Type*} {idx : Type*} [comm_ring R] open_locale witt open_locale big_operators section p_prime variables (p) [hp : fact p.prime] include hp /-- `witt_structure_rat Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that ``` bind₁ (witt_structure_rat p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_rat Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_rat_prop` for this property, and `witt_structure_rat_exists_unique` for the fact that `witt_structure_rat` gives the unique family of polynomials with this property. These polynomials turn out to have integral coefficients, but it requires some effort to show this. See `witt_structure_int` for the version with integral coefficients, and `map_witt_structure_int` for the fact that it is equal to `witt_structure_rat` when mapped to polynomials over the rationals. -/ noncomputable def witt_structure_rat (Φ : mv_polynomial idx ℚ) (n : ℕ) : mv_polynomial (idx × ℕ) ℚ := bind₁ (λ k, bind₁ (λ i, rename (prod.mk i) (W_ ℚ k)) Φ) (X_in_terms_of_W p ℚ n) theorem witt_structure_rat_prop (Φ : mv_polynomial idx ℚ) (n : ℕ) : bind₁ (witt_structure_rat p Φ) (W_ ℚ n) = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ := calc bind₁ (witt_structure_rat p Φ) (W_ ℚ n) = bind₁ (λ k, bind₁ (λ i, (rename (prod.mk i)) (W_ ℚ k)) Φ) (bind₁ (X_in_terms_of_W p ℚ) (W_ ℚ n)) : by { rw bind₁_bind₁, apply eval₂_hom_congr (ring_hom.ext_rat _ _) rfl rfl } ... = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ : by rw [bind₁_X_in_terms_of_W_witt_polynomial p _ n, bind₁_X_right] theorem witt_structure_rat_exists_unique (Φ : mv_polynomial idx ℚ) : ∃! (φ : ℕ → mv_polynomial (idx × ℕ) ℚ), ∀ (n : ℕ), bind₁ φ (W_ ℚ n) = bind₁ (λ i, (rename (prod.mk i) (W_ ℚ n))) Φ := begin refine ⟨witt_structure_rat p Φ, _, _⟩, { intro n, apply witt_structure_rat_prop }, { intros φ H, funext n, rw show φ n = bind₁ φ (bind₁ (W_ ℚ) (X_in_terms_of_W p ℚ n)), { rw [bind₁_witt_polynomial_X_in_terms_of_W p, bind₁_X_right] }, rw [bind₁_bind₁], exact eval₂_hom_congr (ring_hom.ext_rat _ _) (funext H) rfl }, end lemma witt_structure_rat_rec_aux (Φ : mv_polynomial idx ℚ) (n : ℕ) : witt_structure_rat p Φ n * C (p ^ n : ℚ) = bind₁ (λ b, rename (λ i, (b, i)) (W_ ℚ n)) Φ - ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p Φ i) ^ p ^ (n - i) := begin have := X_in_terms_of_W_aux p ℚ n, replace := congr_arg (bind₁ (λ k : ℕ, bind₁ (λ i, rename (prod.mk i) (W_ ℚ k)) Φ)) this, rw [alg_hom.map_mul, bind₁_C_right] at this, convert this, clear this, conv_rhs { simp only [alg_hom.map_sub, bind₁_X_right] }, rw sub_right_inj, simp only [alg_hom.map_sum, alg_hom.map_mul, bind₁_C_right, alg_hom.map_pow], refl end /-- Write `witt_structure_rat p φ n` in terms of `witt_structure_rat p φ i` for `i < n`. -/ lemma witt_structure_rat_rec (Φ : mv_polynomial idx ℚ) (n : ℕ) : (witt_structure_rat p Φ n) = C (1 / p ^ n : ℚ) * (bind₁ (λ b, (rename (λ i, (b, i)) (W_ ℚ n))) Φ - ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p Φ i) ^ p ^ (n - i)) := begin calc witt_structure_rat p Φ n = C (1 / p ^ n : ℚ) * (witt_structure_rat p Φ n * C (p ^ n : ℚ)) : _ ... = _ : by rw witt_structure_rat_rec_aux, rw [mul_left_comm, ← C_mul, div_mul_cancel, C_1, mul_one], exact pow_ne_zero _ (nat.cast_ne_zero.2 $ ne_of_gt (nat.prime.pos ‹_›)), end /-- `witt_structure_int Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that ``` bind₁ (witt_structure_int p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_int Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_int_prop` for this property, and `witt_structure_int_exists_unique` for the fact that `witt_structure_int` gives the unique family of polynomials with this property. -/ noncomputable def witt_structure_int (Φ : mv_polynomial idx ℤ) (n : ℕ) : mv_polynomial (idx × ℕ) ℤ := finsupp.map_range rat.num (rat.coe_int_num 0) (witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) n) variable {p} lemma bind₁_rename_expand_witt_polynomial (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ m : ℕ, m < (n + 1) → map (int.cast_ring_hom ℚ) (witt_structure_int p Φ m) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) m) : bind₁ (λ b, rename (λ i, (b, i)) (expand p (W_ ℤ n))) Φ = bind₁ (λ i, expand p (witt_structure_int p Φ i)) (W_ ℤ n) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_bind₁, map_rename, map_expand, rename_expand, map_witt_polynomial], have key := (witt_structure_rat_prop p (map (int.cast_ring_hom ℚ) Φ) n).symm, apply_fun expand p at key, simp only [expand_bind₁] at key, rw key, clear key, apply eval₂_hom_congr' rfl _ rfl, rintro i hi -, rw [witt_polynomial_vars, finset.mem_range] at hi, simp only [IH i hi], end lemma C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ m : ℕ, m < n → map (int.cast_ring_hom ℚ) (witt_structure_int p Φ m) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) m) : C ↑(p ^ n) ∣ (bind₁ (λ (b : idx), rename (λ i, (b, i)) (witt_polynomial p ℤ n)) Φ - ∑ i in range n, C (↑p ^ i) * witt_structure_int p Φ i ^ p ^ (n - i)) := begin cases n, { simp only [is_unit_one, int.coe_nat_zero, int.coe_nat_succ, zero_add, pow_zero, C_1, is_unit.dvd] }, -- prepare a useful equation for rewriting have key := bind₁_rename_expand_witt_polynomial Φ n IH, apply_fun (map (int.cast_ring_hom (zmod (p ^ (n + 1))))) at key, conv_lhs at key { simp only [map_bind₁, map_rename, map_expand, map_witt_polynomial] }, -- clean up and massage rw [nat.succ_eq_add_one, C_dvd_iff_zmod, ring_hom.map_sub, sub_eq_zero, map_bind₁], simp only [map_rename, map_witt_polynomial, witt_polynomial_zmod_self], rw key, clear key IH, rw [bind₁, aeval_witt_polynomial, ring_hom.map_sum, ring_hom.map_sum, finset.sum_congr rfl], intros k hk, rw finset.mem_range at hk, simp only [← sub_eq_zero, ← ring_hom.map_sub, ← C_dvd_iff_zmod, C_eq_coe_nat, ← mul_sub, ← int.nat_cast_eq_coe_nat, ← nat.cast_pow], rw show p ^ (n + 1) = p ^ k * p ^ (n - k + 1), { rw ← pow_add, congr' 1, omega }, rw [nat.cast_mul, nat.cast_pow, nat.cast_pow], apply mul_dvd_mul_left, rw show p ^ (n + 1 - k) = p * p ^ (n - k), { rw ← pow_succ, congr' 1, omega }, rw [pow_mul], -- the machine! apply dvd_sub_pow_of_dvd_sub, rw [← C_eq_coe_nat, int.nat_cast_eq_coe_nat, C_dvd_iff_zmod, ring_hom.map_sub, sub_eq_zero, map_expand, ring_hom.map_pow, mv_polynomial.expand_zmod], end variables (p) @[simp] lemma map_witt_structure_int (Φ : mv_polynomial idx ℤ) (n : ℕ) : map (int.cast_ring_hom ℚ) (witt_structure_int p Φ n) = witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) n := begin apply nat.strong_induction_on n, clear n, intros n IH, rw [witt_structure_int, map_map_range_eq_iff, int.coe_cast_ring_hom], intro c, rw [witt_structure_rat_rec, coeff_C_mul, mul_comm, mul_div_assoc', mul_one], have sum_induction_steps : map (int.cast_ring_hom ℚ) (∑ i in range n, C (p ^ i : ℤ) * (witt_structure_int p Φ i) ^ p ^ (n - i)) = ∑ i in range n, C (p ^ i : ℚ) * (witt_structure_rat p (map (int.cast_ring_hom ℚ) Φ) i) ^ p ^ (n - i), { rw [ring_hom.map_sum], apply finset.sum_congr rfl, intros i hi, rw finset.mem_range at hi, simp only [IH i hi, ring_hom.map_mul, ring_hom.map_pow, map_C], refl }, simp only [← sum_induction_steps, ← map_witt_polynomial p (int.cast_ring_hom ℚ), ← map_rename, ← map_bind₁, ← ring_hom.map_sub, coeff_map], rw show (p : ℚ)^n = ((p^n : ℕ) : ℤ), by norm_cast, rw [← rat.denom_eq_one_iff, ring_hom.eq_int_cast, rat.denom_div_cast_eq_one_iff], swap, { exact_mod_cast pow_ne_zero n hp.ne_zero }, revert c, rw [← C_dvd_iff_dvd_coeff], exact C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum Φ n IH, end variables (p) theorem witt_structure_int_prop (Φ : mv_polynomial idx ℤ) (n) : bind₁ (witt_structure_int p Φ) (witt_polynomial p ℤ n) = bind₁ (λ i, rename (prod.mk i) (W_ ℤ n)) Φ := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, have := witt_structure_rat_prop p (map (int.cast_ring_hom ℚ) Φ) n, simpa only [map_bind₁, ← eval₂_hom_map_hom, eval₂_hom_C_left, map_rename, map_witt_polynomial, alg_hom.coe_to_ring_hom, map_witt_structure_int], end lemma eq_witt_structure_int (Φ : mv_polynomial idx ℤ) (φ : ℕ → mv_polynomial (idx × ℕ) ℤ) (h : ∀ n, bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, rename (prod.mk i) (W_ ℤ n)) Φ) : φ = witt_structure_int p Φ := begin funext k, apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, rw map_witt_structure_int, refine congr_fun _ k, apply unique_of_exists_unique (witt_structure_rat_exists_unique p (map (int.cast_ring_hom ℚ) Φ)), { intro n, specialize h n, apply_fun map (int.cast_ring_hom ℚ) at h, simpa only [map_bind₁, ← eval₂_hom_map_hom, eval₂_hom_C_left, map_rename, map_witt_polynomial, alg_hom.coe_to_ring_hom] using h, }, { intro n, apply witt_structure_rat_prop } end theorem witt_structure_int_exists_unique (Φ : mv_polynomial idx ℤ) : ∃! (φ : ℕ → mv_polynomial (idx × ℕ) ℤ), ∀ (n : ℕ), bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i : idx, (rename (prod.mk i) (W_ ℤ n))) Φ := ⟨witt_structure_int p Φ, witt_structure_int_prop _ _, eq_witt_structure_int _ _⟩ theorem witt_structure_prop (Φ : mv_polynomial idx ℤ) (n) : aeval (λ i, map (int.cast_ring_hom R) (witt_structure_int p Φ i)) (witt_polynomial p ℤ n) = aeval (λ i, rename (prod.mk i) (W n)) Φ := begin convert congr_arg (map (int.cast_ring_hom R)) (witt_structure_int_prop p Φ n); rw hom_bind₁; apply eval₂_hom_congr (ring_hom.ext_int _ _) _ rfl, { refl }, { simp only [map_rename, map_witt_polynomial] } end lemma witt_structure_int_rename {σ : Type*} (Φ : mv_polynomial idx ℤ) (f : idx → σ) (n : ℕ) : witt_structure_int p (rename f Φ) n = rename (prod.map f id) (witt_structure_int p Φ n) := begin apply mv_polynomial.map_injective (int.cast_ring_hom ℚ) int.cast_injective, simp only [map_rename, map_witt_structure_int, witt_structure_rat, rename_bind₁, rename_rename, bind₁_rename], refl end @[simp] lemma constant_coeff_witt_structure_rat_zero (Φ : mv_polynomial idx ℚ) : constant_coeff (witt_structure_rat p Φ 0) = constant_coeff Φ := by simp only [witt_structure_rat, bind₁, map_aeval, X_in_terms_of_W_zero, constant_coeff_rename, constant_coeff_witt_polynomial, aeval_X, constant_coeff_comp_algebra_map, eval₂_hom_zero', ring_hom.id_apply] lemma constant_coeff_witt_structure_rat (Φ : mv_polynomial idx ℚ) (h : constant_coeff Φ = 0) (n : ℕ) : constant_coeff (witt_structure_rat p Φ n) = 0 := by simp only [witt_structure_rat, eval₂_hom_zero', h, bind₁, map_aeval, constant_coeff_rename, constant_coeff_witt_polynomial, constant_coeff_comp_algebra_map, ring_hom.id_apply, constant_coeff_X_in_terms_of_W] @[simp] lemma constant_coeff_witt_structure_int_zero (Φ : mv_polynomial idx ℤ) : constant_coeff (witt_structure_int p Φ 0) = constant_coeff Φ := begin have inj : function.injective (int.cast_ring_hom ℚ), { intros m n, exact int.cast_inj.mp, }, apply inj, rw [← constant_coeff_map, map_witt_structure_int, constant_coeff_witt_structure_rat_zero, constant_coeff_map], end lemma constant_coeff_witt_structure_int (Φ : mv_polynomial idx ℤ) (h : constant_coeff Φ = 0) (n : ℕ) : constant_coeff (witt_structure_int p Φ n) = 0 := begin have inj : function.injective (int.cast_ring_hom ℚ), { intros m n, exact int.cast_inj.mp, }, apply inj, rw [← constant_coeff_map, map_witt_structure_int, constant_coeff_witt_structure_rat, ring_hom.map_zero], rw [constant_coeff_map, h, ring_hom.map_zero], end variable (R) -- we could relax the fintype on `idx`, but then we need to cast from finset to set. -- for our applications `idx` is always finite. lemma witt_structure_rat_vars [fintype idx] (Φ : mv_polynomial idx ℚ) (n : ℕ) : (witt_structure_rat p Φ n).vars ⊆ finset.univ.product (finset.range (n + 1)) := begin rw witt_structure_rat, intros x hx, simp only [finset.mem_product, true_and, finset.mem_univ, finset.mem_range], obtain ⟨k, hk, hx'⟩ := mem_vars_bind₁ _ _ hx, obtain ⟨i, -, hx''⟩ := mem_vars_bind₁ _ _ hx', obtain ⟨j, hj, rfl⟩ := mem_vars_rename _ _ hx'', rw [witt_polynomial_vars, finset.mem_range] at hj, replace hk := X_in_terms_of_W_vars_subset p _ hk, rw finset.mem_range at hk, exact lt_of_lt_of_le hj hk, end -- we could relax the fintype on `idx`, but then we need to cast from finset to set. -- for our applications `idx` is always finite. lemma witt_structure_int_vars [fintype idx] (Φ : mv_polynomial idx ℤ) (n : ℕ) : (witt_structure_int p Φ n).vars ⊆ finset.univ.product (finset.range (n + 1)) := begin have : function.injective (int.cast_ring_hom ℚ) := int.cast_injective, rw [← vars_map_of_injective _ this, map_witt_structure_int], apply witt_structure_rat_vars, end end p_prime
d75abf4f61e04a09324e1cb573b53c74c115a895
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/subsemigroup/basic.lean
a454a84451711dd253b2ca8eb84a54525bcc8d7d
[ "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,714
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, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov, Yakov Pechersky -/ import data.set.lattice import data.set_like.basic /-! # Subsemigroups: definition and `complete_lattice` structure This file defines bundled multiplicative and additive subsemigroups. We also define a `complete_lattice` structure on `subsemigroup`s, and define the closure of a set as the minimal subsemigroup that includes this set. ## Main definitions * `subsemigroup M`: the type of bundled subsemigroup of a magma `M`; the underlying set is given in the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`. * `add_subsemigroup M` : the type of bundled subsemigroups of an additive magma `M`. For each of the following definitions in the `subsemigroup` namespace, there is a corresponding definition in the `add_subsemigroup` namespace. * `subsemigroup.copy` : copy of a subsemigroup with `carrier` replaced by a set that is equal but possibly not definitionally equal to the carrier of the original `subsemigroup`. * `subsemigroup.closure` : semigroup closure of a set, i.e., the least subsemigroup that includes the set. * `subsemigroup.gi` : `closure : set M → subsemigroup M` and coercion `coe : subsemigroup M → set M` form a `galois_insertion`; ## Implementation notes Subsemigroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subsemigroup's underlying set. Note that `subsemigroup M` does not actually require `semigroup M`, instead requiring only the weaker `has_mul M`. This file is designed to have very few dependencies. In particular, it should not use natural numbers. ## Tags subsemigroup, subsemigroups -/ variables {M : Type*} {N : Type*} variables {A : Type*} section non_assoc variables [has_mul M] {s : set M} variables [has_add A] {t : set A} /-- `mul_mem_class S M` says `S` is a type of subsets `s ≤ M` that are closed under `(*)` -/ class mul_mem_class (S : Type*) (M : out_param $ Type*) [has_mul M] [set_like S M] := (mul_mem : ∀ {s : S} {a b : M}, a ∈ s → b ∈ s → a * b ∈ s) export mul_mem_class (mul_mem) /-- `add_mem_class S M` says `S` is a type of subsets `s ≤ M` that are closed under `(+)` -/ class add_mem_class (S : Type*) (M : out_param $ Type*) [has_add M] [set_like S M] := (add_mem : ∀ {s : S} {a b : M}, a ∈ s → b ∈ s → a + b ∈ s) export add_mem_class (add_mem) attribute [to_additive] mul_mem_class /-- A subsemigroup of a magma `M` is a subset closed under multiplication. -/ structure subsemigroup (M : Type*) [has_mul M] := (carrier : set M) (mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) /-- An additive subsemigroup of an additive magma `M` is a subset closed under addition. -/ structure add_subsemigroup (M : Type*) [has_add M] := (carrier : set M) (add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier) attribute [to_additive add_subsemigroup] subsemigroup namespace subsemigroup @[to_additive] instance : set_like (subsemigroup M) M := ⟨subsemigroup.carrier, λ p q h, by cases p; cases q; congr'⟩ @[to_additive] instance : mul_mem_class (subsemigroup M) M := { mul_mem := subsemigroup.mul_mem' } /-- See Note [custom simps projection] -/ @[to_additive " See Note [custom simps projection]"] def simps.coe (S : subsemigroup M) : set M := S initialize_simps_projections subsemigroup (carrier → coe) initialize_simps_projections add_subsemigroup (carrier → coe) @[simp, to_additive] lemma mem_carrier {s : subsemigroup M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma mem_mk {s : set M} {x : M} (h_mul) : x ∈ mk s h_mul ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma coe_set_mk {s : set M} (h_mul) : (mk s h_mul : set M) = s := rfl @[simp, to_additive] lemma mk_le_mk {s t : set M} (h_mul) (h_mul') : mk s h_mul ≤ mk t h_mul' ↔ s ⊆ t := iff.rfl /-- Two subsemigroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subsemigroup`s are equal if they have the same elements."] theorem ext {S T : subsemigroup M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy a subsemigroup replacing `carrier` with a set that is equal to it. -/ @[to_additive "Copy an additive subsemigroup replacing `carrier` with a set that is equal to it."] protected def copy (S : subsemigroup M) (s : set M) (hs : s = S) : subsemigroup M := { carrier := s, mul_mem' := hs.symm ▸ S.mul_mem' } variable {S : subsemigroup M} @[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) : (S.copy s hs : set M) = s := rfl @[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S := set_like.coe_injective hs variable (S) /-- A subsemigroup is closed under multiplication. -/ @[to_additive "An `add_subsemigroup` is closed under addition."] protected theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := subsemigroup.mul_mem' S /-- The subsemigroup `M` of the magma `M`. -/ @[to_additive "The additive subsemigroup `M` of the magma `M`."] instance : has_top (subsemigroup M) := ⟨{ carrier := set.univ, mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩ /-- The trivial subsemigroup `∅` of a magma `M`. -/ @[to_additive "The trivial `add_subsemigroup` `∅` of an additive magma `M`."] instance : has_bot (subsemigroup M) := ⟨{ carrier := ∅, mul_mem' := λ a b, by simp }⟩ @[to_additive] instance : inhabited (subsemigroup M) := ⟨⊥⟩ @[to_additive] lemma not_mem_bot {x : M} : x ∉ (⊥ : subsemigroup M) := set.not_mem_empty x @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : subsemigroup M) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subsemigroup M) : set M) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subsemigroup M) : set M) = ∅ := rfl /-- The inf of two subsemigroups is their intersection. -/ @[to_additive "The inf of two `add_subsemigroup`s is their intersection."] instance : has_inf (subsemigroup M) := ⟨λ S₁ S₂, { carrier := S₁ ∩ S₂, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩ @[simp, to_additive] lemma coe_inf (p p' : subsemigroup M) : ((p ⊓ p' : subsemigroup M) : set M) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subsemigroup M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subsemigroup M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_Inter₂.1 hx i h) (by apply set.mem_Inter₂.1 hy i h) }⟩ @[simp, norm_cast, to_additive] lemma coe_Inf (S : set (subsemigroup M)) : ((Inf S : subsemigroup M) : set M) = ⋂ s ∈ S, ↑s := rfl @[to_additive] lemma mem_Inf {S : set (subsemigroup M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subsemigroup M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, norm_cast, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subsemigroup M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] /-- subsemigroups of a monoid form a complete lattice. -/ @[to_additive "The `add_subsemigroup`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (subsemigroup M) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x hx, (not_mem_bot hx).elim, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subsemigroup M) $ λ s, is_glb.of_image (λ S T, show (S : set M) ≤ T ↔ S ≤ T, from set_like.coe_subset_coe) is_glb_binfi } @[simp, to_additive] lemma subsingleton_of_subsingleton [subsingleton (subsemigroup M)] : subsingleton M := begin constructor; intros x y, have : ∀ a : M, a ∈ (⊥ : subsemigroup M), { simp [subsingleton.elim (⊥ : subsemigroup M) ⊤] }, exact absurd (this x) not_mem_bot end @[to_additive] instance [hn : nonempty M] : nontrivial (subsemigroup M) := ⟨⟨⊥, ⊤, λ h, by { obtain ⟨x⟩ := id hn, refine absurd (_ : x ∈ ⊥) not_mem_bot, simp [h] }⟩⟩ /-- The `subsemigroup` generated by a set. -/ @[to_additive "The `add_subsemigroup` generated by a set"] def closure (s : set M) : subsemigroup M := Inf {S | s ⊆ S} @[to_additive] lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : subsemigroup M, s ⊆ S → x ∈ S := mem_Inf /-- The subsemigroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subsemigroup` generated by a set includes the set."] lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx @[to_additive] lemma not_mem_of_not_mem_closure {P : M} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) variable {S} open set /-- A subsemigroup `S` includes `closure s` if and only if it includes `s`. -/ @[simp, to_additive "An additive subsemigroup `S` includes `closure s` if and only if it includes `s`"] lemma closure_le : closure s ≤ S ↔ s ⊆ S := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ /-- subsemigroup closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ @[to_additive "Additive subsemigroup closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`"] lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ subset.trans h subset_closure @[to_additive] lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S := le_antisymm (closure_le.2 h₁) h₂ variable (S) /-- An induction principle for closure membership. If `p` holds for all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator, to_additive "An induction principle for additive closure membership. If `p` holds for all elements of `s`, and is preserved under addition, then `p` holds for all elements of the additive closure of `s`."] lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, Hmul⟩).2 Hs h /-- A dependent version of `subsemigroup.closure_induction`. -/ @[elab_as_eliminator, to_additive "A dependent version of `add_subsemigroup.closure_induction`. "] lemma closure_induction' (s : set M) {p : Π x, x ∈ closure s → Prop} (Hs : ∀ x (h : x ∈ s), p x (subset_closure h)) (Hmul : ∀ x hx y hy, p x hx → p y hy → p (x * y) (mul_mem hx hy)) {x} (hx : x ∈ closure s) : p x hx := begin refine exists.elim _ (λ (hx : x ∈ closure s) (hc : p x hx), hc), exact closure_induction hx (λ x hx, ⟨_, Hs x hx⟩) (λ x y ⟨hx', hx⟩ ⟨hy', hy⟩, ⟨_, Hmul _ _ _ _ hx hy⟩), end /-- An induction principle for closure membership for predicates with two arguments. -/ @[elab_as_eliminator, to_additive "An induction principle for additive closure membership for predicates with two arguments."] lemma closure_induction₂ {p : M → M → Prop} {x} {y : M} (hx : x ∈ closure s) (hy : y ∈ closure s) (Hs : ∀ (x ∈ s) (y ∈ s), p x y) (Hmul_left : ∀ x y z, p x z → p y z → p (x * y) z) (Hmul_right : ∀ x y z, p z x → p z y → p z (x * y)) : p x y := closure_induction hx (λ x xs, closure_induction hy (Hs x xs) (λ z y h₁ h₂, Hmul_right z _ _ h₁ h₂)) (λ x z h₁ h₂, Hmul_left _ _ _ h₁ h₂) /-- If `s` is a dense set in a magma `M`, `subsemigroup.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, and verify that `p x` and `p y` imply `p (x * y)`. -/ @[elab_as_eliminator, to_additive "If `s` is a dense set in an additive monoid `M`, `add_subsemigroup.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, and verify that `p x` and `p y` imply `p (x + y)`."] lemma dense_induction {p : M → Prop} (x : M) {s : set M} (hs : closure s = ⊤) (Hs : ∀ x ∈ s, p x) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := have ∀ x ∈ closure s, p x, from λ x hx, closure_induction hx Hs Hmul, by simpa [hs] using this x variable (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure M _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {M} /-- Closure of a subsemigroup `S` equals `S`. -/ @[simp, to_additive "Additive closure of an additive subsemigroup `S` equals `S`"] lemma closure_eq : closure (S : set M) = S := (subsemigroup.gi M).l_u_eq S @[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ := (subsemigroup.gi M).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ := @coe_top M _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t := (subsemigroup.gi M).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subsemigroup.gi M).gc.l_supr @[simp, to_additive] lemma closure_singleton_le_iff_mem (m : M) (p : subsemigroup M) : closure {m} ≤ p ↔ m ∈ p := by rw [closure_le, singleton_subset_iff, set_like.mem_coe] @[to_additive] lemma mem_supr {ι : Sort*} (p : ι → subsemigroup M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← closure_singleton_le_iff_mem, le_supr_iff], simp only [closure_singleton_le_iff_mem], end @[to_additive] lemma supr_eq_closure {ι : Sort*} (p : ι → subsemigroup M) : (⨆ i, p i) = subsemigroup.closure (⋃ i, (p i : set M)) := by simp_rw [subsemigroup.closure_Union, subsemigroup.closure_eq] end subsemigroup namespace mul_hom variables [has_mul N] open subsemigroup /-- The subsemigroup of elements `x : M` such that `f x = g x` -/ @[to_additive "The additive subsemigroup of elements `x : M` such that `f x = g x`"] def eq_mlocus (f g : M →ₙ* N) : subsemigroup M := { carrier := {x | f x = g x}, mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] } /-- If two mul homomorphisms are equal on a set, then they are equal on its subsemigroup closure. -/ @[to_additive "If two add homomorphisms are equal on a set, then they are equal on its additive subsemigroup closure."] lemma eq_on_mclosure {f g : M →ₙ* N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_mlocus g, from closure_le.2 h @[to_additive] lemma eq_of_eq_on_mtop {f g : M →ₙ* N} (h : set.eq_on f g (⊤ : subsemigroup M)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →ₙ* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h end mul_hom end non_assoc section assoc namespace mul_hom open subsemigroup /-- Let `s` be a subset of a semigroup `M` such that the closure of `s` is the whole semigroup. Then `mul_hom.of_mdense` defines a mul homomorphism from `M` asking for a proof of `f (x * y) = f x * f y` only for `y ∈ s`. -/ @[to_additive] def of_mdense {M N} [semigroup M] [semigroup N] {s : set M} (f : M → N) (hs : closure s = ⊤) (hmul : ∀ x (y ∈ s), f (x * y) = f x * f y) : M →ₙ* N := { to_fun := f, map_mul' := λ x y, dense_induction y hs (λ y hy x, hmul x y hy) (λ y₁ y₂ h₁ h₂ x, by simp only [← mul_assoc, h₁, h₂]) x } /-- Let `s` be a subset of an additive semigroup `M` such that the closure of `s` is the whole semigroup. Then `add_hom.of_mdense` defines an additive homomorphism from `M` asking for a proof of `f (x + y) = f x + f y` only for `y ∈ s`. -/ add_decl_doc add_hom.of_mdense @[simp, norm_cast, to_additive] lemma coe_of_mdense [semigroup M] [semigroup N] {s : set M} (f : M → N) (hs : closure s = ⊤) (hmul) : (of_mdense f hs hmul : M → N) = f := rfl end mul_hom end assoc
157359d250c73fc1a02b4398569a52a8dd6f8ccd
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/list/perm.lean
712bdcac4d58b8007a5b100176cc1a3388d8616c
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,154
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.list.erase_dup import data.list.lattice import data.list.permutation import data.list.zip import logic.relation /-! # List Permutations This file introduces the `list.perm` relation, which is true if two lists are permutations of one another. ## Notation The notation `~` is used for permutation equivalence. -/ open_locale nat universes uu vv namespace list variables {α : Type uu} {β : Type vv} /-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations of each other. This is defined by induction using pairwise swaps. -/ inductive perm : list α → list α → Prop | nil : perm [] [] | cons : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ open perm (swap) infix ` ~ `:50 := perm @[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l | [] := perm.nil | (x::xs) := (perm.refl xs).cons x @[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p perm.nil (λ x l₁ l₂ p₁ r₁, r₁.cons x) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₂.trans r₁) theorem perm_comm {l₁ l₂ : list α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨perm.symm, perm.symm⟩ theorem perm.swap' (x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ := (swap _ _ _).trans ((p.cons _).cons _) attribute [trans] perm.trans theorem perm.eqv (α) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) instance is_setoid (α) : setoid (list α) := setoid.mk (@perm α) (perm.eqv α) theorem perm.subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ := λ a, perm.rec_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim i (λ ax, by simp [ax]) (λ al₁, or.inr (r₁ al₁))) (λ x y l ayxl, or.elim ayxl (λ ay, by simp [ay]) (λ axl, or.elim axl (λ ax, by simp [ax]) (λ al, or.inr (or.inr al)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem perm.mem_iff {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ := iff.intro (λ m, h.subset m) (λ m, h.symm.subset m) theorem perm.append_right {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ := perm.rec_on p (perm.refl ([] ++ t₁)) (λ x l₁ l₂ p₁ r₁, r₁.cons x) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₁.trans r₂) theorem perm.append_left {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂ | [] p := p | (x::xs) p := (perm.append_left xs p).cons x theorem perm.append {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ := (p₁.append_right t₁).trans (p₂.append_left l₂) theorem perm.append_cons (a : α) {h₁ h₂ t₁ t₂ : list α} (p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ := p₁.append (p₂.cons a) @[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂) | [] l₂ := perm.refl _ | (b::l₁) l₂ := ((@perm_middle l₁ l₂).cons _).trans (swap a b _) @[simp] theorem perm_append_singleton (a : α) (l : list α) : l ++ [a] ~ a::l := perm_middle.trans $ by rw [append_nil] theorem perm_append_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁) | [] l₂ := by simp | (a::t) l₂ := (perm_append_comm.cons _).trans perm_middle.symm theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l := by simp theorem perm.length_eq {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ := perm.rec_on p rfl (λ x l₁ l₂ p r, by simp[r]) (λ x y l, by simp) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem perm.eq_nil {l : list α} (p : l ~ []) : l = [] := eq_nil_of_length_eq_zero p.length_eq theorem perm.nil_eq {l : list α} (p : [] ~ l) : [] = l := p.symm.eq_nil.symm @[simp] theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] := ⟨λ p, p.eq_nil, λ e, e ▸ perm.refl _⟩ @[simp] theorem nil_perm {l₁ : list α} : [] ~ l₁ ↔ l₁ = [] := perm_comm.trans perm_nil theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l | p := by injection p.symm.eq_nil @[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l | [] := perm.nil | (a::l) := by { rw reverse_cons, exact (perm_append_singleton _ _).trans ((reverse_perm l).cons a) } theorem perm_cons_append_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) := (p.cons a).trans perm_middle.symm @[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : l ~ repeat a n ↔ l = repeat a n := ⟨λ p, (eq_repeat.2 ⟨p.length_eq.trans $ length_repeat _ _, λ b m, eq_of_mem_repeat $ p.subset m⟩), λ h, h ▸ perm.refl _⟩ @[simp] theorem repeat_perm {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l := (perm_comm.trans perm_repeat).trans eq_comm @[simp] theorem perm_singleton {a : α} {l : list α} : l ~ [a] ↔ l = [a] := @perm_repeat α a 1 l @[simp] theorem singleton_perm {a : α} {l : list α} : [a] ~ l ↔ [a] = l := @repeat_perm α a 1 l theorem perm.eq_singleton {a : α} {l : list α} (p : l ~ [a]) : l = [a] := perm_singleton.1 p theorem perm.singleton_eq {a : α} {l : list α} (p : [a] ~ l) : [a] = l := p.symm.eq_singleton.symm theorem singleton_perm_singleton {a b : α} : [a] ~ [b] ↔ a = b := by simp theorem perm_cons_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : l ~ a :: l.erase a := let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in e₂.symm ▸ e₁.symm ▸ perm_middle @[elab_as_eliminator] theorem perm_induction_on {P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l, from assume l, list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ @[congr] theorem perm.filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : filter_map f l₁ ~ filter_map f l₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp only [filter_map], cases f x with a; simp [filter_map, IH, perm.cons] }, { simp only [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] }, { exact IH₁.trans IH₂ } end @[congr] theorem perm.map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : map f l₁ ~ map f l₂ := filter_map_eq_map f ▸ p.filter_map _ theorem perm.pmap {p : α → Prop} (f : Π a, p a → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp [IH, perm.cons] }, { simp [swap] }, { refine IH₁.trans IH₂, exact λ a m, H₂ a (p₂.subset m) } end theorem perm.filter (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ := by rw ← filter_map_eq_filter; apply s.filter_map _ theorem exists_perm_sublist {l₁ l₂ l₂' : list α} (s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s, { exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ }, { cases s with _ _ _ s l₁ _ _ s, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ }, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', p'.cons x, s'.cons2 _ _ _⟩ } }, { cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s, { exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ }, { exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ }, { exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ }, { exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } }, { exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in ⟨r₁, pr.trans pm, sr⟩ } end theorem perm.sizeof_eq_sizeof [has_sizeof α] {l₁ l₂ : list α} (h : l₁ ~ l₂) : l₁.sizeof = l₂.sizeof := begin induction h with hd l₁ l₂ h₁₂ h_sz₁₂ a b l l₁ l₂ l₃ h₁₂ h₂₃ h_sz₁₂ h_sz₂₃, { refl }, { simp only [list.sizeof, h_sz₁₂] }, { simp only [list.sizeof, add_left_comm] }, { simp only [h_sz₁₂, h_sz₂₃] } end section rel open relator variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} local infixr ` ∘r ` : 80 := relation.comp lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm := begin funext a c, apply propext, split, { exact assume ⟨b, hab, hba⟩, perm.trans hab hba }, { exact assume h, ⟨a, perm.refl a, h⟩ } end lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v := begin induction hlu generalizing v, case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ }, case perm.cons : a l u hlu ih { cases huv with _ b _ v hab huv', rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩, exact ⟨b::l₂, forall₂.cons hab h₁₂, h₂₃.cons _⟩ }, case perm.swap : a₁ a₂ l₁ l₂ h₂₃ { cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃, cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂, exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩ }, case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ { rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩, rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩, exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩ } end lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r := begin funext l₁ l₃, apply propext, split, { assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩, have : forall₂ (flip r) l₂ l₁, from h₁₂.flip , rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩, exact ⟨l', h₂.symm, h₁.flip⟩ }, { exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ } end lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm := assume a b h₁ c d h₂ h, have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩, have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d, by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this, let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in have b' = b, from right_unique_forall₂' hr hcb hbc, this ▸ hbd lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm := assume a b hab c d hcd, iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp hr.left.flip hab.flip hcd.flip) end rel section subperm /-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects multiplicities of elements, and is used for the `≤` relation on multisets. -/ def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂ infix ` <+~ `:50 := subperm theorem nil_subperm {l : list α} : [] <+~ l := ⟨[], perm.nil, by simp⟩ theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ := suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂, from ⟨this p, this p.symm⟩, λ l₁ l₂ p ⟨u, pu, su⟩, let ⟨v, pv, sv⟩ := exists_perm_sublist su p in ⟨v, pv.trans pu, sv⟩ theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l := ⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩, λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩ theorem sublist.subperm {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ := ⟨l₁, perm.refl _, s⟩ theorem perm.subperm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ := ⟨l₂, p.symm, sublist.refl _⟩ @[refl] theorem subperm.refl (l : list α) : l <+~ l := (perm.refl _).subperm @[trans] theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃ | s ⟨l₂', p₂, s₂⟩ := let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩ theorem subperm.length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂ | ⟨l, p, s⟩ := p.length_eq ▸ length_le_of_sublist s theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂ | ⟨l, p, s⟩ h := suffices l = l₂, from this ▸ p.symm, eq_of_sublist_of_length_le s $ p.symm.length_eq ▸ h theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ := h₁.perm_of_length_le h₂.length_le theorem subperm.subset {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂ | ⟨l, p, s⟩ := subset.trans p.symm.subset s.subset lemma subperm.filter (p : α → Prop) [decidable_pred p] ⦃l l' : list α⦄ (h : l <+~ l') : filter p l <+~ filter p l' := begin obtain ⟨xs, hp, h⟩ := h, exact ⟨_, hp.filter p, h.filter p⟩ end end subperm theorem sublist.exists_perm_append : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l | ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩ | ._ ._ (sublist.cons l₁ l₂ a s) := let ⟨l, p⟩ := sublist.exists_perm_append s in ⟨a::l, (p.cons a).trans perm_middle.symm⟩ | ._ ._ (sublist.cons2 l₁ l₂ a s) := let ⟨l, p⟩ := sublist.exists_perm_append s in ⟨l, p.cons a⟩ theorem perm.countp_eq (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ := by rw [countp_eq_length_filter, countp_eq_length_filter]; exact (s.filter _).length_eq theorem subperm.countp_le (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂ | ⟨l, p', s⟩ := p'.countp_eq p ▸ countp_le_of_sublist p s theorem perm.count_eq [decidable_eq α] {l₁ l₂ : list α} (p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ := p.countp_eq _ theorem subperm.count_le [decidable_eq α] {l₁ l₂ : list α} (s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ := s.countp_le _ theorem perm.foldl_eq' {f : β → α → β} {l₁ l₂ : list α} (p : l₁ ~ l₂) : (∀ (x ∈ l₁) (y ∈ l₁) z, f (f z x) y = f (f z y) x) → ∀ b, foldl f b l₁ = foldl f b l₂ := perm_induction_on p (λ H b, rfl) (λ x t₁ t₂ p r H b, r (λ x hx y hy, H _ (or.inr hx) _ (or.inr hy)) _) (λ x y t₁ t₂ p r H b, begin simp only [foldl], rw [H x (or.inr $ or.inl rfl) y (or.inl rfl)], exact r (λ x hx y hy, H _ (or.inr $ or.inr hx) _ (or.inr $ or.inr hy)) _ end) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ H b, eq.trans (r₁ H b) (r₂ (λ x hx y hy, H _ (p₁.symm.subset hx) _ (p₁.symm.subset hy)) b)) theorem perm.foldl_eq {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) : ∀ b, foldl f b l₁ = foldl f b l₂ := p.foldl_eq' $ λ x hx y hy z, rcomm z x y theorem perm.foldr_eq {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) : ∀ b, foldr f b l₁ = foldr f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, by simp; rw [r b]) (λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b]) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) lemma perm.rec_heq {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α} (hl : perm l l') (f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b') (f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) : @list.rec α β b f l == @list.rec α β b f l' := begin induction hl, case list.perm.nil { refl }, case list.perm.cons : a l l' h ih { exact f_congr h ih }, case list.perm.swap : a a' l { exact f_swap }, case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ } end section variables {op : α → α → α} [is_associative α op] [is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l lemma perm.fold_op_eq {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a := h.foldl_eq (right_comm _ is_commutative.comm is_associative.assoc) _ end section comm_monoid /-- If elements of a list commute with each other, then their product does not depend on the order of elements-/ @[to_additive] lemma perm.prod_eq' [monoid α] {l₁ l₂ : list α} (h : l₁ ~ l₂) (hc : l₁.pairwise (λ x y, x * y = y * x)) : l₁.prod = l₂.prod := h.foldl_eq' (forall_of_forall_of_pairwise (λ x y h z, (h z).symm) (λ x hx z, rfl) $ hc.imp $ λ x y h z, by simp only [mul_assoc, h]) _ variable [comm_monoid α] @[to_additive] lemma perm.prod_eq {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ := h.fold_op_eq @[to_additive] lemma prod_reverse (l : list α) : prod l.reverse = prod l := (reverse_perm l).prod_eq end comm_monoid theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ := begin generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂, intro p, revert l₁ l₂ r₁ r₂ e₁ e₂, refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _) (λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂, { apply (not_mem_nil a).elim, rw ← e₁, simp }, { cases l₁ with y l₁; cases l₂ with z l₂; dsimp at e₁ e₂; injections; subst x, { substs t₁ t₂, exact p }, { substs z t₁ t₂, exact p.trans perm_middle }, { substs y t₁ t₂, exact perm_middle.symm.trans p }, { substs z t₁ t₂, exact (IH rfl rfl).cons y } }, { rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩; dsimp at e₁ e₂; injections; substs x y, { substs r₁ r₂, exact p.cons a }, { substs r₁ r₂, exact p.cons u }, { substs r₁ v t₂, exact (p.trans perm_middle).cons u }, { substs r₁ r₂, exact p.cons y }, { substs r₁ r₂ y u, exact p.cons a }, { substs r₁ u v t₂, exact ((p.trans perm_middle).cons y).trans (swap _ _ _) }, { substs r₂ z t₁, exact (perm_middle.symm.trans p).cons y }, { substs r₂ y z t₁, exact (swap _ _ _).trans ((perm_middle.symm.trans p).cons u) }, { substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } }, { substs t₁ t₃, have : a ∈ t₂ := p₁.subset (by simp), rcases mem_split this with ⟨l₂, r₂, e₂⟩, subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) } end theorem perm.cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := @perm_inv_core _ _ [] [] _ _ @[simp] theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ := ⟨perm.cons_inv, perm.cons a⟩ theorem perm_append_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂ | [] := iff.rfl | (a::l) := (perm_cons a).trans (perm_append_left_iff l) theorem perm_append_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ := ⟨λ p, (perm_append_left_iff _).1 $ perm_append_comm.trans $ p.trans perm_append_comm, perm.append_right _⟩ theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ := begin refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩, cases o₁ with a; cases o₂ with b, {refl}, { cases p.length_eq }, { cases p.length_eq }, { exact option.mem_to_list.1 (p.symm.subset $ by simp) } end theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ := ⟨λ ⟨l, p, s⟩, begin cases s with _ _ _ s' u _ _ s', { exact (p.subperm_left.2 $ (sublist_cons _ _).subperm).trans s'.subperm }, { exact ⟨u, p.cons_inv, s'⟩ } end, λ ⟨l, p, s⟩, ⟨a::l, p.cons a, s.cons2 _ _ _⟩⟩ theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂) (s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ := begin rcases s with ⟨l, p, s⟩, induction s generalizing l₁, case list.sublist.slnil { cases h₂ }, case list.sublist.cons : r₁ r₂ b s' ih { simp at h₂, cases h₂ with e m, { subst b, exact ⟨a::r₁, p.cons a, s'.cons2 _ _ _⟩ }, { rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } }, case list.sublist.cons2 : r₁ r₂ b s' ih { have bm : b ∈ l₁ := (p.subset $ mem_cons_self _ _), have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm), rcases mem_split bm with ⟨t₁, t₂, rfl⟩, have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp, rcases ih am (nodup_of_sublist st d₁) (mt (λ x, st.subset x) h₁) (perm.cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩, exact ⟨b::t, (p'.cons b).trans $ (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons2 _ _ _⟩ } end theorem subperm_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂ | [] := iff.rfl | (a::l) := (subperm_cons a).trans (subperm_append_left l) theorem subperm_append_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ := (perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l) theorem subperm.exists_of_length_lt {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂ | ⟨l, p, s⟩ h := suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from (this $ p.symm.length_eq ▸ h).imp (λ a, (p.cons a).subperm_right.1), begin clear subperm.exists_of_length_lt p h l₁, rename l₂ u, induction s with l₁ l₂ a s IH _ _ b s IH; intro h, { cases h }, { cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h, { exact (IH h).imp (λ a s, s.trans (sublist_cons _ _).subperm) }, { exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } }, { exact (IH $ nat.lt_of_succ_lt_succ h).imp (λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) } end theorem subperm_of_subset_nodup {l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ := begin induction d with a l₁' h d IH, { exact ⟨nil, perm.nil, nil_sublist _⟩ }, { cases forall_mem_cons.1 H with H₁ H₂, simp at h, exact cons_subperm_of_mem d h H₁ (IH H₂) } end theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) : l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ := ⟨λ p a, p.mem_iff, λ H, subperm.antisymm (subperm_of_subset_nodup d₁ (λ a, (H a).1)) (subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩ theorem nodup.sublist_ext {l₁ l₂ l : list α} (d : nodup l) (s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ := ⟨λ h, begin induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁, { exact h.eq_nil }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { exact IH d.2 s₁ h }, { apply d.1.elim, exact subperm.subset ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { apply d.1.elim, exact subperm.subset ⟨_, h, s₁⟩ (mem_cons_self _ _) }, { rw IH d.2 s₁ h.cons_inv } } end, λ h, by rw h⟩ section variable [decidable_eq α] -- attribute [congr] theorem perm.erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁.erase a ~ l₂.erase a := if h₁ : a ∈ l₁ then have h₂ : a ∈ l₂, from p.subset h₁, perm.cons_inv $ (perm_cons_erase h₁).symm.trans $ p.trans (perm_cons_erase h₂) else have h₂ : a ∉ l₂, from mt p.mem_iff.2 h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p theorem subperm_cons_erase (a : α) (l : list α) : l <+~ a :: l.erase a := begin by_cases h : a ∈ l, { exact (perm_cons_erase h).subperm }, { rw [erase_of_not_mem h], exact (sublist_cons _ _).subperm } end theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l := (erase_sublist _ _).subperm theorem subperm.erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a := let ⟨l, hp, hs⟩ := h in ⟨l.erase a, hp.erase _, hs.erase _⟩ theorem perm.diff_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, perm.erase] theorem perm.diff_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ := by induction h generalizing l; simp [*, perm.erase, erase_comm] <|> exact (ih_1 _).trans (ih_2 _) theorem perm.diff {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.diff t₁ ~ l₂.diff t₂ := ht.diff_left l₂ ▸ hl.diff_right _ theorem subperm.diff_right {l₁ l₂ : list α} (h : l₁ <+~ l₂) (t : list α) : l₁.diff t <+~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, subperm.erase] theorem erase_cons_subperm_cons_erase (a b : α) (l : list α) : (a :: l).erase b <+~ a :: l.erase b := begin by_cases h : a = b, { subst b, rw [erase_cons_head], apply subperm_cons_erase }, { rw [erase_cons_tail _ h] } end theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂ | l₁ [] := ⟨a::l₁, by simp⟩ | l₁ (b::l₂) := begin simp only [diff_cons], refine ((erase_cons_subperm_cons_erase a b l₁).diff_right l₂).trans _, apply subperm_cons_diff end theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ := subperm_cons_diff.subset theorem perm.bag_inter_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.bag_inter t ~ l₂.bag_inter t := begin induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp}, { by_cases x ∈ t; simp [*, perm.cons] }, { by_cases x = y, {simp [h]}, by_cases xt : x ∈ t; by_cases yt : y ∈ t, { simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] }, { simp [xt, yt, mt mem_of_mem_erase, perm.cons] }, { simp [xt, yt, mt mem_of_mem_erase, perm.cons] }, { simp [xt, yt] } }, { exact (ih_1 _).trans (ih_2 _) } end theorem perm.bag_inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l.bag_inter t₁ = l.bag_inter t₂ := begin induction l with a l IH generalizing t₁ t₂ p, {simp}, by_cases a ∈ t₁, { simp [h, p.subset h, IH (p.erase _)] }, { simp [h, mt p.mem_iff.2 h, IH p] } end theorem perm.bag_inter {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.bag_inter t₁ ~ l₂.bag_inter t₂ := ht.bag_inter_left l₂ ▸ hl.bag_inter_right _ theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a := ⟨λ h, have a ∈ l₂, from h.subset (mem_cons_self a l₁), ⟨this, (h.trans $ perm_cons_erase this).cons_inv⟩, λ ⟨m, h⟩, (h.cons a).trans (perm_cons_erase m).symm⟩ theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ := ⟨perm.count_eq, λ H, begin induction l₁ with a l₁ IH generalizing l₂, { cases l₂ with b l₂, {refl}, specialize H b, simp at H, contradiction }, { have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos), refine ((IH $ λ b, _).cons a).trans (perm_cons_erase this).symm, specialize H b, rw (perm_cons_erase this).count_eq at H, by_cases b = a; simp [h] at H ⊢; assumption } end⟩ lemma subperm.cons_right {α : Type*} {l l' : list α} (x : α) (h : l <+~ l') : l <+~ x :: l' := h.trans (sublist_cons x l').subperm /-- The list version of `add_tsub_cancel_of_le` for multisets. -/ lemma subperm_append_diff_self_of_count_le {l₁ l₂ : list α} (h : ∀ x ∈ l₁, count x l₁ ≤ count x l₂) : l₁ ++ l₂.diff l₁ ~ l₂ := begin induction l₁ with hd tl IH generalizing l₂, { simp }, { have : hd ∈ l₂, { rw ←count_pos, exact lt_of_lt_of_le (count_pos.mpr (mem_cons_self _ _)) (h hd (mem_cons_self _ _)) }, replace this : l₂ ~ hd :: l₂.erase hd := perm_cons_erase this, refine perm.trans _ this.symm, rw [cons_append, diff_cons, perm_cons], refine IH (λ x hx, _), specialize h x (mem_cons_of_mem _ hx), rw (perm_iff_count.mp this) at h, by_cases hx : x = hd, { subst hd, simpa [nat.succ_le_succ_iff] using h }, { simpa [hx] using h } }, end /-- The list version of `multiset.le_iff_count`. -/ lemma subperm_ext_iff {l₁ l₂ : list α} : l₁ <+~ l₂ ↔ ∀ x ∈ l₁, count x l₁ ≤ count x l₂ := begin refine ⟨λ h x hx, subperm.count_le h x, λ h, _⟩, suffices : l₁ <+~ (l₂.diff l₁ ++ l₁), { refine this.trans (perm.subperm _), exact perm_append_comm.trans (subperm_append_diff_self_of_count_le h) }, convert (subperm_append_right _).mpr nil_subperm using 1 end lemma subperm.cons_left {l₁ l₂ : list α} (h : l₁ <+~ l₂) (x : α) (hx : count x l₁ < count x l₂) : x :: l₁ <+~ l₂ := begin rw subperm_ext_iff at h ⊢, intros y hy, by_cases hy' : y = x, { subst x, simpa using nat.succ_le_of_lt hx }, { rw count_cons_of_ne hy', refine h y _, simpa [hy'] using hy } end instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) | [] [] := is_true $ perm.refl _ | [] (b::l₂) := is_false $ λ h, by have := h.nil_eq; contradiction | (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a); exact decidable_of_iff' _ cons_perm_iff_perm_erase -- @[congr] theorem perm.erase_dup {l₁ l₂ : list α} (p : l₁ ~ l₂) : erase_dup l₁ ~ erase_dup l₂ := perm_iff_count.2 $ λ a, if h : a ∈ l₁ then by simp [nodup_erase_dup, h, p.subset h] else by simp [h, mt p.mem_iff.2 h] -- attribute [congr] theorem perm.insert (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ := if h : a ∈ l₁ then by simpa [h, p.subset h] using p else by simpa [h, mt p.mem_iff.2 h] using p.cons a theorem perm_insert_swap (x y : α) (l : list α) : insert x (insert y l) ~ insert y (insert x l) := begin by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl], by_cases xy : x = y, { simp [xy] }, simp [not_mem_cons_of_ne_of_not_mem xy xl, not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl], constructor end theorem perm_insert_nth {α} (x : α) (l : list α) {n} (h : n ≤ l.length) : insert_nth n x l ~ x :: l := begin induction l generalizing n, { cases n, refl, cases h }, cases n, { simp [insert_nth] }, { simp only [insert_nth, modify_nth_tail], transitivity, { apply perm.cons, apply l_ih, apply nat.le_of_succ_le_succ h }, { apply perm.swap } } end theorem perm.union_right {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ := begin induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp}, { exact ih.insert a }, { apply perm_insert_swap }, { exact ih_1.trans ih_2 } end theorem perm.union_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ := by induction l; simp [*, perm.insert] -- @[congr] theorem perm.union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ := (p₁.union_right t₁).trans (p₂.union_left l₂) theorem perm.inter_right {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ := perm.filter _ theorem perm.inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ := by { dsimp [(∩), list.inter], congr, funext a, rw [p.mem_iff] } -- @[congr] theorem perm.inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ := p₂.inter_left l₂ ▸ p₁.inter_right t₁ theorem perm.inter_append {l t₁ t₂ : list α} (h : disjoint t₁ t₂) : l ∩ (t₁ ++ t₂) ~ l ∩ t₁ ++ l ∩ t₂ := begin induction l, case list.nil { simp }, case list.cons : x xs l_ih { by_cases h₁ : x ∈ t₁, { have h₂ : x ∉ t₂ := h h₁, simp * }, by_cases h₂ : x ∈ t₂, { simp only [*, inter_cons_of_not_mem, false_or, mem_append, inter_cons_of_mem, not_false_iff], transitivity, { apply perm.cons _ l_ih, }, change [x] ++ xs ∩ t₁ ++ xs ∩ t₂ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ t₂), rw [← list.append_assoc], solve_by_elim [perm.append_right, perm_append_comm] }, { simp * } }, end end theorem perm.pairwise_iff {R : α → α → Prop} (S : symmetric R) : ∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ := suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩, λ l₁ l₂ p d, begin induction d with a l₁ h d IH generalizing l₂, { rw ← p.nil_eq, constructor }, { have : a ∈ l₂ := p.subset (mem_cons_self _ _), rcases mem_split this with ⟨s₂, t₂, rfl⟩, have p' := (p.trans perm_middle).cons_inv, refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩), exact h _ (p'.symm.subset m) } end theorem perm.nodup_iff {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) := perm.pairwise_iff $ @ne.symm α theorem perm.bind_right {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) : l₁.bind f ~ l₂.bind f := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact IH.append_left _ }, { simp, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end theorem perm.bind_left (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) : l.bind f ~ l.bind g := by induction l with a l IH; simp; exact (h a).append IH theorem bind_append_perm (l : list α) (f g : α → list β) : l.bind f ++ l.bind g ~ l.bind (λ x, f x ++ g x) := begin induction l with a l IH; simp, refine (perm.trans _ (IH.append_left _)).append_left _, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ end theorem perm.product_right {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) : product l₁ t₁ ~ product l₂ t₁ := p.bind_right _ theorem perm.product_left (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) : product l t₁ ~ product l t₂ := perm.bind_left _ $ λ a, p.map _ @[congr] theorem perm.product {l₁ l₂ : list α} {t₁ t₂ : list β} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ := (p₁.product_right t₁).trans (p₂.product_left l₂) theorem sublists_cons_perm_append (a : α) (l : list α) : sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) := begin simp only [sublists, sublists_aux_cons_cons, cons_append, perm_cons], refine (perm.cons _ _).trans perm_middle.symm, induction sublists_aux l cons with b l IH; simp, exact (IH.cons _).trans perm_middle.symm end theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l | [] := perm.refl _ | (a::l) := let IH := sublists_perm_sublists' l in by rw sublists'_cons; exact (sublists_cons_perm_append _ _).trans (IH.append (IH.map _)) theorem revzip_sublists (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l := begin rw revzip, apply list.reverse_rec_on l, { intros l₁ l₂ h, simp at h, simp [h] }, { intros l a IH l₁ l₂ h, rw [sublists_concat, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [skip, {simp}], simp only [prod.mk.inj_iff, mem_map, mem_append, prod.map_mk, prod.exists] at h, rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { rw ← append_assoc, exact (IH _ _ h).append_right _ }, { rw append_assoc, apply (perm_append_comm.append_left _).trans, rw ← append_assoc, exact (IH _ _ h).append_right _ } } end theorem revzip_sublists' (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l := begin rw revzip, induction l with a l IH; intros l₁ l₂ h, { simp at h, simp [h] }, { rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [simp at h, simp], rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', h, rfl⟩, { exact perm_middle.trans ((IH _ _ h).cons _) }, { exact (IH _ _ h).cons _ } } end theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α} (H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁) (p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ := begin let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { cases h : f a, { simp [h], exact IH (pairwise_cons.1 H).2 }, { simp [lookmap_cons_some _ _ h, p] } }, { cases h₁ : f a with c; cases h₂ : f b with d, { simp [h₁, h₂], apply swap }, { simp [h₁, lookmap_cons_some _ _ h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂], rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩, refl } }, { refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)), exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm } end theorem perm.erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α} (H : pairwise (λ a b, f a → f b → false) l₁) (p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ := begin let F := λ a b, f a → f b → false, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { by_cases h : f a, { simp [h, p] }, { simp [h], exact IH (pairwise_cons.1 H).2 } }, { by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂], { cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ }, { apply swap } }, { refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)), exact λ a b h h₁ h₂, h h₂ h₁ } end lemma perm.take_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ) (h : xs ~ ys) (h' : ys.nodup) : xs.take n ~ ys.inter (xs.take n) := begin simp only [list.inter] at *, induction h generalizing n, case list.perm.nil : n { simp only [not_mem_nil, filter_false, take_nil] }, case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih n { cases n; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos, perm_cons, take, not_mem_nil, filter_false], cases h' with _ _ h₁ h₂, convert h_ih h₂ n using 1, apply filter_congr, introv h, simp only [(h₁ x h).symm, false_or], }, case list.perm.swap : h_x h_y h_l n { cases h' with _ _ h₁ h₂, cases h₂ with _ _ h₂ h₃, have := h₁ _ (or.inl rfl), cases n; simp only [mem_cons_iff, not_mem_nil, filter_false, take], cases n; simp only [mem_cons_iff, false_or, true_or, filter, *, nat.nat_zero_eq_zero, if_true, not_mem_nil, eq_self_iff_true, or_false, if_false, perm_cons, take], { rw filter_eq_nil.2, intros, solve_by_elim [ne.symm], }, { convert perm.swap _ _ _, rw @filter_congr _ _ (∈ take n h_l), { clear h₁, induction n generalizing h_l; simp only [not_mem_nil, filter_false, take], cases h_l; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos, true_and, take, not_mem_nil, filter_false, take_nil], cases h₃ with _ _ h₃ h₄, rwa [@filter_congr _ _ (∈ take n_n h_l_tl), n_ih], { introv h, apply h₂ _ (or.inr h), }, { introv h, simp only [(h₃ x h).symm, false_or], }, }, { introv h, simp only [(h₂ x h).symm, (h₁ x (or.inr h)).symm, false_or], } } }, case list.perm.trans : h_l₁ h_l₂ h_l₃ h₀ h₁ h_ih₀ h_ih₁ n { transitivity, { apply h_ih₀, rwa h₁.nodup_iff }, { apply perm.filter _ h₁, } }, end lemma perm.drop_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ) (h : xs ~ ys) (h' : ys.nodup) : xs.drop n ~ ys.inter (xs.drop n) := begin by_cases h'' : n ≤ xs.length, { let n' := xs.length - n, have h₀ : n = xs.length - n', { dsimp [n'], rwa tsub_tsub_cancel_of_le, } , have h₁ : n' ≤ xs.length, { apply tsub_le_self }, have h₂ : xs.drop n = (xs.reverse.take n').reverse, { rw [reverse_take _ h₁, h₀, reverse_reverse], }, rw [h₂], apply (reverse_perm _).trans, rw inter_reverse, apply perm.take_inter _ _ h', apply (reverse_perm _).trans; assumption, }, { have : drop n xs = [], { apply eq_nil_of_length_eq_zero, rw [length_drop, tsub_eq_zero_iff_le], apply le_of_not_ge h'' }, simp [this, list.inter], } end lemma perm.slice_inter {α} [decidable_eq α] {xs ys : list α} (n m : ℕ) (h : xs ~ ys) (h' : ys.nodup) : list.slice n m xs ~ ys ∩ (list.slice n m xs) := begin simp only [slice_eq], have : n ≤ n + m := nat.le_add_right _ _, have := h.nodup_iff.2 h', apply perm.trans _ (perm.inter_append _).symm; solve_by_elim [perm.append, perm.drop_inter, perm.take_inter, disjoint_take_drop, h, h'] { max_depth := 7 }, end /- enumerating permutations -/ section permutations theorem perm_of_mem_permutations_aux : ∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2 m, rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m, rcases m with m | ⟨l₁, l₂, m, _, e⟩, { exact (IH1 m).trans perm_middle }, { subst e, have p : l₁ ++ l₂ ~ is, { simp [permutations] at m, cases m with e m, {simp [e]}, exact is.append_nil ▸ IH2 m }, exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) } end theorem perm_of_mem_permutations {l₁ l₂ : list α} (h : l₁ ∈ permutations l₂) : l₁ ~ l₂ := (eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _) (λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m) theorem length_permutations_aux : ∀ ts is : list α, length (permutations_aux ts is) + is.length! = (length ts + length is)! := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2, have IH2 : length (permutations_aux is nil) + 1 = is.length!, { simpa using IH2 }, simp [-add_comm, nat.factorial, nat.add_succ, mul_comm] at IH1, rw [permutations_aux_cons, length_foldr_permutations_aux2' _ _ _ _ _ (λ l m, (perm_of_mem_permutations m).length_eq), permutations, length, length, IH2, nat.succ_add, nat.factorial_succ, mul_comm (nat.succ _), ← IH1, add_comm (_*_), add_assoc, nat.mul_succ, mul_comm] end theorem length_permutations (l : list α) : length (permutations l) = (length l)! := length_permutations_aux l [] theorem mem_permutations_of_perm_lemma {is l : list α} (H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is []) : l ~ is → l ∈ permutations is := by simpa [permutations, perm_nil] using H theorem mem_permutations_aux_of_perm : ∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2 l p, rw [permutations_aux_cons, mem_foldr_permutations_aux2], rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m, { clear p, subst e, rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩, subst is', have p := (perm_middle.symm.trans p').cons_inv, cases l₂ with a l₂', { exact or.inl ⟨l₁, by simpa using p⟩ }, { exact or.inr (or.inr ⟨l₁, a::l₂', mem_permutations_of_perm_lemma IH2 p, by simp⟩) } }, { exact or.inr (or.inl m) } end @[simp] theorem mem_permutations {s t : list α} : s ∈ permutations t ↔ s ~ t := ⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩ theorem perm_permutations'_aux_comm (a b : α) (l : list α) : (permutations'_aux a l).bind (permutations'_aux b) ~ (permutations'_aux b l).bind (permutations'_aux a) := begin induction l with c l ih, {simp [swap]}, simp [permutations'_aux], apply perm.swap', have : ∀ a b, (map (cons c) (permutations'_aux a l)).bind (permutations'_aux b) ~ map (cons b ∘ cons c) (permutations'_aux a l) ++ map (cons c) ((permutations'_aux a l).bind (permutations'_aux b)), { intros, simp only [map_bind, permutations'_aux], refine (bind_append_perm _ (λ x, [_]) _).symm.trans _, rw [← map_eq_bind, ← bind_map] }, refine (((this _ _).append_left _).trans _).trans ((this _ _).append_left _).symm, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append (ih.map _), end theorem perm.permutations' {s t : list α} (p : s ~ t) : permutations' s ~ permutations' t := begin induction p with a s t p IH a b l s t u p₁ p₂ IH₁ IH₂, {simp}, { simp only [permutations'], exact IH.bind_right _ }, { simp only [permutations'], rw [bind_assoc, bind_assoc], apply perm.bind_left, apply perm_permutations'_aux_comm }, { exact IH₁.trans IH₂ } end theorem permutations_perm_permutations' (ts : list α) : ts.permutations ~ ts.permutations' := begin obtain ⟨n, h⟩ : ∃ n, length ts < n := ⟨_, nat.lt_succ_self _⟩, induction n with n IH generalizing ts, {cases h}, refine list.reverse_rec_on ts (λ h, _) (λ ts t _ h, _) h, {simp [permutations]}, rw [← concat_eq_append, length_concat, nat.succ_lt_succ_iff] at h, have IH₂ := (IH ts.reverse (by rwa [length_reverse])).trans (reverse_perm _).permutations', simp only [permutations_append, foldr_permutations_aux2, permutations_aux_nil, permutations_aux_cons, append_nil], refine (perm_append_comm.trans ((IH₂.bind_right _).append ((IH _ h).map _))).trans (perm.trans _ perm_append_comm.permutations'), rw [map_eq_bind, singleton_append, permutations'], convert bind_append_perm _ _ _, funext ys, rw [permutations'_aux_eq_permutations_aux2, permutations_aux2_append] end @[simp] theorem mem_permutations' {s t : list α} : s ∈ permutations' t ↔ s ~ t := (permutations_perm_permutations' _).symm.mem_iff.trans mem_permutations theorem perm.permutations {s t : list α} (h : s ~ t) : permutations s ~ permutations t := (permutations_perm_permutations' _).trans $ h.permutations'.trans (permutations_perm_permutations' _).symm @[simp] theorem perm_permutations_iff {s t : list α} : permutations s ~ permutations t ↔ s ~ t := ⟨λ h, mem_permutations.1 $ h.mem_iff.1 $ mem_permutations.2 (perm.refl _), perm.permutations⟩ @[simp] theorem perm_permutations'_iff {s t : list α} : permutations' s ~ permutations' t ↔ s ~ t := ⟨λ h, mem_permutations'.1 $ h.mem_iff.1 $ mem_permutations'.2 (perm.refl _), perm.permutations'⟩ lemma nth_le_permutations'_aux (s : list α) (x : α) (n : ℕ) (hn : n < length (permutations'_aux x s)) : (permutations'_aux x s).nth_le n hn = s.insert_nth n x := begin induction s with y s IH generalizing n, { simp only [length, permutations'_aux, nat.lt_one_iff] at hn, simp [hn] }, { cases n, { simp }, { simpa using IH _ _ } } end lemma count_permutations'_aux_self [decidable_eq α] (l : list α) (x : α) : count (x :: l) (permutations'_aux x l) = length (take_while ((=) x) l) + 1 := begin induction l with y l IH generalizing x, { simp [take_while], }, { rw [permutations'_aux, count_cons_self], by_cases hx : x = y, { subst hx, simpa [take_while, nat.succ_inj'] using IH _ }, { rw take_while, rw if_neg hx, cases permutations'_aux x l with a as, { simp }, { rw [count_eq_zero_of_not_mem, length, zero_add], simp [hx, ne.symm hx] } } } end @[simp] lemma length_permutations'_aux (s : list α) (x : α) : length (permutations'_aux x s) = length s + 1 := begin induction s with y s IH, { simp }, { simpa using IH } end @[simp] lemma permutations'_aux_nth_le_zero (s : list α) (x : α) (hn : 0 < length (permutations'_aux x s) := by simp) : (permutations'_aux x s).nth_le 0 hn = x :: s := nth_le_permutations'_aux _ _ _ _ lemma injective_permutations'_aux (x : α) : function.injective (permutations'_aux x) := begin intros s t h, apply insert_nth_injective s.length x, have hl : s.length = t.length := by simpa using congr_arg length h, rw [←nth_le_permutations'_aux s x s.length (by simp), ←nth_le_permutations'_aux t x s.length (by simp [hl])], simp [h, hl] end lemma nodup_permutations'_aux_of_not_mem (s : list α) (x : α) (hx : x ∉ s) : nodup (permutations'_aux x s) := begin induction s with y s IH, { simp }, { simp only [not_or_distrib, mem_cons_iff] at hx, simp only [not_and, exists_eq_right_right, mem_map, permutations'_aux, nodup_cons], refine ⟨λ _, ne.symm hx.left, _⟩, rw nodup_map_iff, { exact IH hx.right }, { simp } } end lemma nodup_permutations'_aux_iff {s : list α} {x : α} : nodup (permutations'_aux x s) ↔ x ∉ s := begin refine ⟨λ h, _, nodup_permutations'_aux_of_not_mem _ _⟩, intro H, obtain ⟨k, hk, hk'⟩ := nth_le_of_mem H, rw nodup_iff_nth_le_inj at h, suffices : k = k + 1, { simpa using this }, refine h k (k + 1) _ _ _, { simpa [nat.lt_succ_iff] using hk.le }, { simpa using hk }, rw [nth_le_permutations'_aux, nth_le_permutations'_aux], have hl : length (insert_nth k x s) = length (insert_nth (k + 1) x s), { rw [length_insert_nth _ _ hk.le, length_insert_nth _ _ (nat.succ_le_of_lt hk)] }, refine ext_le hl (λ n hn hn', _), rcases lt_trichotomy n k with H|rfl|H, { rw [nth_le_insert_nth_of_lt _ _ _ _ H (H.trans hk), nth_le_insert_nth_of_lt _ _ _ _ (H.trans (nat.lt_succ_self _))] }, { rw [nth_le_insert_nth_self _ _ _ hk.le, nth_le_insert_nth_of_lt _ _ _ _ (nat.lt_succ_self _) hk, hk'] }, { rcases (nat.succ_le_of_lt H).eq_or_lt with rfl|H', { rw [nth_le_insert_nth_self _ _ _ (nat.succ_le_of_lt hk)], convert hk' using 1, convert nth_le_insert_nth_add_succ _ _ _ 0 _, simpa using hk }, { obtain ⟨m, rfl⟩ := nat.exists_eq_add_of_lt H', rw [length_insert_nth _ _ hk.le, nat.succ_lt_succ_iff, nat.succ_add] at hn, rw nth_le_insert_nth_add_succ, convert nth_le_insert_nth_add_succ s x k m.succ _ using 2, { simp [nat.add_succ, nat.succ_add] }, { simp [add_left_comm, add_comm] }, { simpa [nat.add_succ] using hn }, { simpa [nat.succ_add] using hn } } } end lemma nodup_permutations (s : list α) (hs : nodup s) : nodup s.permutations := begin rw (permutations_perm_permutations' s).nodup_iff, induction hs with x l h h' IH, { simp }, { rw [permutations'], rw nodup_bind, split, { intros ys hy, rw mem_permutations' at hy, rw [nodup_permutations'_aux_iff, hy.mem_iff], exact λ H, h x H rfl }, { refine IH.pairwise_of_forall_ne (λ as ha bs hb H, _), rw disjoint_iff_ne, rintro a ha' b hb' rfl, obtain ⟨n, hn, hn'⟩ := nth_le_of_mem ha', obtain ⟨m, hm, hm'⟩ := nth_le_of_mem hb', rw mem_permutations' at ha hb, have hl : as.length = bs.length := (ha.trans hb.symm).length_eq, simp only [nat.lt_succ_iff, length_permutations'_aux] at hn hm, rw nth_le_permutations'_aux at hn' hm', have hx : nth_le (insert_nth n x as) m (by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff, hl]) = x, { simp [hn', ←hm', hm] }, have hx' : nth_le (insert_nth m x bs) n (by rwa [length_insert_nth _ _ hm, nat.lt_succ_iff, ←hl]) = x, { simp [hm', ←hn', hn] }, rcases lt_trichotomy n m with ht|ht|ht, { suffices : x ∈ bs, { exact h x (hb.subset this) rfl }, rw [←hx', nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hm)], exact nth_le_mem _ _ _ }, { simp only [ht] at hm' hn', rw ←hm' at hn', exact H (insert_nth_injective _ _ hn') }, { suffices : x ∈ as, { exact h x (ha.subset this) rfl }, rw [←hx, nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hn)], exact nth_le_mem _ _ _ } } } end -- TODO: `nodup s.permutations ↔ nodup s` -- TODO: `count s s.permutations = (zip_with count s s.tails).prod` end permutations end list
ba003b6ce4ec251cd6f38d81a49676588955cc7a
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/topology/metric_space/antilipschitz.lean
0a720176cc78b850770e6a05ed5f95687a41855a
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
5,445
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.lipschitz /-! # Antilipschitz functions We say that a map `f : α → β` between two (extended) metric spaces is `antilipschitz_with K`, `K ≥ 0`, if for all `x, y` we have `edist x y ≤ K * edist (f x) (f y)`. For a metric space, the latter inequality is equivalent to `dist x y ≤ K * dist (f x) (f y)`. ## Implementation notes The parameter `K` has type `ℝ≥0`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ennreal`. We do not require `0 < K` in the definition, mostly because we do not have a `posreal` type. -/ variables {α : Type*} {β : Type*} {γ : Type*} open_locale nnreal open set /-- We say that `f : α → β` is `antilipschitz_with K` if for any two points `x`, `y` we have `K * edist x y ≤ edist (f x) (f y)`. -/ def antilipschitz_with [emetric_space α] [emetric_space β] (K : ℝ≥0) (f : α → β) := ∀ x y, edist x y ≤ K * edist (f x) (f y) lemma antilipschitz_with_iff_le_mul_dist [metric_space α] [metric_space β] {K : ℝ≥0} {f : α → β} : antilipschitz_with K f ↔ ∀ x y, dist x y ≤ K * dist (f x) (f y) := by { simp only [antilipschitz_with, edist_nndist, dist_nndist], norm_cast } alias antilipschitz_with_iff_le_mul_dist ↔ antilipschitz_with.le_mul_dist antilipschitz_with.of_le_mul_dist lemma antilipschitz_with.mul_le_dist [metric_space α] [metric_space β] {K : ℝ≥0} {f : α → β} (hf : antilipschitz_with K f) (x y : α) : ↑K⁻¹ * dist x y ≤ dist (f x) (f y) := begin by_cases hK : K = 0, by simp [hK, dist_nonneg], rw [nnreal.coe_inv, ← div_eq_inv_mul], rw div_le_iff' (nnreal.coe_pos.2 $ pos_iff_ne_zero.2 hK), exact hf.le_mul_dist x y end namespace antilipschitz_with variables [emetric_space α] [emetric_space β] [emetric_space γ] {K : ℝ≥0} {f : α → β} /-- Extract the constant from `hf : antilipschitz_with K f`. This is useful, e.g., if `K` is given by a long formula, and we want to reuse this value. -/ @[nolint unused_arguments] -- uses neither `f` nor `hf` protected def K (hf : antilipschitz_with K f) : ℝ≥0 := K protected lemma injective (hf : antilipschitz_with K f) : function.injective f := λ x y h, by simpa only [h, edist_self, mul_zero, edist_le_zero] using hf x y lemma mul_le_edist (hf : antilipschitz_with K f) (x y : α) : ↑K⁻¹ * edist x y ≤ edist (f x) (f y) := begin by_cases hK : K = 0, by simp [hK], rw [ennreal.coe_inv hK, mul_comm, ← ennreal.div_def], apply ennreal.div_le_of_le_mul, rw mul_comm, exact hf x y end protected lemma id : antilipschitz_with 1 (id : α → α) := λ x y, by simp only [ennreal.coe_one, one_mul, id, le_refl] lemma comp {Kg : ℝ≥0} {g : β → γ} (hg : antilipschitz_with Kg g) {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) : antilipschitz_with (Kf * Kg) (g ∘ f) := λ x y, calc edist x y ≤ Kf * edist (f x) (f y) : hf x y ... ≤ Kf * (Kg * edist (g (f x)) (g (f y))) : ennreal.mul_left_mono (hg _ _) ... = _ : by rw [ennreal.coe_mul, mul_assoc] lemma restrict (hf : antilipschitz_with K f) (s : set α) : antilipschitz_with K (s.restrict f) := λ x y, hf x y lemma cod_restrict (hf : antilipschitz_with K f) {s : set β} (hs : ∀ x, f x ∈ s) : antilipschitz_with K (s.cod_restrict f hs) := λ x y, hf x y lemma to_right_inv_on' {s : set α} (hf : antilipschitz_with K (s.restrict f)) {g : β → α} {t : set β} (g_maps : maps_to g t s) (g_inv : right_inv_on g f t) : lipschitz_with K (t.restrict g) := λ x y, by simpa only [restrict_apply, g_inv x.mem, g_inv y.mem, subtype.edist_eq, subtype.coe_mk] using hf ⟨g x, g_maps x.mem⟩ ⟨g y, g_maps y.mem⟩ lemma to_right_inv_on (hf : antilipschitz_with K f) {g : β → α} {t : set β} (h : right_inv_on g f t) : lipschitz_with K (t.restrict g) := (hf.restrict univ).to_right_inv_on' (maps_to_univ g t) h lemma to_right_inverse (hf : antilipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : lipschitz_with K g := begin intros x y, have := hf (g x) (g y), rwa [hg x, hg y] at this end lemma uniform_embedding (hf : antilipschitz_with K f) (hfc : uniform_continuous f) : uniform_embedding f := begin refine emetric.uniform_embedding_iff.2 ⟨hf.injective, hfc, λ δ δ0, _⟩, by_cases hK : K = 0, { refine ⟨1, ennreal.zero_lt_one, λ x y _, lt_of_le_of_lt _ δ0⟩, simpa only [hK, ennreal.coe_zero, zero_mul] using hf x y }, { refine ⟨K⁻¹ * δ, _, λ x y hxy, lt_of_le_of_lt (hf x y) _⟩, { exact canonically_ordered_semiring.mul_pos.2 ⟨ennreal.inv_pos.2 ennreal.coe_ne_top, δ0⟩ }, { rw [mul_comm, ← ennreal.div_def] at hxy, have := ennreal.mul_lt_of_lt_div hxy, rwa mul_comm } } end lemma subtype_coe (s : set α) : antilipschitz_with 1 (coe : s → α) := antilipschitz_with.id.restrict s lemma of_subsingleton [subsingleton α] {K : ℝ≥0} : antilipschitz_with K f := λ x y, by simp only [subsingleton.elim x y, edist_self, zero_le] end antilipschitz_with lemma lipschitz_with.to_right_inverse [emetric_space α] [emetric_space β] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) {g : β → α} (hg : function.right_inverse g f) : antilipschitz_with K g := λ x y, by simpa only [hg _] using hf (g x) (g y)
e8b4ed6d88f7965dcfee3a0312284f617a077699
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/module_info.lean
a06864f2ed24d7fc94c4b260fd810cb094a52f0a
[ "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
917
lean
open tactic #eval (module_info.resolve_module_name `data.dlist).backn 10 #eval (environment.from_imported_module_name `data.dlist).contains `dlist meta def dlist_mod_until_to_list_empty : tactic environment := do e ← get_env, pure $ e.import_until_decl (module_info.of_module_name `data.dlist) `dlist.to_list_empty -- last declaration before to_list_empty is included #eval flip environment.contains `dlist.of_list_to_list <$> dlist_mod_until_to_list_empty >>= trace -- but to_list_empty is not #eval flip environment.contains `dlist.to_list_empty <$> dlist_mod_until_to_list_empty >>= trace -- do not do this #eval by do e ← get_env, set_env_core $ e.import' (module_info.of_module_name `data.dlist), exact `("imported") #eval get_decl `dlist.to_list >>= trace ∘ declaration.type -- double imports will just fail #eval do e ← get_env, set_env_core $ e.import' (module_info.of_module_name `data.dlist)
4b532ed20396ee34aa691ed4b6085831939058d1
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/CheatSheet.lean
e8b4533dcdf97058e28e9f800b7dbe729161a72f
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
35,292
lean
/- This cheat sheet summarizes the crucial introduction and elimination reasoning rules for each connective and quantifier in predicate logic. * true * false * P ∧ Q * ∀ p : P, Q -- predicate Q usually involves p * P → Q (view as function type) * P → Q (viewed as implication) * ¬ P * P ↔ Q * P ∨ Q * ∃ p : P, Q -- predicate Q usually involves p Introduction rules are used when your goal is to prove a proposition (below the line or to the right of the turnstile) that contains a given connective or quantifier. For example, you would use the introduction rule for ∧ to prove a propopsition of the form, P ∧ Q. Elimination rules are used to prove something else when you are given, as an assumption, a proof of a proposition that uses a given connective or quantifier. You would use an elimination rule for ∧, for example to prove P when you already have a proof of P ∧ Q. -/ /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ variables P Q : Type #check (P → Q) /- **** -/ /- true -/ /- **** -/ /- The proposition, true, has a single proof and can thus always be judged to be true. The introduction rule gives us a proof without conditions. ---------------- (true.intro) true.intro: true Having a proof of true isn't very useful. One is always available, and no information can be obtained from a proof of true. We thus don't see a proof of true very often in practice. -/ /- ----------------- -/ /- true introduction -/ /- ----------------- -/ theorem trueIsTrue : true := true.intro theorem trueIsTrue' : true := begin exact (true.intro), end /- ----------------- -/ /- true elimination -/ /- ----------------- -/ /- A proof of true, true.intro, doesn't tell you anything meaningful, so a proof of true never really helps to prove anything else. A proof of true is both free and worthless. Elimination rules let you deduce something meaningful from a proof of something else. For example from a proof of P ∧ Q one can obtain a proof of P (which can be useful!). There is thus no meaningful elimination rule for true. -/ /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /-*******-/ /- false -/ /-*******-/ /- The proposition, false, has no proofs, and can thus be judged to be false. -/ /- false introduction -/ /- Because there is no proof of false, there is no introduction rule for false. -/ /- false elimination -/ /- On the other hand, it often happens in real proofs that one ends up with inconsistent assumptions. When this happens, it shows that in reality such a case can't occur. When one ends up in such a situation, a proof of false can be derived from the contradiction, and the elimination rule for false can then be used to finish off the proof of the current proof goal. It might seem a bit like magic that false elimination can be used to prove anything at all, but all that it really says is "we can safely ignore this case because it can never really happen." What the rule technically says is that from an assumed proof of false (or from a proof of false that is obtained from a contradiction), any proposition, P, can be proved by applying false.elim to the proof of false. P : Prop, f : false ------------------- false.elim pf : P -/ def fromFalse (P: Prop) (f: false) : P := false.elim f theorem fromFalse': ∀ P : Prop, false → P := λ P f, false.elim f theorem fromFalse'': ∀ P : Prop, false → P := begin assume P, assume f, show P, from false.elim f, end /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /-**** -/ /- and -/ /-**** -/ /- If P and Q are propositions, then P ∧ Q is a proposition. It is read as asserting that both P and Q are true. To prove P ∧ Q, one applies the introduction rule for ∧ to a proof of P and to a proof of Q. { P, Q : Prop } (p: P) (q: Q) ----------------------------- and.intro ⟨ p, q ⟩ : P ∧ Q From a proof of P and Q one can derive proofs of P and of Q by applying the left and right elimination rules, respectively. { P Q: Prop } (pq : P ∧ Q) --------------------------- and.elim_left p : P { P Q: Prop } (pq : P ∧ Q) --------------------------- and.elim_right q : Q -/ /- and introduction -/ def PandQ (P Q : Prop) (p: P) (q: Q) : P ∧ Q := and.intro p q #check PandQ -- P → Q → P ∧ Q theorem PandQ' : ∀ ( P Q : Prop ), P → Q → P ∧ Q := λ P Q p q, ⟨ p, q ⟩ -- shorthand for and.intro p q #check PandQ' theorem PandQ'' : ∀ { P Q : Prop }, P → Q → P ∧ Q := begin assume P Q p q, show P ∧ Q, from ⟨ p, q ⟩, -- again shorthand for and.intro p q end /- and elimination -/ def PfromPandQ (P Q: Prop) (pq: P ∧ Q) : P := and.elim_left pq def QfromPandQ (P Q: Prop) (pq: P ∧ Q) : Q := and.elim_right pq theorem PfromPandQ' : ∀ { P Q : Prop }, P ∧ Q → P := λ P Q pq, pq.left -- shorthand for and.elim_left pq theorem QfromPandQ' : ∀ { P Q : Prop }, P ∧ Q → Q := λ P Q pq, pq.right -- shorthand for and.elim_right pq theorem PfromPandQ'' : ∀ { P Q : Prop }, P ∧ Q → P := begin assume P Q pq, show P, from pq.left end theorem QfromPandQ'' : ∀ { P Q : Prop }, P ∧ Q → Q := begin assume P Q pq, show Q, from pq.right end /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /- ********* -/ /- functions -/ /- ********* -/ /- If P and Q are arbitrary types (examples of which include bool, nat, and string), then P → Q is the type of a total function that takes, as an argument, any value of type P, and that always then returns some value of type Q. The type judgment, f : P → Q, asserts that the identifier, f, will bound to a value of type, P → Q: that is to say, f is (bound to) some function that takes values of type P as arguments and that returns values of type Q as results. To "prove" (which means to provide a value of) type P → Q, you have to provide a lambda abstraction that defines some particular function from type P to type Q. -/ /- → introduction -/ /- To "prove" a function type, P → Q, you provide a lambda abstraction that defines a particular function value of this type. The particular lambda expressions selected as a proof is significant, as their are many functions values of most function types. For example, a function that takes a ℕ, n, and that returns n + 1, and a function that takes a ℕ, n and returns n * n, are both of type ℕ → ℕ, but in most cases would not be interchangeable in a program. So, when "proving" a function type, we're almost always very careful to pick a specific function definition of interest as a proof. -/ /- For example, we could exhibit a proof, inc, of ℕ → ℕ, which is to say that we could define a function, inc, that simply increments its argument, with the lambda abstraction, λ n, n + 1. This is the function that adds one to its argument, n, of type ℕ. Let's look at different ways this function can be defined in Lean. -/ /- First, we define inc to be a value of type ℕ → ℕ, namely the value, λ n : ℕ, n + 1. -/ def inc : ℕ → ℕ := λ n : ℕ, (n + 1 : ℕ) #check inc -- type: ℕ → ℕ #reduce inc -- value/proof: λ n : ℕ, n + 1 #check inc 3 #reduce inc 3 /- Typically we would drop explicit types in places where Lean can infer them. -/ def inc' : ℕ → ℕ := λ n, n + 1 /- We can also write such a function in a more Python-like style. -/ def inc'' (n : ℕ) : ℕ := n + 1 -- It really is the same function type and value #check inc'' #reduce inc'' /- Again we can often simplify code by leaving out explicit types -/ def inc''' (n : ℕ) := n + 1 /- We can confirm that the type of this function is still ℕ → ℕ. -/ #check inc''' /- You must be able to express function values using both Python-like expressions and lambda abstractions. -/ /- We note that we can even construct function values using tactic scripts. Knowing how to do this can be useful both in handling unexpected proof states, and might be useful for some who like to create functions in an imperative style. -/ def inc'''' (n : ℕ) : ℕ := begin exact n + 1 end def inc''''' : ℕ → ℕ := begin assume n, show ℕ, from n + 1 end -- these are all exactly the same function #reduce inc #reduce inc' #reduce inc''' #reduce inc'''' #reduce inc''''' /- multiple arguments -/ /- If P, Q, and R are types, then P → Q → R is also a type. Because → is right associative, this type can also be written as P → (Q → R). This is the type of functions that take values of type P as arguments and that return values of type (Q → R) as results. If we have a function, f, of type P → Q → R, we can apply it to a value p : P and get back some function of type Q → R. So the result of (f p) is a function of type Q → R. The function (f p) can thus be applied to an value, q, of type Q to obtain a result, r, of type R, with the expression (f p) q. Because function application is left associative the parenthesis can be dropped and you can just write f p q, giving the impression that f is a function that takes two arguments, one of type P and one of type Q (and that then returns a value of type R). Here's an example. -/ def plus (n m: ℕ) : ℕ := n + m #check plus #reduce plus #check plus 3 #reduce plus 3 -- a function taking one argument! #reduce (plus 3) 4 -- that function applied to 4 #reduce plus 3 4 -- the parentheses were redundant /- The following section addresses implication, where, if P and Q are propositions, P → Q, is the logical implication, if there is a proof of P then a proof of Q can be constructed. A proof of this proposition is given by any function of type P → Q. Everything in this section about function types and values/implementations (lambda expressions) applies to implications, so bear the lessons of this section in mind as you read the next one. -/ /- → elimination -/ /- The elimination rule for functions is easy. The application of a function, f : P → Q, to a value, p : P, will produce a value of type Q. -/ #check inc 3 #reduce inc 3 /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /- *********** -/ /- implication -/ /-************ -/ /- If P and Q are propositions, then P → Q is a proposition. It read as asserting that if P is true then Q is true. To prove P → Q, one must show that there is a (total) function that, when given a proof of P as an argument, constructs a proof of Q as a result. NB: Functions can be defined to take argument of types that have no value! See the false elimination examples above. It is very important to understand that P → Q being true does not necessarily mean that P is true, but only that *if* P is true (there is a proof of P) then Q is true (a proof of Q can be constructed). To prove P → Q, provide a function that shows that from an assumed proof of P one can construct a proof of Q. The type of such a function is P → Q. -/ -- implication introduction def falseImpliesTrue (f : false) : true := true.intro #check falseImpliesTrue example : false → true := λ f : false, true.intro example : false → true := falseImpliesTrue /- → implication elimination -/ /- From a proof of P → Q and a proof of P one can derive a proof of Q. This is done by "applying" the proof of the implication (which in Lean is a function) to the proof of P, the result of which is a proof of Q. (P Q : Prop) (p2q: P → Q) (p : P) --------------------------------- → elim (p2q p) : Q -/ def arrowElim {P Q : Prop} (p2q: P → Q) (p : P) : Q := p2q p theorem arrowElim': ∀ { P Q : Prop}, (P → Q) → P → Q := λ P Q p2q p, p2q p theorem arrowElim'': ∀ { P Q : Prop}, (P → Q) → P → Q := begin assume P Q p2q p, show Q, from p2q p end /- ********** -/ /- forall (∀) -/ /- ********** -/ /- If P is a type and Q is a predicate, then ∀ p : P, Q is a proposition. It is read as stating that the predicate, Q, is true for any value, p, in the set of values (domain of discourse) given by the type, P. The predicate, Q, is usually one that takes a value of type, P, as an argument, but this is not always the case. For example, one could write, ∀ n : ℕ, true. Here the predicate, true, is a predicate that takes no arguments at all, and so it is simply a proposition, and it is true for every value of n, so the proposition, ∀ n : ℕ, true, is true. More commonly, the predicate part of a universally quantified proposition will be "about" the values over which the quantification ranges. Here is an example: ∀ n : ℕ : (n > 2 ∧ prime n) → odd n This proposition asserts that any n greater than 2 and prime is also odd (which also happens to be true). The predicate, (n > 2 ∧ prime n) → odd n, in this case takes n as an argument, and is thus "about" each of the values over which the ∀ ranges. -/ /- ∀ introduction -/ /- To prove a proposition, ∀ p : P, Q, assume an arbitrary value, p : P, and shows that the predicate, Q, is true for that assumed value. As the value was chosen arbitrarily, it thus follows that the predicate is true for *any* such value, proving the ∀. To see this principle in action, study the following proof script. -/ theorem allNEqualSelf: ∀ n : ℕ, n = n := begin assume n, -- assume an arbitrary n show n = n, -- show predicate true for n from rfl, -- thus proving ∀ n, n = n end /- ∀ elimination -/ /- ∀ elimination reasons that if some predicate, Q, is true for every value of some type, then it must also be true for any particular value of that type. So from a proof, p2q, of ∀ P, Q and a proof, p : P, we conclude Q. P : Type, Q : P → Prop, p2q : ∀ p : P, Q, p : P ----------------------------------------------- (p2q p) : Q p Forall elimination is just another form of arrow elimination. In constructive logic this is function application. Study the following examples carefully to see how this works. -/ def forallElim (p2q: ∀ n : nat, n = n) (p : nat) : p = p := p2q p def forallElim' (p2q: ∀ n : nat, n = n) (p : nat) : p = p := begin exact (p2q p) end #reduce forallElim allNEqualSelf 7 /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /- ************** -/ /- ** Negation ** -/ /- ************** -/ /- If P is a proposition, then ¬ P is one, too. We read ¬ P as asserting that P is false. In constructive logic this means that there is no proof of P. In constructive logic, ¬ P is thus actually defined as P → false. So ¬ P means P → false, and a proof of ¬ P is just a proof of P → false. To prove ¬ P, one thus assumes a proof of P and shows that, in that context, one can construct a proof of false. That is, one exhibits a function that takes a proof of P as an argument and constructs and returns a proof of false as a result. This is the introduction rule for ¬. Another way to say this: To prove ¬ P, assume P and show that this leads to a contradiction. This is of course just the principle of proof by negation, equivalent to the introduction rule for false. P: Prop, f2p : P → false ------------------------ false introduction np : ¬ P We discuss the elimination rule for ¬ below. The key idea is that it's really a rule for double negation elimination, and it requires classical reasoning. More on this later. -/ -- negation introduction /- That Lean accepts the following function definition shows that a proof of P → false *is* a proof of ¬ P -/ def notIntro (P : Prop) (p2f: P → false) : ¬P := p2f /- An equivalent proof script. -/ theorem notIntro': ∀ P : Prop, (P → false) → ¬P := begin assume P : Prop, assume p2f : P → false, show ¬P, from p2f end /- Example: from the assumption that a proposition, P, is true, we can deduce that ¬ ¬ P is true, as well. This is a rule for double negation introduction, though not a rule that is commonly needed. -/ theorem doubleNegIntro : ∀ P : Prop, P → ¬¬P := begin assume P : Prop, assume p : P, assume np : ¬P, -- ¬¬P means ¬P → false, so assume ¬P show false, --from np p, contradiction, end theorem doubleNegIntro' : ∀ P : Prop, P → ¬¬P := λ P p np, np p /- negation elimination -/ /- The rule for negation elimination in natural deduction is really a rule for double negation elimination: it states that, ∀ P : Prop, ¬ (¬ P) → P. Because ¬ is right associative, we can drop the parenthesis: ¬ ¬ P → P. This rule is not valid in constructive logic. You can't prove the following unless you also accept the axiom of the excluded middle, or equivalent. -/ example: ∀ P : Prop, ¬¬P → P := begin assume P nnp, /- No way to get from ¬¬P to P. stuck and giving up on this proof. -/ end /- However, if we accept the axiom of the excluded middle, which we can do by "opening" Lean's "classical" module, then we can prove that double negation elimination is valid. -/ open classical #check em /- Now em is the axiom of the excluded middle. What em tells us is that if P is any proposition, then either one of P or ¬ P is true, and there are no other possibilities. And from em we can now prove double negation elimination. The proof is by "case analysis." We consider each of the two possible cases for P (true and false) in turn. If we assume P is true, then we are done, as our goal is to show P (from ¬ ¬ P). On the other hand, if we assume P is false, i.e., ¬ P, then we reach a contradiction. We have already assumed ¬ ¬ P is true and we are trying to prove P. But now if we also assume that ¬ P is true, then clearly we have a contradiction (between ¬ P and ¬ ¬ P). Using false elimination finishes this case leaving us with the conclusion that P is true in either case. -/ theorem doubleNegationElim: ∀(P : Prop), ¬¬P → P := begin assume P nnp, show P, from begin -- preview: we study case analysis later -- proof by case analysis for P cases (em P) with pf_P pf_nP, -- (em P) is (P ∨ ¬ P) -- case with P is assumed to be true exact pf_P, -- case with P is assumed to be false exact false.elim (nnp pf_nP) -- em says there are no other cases end, end /- Double negation elimination is the fundamental operation needed in a proof by contradiction. In a proof by contradiction, on tries to prove P by assuming ¬ P and showing that that leads to a contradiction, thus to a proof that ¬ P is not true, that is, ¬ (¬ P). The negation elimination rule lets us then conclude P. -/ /- Note: The law of the excluded middle allows you to conclude P ∨ ¬ P "for free," without giving a proof of either P or of ¬ P. It is in this precise sense that em is not "constructive." When using em, you do not build a "bigger" proof (of P ∨ ¬ P) from one or more "smaller" proofs (of P or of ¬ P). Whereas constructive proofs are "informative," in that they contain the smaller proofs needed to justify a given conclusion, classical proofs are not, in general. Accepting that P ∨ ¬ P by using em gives you a proof but such a proof does not tell you anything at all about which case is true, whereas a constructive proof does. -/ /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /- *************** -/ /- bi-implication -/ /- *************** -/ /- If P and Q are propositions then so is P ↔ Q. We read P ↔ Q as asserting P → Q ∧ Q → P. To prove P ↔ Q, we have to provide proofs of both conjunctions, and from a proof of P ↔ Q we can obtain proofs of P → Q and of Q → P by use of the elimination rule for ↔. The ↔ symbol is pronounced as is equivalent to," or as "if and only if," In mathematical writing it is often written as "iff". And to get the ↔ symbol in Lean, use backslash-iff. Its introduction and elimination rules are equivalent to those for conjunction, but specialized to the case where each of the conjuncts is an implication and where one is the other going in the other direction. -/ /- iff introduction -/ /- To prove P ↔ Q (introduction), apply iff.intro to proofs of P and Q. (P Q : Prop), (pq : P → Q) (qp : Q → P) --------------------------------------- iff.intro pqEquiv: P ↔ Q -/ theorem iffIntro: ∀(P Q: Prop), (P → Q) → (Q → P) → (P ↔ Q) := begin assume P Q : Prop, assume p2q q2p, apply iff.intro p2q q2p end theorem iffIntro': ∀(P Q : Prop), (P → Q) → (Q → P) → (P ↔ Q) := λ P Q pq qp, iff.intro pq qp theorem iffIntro'': ∀(P Q: Prop), (P → Q) → (Q → P) → (P ↔ Q) := begin assume P Q : Prop, assume p2q q2p, apply iff.intro, exact p2q, exact q2p end /- iff elimination -/ /- Similarly, the left and right iff elimination rules are equivalent to the and elimination rules but for the special case where the conjunction is a bi-implication in particular. -/ theorem iffElimLeft: ∀(P Q : Prop), (P ↔ Q) → P → Q := begin assume P Q : Prop, assume bi : P ↔ Q, show P → Q, from iff.elim_left bi -- bi.1 is a shorthand end theorem iffElimLeft': ∀(P Q : Prop), (P ↔ Q) → P → Q := λ P Q bi, iff.elim_left bi theorem iffElimRight: ∀(P Q : Prop), (P ↔ Q) → Q → P := λ P Q bi, iff.elim_right bi /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /- **************** -/ /- or (disjunction) -/ /- **************** -/ /- If P and Q are propositions, then so is P ∨ Q. P ∨ Q asserts that at least one of P, Q is true, but it does not indicate which case holds. -/ /- introduction rules for or -/ /- To prove P ∨ Q, in constructive logic one either applies the or.intro_left rule to a proof of P or the or.intro_right rule to a proof of Q. In either case, one must also provide, as the first argument, the proposition that is not being proved. The shorthand or.inl and or.inr rules infer these propositional arguments and are easier and clearer to use in practice. -/ theorem orIntroLeft (P Q : Prop) (p : P) : P ∨ Q := or.intro_left Q p -- args: proposition Q, proof of P theorem orIntroLeft': forall P Q: Prop, P → (P ∨ Q) := λ P Q p, or.inl p -- shorthand theorem orIntroLeft'' (P Q : Prop) (p : P) : P ∨ Q := begin apply or.intro_left, assumption end theorem orIntroRight: forall P Q: Prop, Q → (P ∨ Q) := λ P Q q, or.inr q /- or elimination -/ /- The elimination rule for or says that if (1) P ∨ Q is true, (2) P → R, and (3) Q → R, then you can conclude R. The reasoning in by "case analysis." In one case, if P ∨ Q because P is, then use P → R to prove R. Otherwise, if P ∨ Q is true because Q is, then use Q → R to prove R. Usually you don't know which case holds so to prove R from P ∨ Q you have to show that R follows "in either case", and to do that, you need both P → R and Q → R. pfPQ: P ∨ Q, pfPR: P → R, pfQR: Q → R -------------------------------------- or.elim R So, for example if (1) "it's raining or the fire hydrant is running" (P ∨ Q), (2)"if it's raining then the streets are wet", and (3) "if the fire hydrant is running then the streets are wet", then the streets are wet! -/ theorem orElim : ∀(P Q R: Prop), (P ∨ Q) → (P → R) → (Q → R) → R := begin assume P Q R, assume PorQ: (P ∨ Q), assume pr: (P → R), assume qr: (Q → R), show R, from or.elim PorQ pr qr end theorem orElim' : ∀(P Q R: Prop), (P ∨ Q) → (P → R) → (Q → R) → R := begin assume P Q R, assume PorQ: (P ∨ Q), assume pr: (P → R), assume qr: (Q → R), show R, from -- compare carefully with previous example begin cases PorQ with p q, exact (pr p), exact (qr q) end end -- Same proof, different identifiers theorem orElimExample' : forall Rain Hydrant Wet: Prop, (Rain ∨ Hydrant) → -- raining or hydrant on; (Rain → Wet) → -- if raining then wet; (Hydrant → Wet) → -- if hydrant on then wet; Wet -- then wet := begin -- setup assume Rain Hydrant Wet, assume RainingOrHydrantRunning: (Rain ∨ Hydrant), assume RainMakesWet: (Rain → Wet), assume HydrantMakesWet: (Hydrant → Wet), -- the core of the proof cases RainingOrHydrantRunning with raining running, show Wet, from RainMakesWet raining, show Wet, from HydrantMakesWet running, end /- Note: The axiom of the excluded middle allows us to do case analysis even if we don't have an explicit disjunction to work with, because we can always apply em to any proposition P to get a proof of P ∨ ¬ P. Here's an example. (There is a more direct proof, but we're showing how to apply em to a proposition to get a disjunction to do case analysis on. -/ open classical example : ∀(P : Prop), P ∨ ¬ P := begin assume P : Prop, cases (em P) with p np, --(em P) is a proof of P ∨ ¬ P exact or.inl p, -- case where P assumed true exact or.inr np, -- case where ¬ P assumed true end example : ∀(P : Prop), P ∨ ¬ P := begin assume P : Prop, apply em P end /- Go back and without fail see where this trick was used to prove one of the DeMorgan laws and the validity of double negation elimination. -/ /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /- ********** -/ /- Predicates -/ /- ********** -/ /- A predicate is a proposition with parameters whose values need to be supplied to reduce the predicate to a proposition. For example, even (n : ℕ) : Prop, could be a predicate that takes a value, n : ℕ, and that reduces to a proposition that in general will assert something about the particular n that was supplied as an argument. So, even 3, for example would reduce to the proposition that we would interpret as "three is even", while "even 7" would be (reduce to) a proposition that 7 is even. We formalize predicates as functions that take arguments and that return propositions about those arguments. If this is unclear, re-read the preceding paragraph. A predicate thus generates a whole family of propositions, one for each combination of values of its arguments. The "even n" predicate, for example, gives rise to a whole family of propositions, one for each ℕ value of n. Note that you can think of a predicate with no parameters as just a proposition. A predicate with one parameter can be read as defining a "property" of the values of its argument type. A sensibly defined even n predicate, for example, will generate a proposition that is true for every even natural number and that is false for every odd natural number. Such a predicate can also be understood to define a set, namely the set of all values for which the corresponding propositions are true. A predicate with multiple parameters can be read as defining a property of, and thus a set of, ordered pairs (for two arguments) or more generally tuples of arguments. We call a set of pairs (or tuples) a relation. As an example, a predicate "lessThan m n" could be defined to reduce to a proposition that is true whenever m is less than n and that is false otherwise. This predicate implicitly "picks out" the set of (m, n) pairs where m is less than n and excludes all pairs where m is not less than n. The pair (3, 4) is in the lessThan relation in that the proposition, lessThan 3 4, would be true, while (4, 3) would not be in the relation, in that "lessThan 4 3" would not be a true/provable proposition. We formalize predicates as functions from argument values to propositions. Here are some examples. -/ /- First, we define zEqz as a predicate with no arguments. That is to say, it is just a plain old proposition. No more need be said. -/ def zEqz : Prop := 0 = 0 /- Next, we generalize by making one of the zero values into a parameter. The predicate, when provided with a value for n, reduces to the proposition that that zero is equal to that particular n. -/ def nEqz (n : ℕ) : Prop := 0 = n /- Note that we could have written this definition using a lambda abstraction. A benefit is that this way of writing the same thing makes the nature of zEqz'clear by expressing its type explicitly: ℕ → Prop. -/ def nEqz' : ℕ → Prop := λ n, 0 = n /- The only value of n that satisfies this predicate, in the sense that it makes the corresponding proposition true, is n = 0. This predicate thus implicitly represents the set, { 0 }. -/ /- We can further generalize this predicate by making both values to be compared into arguments. -/ def nEqm (n m: ℕ) : Prop := n = m def isSquare (n m : ℕ) := n^2 = m #check isSquare #check isSquare 3 9 #reduce isSquare 3 9 /- *****************************************-/ /- *****************************************-/ /- *****************************************-/ /- ******* -/ /- Exists -/ /- ******* -/ /- If P is a type and Q is a predicate, then ∃ p : P, Q is a proposition. It asserts that there is some value, p : P, that makes the predicate, Q, true. -/ /- ∃ introduction -/ /- To prove a proposition of the form, ∃ p : P, Q, one must provide two things: (1) a specific value, w : P, that we often call a "witness", and a proof that Q is true for that specific w. So, for example, to prove that there exists an object, o, that is a cat, it would suffice to exhibit some object (the witness), let's call it Nifty, and a proof, pf, of the proposition, Nifty is a cat. Then the pair, ⟨ nifty, pf ⟩ would be a proof of ∃ o: Object, Cat o. The proposition, ∃ o: Object, Cat o, does not refer to Nifty or any other object in particular. It just asserts that *some* object out there is a cat. To prove it, though, you do need to exhibit a specific object and give a proof that that object is a cat. You can then conclude that there is some object that is a cat. Here's the exists.intro rule, after which we give some very simple examples of how it would be used in code. (T : Type), (P : T → Prop), (t : T), (pf: P t) ---------------------------------------------- exists.intro ⟨ t, pf ⟩ : exists t : T, P t -/ #check exists.intro theorem existsIntro : ∀(T : Type), -- suppose T is a type ∀(P : T → Prop), -- suppose P is a property of values of type T /- now if for any t : T, we can show that t has property P, then we can construct a proof that *there exists* an x : T with property P -/ ∀(t : T), (P t) → ∃ x : T, P x := begin assume T: Type, -- assume T is some type assume P: T → Prop, -- and P is a property -- show that if there's a t with property P (P t), the ∃ is true show ∀ (t : T), P t → (∃ (x : T), P x), from begin assume t : T, -- assume t is some object of type T assume pf : P t, -- and that t has property P show ∃ x, P x, from -- now we can show ∃ x, P x (exists.intro t pf) -- using exists.intro -- ⟨ t, pf ⟩ would be a shorthand for (exists.intro t pf) end, end /- existential elimination -/ /- The reasoning about existential elimination goes like this. If we know that (∃ x : T, P x), that there is some value, x of type T with property P, then we can temporarily assume that there is some specific value, that we will call it by an otherwise unused name, u, where u has property P, which is to say that we also have a proof of (P u). If the meaning of "a proof of (P u)" doesn't make sense, go back and review the class material on predicates. P is a predicate, i.e., a function from T to Prop, u is the name we've given to some value of type T with property P such that u has property P, which is to say there is a proof of the proposition, (P u). Now, if from u and a proof of (P u) we can construct a proof of some proposition S (a proposition that does not involve u in any way), then we can conclude that S follows from the mere existence of such a u, i.e., from the truth of ∃ x : T, P x. Here is slightly simplified version of the exists.elim rule. {T : Type}, {P : T → Prop}, {Q : Prop}, (ex: ∃ x : T, P x) (p2q: ∀ t : T, P t → Q) ---------------------------------------------------------------------------------- ∃.intro q : Q Let's unpack this. The assumptions are that T is any type and P is any property of values of that type. Q is the proposition that we want to prove follows from ∃ x : T, P x. The additional fact that is needed to conclude that Q is true is a proof, p2q, f that if any t : T has property P, then Q follows. If we combine this fact, p2q, with the fact, ex, that there exists such a t, then we can conclude that Q must be true. -/ #check exists.elim /- Here's some code that illustrates the use of the exists.elim principle in Lean. -/ def existElimExample (T : Type) -- Suppose T is any type (P S : T → Prop) -- and P, S are properties of T (ex : exists x, P x ∧ S x) -- and there is an x with P and S : (exists y, S y ∧ P y) -- show there is a y with P := begin /- The only thing we have to work with is ex. So we will apply exists.elim to it. We supply the first argument, namely the proof of exists x, P x ∧ Q x-/ apply exists.elim ex, /- What we then have to provide is the proof required as the second argument to exists.elim. This is a proof of the proposition that that for any object, a : T, if a has properties P and S, then (∃ (y : T), S y ∧ P y) is true. We will now prove this proposition to finish off the proof. What we have to prove is an implication, so we will start by assuming its premises: that a is some value of type T and that we have a proof that a has the properties P and S. -/ assume w : T, assume pfa : P w ∧ S w, /- Given these assumption we now need to show the final conclusion, that (∃ (y : T), S y ∧ P y). This is a job for exists.intro. The arguments we will give it are, a, as a witness, and a proof of (S a ∧ P a) as a proof. That is then all that we need to prove the final goal, (∃ (y : T), S y ∧ P y), using exists.intro. -/ show (∃ (y : T), S y ∧ P y), from begin have pa := pfa.left, have qa := pfa.right, have qp := and.intro qa pa, exact exists.intro w qp, end, end
5c6ad94dc813f7346a81e92ebb46082d5f36a2aa
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/monoidal/functorial.lean
c182d200fb38bd986a1b49fe77f5ea6c7bb2e0d9
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,673
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.monoidal.functor import category_theory.functorial /-! # Unbundled lax monoidal functors ## Design considerations The essential problem I've encountered that requires unbundled functors is having an existing (non-monoidal) functor `F : C ⥤ D` between monoidal categories, and wanting to assert that it has an extension to a lax monoidal functor. The two options seem to be 1. Construct a separate `F' : lax_monoidal_functor C D`, and assert `F'.to_functor ≅ F`. 2. Introduce unbundled functors and unbundled lax monoidal functors, and construct `lax_monoidal F.obj`, then construct `F' := lax_monoidal_functor.of F.obj`. Both have costs, but as for option 2. the cost is in library design, while in option 1. the cost is users having to carry around additional isomorphisms forever, I wanted to introduce unbundled functors. TODO: later, we may want to do this for strong monoidal functors as well, but the immediate application, for enriched categories, only requires this notion. -/ open category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory.category open category_theory.functor namespace category_theory open monoidal_category variables {C : Type u₁} [category.{v₁} C] [monoidal_category.{v₁} C] {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D] /-- An unbundled description of lax monoidal functors. -/ -- Perhaps in the future we'll redefine `lax_monoidal_functor` in terms of this, -- but that isn't the immediate plan. class lax_monoidal (F : C → D) [functorial.{v₁ v₂} F] := -- unit morphism (ε [] : 𝟙_ D ⟶ F (𝟙_ C)) -- tensorator (μ [] : Π X Y : C, (F X) ⊗ (F Y) ⟶ F (X ⊗ Y)) (μ_natural' : ∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), ((map F f) ⊗ (map F g)) ≫ μ Y Y' = μ X X' ≫ map F (f ⊗ g) . obviously) -- associativity of the tensorator (associativity' : ∀ (X Y Z : C), (μ X Y ⊗ 𝟙 (F Z)) ≫ μ (X ⊗ Y) Z ≫ map F (α_ X Y Z).hom = (α_ (F X) (F Y) (F Z)).hom ≫ (𝟙 (F X) ⊗ μ Y Z) ≫ μ X (Y ⊗ Z) . obviously) -- unitality (left_unitality' : ∀ X : C, (λ_ (F X)).hom = (ε ⊗ 𝟙 (F X)) ≫ μ (𝟙_ C) X ≫ map F (λ_ X).hom . obviously) (right_unitality' : ∀ X : C, (ρ_ (F X)).hom = (𝟙 (F X) ⊗ ε) ≫ μ X (𝟙_ C) ≫ map F (ρ_ X).hom . obviously) restate_axiom lax_monoidal.μ_natural' attribute [simp] lax_monoidal.μ_natural restate_axiom lax_monoidal.left_unitality' restate_axiom lax_monoidal.right_unitality' -- The unitality axioms cannot be used as simp lemmas because they require -- higher-order matching to figure out the `F` and `X` from `F X`. restate_axiom lax_monoidal.associativity' attribute [simp] lax_monoidal.associativity namespace lax_monoidal_functor /-- Construct a bundled `lax_monoidal_functor` from the object level function and `functorial` and `lax_monoidal` typeclasses. -/ @[simps] def of (F : C → D) [I₁ : functorial.{v₁ v₂} F] [I₂ : lax_monoidal.{v₁ v₂} F] : lax_monoidal_functor.{v₁ v₂} C D := { obj := F, ..I₁, ..I₂ } end lax_monoidal_functor instance (F : lax_monoidal_functor.{v₁ v₂} C D) : lax_monoidal.{v₁ v₂} (F.obj) := { .. F } section instance lax_monoidal_id : lax_monoidal.{v₁ v₁} (id : C → C) := { ε := 𝟙 _, μ := λ X Y, 𝟙 _ } end -- TODO instances for composition, as required -- TODO `strong_monoidal`, as well as `lax_monoidal` end category_theory
ae6c3d129b7f353531ee84469957d6b336c0b467
bdb33f8b7ea65f7705fc342a178508e2722eb851
/order/complete_boolean_algebra.lean
31062c8d5e2f4015255e2963fe8a8b1a92798f51
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
2,508
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Theory of complete Boolean algebras. -/ import order.complete_lattice order.boolean_algebra data.set.basic set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} namespace lattice /-- A complete distributive lattice is a bit stronger than the name might suggest; perhaps completely distributive lattice is more descriptive, as this class includes a requirement that the lattice join distribute over *arbitrary* infima, and similarly for the dual. -/ class complete_distrib_lattice α extends complete_lattice α := (infi_sup_le_sup_Inf : ∀a s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s) (inf_Sup_le_supr_inf : ∀a s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b)) section complete_distrib_lattice variables [complete_distrib_lattice α] {a : α} {s : set α} theorem sup_Inf_eq : a ⊔ Inf s = (⨅ b ∈ s, a ⊔ b) := le_antisymm (le_infi $ assume i, le_infi $ assume h, sup_le_sup (le_refl _) (Inf_le h)) (complete_distrib_lattice.infi_sup_le_sup_Inf _ _) theorem inf_Sup_eq : a ⊓ Sup s = (⨆ b ∈ s, a ⊓ b) := le_antisymm (complete_distrib_lattice.inf_Sup_le_supr_inf _ _) (supr_le $ assume i, supr_le $ assume h, inf_le_inf (le_refl _) (le_Sup h)) end complete_distrib_lattice instance [d : complete_distrib_lattice α] : bounded_distrib_lattice α := { le_sup_inf := assume x y z, calc (x ⊔ y) ⊓ (x ⊔ z) ≤ (⨅ b ∈ ({z, y} : set α), x ⊔ b) : by rw insert_of_has_insert; finish ... = x ⊔ Inf {z, y} : sup_Inf_eq.symm ... = x ⊔ y ⊓ z : by rw insert_of_has_insert; simp, ..d } /-- A complete boolean algebra is a completely distributive boolean algebra. -/ class complete_boolean_algebra α extends boolean_algebra α, complete_distrib_lattice α section complete_boolean_algebra variables [complete_boolean_algebra α] {a b : α} {s : set α} {f : ι → α} theorem neg_infi : - infi f = (⨆i, - f i) := le_antisymm (neg_le_of_neg_le $ le_infi $ assume i, neg_le_of_neg_le $ le_supr (λi, - f i) i) (supr_le $ assume i, neg_le_neg $ infi_le _ _) theorem neg_supr : - supr f = (⨅i, - f i) := neg_eq_neg_of_eq (by simp [neg_infi]) theorem neg_Inf : - Inf s = (⨆i∈s, - i) := by simp [Inf_eq_infi, neg_infi] theorem neg_Sup : - Sup s = (⨅i∈s, - i) := by simp [Sup_eq_supr, neg_supr] end complete_boolean_algebra end lattice
b9b8d4389147c3489ba5165a9ce2e4a709149798
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Tactic/Cache.lean
aab59784639026b098d2701517fb71e8c64c447e
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
3,695
lean
/- Copyright (c) 2021 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import Lean /-! # Once-per-file cache for tactics This file defines cache data structures for tactics that are initialized the first time they are accessed. Since Lean 4 starts one process per file, these caches are once-per-file and can for example be used to cache information about the imported modules. The `Cache α` data structure is the most generic version we define. It is created using `Cache.mk f` where `f : MetaM α` performs the initialization of the cache: ``` initialize numberOfImports : Cache Nat ← Cache.mk do (← getEnv).imports.size -- (does not work in the same module where the cache is defined) #eval show MetaM Nat from numberOfImports.get ``` The `DeclCache α` data structure computes a fold over the environment's constants: `DeclCache.mk empty f` constructs such a cache where `empty : α` and `f : Name → ConstantInfo → α → MetaM α`. The result of the constants in the imports is cached between tactic invocations, while for constants defined in the same file `f` is evaluated again every time. This kind of cache can be used e.g. to populate discrimination trees. -/ open Lean Meta namespace Tactic /-- Once-per-file cache. -/ def Cache (α : Type) := IO.Ref <| Sum (MetaM α) <| Task <| Except Exception α instance : Inhabited (Cache α) := inferInstanceAs <| Inhabited (IO.Ref _) /-- Creates a cache with an initialization function. -/ def Cache.mk (init : MetaM α) : IO (Cache α) := IO.mkRef <| Sum.inl init /-- Access the cache. Calling this function for the first time will initialize the cache with the function provided in the constructor. -/ def Cache.get [Monad m] [MonadEnv m] [MonadOptions m] [MonadLiftT BaseIO m] [MonadExcept Exception m] (cache : Cache α) : m α := do let t ← match ← show BaseIO _ from ST.Ref.get cache with | Sum.inr t => t | Sum.inl init => let env ← getEnv let options ← getOptions -- TODO: sanitize options? let res ← EIO.asTask do let metaCtx : Meta.Context := {} let metaState : Meta.State := {} let coreCtx : Core.Context := {options} let coreState : Core.State := {env} (← ((init ‹_›).run ‹_› ‹_›).run ‹_›).1.1 show BaseIO _ from cache.set (Sum.inr res) pure res match t.get with | Except.ok res => pure res | Except.error err => throw err /-- Cached fold over the environment's declarations, where a given function is applied to `α` for every constant. -/ def DeclCache (α : Type) := Cache α × (Name → ConstantInfo → α → MetaM α) instance : Inhabited (DeclCache α) := inferInstanceAs <| Inhabited (_ × _) /-- Creates a `DeclCache`. The cached structure `α` is initialized with `empty`, and then `addDecl` is called for every constant in the environment. Calls to `addDecl` for imported constants are cached. -/ def DeclCache.mk (profilingName : String) (empty : α) (addDecl : Name → ConstantInfo → α → MetaM α) : IO (DeclCache α) := do let cache ← Cache.mk do profileitM Exception profilingName (← getOptions) do let mut a ← empty for (n, c) in (← getEnv).constants.map₁.toList do a ← addDecl n c a return a (cache, addDecl) /-- Access the cache. Calling this function for the first time will initialize the cache with the function provided in the constructor. -/ def DeclCache.get (cache : DeclCache α) : MetaM α := do let mut a ← cache.1.get for (n, c) in (← getEnv).constants.map₂.toList do a ← cache.2 n c a return a
1c747443a9ec86c930b420b2d950d7385186e83b
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/analysis/complex/conformal.lean
d3630cadc39c917bf23948d965b677102259c5b8
[ "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
4,859
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.complex.isometry import analysis.normed_space.conformal_linear_map /-! # Conformal maps between complex vector spaces We prove the sufficient and necessary conditions for a real-linear map between complex vector spaces to be conformal. ## Main results * `is_conformal_map_complex_linear`: a nonzero complex linear map into an arbitrary complex normed space is conformal. * `is_conformal_map_complex_linear_conj`: the composition of a nonzero complex linear map with `conj` is complex linear. * `is_conformal_map_iff_is_complex_or_conj_linear`: a real linear map between the complex plane is conformal iff it's complex linear or the composition of some complex linear map and `conj`. ## Warning Antiholomorphic functions such as the complex conjugate are considered as conformal functions in this file. -/ noncomputable theory open complex continuous_linear_map lemma is_conformal_map_conj : is_conformal_map (conj_lie : ℂ →L[ℝ] ℂ) := conj_lie.to_linear_isometry.is_conformal_map section conformal_into_complex_normed variables {E : Type*} [normed_group E] [normed_space ℝ E] [normed_space ℂ E] [is_scalar_tower ℝ ℂ E] {z : ℂ} {g : ℂ →L[ℝ] E} {f : ℂ → E} lemma is_conformal_map_complex_linear {map : ℂ →L[ℂ] E} (nonzero : map ≠ 0) : is_conformal_map (map.restrict_scalars ℝ) := begin have minor₁ : ∥map 1∥ ≠ 0, { simpa [ext_ring_iff] using nonzero }, refine ⟨∥map 1∥, minor₁, ⟨∥map 1∥⁻¹ • map, _⟩, _⟩, { intros x, simp only [linear_map.smul_apply], have : x = x • 1 := by rw [smul_eq_mul, mul_one], nth_rewrite 0 [this], rw [_root_.coe_coe map, linear_map.coe_coe_is_scalar_tower], simp only [map.coe_coe, map.map_smul, norm_smul, normed_field.norm_inv, norm_norm], field_simp [minor₁], }, { ext1, rw [← linear_isometry.coe_to_linear_map], simp [minor₁], }, end lemma is_conformal_map_complex_linear_conj {map : ℂ →L[ℂ] E} (nonzero : map ≠ 0) : is_conformal_map ((map.restrict_scalars ℝ).comp (conj_cle : ℂ →L[ℝ] ℂ)) := (is_conformal_map_complex_linear nonzero).comp is_conformal_map_conj end conformal_into_complex_normed section conformal_into_complex_plane open continuous_linear_map variables {f : ℂ → ℂ} {z : ℂ} {g : ℂ →L[ℝ] ℂ} lemma is_conformal_map.is_complex_or_conj_linear (h : is_conformal_map g) : (∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g) ∨ (∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g ∘L ↑conj_cle) := begin rcases h with ⟨c, hc, li, hg⟩, rcases linear_isometry_complex (li.to_linear_isometry_equiv rfl) with ⟨a, ha⟩, let rot := c • (a : ℂ) • continuous_linear_map.id ℂ ℂ, cases ha, { refine or.intro_left _ ⟨rot, _⟩, ext1, simp only [coe_restrict_scalars', hg, ← li.coe_to_linear_isometry_equiv, ha, pi.smul_apply, continuous_linear_map.smul_apply, rotation_apply, continuous_linear_map.id_apply, smul_eq_mul], }, { refine or.intro_right _ ⟨rot, _⟩, ext1, rw [continuous_linear_map.coe_comp', hg, ← li.coe_to_linear_isometry_equiv, ha], simp only [coe_restrict_scalars', function.comp_app, pi.smul_apply, linear_isometry_equiv.coe_trans, conj_lie_apply, rotation_apply, continuous_linear_equiv.coe_apply, conj_cle_apply], simp only [continuous_linear_map.smul_apply, continuous_linear_map.id_apply, smul_eq_mul, conj_conj], }, end /-- A real continuous linear map on the complex plane is conformal if and only if the map or its conjugate is complex linear, and the map is nonvanishing. -/ lemma is_conformal_map_iff_is_complex_or_conj_linear: is_conformal_map g ↔ ((∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g) ∨ (∃ (map : ℂ →L[ℂ] ℂ), map.restrict_scalars ℝ = g ∘L ↑conj_cle)) ∧ g ≠ 0 := begin split, { exact λ h, ⟨h.is_complex_or_conj_linear, h.ne_zero⟩, }, { rintros ⟨⟨map, rfl⟩ | ⟨map, hmap⟩, h₂⟩, { refine is_conformal_map_complex_linear _, contrapose! h₂ with w, simp [w] }, { have minor₁ : g = (map.restrict_scalars ℝ) ∘L ↑conj_cle, { ext1, simp [hmap] }, rw minor₁ at ⊢ h₂, refine is_conformal_map_complex_linear_conj _, contrapose! h₂ with w, simp [w] } } end end conformal_into_complex_plane
0e1195b7faf52ea960f3ff21653c699dc21a844e
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/tests/lean/match3.lean
2633ad6708345fe68ce047e6ee572686028182d2
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
2,076
lean
def f (x : Nat) : Nat := match x with | 30 => 31 | y+1 => y | 0 => 10 #eval f 20 #eval f 0 #eval f 30 universes u theorem ex1 {α : Sort u} {a b : α} (h : a ≅ b) : a = b := match α, a, b, h with | _, _, _, HEq.refl _ => rfl theorem ex2 {α : Sort u} {a b : α} (h : a ≅ b) : a = b := match a, b, h with | _, _, HEq.refl _ => rfl theorem ex3 {α : Sort u} {a b : α} (h : a ≅ b) : a = b := match b, h with | _, HEq.refl _ => rfl theorem ex4 {α β : Sort u} {b : β} {a a' : α} (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := match β, a', b, h₁, h₂ with | _, _, _, rfl, HEq.refl _ => HEq.refl _ theorem ex5 {α β : Sort u} {b : β} {a a' : α} (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := match a', h₁, h₂ with | _, rfl, h₂ => h₂ theorem ex6 {α β : Sort u} {b : β} {a a' : α} (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := by { subst h₁; assumption } theorem ex7 (a : Bool) (p q : Prop) (h₁ : a = true → p) (h₂ : a = false → q) : p ∨ q := match h:a with | true => Or.inl $ h₁ h | false => Or.inr $ h₂ h def head {α} (xs : List α) (h : xs = [] → False) : α := match he:xs with | [] => by contradiction | x::_ => x variable {α : Type u} {p : α → Prop} theorem ex8 {a1 a2 : {x // p x}} (h : a1.val = a2.val) : a1 = a2 := match a1, a2, h with | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl universes v variable {β : α → Type v} theorem ex9 {p₁ p₂ : Sigma (fun a => β a)} (h₁ : p₁.1 = p₂.1) (h : p₁.2 ≅ p₂.2) : p₁ = p₂ := match p₁, p₂, h₁, h with | ⟨_, _⟩, ⟨_, _⟩, rfl, HEq.refl _ => rfl inductive F : Nat → Type | z : {n : Nat} → F (n+1) | s : {n : Nat} → F n → F (n+1) def f0 {α : Sort u} (x : F 0) : α := nomatch x def f0' {α : Sort u} (x : F 0) : α := nomatch id x def f1 {α : Sort u} (x : F 0 × Bool) : α := nomatch x def f2 {α : Sort u} (x : Sum (F 0) (F 0)) : α := nomatch x def f3 {α : Sort u} (x : Bool × F 0) : α := nomatch x def f4 (x : Sum (F 0 × Bool) Nat) : Nat := match x with | Sum.inr x => x #eval f4 $ Sum.inr 100
ef0497f39a928544378bf403d1a1a94754b94155
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0307.lean
3732b5a2fa6663dc37a6ec12b644a1de0b5f0e9c
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
391
lean
example (x y : ℕ) : (x + y) * (x + y) = x * x + y * x + x * y + y * y := calc (x + y) * (x + y) = (x + y) * x + (x + y) * y : by rw mul_add ... = x * x + y * x + (x + y) * y : by rw add_mul ... = x * x + y * x + (x * y + y * y) : by rw add_mul ... = x * x + y * x + x * y + y * y : by rw ←add_assoc
5d407556889242f42f6fdf7e3065d11df69f5b03
25803f2d9ccf464b08982d15db52a0ef604c8514
/src/model.lean
fa97334de1a5f774741206ca635768a2dfb7cae1
[]
no_license
kthmp/igl2020
b640d6064b9387f991c35bf57c33ff1dd14dfa95
a9dfc9956d55e85dcd38fefb3644cdf64953470d
refs/heads/master
1,671,721,032,056
1,600,198,086,000
1,600,198,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,651
lean
import tactic import data.real.basic import set_theory.cardinal /- This is an attempt to define Languages and Structures on these Languages.-/ /-A language is given by specifying functions, relations and constants along with the arity of each function and each relation.-/ structure lang := (F : Type) -- functions (n_f : F → ℕ) -- arity of each function (R : Type) -- relations (n_r : R → ℕ) -- arity of each relation (C : Type) -- constants /-We now define some example languages. We start with the simplest possible language, the language of pure sets. This language has no functions, relations or constants.-/ def set_lang : lang := begin fconstructor, -- we will construct the lang by specifying its fields. use empty, -- empty is the name of the empty type (0 elements) use (λ_, 0), -- doesn't matter. Vacuous definition. use empty, -- empty type because no relations. use (λ _, 0), -- doesn't matter. Vacuous definition. use empty, -- empty type because no constants. end /-A magma is a {×}-structure. So this has 1 function, 0 relations and 0 constants.-/ def magma_lang : lang := begin fconstructor, use unit, -- unit is the name of the type with only 1 member. use (λ _, 2), -- this member is a binary operation use empty, -- no relations. use (λ _, 0), -- vacuous definition. use empty -- no constants end /-A semigroup is a {×}-structure which satisfies the identity u × (v × w) = (u × v) × w-/ def semigroup_lang : lang := begin fconstructor, use unit, -- one function, therefore we use unit use (λ _, 2), -- the function is a binary operation use unit, -- one relation, therefore we use unit use (λ _, 3), -- the relation is ternary (uses u, v, w) use empty, -- no constants. end /- A monoid is a {×, 1}-structure which satisfies the identities 1. u × (v × w) = (u × v) × w 2. u × 1 = u 3. 1 × u = u. -/ def monoid_lang : lang := sorry /- A group is a {×, ⁻¹, 1}-structure which satisfies the identities 1. u × (v × w) = (u × v) × w 2. u × 1 = u 3. 1 × u = u 4. u × u−1 = 1 5. u−1 × u = 1 -/ def group_lang : lang := sorry /- A semiring is a {×, +, 0, 1}-structure which satisfies the identities 1. u + (v + w) = (u + v) + w 2. u + v = v + u 3. u + 0 = u 5. u × (v × w) = (u × v) × w 6. u × 1 = u, 1 × u = u 7. u × (v + w) = (u × v) + (u × w) 8. (v + w) × u = (v × u) + (w × u)-/ def semiring_lang : lang := sorry /- A ring is a {×,+,−,0,1}-structure which satisfies the identities 1. u + (v + w) = (u + v) + w 2. u + v = v + u 3. u + 0 = u 4. u + (−u) = 0 5. u × (v × w) = (u × v) × w 6. u × 1 = u, 1 × u = u 7. u × (v + w) = (u × v) + (u × w) 8. (v + w) × u = (v × u) + (w × u)-/ def ring_lang : lang := sorry /- We now define an L-structure to be interpretations of functions, relations and constants. -/ structure struc (L : lang) := (univ : Type) -- universe/domain (F (f : L.F) : vector univ (L.n_f f) → univ) -- interpretation of each function (R (r : L.R) : set (vector univ (L.n_r r))) -- interpretation of each relation (C : L.C → univ) -- interpretation of each constant /-An L-embedding is a map between two L-structures that is injective on the domain and preserves the interpretation of all the symbols of L.-/ structure embedding {L : lang} (M N : struc L) : Type := (η : M.univ → N.univ) -- map of underlying domains (η_inj : function.injective η) -- should be one-to-one (η_F : ∀ f v, -- preserves action of each function η (M.F f v) = N.F f (vector.map η v)) (η_R : ∀ r v, -- preserves each relation v ∈ (M.R r) ↔ (vector.map η v) ∈ (N.R r)) (η_C : ∀ c, -- preserves each constant η (M.C c) = N.C c) /-A bijective L-embedding is called an L-isomorphism.-/ structure isomorphism {L: lang} (M N : struc L) extends (embedding M N) : Type := (η_bij : function.bijective η) /-The cardinality of a struc is the cardinality of its domain.-/ def card {L : lang} (M : struc L) : cardinal := cardinal.mk M.univ /-If η: M → N is an embedding, then the cardinality of N is at least the cardinality of M.-/ lemma le_card_of_embedding {L : lang} (M N : struc L) (η : embedding M N) : card M ≤ card N := begin sorry -- Look for a theorem in mathlib that guarantees the result -- using injectivity of η. end
2d0199e97c32bd6c620338b1b9fda20bcb2ca196
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/semigroup.lean
d47361d4c410df7e85fe7691d75c0b3281c7b751
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
176
lean
universe u structure Semigroup := (carrier : Type u) (mul : carrier → carrier → carrier) (mul_assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)) --#check @Semigroup
de7ac0f1d6e0994efb6a58ff013a01d3b6883612
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/smt/prove.lean
2c6ec68e52e3c3e8a717b71c2d779a385a3f3329
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
561
lean
namespace smt open tactic private meta def collect_props : list expr → tactic (list expr) | [] := return [] | (H :: Hs) := do Eqs ← collect_props Hs, Htype ← infer_type H >>= infer_type >>= whnf, return $ if Htype = `(Prop) then (H :: Eqs) else Eqs -- This tactic is just a placeholder, designed to be modified for specific performance experiments meta def prove : tactic unit := do local_context >>= collect_props >>= revert_lst, trace "SMT state, after reverting propositions:", trace_state, simp { contextual := tt } end smt
4e0022d616e9db072b863c2f8dafb2504ad38ece
4ec0e92c725fad3fd2871a0ab050a7da1c719444
/src/mywork/lecture_8.lean
e7bfb8a4b166de444ef81ffc69ecf66b4560a0ac
[]
no_license
mitchelltaylor06/cs2120f21
cc2c2b61a7e45c07faa849fcb8a66eb948753a25
efb71a748d7c76e24834d03b8f01c3ae084c1756
refs/heads/main
1,693,841,444,092
1,633,713,850,000
1,633,713,850,000
399,946,415
0
0
null
null
null
null
UTF-8
Lean
false
false
4,744
lean
/- The or connective, ∨, in predicate logic join any two propositions, P, Q, into a larger proposition, P ∨ Q. This proposition is judged as true if either (or both) P, Q are true. -/ theorem and_associative : ∀ (P Q R : Prop), (P ∧ Q) ∧ R → P ∧ (Q ∧ R) := begin assume P Q R, assume h, have pq : P ∧ Q := and.elim_left h, have p : P := and.elim_left pq, have q : Q := and.elim_right pq, have r : R := and.elim_right h, exact and.intro p (and.intro q r), end /- Introduction rules (two of them). There are two ways to prove a proposition, (P ∨ Q): with a proof of P, or with a proof of Q. Either will do. We thus have two intro rules for ∨. They are called the left and right introduction rules. The left one takes a proof, let's say, p, of the left proposition, P (from which it infers) P along with the right proposition, Q, and then returns a proof of P ∨ Q. The arguments are actually given in the other order. The right introduction rule thus takes the proposition, P and a proof of the proposition, Q, and also returns a proof of P ∨ Q. Exercise: Suppose that it's true (and thus that we we have a proof) that Joe chews gum. Give an English proof of the proposition that (Joe is tall) ∨ (Joe chews gum). Proof: Apply the right introduction rule for ∨ to (1) our proof that Joe chews gum, and (2) the proposition that Joe is tall. The result is the proof we want, of the proposition (Joe chews gum) ∨ (Joe is tall). Exercise: Give an English language proof of: (Joe is tall) ∨ (Joe chews gum). -/ /- In Lean, the rules are called or.intro_left and or.intro_right. -/ #check @or.intro_left #check @or.intro_right /- In the preceding outputs, you can see that the arguments that are required explicitly are in parentheses, and the arguments whose values are inferred from other arguments are given in {}. -/ /- Let's formalize our example in Lean. -/ axioms (Joe_is_tall Joe_chews_gum : Prop) axiom jcg: Joe_chews_gum theorem jcg_or_jit: Joe_chews_gum ∨ Joe_is_tall := or.intro_left Joe_is_tall jcg /- Exercise: Formalize our second version of this proposition and a proof of it. -/ /- We thus have two inference rules (axioms) that we can use to create a proof of a "disjunction". (Q : Prop) {P : Prop} (p : P) ----------------------------- ∨ intro_left pf : P ∨ Q (P : Prop) {Q : Prop} (q : Q) ----------------------------- ∨ intro_right pf : P ∨ Q -/ /- Suppose that if Joe is tall then he is funny, that if Joe chews gum he is also funny, and that Joe chews gum ∨ Joe is tall. What can we deduce from these assumptions/facts? -/ /- You have just used the elimination rule for ∨. Here it is a little more generally. Suppose P, Q, and R are propositions, that P → R and Q → R, and finally that P ∨ Q is true? What can we then deduce? Why, R, of course! {P Q R : Prop} (pq : P ∨ Q) (pr : P → R) (qr : Q → R) ----------------------------------------------------- pf : R -/ #check @or.elim /- Let's add a few assumptions and see this rule in action. -/ axioms (P Q R : Prop) (pq : P ∨ Q) (pr : P → R) (qr : Q → R) example : R := _ axioms (Joe_is_funny : Prop) (torf : Joe_is_tall ∨ Joe_chews_gum) (tf: Joe_is_tall → Joe_is_funny) (gf : Joe_chews_gum → Joe_is_funny) example : Joe_is_funny := or.elim torf tf gf /- In English, under the given assumptions (axioms, just above) we can prove that Joe is funny *by cases*. We know that Joe chews gum OR Joe is tall, so least one of these cases must hold. Let's consider the cases in turn. Case 1: Suppose that (Joe is tall ∨ Joe chews gum) is true because Joe is tall. In this case we apply the fact that (Joe is tall → Joe is funny) to the fact hat (Joe is tall) to deduce that Joe is funny. Exercise: What inference rule did we use right there? Case 2: The reasoning is similar. Suppose the disjunction is true because Joe chews gum. We can use "modus ponens", applying the fact that (Joe chews gum → Joe is funny) to deduce (Joe is funny). Therefore Joe is funny *in either case*, and *there are no other cases to consider* so we can deduce that Joe is funny. -/ /- Here it is formally! -/ -- By cases example : Joe_is_funny := begin cases torf, -- applies or.elim apply tf h, apply gf h, end -- Equivalent direct application of or.elim example : Joe_is_funny := begin apply or.elim torf _ _, -- applies or.elim exact tf, exact gf, end /- Yay, now how about proving some theorems. -/ /- Problem #1: State precisely and prove that ∨ is commutative, in English then formally. -/ /- Problem #2: State precisely and prove that ∨ is associative, first in English then formally. -/
e1a4c48deeb753a2a0e1badf93e79f3b8ffccbb8
618003631150032a5676f229d13a079ac875ff77
/src/analysis/normed_space/complemented.lean
a7d0e4eaa91e2f2fcd5e5f987bcfbec38cc8ee7c
[ "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
5,820
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import analysis.normed_space.banach import analysis.normed_space.finite_dimension /-! # Complemented subspaces of normed vector spaces A submodule `p` of a topological module `E` over `R` is called *complemented* if there exists a continuous linear projection `f : E →ₗ[R] p`, `∀ x : p, f x = x`. We prove that for a closed subspace of a normed space this condition is equivalent to existence of a closed subspace `q` such that `p ⊓ q = ⊥`, `p ⊔ q = ⊤`. We also prove that a subspace of finite codimension is always a complemented subspace. ## Tags complemented subspace, normed vector space -/ variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] noncomputable theory namespace continuous_linear_map section variables [complete_space 𝕜] lemma ker_closed_complemented_of_finite_dimensional_range (f : E →L[𝕜] F) [finite_dimensional 𝕜 f.range] : f.ker.closed_complemented := begin set f' : E →L[𝕜] f.range := f.cod_restrict _ (f : E →ₗ[𝕜] F).mem_range_self, rcases f'.exists_right_inverse_of_surjective (f : E →ₗ[𝕜] F).range_range_restrict with ⟨g, hg⟩, simpa only [ker_cod_restrict] using f'.closed_complemented_ker_of_right_inverse g (ext_iff.1 hg) end end variables [complete_space E] [complete_space (F × G)] /-- If `f : E →L[R] F` and `g : E →L[R] G` are two surjective linear maps and their kernels are complement of each other, then `x ↦ (f x, g x)` defines a linear equivalence `E ≃L[R] F × G`. -/ def equiv_prod_of_surjective_of_is_compl (f : E →L[𝕜] F) (g : E →L[𝕜] G) (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) : E ≃L[𝕜] F × G := ((f : E →ₗ[𝕜] F).equiv_prod_of_surjective_of_is_compl ↑g hf hg hfg).to_continuous_linear_equiv_of_continuous (f.continuous.prod_mk g.continuous) @[simp] lemma coe_equiv_prod_of_surjective_of_is_compl {f : E →L[𝕜] F} {g : E →L[𝕜] G} (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) : (equiv_prod_of_surjective_of_is_compl f g hf hg hfg : E →ₗ[𝕜] F × G) = f.prod g := rfl @[simp] lemma equiv_prod_of_surjective_of_is_compl_to_linear_equiv {f : E →L[𝕜] F} {g : E →L[𝕜] G} (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) : (equiv_prod_of_surjective_of_is_compl f g hf hg hfg).to_linear_equiv = linear_map.equiv_prod_of_surjective_of_is_compl f g hf hg hfg := rfl @[simp] lemma equiv_prod_of_surjective_of_is_compl_apply {f : E →L[𝕜] F} {g : E →L[𝕜] G} (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) (x : E): equiv_prod_of_surjective_of_is_compl f g hf hg hfg x = (f x, g x) := rfl end continuous_linear_map namespace subspace variables [complete_space E] (p q : subspace 𝕜 E) open continuous_linear_map (subtype_val) /-- If `q` is a closed complement of a closed subspace `p`, then `p × q` is continuously isomorphic to `E`. -/ def prod_equiv_of_closed_compl (h : is_compl p q) (hp : is_closed (p : set E)) (hq : is_closed (q : set E)) : (p × q) ≃L[𝕜] E := begin haveI := hp.complete_space_coe, haveI := hq.complete_space_coe, refine (p.prod_equiv_of_is_compl q h).to_continuous_linear_equiv_of_continuous _, exact ((subtype_val p).coprod (subtype_val q)).continuous end /-- Projection to a closed submodule along a closed complement. -/ def linear_proj_of_closed_compl (h : is_compl p q) (hp : is_closed (p : set E)) (hq : is_closed (q : set E)) : E →L[𝕜] p := (continuous_linear_map.fst 𝕜 p q).comp $ (prod_equiv_of_closed_compl p q h hp hq).symm variables {p q} @[simp] lemma coe_prod_equiv_of_closed_compl (h : is_compl p q) (hp : is_closed (p : set E)) (hq : is_closed (q : set E)) : ⇑(p.prod_equiv_of_closed_compl q h hp hq) = p.prod_equiv_of_is_compl q h := rfl @[simp] lemma coe_prod_equiv_of_closed_compl_symm (h : is_compl p q) (hp : is_closed (p : set E)) (hq : is_closed (q : set E)) : ⇑(p.prod_equiv_of_closed_compl q h hp hq).symm = (p.prod_equiv_of_is_compl q h).symm := rfl @[simp] lemma coe_continuous_linear_proj_of_closed_compl (h : is_compl p q) (hp : is_closed (p : set E)) (hq : is_closed (q : set E)) : (p.linear_proj_of_closed_compl q h hp hq : E →ₗ[𝕜] p) = p.linear_proj_of_is_compl q h := rfl @[simp] lemma coe_continuous_linear_proj_of_closed_compl' (h : is_compl p q) (hp : is_closed (p : set E)) (hq : is_closed (q : set E)) : ⇑(p.linear_proj_of_closed_compl q h hp hq) = p.linear_proj_of_is_compl q h := rfl lemma closed_complemented_of_closed_compl (h : is_compl p q) (hp : is_closed (p : set E)) (hq : is_closed (q : set E)) : p.closed_complemented := ⟨p.linear_proj_of_closed_compl q h hp hq, submodule.linear_proj_of_is_compl_apply_left h⟩ lemma closed_complemented_iff_has_closed_compl : p.closed_complemented ↔ is_closed (p : set E) ∧ ∃ (q : subspace 𝕜 E) (hq : is_closed (q : set E)), is_compl p q := ⟨λ h, ⟨h.is_closed, h.has_closed_complement⟩, λ ⟨hp, ⟨q, hq, hpq⟩⟩, closed_complemented_of_closed_compl hpq hp hq⟩ lemma closed_complemented_of_quotient_finite_dimensional [complete_space 𝕜] [finite_dimensional 𝕜 p.quotient] (hp : is_closed (p : set E)) : p.closed_complemented := begin obtain ⟨q, hq⟩ : ∃ q, is_compl p q := p.exists_is_compl, haveI : finite_dimensional 𝕜 q := (p.quotient_equiv_of_is_compl q hq).finite_dimensional, exact closed_complemented_of_closed_compl hq hp q.closed_of_finite_dimensional end end subspace
f7256e3d22d63a412472c913c820ad3f669f697d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/real/cau_seq_completion.lean
44a7d0f2028bf13991d765c4eea901c0819c9b8a
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
10,518
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis -/ import data.real.cau_seq /-! # Cauchy completion This file generalizes the Cauchy completion of `(ℚ, abs)` to the completion of a commutative ring with absolute value. -/ namespace cau_seq.completion open cau_seq section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] /-- The Cauchy completion of a commutative ring with absolute value. -/ def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv /-- The map from Cauchy sequences into the Cauchy completion. -/ def mk : cau_seq _ abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq /-- The map from the original ring into the Cauchy completion. -/ def of_rat (x : β) : Cauchy := mk (const abv x) instance : has_zero Cauchy := ⟨of_rat 0⟩ instance : has_one Cauchy := ⟨of_rat 1⟩ instance : inhabited Cauchy := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using add_lim_zero hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk (-f)) $ λ f₁ f₂ hf, quotient.sound $ by simpa [(≈), setoid.r] using neg_lim_zero hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, mul_add, mul_comm, add_assoc, sub_eq_add_neg] using add_lim_zero (mul_lim_zero_right g₁ hf) (mul_lim_zero_right f₂ hg)⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl instance : has_sub Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f - g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ show ((f₁ - g₁) - (f₂ - g₂)).lim_zero, by simpa [sub_eq_add_neg, add_assoc, add_comm, add_left_comm] using sub_lim_zero hf hg⟩ @[simp] theorem mk_sub (f g : cau_seq β abv) : mk f - mk g = mk (f - g) := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = mk 0 := rfl private lemma one_def : 1 = mk 1 := rfl instance : comm_ring Cauchy := by refine { neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, add := (+), zero := (0 : Cauchy), mul := (*), one := 1, nsmul := nsmul_rec, npow := npow_rec, zsmul := zsmul_rec, .. }; try { intros; refl }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm, sub_eq_add_neg] } theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) end open_locale classical section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] local notation `Cauchy` := @Cauchy _ _ _ _ abv _ noncomputable instance : has_inv Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end /-- The Cauchy completion forms a field. See note [reducible non-instances]. -/ @[reducible] noncomputable def field : field Cauchy := { inv := has_inv.inv, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], exists_pair_ne := ⟨0, 1, zero_ne_one⟩, inv_zero := inv_zero, .. Cauchy.comm_ring } local attribute [instance] field theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) := congr_arg mk $ by split_ifs with h; [simp [const_lim_zero.1 h], refl] theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) := by simp only [div_eq_inv_mul, of_rat_inv, of_rat_mul] end end cau_seq.completion variables {α : Type*} [linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] /-- A class stating that a ring with an absolute value is complete, i.e. every Cauchy sequence has a limit. -/ class is_complete := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete /-- The limit of a Cauchy sequence in a complete ring. Chosen non-computably. -/ noncomputable def lim (s : cau_seq β abv) : β := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm, ← sub_eq_add_neg]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
4e03e473ab36495bde45943e37ee6a37388f83bd
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Syntax.lean
e62405c3531cd0e5c3334e0fc945ab9b95ee477f
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
15,854
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Data.Name import Lean.Data.Format namespace Lean def SourceInfo.updateTrailing (trailing : Substring) : SourceInfo → SourceInfo | SourceInfo.original leading pos _ endPos => SourceInfo.original leading pos trailing endPos | info => info /- Syntax AST -/ inductive IsNode : Syntax → Prop where | mk (kind : SyntaxNodeKind) (args : Array Syntax) : IsNode (Syntax.node kind args) def SyntaxNode : Type := {s : Syntax // IsNode s } def unreachIsNodeMissing {β} (h : IsNode Syntax.missing) : β := False.elim (nomatch h) def unreachIsNodeAtom {β} {info val} (h : IsNode (Syntax.atom info val)) : β := False.elim (nomatch h) def unreachIsNodeIdent {β info rawVal val preresolved} (h : IsNode (Syntax.ident info rawVal val preresolved)) : β := False.elim (nomatch h) namespace SyntaxNode @[inline] def getKind (n : SyntaxNode) : SyntaxNodeKind := match n with | ⟨Syntax.node k args, _⟩ => k | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom .., h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident .., h⟩ => unreachIsNodeIdent h @[inline] def withArgs {β} (n : SyntaxNode) (fn : Array Syntax → β) : β := match n with | ⟨Syntax.node _ args, _⟩ => fn args | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h @[inline] def getNumArgs (n : SyntaxNode) : Nat := withArgs n $ fun args => args.size @[inline] def getArg (n : SyntaxNode) (i : Nat) : Syntax := withArgs n $ fun args => args.get! i @[inline] def getArgs (n : SyntaxNode) : Array Syntax := withArgs n $ fun args => args @[inline] def modifyArgs (n : SyntaxNode) (fn : Array Syntax → Array Syntax) : Syntax := match n with | ⟨Syntax.node kind args, _⟩ => Syntax.node kind (fn args) | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h end SyntaxNode namespace Syntax def getAtomVal! : Syntax → String | atom _ val => val | _ => panic! "getAtomVal!: not an atom" def setAtomVal : Syntax → String → Syntax | atom info _, v => (atom info v) | stx, _ => stx @[inline] def ifNode {β} (stx : Syntax) (hyes : SyntaxNode → β) (hno : Unit → β) : β := match stx with | Syntax.node k args => hyes ⟨Syntax.node k args, IsNode.mk k args⟩ | _ => hno () @[inline] def ifNodeKind {β} (stx : Syntax) (kind : SyntaxNodeKind) (hyes : SyntaxNode → β) (hno : Unit → β) : β := match stx with | Syntax.node k args => if k == kind then hyes ⟨Syntax.node k args, IsNode.mk k args⟩ else hno () | _ => hno () def asNode : Syntax → SyntaxNode | Syntax.node kind args => ⟨Syntax.node kind args, IsNode.mk kind args⟩ | _ => ⟨Syntax.node nullKind #[], IsNode.mk nullKind #[]⟩ def getIdAt (stx : Syntax) (i : Nat) : Name := (stx.getArg i).getId @[inline] def modifyArgs (stx : Syntax) (fn : Array Syntax → Array Syntax) : Syntax := match stx with | node k args => node k (fn args) | stx => stx @[inline] def modifyArg (stx : Syntax) (i : Nat) (fn : Syntax → Syntax) : Syntax := match stx with | node k args => node k (args.modify i fn) | stx => stx @[specialize] partial def replaceM {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) : Syntax → m (Syntax) | stx@(node kind args) => do match (← fn stx) with | some stx => return stx | none => return node kind (← args.mapM (replaceM fn)) | stx => do let o ← fn stx return o.getD stx @[specialize] partial def rewriteBottomUpM {m : Type → Type} [Monad m] (fn : Syntax → m (Syntax)) : Syntax → m (Syntax) | node kind args => do let args ← args.mapM (rewriteBottomUpM fn) fn (node kind args) | stx => fn stx @[inline] def rewriteBottomUp (fn : Syntax → Syntax) (stx : Syntax) : Syntax := Id.run $ stx.rewriteBottomUpM fn private def updateInfo : SourceInfo → String.Pos → String.Pos → SourceInfo | SourceInfo.original lead pos trail endPos, leadStart, trailStop => SourceInfo.original { lead with startPos := leadStart } pos { trail with stopPos := trailStop } endPos | info, _, _ => info private def chooseNiceTrailStop (trail : Substring) : String.Pos := trail.startPos + trail.posOf '\n' /- Remark: the State `String.Pos` is the `SourceInfo.trailing.stopPos` of the previous token, or the beginning of the String. -/ @[inline] private def updateLeadingAux : Syntax → StateM String.Pos (Option Syntax) | atom info@(SourceInfo.original lead _ trail _) val => do let trailStop := chooseNiceTrailStop trail let newInfo := updateInfo info (← get) trailStop set trailStop pure $ some (atom newInfo val) | ident info@(SourceInfo.original lead _ trail _) rawVal val pre => do let trailStop := chooseNiceTrailStop trail let newInfo := updateInfo info (← get) trailStop set trailStop pure $ some (ident newInfo rawVal val pre) | _ => pure none /-- Set `SourceInfo.leading` according to the trailing stop of the preceding token. The result is a round-tripping syntax tree IF, in the input syntax tree, * all leading stops, atom contents, and trailing starts are correct * trailing stops are between the trailing start and the next leading stop. Remark: after parsing, all `SourceInfo.leading` fields are empty. The `Syntax` argument is the output produced by the parser for `source`. This function "fixes" the `source.leading` field. Additionally, we try to choose "nicer" splits between leading and trailing stops according to some heuristics so that e.g. comments are associated to the (intuitively) correct token. Note that the `SourceInfo.trailing` fields must be correct. The implementation of this Function relies on this property. -/ def updateLeading : Syntax → Syntax := fun stx => (replaceM updateLeadingAux stx).run' 0 partial def updateTrailing (trailing : Substring) : Syntax → Syntax | Syntax.atom info val => Syntax.atom (info.updateTrailing trailing) val | Syntax.ident info rawVal val pre => Syntax.ident (info.updateTrailing trailing) rawVal val pre | n@(Syntax.node k args) => if args.size == 0 then n else let i := args.size - 1 let last := updateTrailing trailing args[i] let args := args.set! i last; Syntax.node k args | s => s partial def getTailWithPos : Syntax → Option Syntax | stx@(atom info _) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node _ args => args.findSomeRev? getTailWithPos | _ => none structure TopDown where firstChoiceOnly : Bool stx : Syntax /-- `for _ in stx.topDown` iterates through each node and leaf in `stx` top-down, left-to-right. If `firstChoiceOnly` is `true`, only visit the first argument of each choice node. -/ def topDown (stx : Syntax) (firstChoiceOnly := false) : TopDown := ⟨firstChoiceOnly, stx⟩ partial instance : ForIn m TopDown Syntax where forIn := fun ⟨firstChoiceOnly, stx⟩ init f => do let rec @[specialize] loop stx b [Inhabited (typeOf% b)] := do match ← f stx b with | ForInStep.yield b' => let mut b := b' if let Syntax.node k args := stx then if firstChoiceOnly && k == choiceKind then return ← loop args[0] b else for arg in args do match ← loop arg b with | ForInStep.yield b' => b := b' | ForInStep.done b' => return ForInStep.done b' return ForInStep.yield b | ForInStep.done b => return ForInStep.done b match ← @loop stx init ⟨init⟩ with | ForInStep.yield b => return b | ForInStep.done b => return b partial def reprint (stx : Syntax) : Option String := OptionM.run do let mut s := "" for stx in stx.topDown (firstChoiceOnly := true) do match stx with | atom info val => s := s ++ reprintLeaf info val | ident info rawVal _ _ => s := s ++ reprintLeaf info rawVal.toString | node kind args => if kind == choiceKind then -- this visit the first arg twice, but that should hardly be a problem -- given that choice nodes are quite rare and small let s0 ← reprint args[0] for arg in args[1:] do let s' ← reprint stx guard (s0 == s') | _ => pure () return s where reprintLeaf (info : SourceInfo) (val : String) : String := match info with | SourceInfo.original lead _ trail _ => s!"{lead}{val}{trail}" -- no source info => add gracious amounts of whitespace to definitely separate tokens -- Note that the proper pretty printer does not use this function. -- The parser as well always produces source info, so round-tripping is still -- guaranteed. | _ => s!" {val} " def hasMissing (stx : Syntax) : Bool := do for stx in stx.topDown do if stx.isMissing then return true return false /-- Represents a cursor into a syntax tree that can be read, written, and advanced down/up/left/right. Indices are allowed to be out-of-bound, in which case `cur` is `Syntax.missing`. If the `Traverser` is used linearly, updates are linear in the `Syntax` object as well. -/ structure Traverser where cur : Syntax parents : Array Syntax idxs : Array Nat namespace Traverser def fromSyntax (stx : Syntax) : Traverser := ⟨stx, #[], #[]⟩ def setCur (t : Traverser) (stx : Syntax) : Traverser := { t with cur := stx } /-- Advance to the `idx`-th child of the current node. -/ def down (t : Traverser) (idx : Nat) : Traverser := if idx < t.cur.getNumArgs then { cur := t.cur.getArg idx, parents := t.parents.push $ t.cur.setArg idx arbitrary, idxs := t.idxs.push idx } else { cur := Syntax.missing, parents := t.parents.push t.cur, idxs := t.idxs.push idx } /-- Advance to the parent of the current node, if any. -/ def up (t : Traverser) : Traverser := if t.parents.size > 0 then let cur := if t.idxs.back < t.parents.back.getNumArgs then t.parents.back.setArg t.idxs.back t.cur else t.parents.back { cur := cur, parents := t.parents.pop, idxs := t.idxs.pop } else t /-- Advance to the left sibling of the current node, if any. -/ def left (t : Traverser) : Traverser := if t.parents.size > 0 then t.up.down (t.idxs.back - 1) else t /-- Advance to the right sibling of the current node, if any. -/ def right (t : Traverser) : Traverser := if t.parents.size > 0 then t.up.down (t.idxs.back + 1) else t end Traverser /-- Monad class that gives read/write access to a `Traverser`. -/ class MonadTraverser (m : Type → Type) where st : MonadState Traverser m namespace MonadTraverser variable {m : Type → Type} [Monad m] [t : MonadTraverser m] def getCur : m Syntax := Traverser.cur <$> t.st.get def setCur (stx : Syntax) : m Unit := @modify _ _ t.st (fun t => t.setCur stx) def goDown (idx : Nat) : m Unit := @modify _ _ t.st (fun t => t.down idx) def goUp : m Unit := @modify _ _ t.st (fun t => t.up) def goLeft : m Unit := @modify _ _ t.st (fun t => t.left) def goRight : m Unit := @modify _ _ t.st (fun t => t.right) def getIdx : m Nat := do let st ← t.st.get st.idxs.back?.getD 0 end MonadTraverser end Syntax namespace SyntaxNode @[inline] def getIdAt (n : SyntaxNode) (i : Nat) : Name := (n.getArg i).getId end SyntaxNode def mkListNode (args : Array Syntax) : Syntax := Syntax.node nullKind args namespace Syntax -- quotation node kinds are formed from a unique quotation name plus "quot" def isQuot : Syntax → Bool | Syntax.node (Name.str _ "quot" _) _ => true | Syntax.node `Lean.Parser.Term.dynamicQuot _ => true | _ => false def getQuotContent (stx : Syntax) : Syntax := if stx.isOfKind `Lean.Parser.Term.dynamicQuot then stx[3] else stx[1] -- antiquotation node kinds are formed from the original node kind (if any) plus "antiquot" def isAntiquot : Syntax → Bool | Syntax.node (Name.str _ "antiquot" _) _ => true | _ => false def mkAntiquotNode (term : Syntax) (nesting := 0) (name : Option String := none) (kind := Name.anonymous) : Syntax := let nesting := mkNullNode (mkArray nesting (mkAtom "$")) let term := match term.isIdent with | true => term | false => mkNode `antiquotNestedExpr #[mkAtom "(", term, mkAtom ")"] let name := match name with | some name => mkNode `antiquotName #[mkAtom ":", mkAtom name] | none => mkNullNode mkNode (kind ++ `antiquot) #[mkAtom "$", nesting, term, name] -- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. Also works for antiquotation splices. def isEscapedAntiquot (stx : Syntax) : Bool := !stx[1].getArgs.isEmpty -- Also works for antiquotation splices. def unescapeAntiquot (stx : Syntax) : Syntax := if isAntiquot stx then stx.setArg 1 $ mkNullNode stx[1].getArgs.pop else stx -- Also works for token antiquotations. def getAntiquotTerm (stx : Syntax) : Syntax := let e := if stx.isAntiquot then stx[2] else stx[3] if e.isIdent then e else -- `e` is from `"(" >> termParser >> ")"` e[1] def antiquotKind? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot" _) args => if args[3].isOfKind `antiquotName then some k else -- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`) some Name.anonymous | _ => none -- An "antiquotation splice" is something like `$[...]?` or `$[...]*`. def antiquotSpliceKind? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot_scope" _) args => some k | _ => none def isAntiquotSplice (stx : Syntax) : Bool := antiquotSpliceKind? stx |>.isSome def getAntiquotSpliceContents (stx : Syntax) : Array Syntax := stx[3].getArgs -- `$[..],*` or `$x,*` ~> `,*` def getAntiquotSpliceSuffix (stx : Syntax) : Syntax := if stx.isAntiquotSplice then stx[5] else stx[1] def mkAntiquotSpliceNode (kind : SyntaxNodeKind) (contents : Array Syntax) (suffix : String) (nesting := 0) : Syntax := let nesting := mkNullNode (mkArray nesting (mkAtom "$")) mkNode (kind ++ `antiquot_splice) #[mkAtom "$", nesting, mkAtom "[", mkNullNode contents, mkAtom "]", mkAtom suffix] -- `$x,*` etc. def antiquotSuffixSplice? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot_suffix_splice" _) args => some k | _ => none def isAntiquotSuffixSplice (stx : Syntax) : Bool := antiquotSuffixSplice? stx |>.isSome -- `$x` in the example above def getAntiquotSuffixSpliceInner (stx : Syntax) : Syntax := stx[0] def mkAntiquotSuffixSpliceNode (kind : SyntaxNodeKind) (inner : Syntax) (suffix : String) : Syntax := mkNode (kind ++ `antiquot_suffix_splice) #[inner, mkAtom suffix] def isTokenAntiquot (stx : Syntax) : Bool := stx.isOfKind `token_antiquot def isAnyAntiquot (stx : Syntax) : Bool := stx.isAntiquot || stx.isAntiquotSplice || stx.isAntiquotSuffixSplice || stx.isTokenAntiquot end Syntax end Lean
a09e8c6f7b287ac4401ca3ab90fbb95704e3e75d
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Elab/Binders.lean
1f4d35cc018e2270a9186830ca0a12cc780b8fb3
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,309
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /-- Given syntax of the forms a) (`:` term)? b) `:` term return `term` if it is present, or a hole if not. -/ private def expandBinderType (ref : Syntax) (stx : Syntax) : Syntax := if stx.getNumArgs == 0 then mkHole ref else stx[1] /-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/ private def expandBinderIdent (stx : Syntax) : TermElabM Syntax := match stx with | `(_) => mkFreshIdent stx | _ => pure stx /-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/ private def expandOptIdent (stx : Syntax) : TermElabM Syntax := do if stx.isNone then let id ← withFreshMacroScope <| MonadQuotation.addMacroScope `inst return mkIdentFrom stx id else return stx[0] structure BinderView where id : Syntax type : Syntax bi : BinderInfo partial def quoteAutoTactic : Syntax → TermElabM Syntax | stx@(Syntax.ident _ _ _ _) => throwErrorAt stx "invalid auto tactic, identifier is not allowed" | stx@(Syntax.node k args) => do if stx.isAntiquot then throwErrorAt stx "invalid auto tactic, antiquotation is not allowed" else let mut quotedArgs ← `(Array.empty) for arg in args do if k == nullKind && (arg.isAntiquotSuffixSplice || arg.isAntiquotSplice) then throwErrorAt arg "invalid auto tactic, antiquotation is not allowed" else let quotedArg ← quoteAutoTactic arg quotedArgs ← `(Array.push $quotedArgs $quotedArg) `(Syntax.node $(quote k) $quotedArgs) | Syntax.atom info val => `(Syntax.atom {} $(quote val)) | Syntax.missing => unreachable! def declareTacticSyntax (tactic : Syntax) : TermElabM Name := withFreshMacroScope do let name ← MonadQuotation.addMacroScope `_auto let type := Lean.mkConst `Lean.Syntax let tactic ← quoteAutoTactic tactic let val ← elabTerm tactic type let val ← instantiateMVars val trace[Elab.autoParam]! val let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } addDecl decl compileDecl decl pure name /- Expand `optional (binderTactic <|> binderDefault)` def binderTactic := parser! " := " >> " by " >> tacticParser def binderDefault := parser! " := " >> termParser -/ private def expandBinderModifier (type : Syntax) (optBinderModifier : Syntax) : TermElabM Syntax := do if optBinderModifier.isNone then pure type else let modifier := optBinderModifier[0] let kind := modifier.getKind if kind == `Lean.Parser.Term.binderDefault then let defaultVal := modifier[1] `(optParam $type $defaultVal) else if kind == `Lean.Parser.Term.binderTactic then let tac := modifier[2] let name ← declareTacticSyntax tac `(autoParam $type $(mkIdentFrom tac name)) else throwUnsupportedSyntax private def getBinderIds (ids : Syntax) : TermElabM (Array Syntax) := ids.getArgs.mapM fun id => let k := id.getKind if k == identKind || k == `Lean.Parser.Term.hole then pure id else throwErrorAt id "identifier or `_` expected" /- Recall that ``` def typeSpec := parser! " : " >> termParser def optType : Parser := optional typeSpec ``` -/ def expandOptType (ref : Syntax) (optType : Syntax) : Syntax := if optType.isNone then mkHole ref else optType[0][1] private def matchBinder (stx : Syntax) : TermElabM (Array BinderView) := match stx with | Syntax.node k args => do if k == `Lean.Parser.Term.simpleBinder then -- binderIdent+ >> optType let ids ← getBinderIds args[0] let type := expandOptType stx args[1] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default } else if k == `Lean.Parser.Term.explicitBinder then -- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)` let ids ← getBinderIds args[1] let type := expandBinderType stx args[2] let optModifier := args[3] let type ← expandBinderModifier type optModifier ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default } else if k == `Lean.Parser.Term.implicitBinder then -- `{` binderIdent+ binderType `}` let ids ← getBinderIds args[1] let type := expandBinderType stx args[2] ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.implicit } else if k == `Lean.Parser.Term.instBinder then -- `[` optIdent type `]` let id ← expandOptIdent args[1] let type := args[2] pure #[ { id := id, type := type, bi := BinderInfo.instImplicit } ] else throwUnsupportedSyntax | _ => throwUnsupportedSyntax private def registerFailedToInferBinderTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer binder type" private partial def elabBinderViews {α} (binderViews : Array BinderView) (catchAutoBoundImplicit : Bool) (fvars : Array Expr) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := do if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩ if catchAutoBoundImplicit then elabTypeWithAutoBoundImplicit binderView.type fun type => do registerFailedToInferBinderTypeInfo type binderView.type withLocalDecl binderView.id.getId binderView.bi type fun fvar => loop (i+1) (fvars.push fvar) else let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type withLocalDecl binderView.id.getId binderView.bi type fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 fvars private partial def elabBindersAux {α} (binders : Array Syntax) (catchAutoBoundImplicit : Bool) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := do if h : i < binders.size then let binderViews ← matchBinder (binders.get ⟨i, h⟩) elabBinderViews binderViews catchAutoBoundImplicit fvars <| loop (i+1) else k fvars loop 0 #[] /-- Elaborate the given binders (i.e., `Syntax` objects for `simpleBinder <|> bracketedBinder`), update the local context, set of local instances, reset instance chache (if needed), and then execute `x` with the updated context. -/ def elabBinders {α} (binders : Array Syntax) (k : Array Expr → TermElabM α) (catchAutoBoundImplicit := false) : TermElabM α := withoutPostponingUniverseConstraints do if binders.isEmpty then k #[] else elabBindersAux binders catchAutoBoundImplicit k @[inline] def elabBinder {α} (binder : Syntax) (x : Expr → TermElabM α) (catchAutoBoundImplicit := false) : TermElabM α := elabBinders #[binder] (catchAutoBoundImplicit := catchAutoBoundImplicit) (fun fvars => x (fvars.get! 0)) @[builtinTermElab «forall»] def elabForall : TermElab := fun stx _ => match stx with | `(forall $binders*, $term) => elabBinders binders fun xs => do let e ← elabType term mkForallFVars xs e | _ => throwUnsupportedSyntax @[builtinTermElab arrow] def elabArrow : TermElab := adaptExpander fun stx => match stx with | `($dom:term -> $rng) => `(forall (a : $dom), $rng) | _ => throwUnsupportedSyntax @[builtinTermElab depArrow] def elabDepArrow : TermElab := fun stx _ => -- bracketedBinder `->` term let binder := stx[0] let term := stx[2] elabBinders #[binder] fun xs => do mkForallFVars xs (← elabType term) /-- Auxiliary functions for converting `id_1 ... id_n` application into `#[id_1, ..., id_m]` It is used at `expandFunBinders`. -/ private partial def getFunBinderIds? (stx : Syntax) : OptionT TermElabM (Array Syntax) := let convertElem (stx : Syntax) : OptionT TermElabM Syntax := match stx with | `(_) => do let ident ← mkFreshIdent stx; pure ident | `($id:ident) => pure id | _ => failure match stx with | `($f $args*) => do let mut acc := #[].push (← convertElem f) for arg in args do acc := acc.push (← convertElem arg) return acc | _ => return #[].push (← convertElem stx) /-- Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as ``` def funBinder : Parser := implicitBinder <|> instBinder <|> termParser maxPrec parser! unicodeSymbol "λ" "fun" >> many1 funBinder >> "=>" >> termParser ``` to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern. The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form ``` `(` ident `:` term `)` ``` which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax. We update the `body` syntax when expanding the pattern notation. Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`. See local function `processAsPattern` at `expandFunBindersAux`. The resulting `Bool` is true if a pattern was found. We use it "mark" a macro expansion. -/ partial def expandFunBinders (binders : Array Syntax) (body : Syntax) : TermElabM (Array Syntax × Syntax × Bool) := let rec loop (body : Syntax) (i : Nat) (newBinders : Array Syntax) := do if h : i < binders.size then let binder := binders.get ⟨i, h⟩ let processAsPattern : Unit → TermElabM (Array Syntax × Syntax × Bool) := fun _ => do let pattern := binder let major ← mkFreshIdent binder let (binders, newBody, _) ← loop body (i+1) (newBinders.push $ mkExplicitBinder major (mkHole binder)) let newBody ← `(match $major:ident with | $pattern => $newBody) pure (binders, newBody, true) match binder with | Syntax.node `Lean.Parser.Term.implicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.instBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.explicitBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.simpleBinder _ => loop body (i+1) (newBinders.push binder) | Syntax.node `Lean.Parser.Term.hole _ => let ident ← mkFreshIdent binder let type := binder loop body (i+1) (newBinders.push $ mkExplicitBinder ident type) | Syntax.node `Lean.Parser.Term.paren args => -- `(` (termParser >> parenSpecial)? `)` -- parenSpecial := (tupleTail <|> typeAscription)? let binderBody := binder[1] if binderBody.isNone then processAsPattern () else let idents := binderBody[0] let special := binderBody[1] if special.isNone then processAsPattern () else if special[0].getKind != `Lean.Parser.Term.typeAscription then processAsPattern () else -- typeAscription := `:` term let type := special[0][1] match (← getFunBinderIds? idents) with | some idents => loop body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type)) | none => processAsPattern () | Syntax.ident _ _ _ _ => let type := mkHole binder loop body (i+1) (newBinders.push $ mkExplicitBinder binder type) | _ => processAsPattern () else pure (newBinders, body, false) loop body 0 #[] namespace FunBinders structure State where fvars : Array Expr := #[] lctx : LocalContext localInsts : LocalInstances expectedType? : Option Expr := none private def propagateExpectedType (fvar : Expr) (fvarType : Expr) (s : State) : TermElabM State := do match s.expectedType? with | none => pure s | some expectedType => let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ d b _ => discard <| isDefEq fvarType d let b := b.instantiate1 fvar pure { s with expectedType? := some b } | _ => pure { s with expectedType? := none } private partial def elabFunBinderViews (binderViews : Array BinderView) (i : Nat) (s : State) : TermElabM State := if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩ withRef binderView.type $ withLCtx s.lctx s.localInsts do let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type let fvarId ← mkFreshFVarId let fvar := mkFVar fvarId let s := { s with fvars := s.fvars.push fvar } -- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type) /- We do **not** want to support default and auto arguments in lambda abstractions. Example: `fun (x : Nat := 10) => x+1`. We do not believe this is an useful feature, and it would complicate the logic here. -/ let lctx := s.lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi let s ← withRef binderView.id $ propagateExpectedType fvar type s let s := { s with lctx := lctx } match (← isClass? type) with | none => elabFunBinderViews binderViews (i+1) s | some className => resettingSynthInstanceCache do let localInsts := s.localInsts.push { className := className, fvar := mkFVar fvarId } elabFunBinderViews binderViews (i+1) { s with localInsts := localInsts } else pure s partial def elabFunBindersAux (binders : Array Syntax) (i : Nat) (s : State) : TermElabM State := do if h : i < binders.size then let binderViews ← matchBinder (binders.get ⟨i, h⟩) let s ← elabFunBinderViews binderViews 0 s elabFunBindersAux binders (i+1) s else pure s end FunBinders def elabFunBinders {α} (binders : Array Syntax) (expectedType? : Option Expr) (x : Array Expr → Option Expr → TermElabM α) : TermElabM α := if binders.isEmpty then x #[] expectedType? else do let lctx ← getLCtx let localInsts ← getLocalInstances let s ← FunBinders.elabFunBindersAux binders 0 { lctx := lctx, localInsts := localInsts, expectedType? := expectedType? } resettingSynthInstanceCacheWhen (s.localInsts.size > localInsts.size) $ withLCtx s.lctx s.localInsts $ x s.fvars s.expectedType? /- Helper function for `expandEqnsIntoMatch` -/ private def getMatchAltsNumPatterns (matchAlts : Syntax) : Nat := let alt0 := matchAlts[0][0] let pats := alt0[1].getSepArgs pats.size def expandWhereDecls (whereDecls : Syntax) (body : Syntax) : MacroM Syntax := match whereDecls with | `(whereDecls|where $[$decls:letRecDecl $[;]?]*) => `(let rec $decls:letRecDecl,*; $body) | _ => unreachable! def expandWhereDeclsOpt (whereDeclsOpt : Syntax) (body : Syntax) : MacroM Syntax := if whereDeclsOpt.isNone then body else expandWhereDecls whereDeclsOpt[0] body /- Helper function for `expandMatchAltsIntoMatch` -/ private def expandMatchAltsIntoMatchAux (matchAlts : Syntax) (matchTactic : Bool) : Nat → Array Syntax → MacroM Syntax | 0, discrs => do if matchTactic then `(tactic|match $[$discrs:term],* with $matchAlts:matchAlts) else `(match $[$discrs:term],* with $matchAlts:matchAlts) | n+1, discrs => withFreshMacroScope do let x ← `(x) let body ← expandMatchAltsIntoMatchAux matchAlts matchTactic n (discrs.push x) if matchTactic then `(tactic| intro $x:term; $body:tactic) else `(@fun $x => $body) /-- Expand `matchAlts` syntax into a full `match`-expression. Example ``` | 0, true => alt_1 | i, _ => alt_2 ``` expands into (for tactic == false) ``` fun x_1 x_2 => match x_1, x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` and (for tactic == true) ``` intro x_1; intro x_2; match x_1, x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` -/ def expandMatchAltsIntoMatch (ref : Syntax) (matchAlts : Syntax) (tactic := false) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts tactic (getMatchAltsNumPatterns matchAlts) #[] def expandMatchAltsIntoMatchTactic (ref : Syntax) (matchAlts : Syntax) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts true (getMatchAltsNumPatterns matchAlts) #[] /-- Similar to `expandMatchAltsIntoMatch`, but supports an optional `where` clause. Expand `matchAltsWhereDecls` into `let rec` + `match`-expression. Example ``` | 0, true => ... f 0 ... | i, _ => ... f i + g i ... where f x := g x + 1 g : Nat → Nat | 0 => 1 | x+1 => f x ``` expands into ``` fux x_1 x_2 => let rec f x := g x + 1, g : Nat → Nat | 0 => 1 | x+1 => f x match x_1, x_2 with | 0, true => ... f 0 ... | i, _ => ... f i + g i ... ``` -/ def expandMatchAltsWhereDecls (matchAltsWhereDecls : Syntax) : MacroM Syntax := let matchAlts := matchAltsWhereDecls[0] let whereDeclsOpt := matchAltsWhereDecls[1] let rec loop (i : Nat) (discrs : Array Syntax) : MacroM Syntax := match i with | 0 => do let matchStx ← `(match $[$discrs:term],* with $matchAlts:matchAlts) if whereDeclsOpt.isNone then return matchStx else expandWhereDeclsOpt whereDeclsOpt matchStx | n+1 => withFreshMacroScope do let x ← `(x) let body ← loop n (discrs.push x) `(@fun $x => $body) loop (getMatchAltsNumPatterns matchAlts) #[] @[builtinTermElab «fun»] def elabFun : TermElab := fun stx expectedType? => match stx with | `(fun $binders* => $body) => do let (binders, body, expandedPattern) ← expandFunBinders binders body if expandedPattern then let newStx ← `(fun $binders* => $body) withMacroExpansion stx newStx $ elabTerm newStx expectedType? else elabFunBinders binders expectedType? fun xs expectedType? => do /- We ensure the expectedType here since it will force coercions to be applied if needed. If we just use `elabTerm`, then we will need to a coercion `Coe (α → β) (α → δ)` whenever there is a coercion `Coe β δ`, and another instance for the dependent version. -/ let e ← elabTermEnsuringType body expectedType? mkLambdaFVars xs e | `(fun $m:matchAlts) => do let stxNew ← liftMacroM $ expandMatchAltsIntoMatch stx m withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax /- If `useLetExpr` is true, then a kernel let-expression `let x : type := val; body` is created. Otherwise, we create a term of the form `(fun (x : type) => body) val` The default elaboration order is `binders`, `typeStx`, `valStx`, and `body`. If `elabBodyFirst == true`, then we use the order `binders`, `typeStx`, `body`, and `valStx`. -/ def elabLetDeclAux (n : Name) (binders : Array Syntax) (typeStx : Syntax) (valStx : Syntax) (body : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do let (type, val, arity) ← elabBinders binders fun xs => do let type ← elabType typeStx registerCustomErrorIfMVar type typeStx "failed to infer 'let' declaration type" if elabBodyFirst then let type ← mkForallFVars xs type let val ← mkFreshExprMVar type pure (type, val, xs.size) else let val ← elabTermEnsuringType valStx type let type ← mkForallFVars xs type let val ← mkLambdaFVars xs val pure (type, val, xs.size) trace[Elab.let.decl]! "{n} : {type} := {val}" let result ← if useLetExpr then withLetDecl n type val fun x => do let body ← elabTerm body expectedType? let body ← instantiateMVars body mkLetFVars #[x] body else let f ← withLocalDecl n BinderInfo.default type fun x => do let body ← elabTerm body expectedType? let body ← instantiateMVars body mkLambdaFVars #[x] body pure $ mkApp f val if elabBodyFirst then forallBoundedTelescope type arity fun xs type => do let valResult ← elabTermEnsuringType valStx type let valResult ← mkLambdaFVars xs valResult unless (← isDefEq val valResult) do throwError "unexpected error when elaborating 'let'" pure result structure LetIdDeclView where id : Name binders : Array Syntax type : Syntax value : Syntax def mkLetIdDeclView (letIdDecl : Syntax) : LetIdDeclView := -- `letIdDecl` is of the form `ident >> many bracketedBinder >> optType >> " := " >> termParser let id := letIdDecl[0].getId let binders := letIdDecl[1].getArgs let optType := letIdDecl[2] let type := expandOptType letIdDecl optType let value := letIdDecl[4] { id := id, binders := binders, type := type, value := value } private def expandLetEqnsDeclVal (ref : Syntax) (alts : Syntax) : Nat → Array Syntax → MacroM Syntax | 0, discrs => pure $ Syntax.node `Lean.Parser.Term.match #[mkAtomFrom ref "match ", mkNullNode discrs, mkNullNode, mkAtomFrom ref " with ", alts] | n+1, discrs => withFreshMacroScope do let x ← `(x) let discrs := if discrs.isEmpty then discrs else discrs.push $ mkAtomFrom ref ", " let discrs := discrs.push $ Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, x] let body ← expandLetEqnsDeclVal ref alts n discrs `(fun $x => $body) def expandLetEqnsDecl (letDecl : Syntax) : MacroM Syntax := do let ref := letDecl let matchAlts := letDecl[3] let val ← expandMatchAltsIntoMatch ref matchAlts pure $ Syntax.node `Lean.Parser.Term.letIdDecl #[letDecl[0], letDecl[1], letDecl[2], mkAtomFrom ref " := ", val] def elabLetDeclCore (stx : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do let ref := stx let letDecl := stx[1][0] let body := stx[3] if letDecl.getKind == `Lean.Parser.Term.letIdDecl then let { id := id, binders := binders, type := type, value := val } := mkLetIdDeclView letDecl elabLetDeclAux id binders type val body expectedType? useLetExpr elabBodyFirst else if letDecl.getKind == `Lean.Parser.Term.letPatDecl then -- node `Lean.Parser.Term.letPatDecl $ try (termParser >> pushNone >> optType >> " := ") >> termParser let pat := letDecl[0] let optType := letDecl[2] let type := expandOptType stx optType let val := letDecl[4] let stxNew ← `(let x : $type := $val; match x with | $pat => $body) let stxNew := match useLetExpr, elabBodyFirst with | true, false => stxNew | true, true => stxNew.setKind `Lean.Parser.Term.«let*» | false, true => stxNew.setKind `Lean.Parser.Term.«let!» | false, false => unreachable! withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? else if letDecl.getKind == `Lean.Parser.Term.letEqnsDecl then let letDeclIdNew ← liftMacroM $ expandLetEqnsDecl letDecl let declNew := stx[1].setArg 0 letDeclIdNew let stxNew := stx.setArg 1 declNew withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? else throwUnsupportedSyntax @[builtinTermElab «let»] def elabLetDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? true false @[builtinTermElab «let!»] def elabLetBangDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? false false @[builtinTermElab «let*»] def elabLetStarDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? true true builtin_initialize registerTraceClass `Elab.let end Lean.Elab.Term
3ff6c24e8e422ca40da217e7188b849f0db8dba7
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/data/polynomial.lean
5464b6fa0250ceec3b24f76ec8e1b5c0f88730e0
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
106,717
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 Theory of univariate polynomials, represented as `add_monoid_algebra R ℕ`, where `R` is a commutative semiring. -/ import data.monoid_algebra import algebra.gcd_domain import ring_theory.euclidean_domain import ring_theory.multiplicity import tactic.ring_exp noncomputable theory local attribute [instance, priority 100] classical.prop_decidable local attribute [instance, priority 10] is_semiring_hom.comp is_ring_hom.comp /-- `polynomial R` is the type of univariate polynomials over `R`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from `R` is called `C`. -/ def polynomial (R : Type*) [comm_semiring R] := add_monoid_algebra R ℕ open finsupp finset add_monoid_algebra namespace polynomial universes u v w x y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type x} {k : Type y} {A : Type z} {a b : R} {m n : ℕ} section comm_semiring variables [comm_semiring R] {p q r : polynomial R} instance : inhabited (polynomial R) := finsupp.inhabited instance : comm_semiring (polynomial R) := add_monoid_algebra.comm_semiring instance : has_scalar R (polynomial R) := add_monoid_algebra.has_scalar instance : semimodule R (polynomial R) := add_monoid_algebra.semimodule /-- the coercion turning a `polynomial` into the function which reports the coefficient of a given monomial `X^n` -/ def coeff_coe_to_fun : has_coe_to_fun (polynomial R) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun @[simp] lemma support_zero : (0 : polynomial R).support = ∅ := rfl /-- `monomial s a` is the monomial `a * X^s` -/ @[reducible] def monomial (n : ℕ) (a : R) : polynomial R := finsupp.single n a /-- `C a` is the constant polynomial `a`. -/ def C (a : R) : polynomial R := monomial 0 a /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial R := monomial 1 1 /-- coeff p n is the coefficient of X^n in p -/ def coeff (p : polynomial R) := p.to_fun @[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial R) = f := rfl instance [has_repr R] : has_repr (polynomial R) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ theorem ext_iff {p q : polynomial R} : p = q ↔ ∀ n, coeff p n = coeff q n := ⟨λ h n, h ▸ rfl, finsupp.ext⟩ @[ext] lemma ext {p q : polynomial R} : (∀ n, coeff p n = coeff q n) → p = q := (@ext_iff _ _ p q).2 /-- `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 : polynomial R) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial R, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial R) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial R) : ℕ := (degree p).get_or_else 0 lemma single_eq_C_mul_X : ∀{n}, monomial n a = C a * X^n | 0 := (mul_one _).symm | (n+1) := calc monomial (n + 1) a = monomial n a * X : by rw [X, single_mul_single, mul_one] ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one] lemma sum_C_mul_X_eq (p : polynomial R) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) (finsupp.sum_single _) @[elab_as_eliminator] protected lemma induction_on {M : polynomial R → Prop} (p : polynomial R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by { convert this, exact single_zero.symm, }, h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by { convert this, exact single_eq_C_mul_X }, h_add _ _ this hp) @[simp] lemma C_0 : C (0 : R) = 0 := single_zero @[simp] lemma C_1 : C (1 : R) = 1 := rfl @[simp] lemma C_mul : C (a * b) = C a * C b := (@single_mul_single _ _ _ _ 0 0 a b).symm @[simp] lemma C_add : C (a + b) = C a + C b := finsupp.single_add instance C.is_semiring_hom : is_semiring_hom (C : R → polynomial R) := ⟨C_0, C_1, λ _ _, C_add, λ _ _, C_mul⟩ @[simp] lemma C_pow : C (a ^ n) = C a ^ n := is_semiring_hom.map_pow _ _ _ lemma nat_cast_eq_C (n : ℕ) : (n : polynomial R) = C n := ((ring_hom.of C).map_nat_cast n).symm section coeff lemma apply_eq_coeff : p n = coeff p n := rfl @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial R) n = 0 := rfl lemma coeff_single : coeff (single n a) m = if n = m then a else 0 := by { dsimp [single, finsupp.single], congr } @[simp] lemma coeff_one_zero : coeff (1 : polynomial R) 0 = 1 := coeff_single @[simp] lemma coeff_add (p q : polynomial R) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl instance coeff.is_add_monoid_hom {n : ℕ} : is_add_monoid_hom (λ p : polynomial R, p.coeff n) := { map_add := λ p q, coeff_add p q n, map_zero := coeff_zero _ } lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 := by simp [coeff, eq_comm, C, monomial, single]; congr @[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_single @[simp] lemma coeff_X_one : coeff (X : polynomial R) 1 = 1 := coeff_single @[simp] lemma coeff_X_zero : coeff (X : polynomial R) 0 = 0 := coeff_single lemma coeff_X : coeff (X : polynomial R) n = if 1 = n then 1 else 0 := coeff_single lemma coeff_C_mul_X (x : R) (k n : ℕ) : coeff (C x * X^k : polynomial R) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [monomial, single, eq_comm, coeff]; congr lemma coeff_sum [comm_semiring S] (n : ℕ) (f : ℕ → R → polynomial S) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply @[simp] lemma coeff_C_mul (p : polynomial R) : coeff (C a * p) n = a * coeff p n := begin conv in (a * _) { rw [← @sum_single _ _ _ p, coeff_sum] }, rw [mul_def, C, sum_single_index], { simp [coeff_single, finsupp.mul_sum, coeff_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, { simp [finsupp.sum] } end @[simp] lemma coeff_smul (p : polynomial R) (r : R) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply lemma C_mul' (a : R) (f : polynomial R) : C a * f = a • f := ext $ λ n, coeff_C_mul f @[simp, priority 990] lemma coeff_one (n : ℕ) : coeff (1 : polynomial R) n = if 0 = n then 1 else 0 := coeff_single @[simp] lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial R) n = if n = k then 1 else 0 := by simpa only [C_1, one_mul] using coeff_C_mul_X (1:R) k n lemma coeff_mul (p q : polynomial R) (n : ℕ) : coeff (p * q) n = (nat.antidiagonal n).sum (λ x, coeff p x.1 * coeff q x.2) := have hite : ∀ a : ℕ × ℕ, ite (a.1 + a.2 = n) (coeff p (a.fst) * coeff q (a.snd)) 0 ≠ 0 → a.1 + a.2 = n, from λ a ha, by_contradiction (λ h, absurd (eq.refl (0 : R)) (by rwa if_neg h at ha)), calc coeff (p * q) n = p.support.sum (λ a, q.support.sum (λ b, ite (a + b = n) (coeff p a * coeff q b) 0)) : by simp only [mul_def, coeff_sum, coeff_single]; refl ... = (p.support.product q.support).sum (λ v : ℕ × ℕ, ite (v.1 + v.2 = n) (coeff p v.1 * coeff q v.2) 0) : by rw sum_product ... = (nat.antidiagonal n).sum (λ x, coeff p x.1 * coeff q x.2) : begin refine sum_bij_ne_zero (λ x _ _, x) (λ x _ hx, nat.mem_antidiagonal.2 (hite x hx)) (λ _ _ _ _ _ _ h, h) (λ x h₁ h₂, ⟨x, _, _, rfl⟩) _, { rw [mem_product, mem_support_iff, mem_support_iff], exact ⟨ne_zero_of_mul_ne_zero_right h₂, ne_zero_of_mul_ne_zero_left h₂⟩ }, { rw nat.mem_antidiagonal at h₁, rwa [if_pos h₁] }, { intros x h hx, rw [if_pos (hite x hx)] } end theorem coeff_mul_X_pow (p : polynomial R) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end theorem coeff_mul_X (p : polynomial R) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial R} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n) end coeff lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩ section eval₂ variables [semiring S] variables (f : R → S) (x : S) open is_semiring_hom /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial R) : S := p.sum (λ e a, f a * x ^ e) variables [is_semiring_hom f] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [map_one f, one_mul, pow_one] @[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [map_zero f, zero_mul]) (λ _ _ _, by rw [map_add f, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 := by rw [← C_1, eval₂_C, map_one f] instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } end eval₂ section eval₂ variables [comm_semiring S] variables (f : R → S) [is_semiring_hom f] (x : S) open is_semiring_hom @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin dunfold eval₂, rw [mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, map_mul f, pow_add], { simp only [mul_assoc, mul_left_comm] }, { rw [map_zero f, zero_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x) : polynomial R →+* S := ring_hom.of (eval₂ f x) @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _ lemma eval₂_sum (p : polynomial R) (g : ℕ → R → polynomial R) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) end eval₂ section eval variable {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → polynomial R → R := eval₂ id @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval₂_hom [comm_semiring S] (f : R → S) [is_semiring_hom f] (x : R) : p.eval₂ f (f x) = f (p.eval x) := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, eval_pow, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] lemma coeff_zero_eq_eval_zero (p : polynomial R) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp end eval section comp def comp (p q : polynomial R) : polynomial R := p.eval₂ C q lemma eval₂_comp [comm_semiring S] (f : R → S) [is_semiring_hom f] {x : S} : (p.comp q).eval₂ f x = p.eval₂ f (q.eval₂ f x) := show (p.sum (λ e a, C a * q ^ e)).eval₂ f x = p.eval₂ f (eval₂ f x q), by simp only [eval₂_mul, eval₂_C, eval₂_pow, eval₂_sum]; refl lemma eval_comp : (p.comp q).eval a = p.eval (q.eval a) := eval₂_comp _ @[simp] lemma comp_X : p.comp X = p := begin refine ext (λ n, _), rw [comp, eval₂], conv in (C _ * _) { rw ← single_eq_C_mul_X }, rw finsupp.sum_single end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, finsupp.sum], rw [← p.support.sum_hom (@C R _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial R) p = 1 := by rw [← C_1, C_comp] instance : is_semiring_hom (λ q : polynomial R, q.comp p) := by unfold comp; apply_instance @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma mul_comp : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ end comp /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial R) := leading_coeff p = (1 : R) 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 : polynomial R} (hp : p.monic) : leading_coeff p = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial R) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial R) = 0 := rfl @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial R) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le 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⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := classical.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 : polynomial R} {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 : polynomial R} {n : ℕ} (hn : n > 0) : 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 : polynomial R} {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 := begin by_cases hp : p = 0, { rw hp, exact bot_le }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq [comm_semiring S] {q : polynomial S} (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 (finsupp.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 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 @[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 : polynomial R) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial R) = 0 := by simp [nat_cast_eq_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h) 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 : polynomial R} {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 -- TODO find a home (this file) @[simp] lemma finset_sum_coeff (s : finset ι) (f : ι → polynomial R) (n : ℕ) : coeff (s.sum f) n = s.sum (λ b, coeff (f b) n) := (s.sum_hom (λ q : polynomial R, q.coeff n)).symm -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial R) (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 (p : polynomial R) : p = (range (p.nat_degree + 1)).sum (λ i, C (p.coeff i) * X^i) := begin ext n, simp only [add_comm, coeff_X_pow, coeff_C_mul, finset.mem_range, finset.sum_mul_boole, finset_sum_coeff, ite_le_nat_degree_coeff], end lemma monic.as_sum {p : polynomial R} (hp : p.monic) : p = X^(p.nat_degree) + ((finset.range p.nat_degree).sum $ λ i, C (p.coeff i) * X^i) := begin conv_lhs { rw [p.as_sum, finset.sum_range_succ] }, suffices : C (p.coeff p.nat_degree) = 1, { rw [this, one_mul] }, exact congr_arg C hp end section map variables [comm_semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial R → polynomial S := eval₂ (C ∘ f) X instance is_semiring_hom_C_f : is_semiring_hom (C ∘ f) := is_semiring_hom.comp _ _ @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _ instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _ @[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _ lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum, ← p.support.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, is_semiring_hom.map_mul f], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map [comm_semiring T] (g : S →+* T) (p : polynomial R) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) lemma eval₂_map [comm_semiring T] (g : S → T) [is_semiring_hom g] (x : T) : (p.map f).eval₂ g x = p.eval₂ (λ y, g (f y)) x := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := eval₂_map _ _ _ @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma mem_map_range {p : polynomial S} : p ∈ set.range (map f) ↔ ∀ n, p.coeff n ∈ (set.range f) := begin split, { rintro ⟨p, rfl⟩ n, rw coeff_map, exact set.mem_range_self _ }, { intro h, rw p.as_sum, apply is_add_submonoid.finset_sum_mem, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [map_mul, map_C, hc, map_pow, map_X] } end end map section variables [comm_semiring S] [comm_semiring T] variables (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g ∘ f) (g x) := begin apply polynomial.induction_on p; clear p, { intros a, rw [eval₂_C, eval₂_C] }, { intros p q hp hq, simp only [hp, hq, eval₂_add, is_semiring_hom.map_add g] }, { intros n a ih, replace ih := congr_arg (λ y, y * g x) ih, simpa [pow_succ', is_semiring_hom.map_mul g, (mul_assoc _ _ _).symm, eval₂_C, eval₂_mul, eval₂_X] using ih } end end 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 eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin refine ext (λ n, _), cases n, { simp }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] } 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_refl _) 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 : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial R) = 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_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_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_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | 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 [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial R) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset ι) (f : ι → polynomial R) : degree (s.sum f) ≤ 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 ((insert a s).sum f) ≤ max (degree (f a)) (degree (s.sum f)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial R) : 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)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ 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_monomial_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 : polynomial R) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p) | 0 := by rw [pow_zero, add_monoid.zero_smul]; 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_smul; exact add_le_add' (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact @finsupp.single_eq_same _ _ _ n a } end @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial R) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial R) := leading_coeff_C _ lemma monic.ne_zero_of_zero_ne_one (h : (0:R) ≠ 1) {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { contrapose! h, rwa [h] at hp } lemma monic.ne_zero {R : Type*} [nonzero_comm_ring R] {p : polynomial R} (hp : p.monic) : p ≠ 0 := hp.ne_zero_of_zero_ne_one $ zero_ne_one 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_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 : polynomial R) : 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) = (nat.antidiagonal (nat_degree p + nat_degree q)).sum (λ x, 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_eq' (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 nat_degree_mul_eq' (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]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, 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_eq' h, coeff_mul_degree_add_degree], refl end 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_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = add_monoid.smul n (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, add_monoid.zero_smul] | (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_eq' h₂, succ_smul, degree_pow_eq' h₁] lemma nat_degree_pow_eq' {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_eq' h, degree_eq_nat_degree hp0, ← with_bot.coe_smul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial R) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : R) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial R) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (degree q) : add_le_add' degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + add_monoid.smul n (nat_degree q) : add_le_add_left' (add_monoid.smul_le_smul_of_le_right (@degree_le_nat_degree _ _ q) n) ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_smul, add_monoid.smul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_le [comm_semiring S] (f : R →+* S) : degree (p.map f) ≤ degree p := if h : p.map f = 0 then by simp [h] else begin rw [degree_eq_nat_degree h], refine le_degree_of_ne_zero (mt (congr_arg f) _), rw [← coeff_map f, is_semiring_hom.map_zero f], exact mt leading_coeff_eq_zero.1 h end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial R)) : (∀ p q : polynomial R, 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 degree_map_eq_of_leading_coeff_ne_zero [comm_semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma monic_map [comm_semiring S] (f : R →+* S) (hp : monic p) : monic (p.map f) := if h : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one S h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by erw [monic, leading_coeff, nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f this), coeff_map, ← leading_coeff, show _ = _, from hp, is_semiring_hom.map_one f] lemma zero_le_degree_iff {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial @[simp] lemma coeff_mul_X_zero (p : polynomial R) : coeff (p * X) 0 = 0 := by rw [coeff_mul, nat.antidiagonal_zero]; simp only [polynomial.coeff_X_zero, finset.insert_empty_eq_singleton, finset.sum_singleton, mul_zero] end comm_semiring instance subsingleton [subsingleton R] [comm_semiring R] : subsingleton (polynomial R) := ⟨λ _ _, ext (λ _, subsingleton.elim _ _)⟩ section comm_semiring variables [comm_semiring R] {p q r : polynomial R} lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : R) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc 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_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) theorem degree_C_mul_X_pow_le (r : R) (n : ℕ) : degree (C r * X^n) ≤ n := begin rw [← single_eq_C_mul_X], refine finset.sup_le (λ b hb, _), rw list.eq_of_mem_singleton (finsupp.support_single_subset hb), exact le_refl _ end theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial R) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:R) n theorem degree_X_le : degree (X : polynomial R) ≤ 1 := by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:R) 1 section injective open function variables [comm_semiring S] {f : R →+* S} (hf : function.injective f) include hf lemma degree_map_eq_of_injective (p : polynomial R) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma degree_map' (p : polynomial R) : degree (p.map f) = degree p := p.degree_map_eq_of_injective hf lemma nat_degree_map' (p : polynomial R) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' hf p) lemma map_injective : injective (map f) := λ p q h, ext $ λ m, hf $ begin rw ext_iff at h, specialize h m, rw [coeff_map f, coeff_map f] at h, exact h end lemma leading_coeff_of_injective (p : polynomial R) : leading_coeff (p.map f) = f (leading_coeff p) := begin delta leading_coeff, rw [coeff_map f, nat_degree_map' hf p] end lemma monic_of_injective {p : polynomial R} (hp : (p.map f).monic) : p.monic := begin apply hf, rw [← leading_coeff_of_injective hf, hp.leading_coeff, is_semiring_hom.map_one f] end end injective theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, @subsingleton.elim _ (subsingleton_of_zero_eq_one R $ H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : R) : monic (X + C x) := pow_one (X : polynomial R) ▸ monic_X_pow_add degree_C_le theorem degree_le_iff_coeff_zero (f : polynomial R) (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 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem nat_degree_le_of_degree_le {p : polynomial R} {n : ℕ} (H : degree p ≤ n) : nat_degree p ≤ n := show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with | none, H := zero_le _ | (some d), H := with_bot.coe_le_coe.1 H end theorem leading_coeff_mul_X_pow {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (assume H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (assume H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : R) = 1 then by haveI := subsingleton_of_zero_eq_one _ h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := monic_mul hp (monic_pow n) lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : R) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hpn0 : p ^ (nat_degree q + 1) ≠ 0, from mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul_eq' hpnr0, nat_degree_pow_eq' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right' (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section nonzero_comm_semiring variables [nonzero_comm_semiring R] {p q : polynomial R} instance : nonzero_comm_semiring (polynomial R) := { zero_ne_one := λ (h : (0 : polynomial R) = 1), @zero_ne_one R _ $ calc (0 : R) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C, ..polynomial.comm_semiring } @[simp] lemma degree_one : degree (1 : polynomial R) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial R) = 1 := begin unfold X degree monomial single finsupp.support, rw if_neg (zero_ne_one).symm, refl end lemma X_ne_zero : (X : polynomial R) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial R) ^ n) = n | 0 := by simp only [pow_zero, degree_one]; refl | (n+1) := have h : leading_coeff (X : polynomial R) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl @[simp] lemma not_monic_zero : ¬monic (0 : polynomial R) := by simpa only [monic, leading_coeff_zero] using zero_ne_one lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero R _ (h₁ ▸ h) end nonzero_comm_semiring section comm_semiring variables [comm_semiring R] {p q : polynomial R} /-- `dix_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : polynomial R) : polynomial R := { to_fun := λ n, p.coeff (n + 1), support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1), multiset.nodup_map_on begin simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter], assume x hx y hy hxy, rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2, nat.sub_add_cancel hy.2] at hxy end (p.support.filter (> 0)).2⟩, mem_support_to_fun := λ n, suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔ ¬coeff p (n + 1) = 0, by simpa [finset.mem_def.symm, apply_eq_coeff], ⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1, λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ } lemma div_X_mul_X_add (p : polynomial R) : div_X p * X + C (p.coeff 0) = p := ext $ λ n, nat.cases_on n (by simp) (by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X]) @[simp] lemma div_X_C (a : R) : div_X (C a) = 0 := ext $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := ext $ by simp [div_X] def nonzero_comm_semiring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_semiring R := { zero_ne_one := λ h01 : 0 = 1, h $ by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero], ..show comm_semiring R, by apply_instance } lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul_eq' 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 degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by letI := nonzero_comm_semiring.of_polynomial_ne hp0; exact calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : polynomial R) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul_eq' this]; exact add_le_add' (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [add_comm, degree_add_eq_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : by rw div_X_mul_X_add @[elab_as_eliminator] noncomputable def rec_on_horner {M : polynomial R → Sort*} : Π (p : polynomial R), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial R → Prop} (p : polynomial R) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, nat.not_lt_zero] using h0')) h0 end comm_semiring section comm_ring variables [comm_ring R] {p q : polynomial R} instance : comm_ring (polynomial R) := add_monoid_algebra.comm_ring instance : module R (polynomial R) := add_monoid_algebra.module variable (R) def lcoeff (n : ℕ) : polynomial R →ₗ R := { to_fun := λ f, coeff f n, add := λ f g, coeff_add f g n, smul := λ r p, coeff_smul p r n } variable {R} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial R) : lcoeff R n f = coeff f n := rfl instance C.is_ring_hom : is_ring_hom (@C R _) := by apply is_ring_hom.of_semiring lemma int_cast_eq_C (n : ℤ) : (n : polynomial R) = C n := ((ring_hom.of C).map_int_cast n).symm @[simp] lemma C_neg : C (-a) = -C a := is_ring_hom.map_neg C @[simp] lemma C_sub : C (a - b) = C a - C b := is_ring_hom.map_sub C instance eval₂.is_ring_hom {S} [comm_ring S] (f : R → S) [is_ring_hom f] {x : S} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : R} : is_ring_hom (eval x) := eval₂.is_ring_hom _ instance map.is_ring_hom {S} [comm_ring S] (f : R →+* S) : is_ring_hom (map f) := eval₂.is_ring_hom (C ∘ f) @[simp] lemma map_sub {S} [comm_ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {S} [comm_ring S] (f : R →+* S) : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma degree_neg (p : polynomial R) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma nat_degree_neg (p : polynomial R) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial R) = 0 := by simp [int_cast_eq_C] @[simp] lemma coeff_neg (p : polynomial R) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] lemma coeff_sub (p q : polynomial R) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl @[simp] lemma eval₂_neg {S} [comm_ring S] (f : R → S) [is_ring_hom f] {x : S} : (-p).eval₂ f x = -p.eval₂ f x := is_ring_hom.map_neg _ @[simp] lemma eval₂_sub {S} [comm_ring S] (f : R → S) [is_ring_hom f] {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := is_ring_hom.map_sub _ @[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ @[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ section aeval /-- `R[X]` is the generator of the category `R-Alg`. -/ instance polynomial (R : Type u) [comm_semiring R] : algebra R (polynomial R) := { commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (polynomial.C_mul' c p).symm, .. polynomial.semimodule, .. ring_hom.of polynomial.C } variables (R) (A) variables [comm_ring A] [algebra R A] variables (x : A) /-- Given a valuation `x` of the variable in an `R`-algebra `A`, `aeval R A x` is the unique `R`-algebra homomorphism from `R[X]` to `A` sending `X` to `x`. -/ def aeval : polynomial R →ₐ[R] A := { commutes' := λ r, eval₂_C _ _, ..eval₂_ring_hom (algebra_map R A) x } variables {R A} theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map R A) x p := rfl @[simp] lemma aeval_X : aeval R A x X = x := eval₂_X _ x @[simp] lemma aeval_C (r : R) : aeval R A x (C r) = algebra_map R A r := eval₂_C _ x theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map R A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [φ.map_add, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, φ.map_mul, eval₂_mul (algebra_map R A), eval₂_X, ih] } end end aeval 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 : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_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 ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 | h := begin rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) noncomputable def div_mod_by_monic_aux : Π (p : polynomial R) {q : polynomial R}, monic q → polynomial R × polynomial R | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial R) {q : polynomial R} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) @[simp] lemma zero_mod_by_monic (p : polynomial R) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial R) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial R) : p %ₘ 0 = p := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial R) : p /ₘ 0 = 0 := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial R), p = 0, from λ p, (@subsingleton_of_monic_zero R _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial R) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial R) {q : polynomial R} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end lemma div_mod_by_monic_unique {f g} (q r : polynomial R) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero (hg0 ▸ hg : monic (0 : polynomial R))).1 _ _ else have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) : degree_add_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul_eq']; simpa [monic.def.1 hg]), ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := if h01 : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one S h01; exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩ else have h01R : (0 : R) ≠ 1, from mt (congr_arg f) (by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]), have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ ... < degree q : degree_mod_by_monic_lt _ hq $ (ne_zero_of_monic_of_zero_ne_one hq h01R) ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩), ⟨this.1.symm, this.2.symm⟩ lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ @[simp] lemma mod_by_monic_one (p : polynomial R) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero monic_one).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial R) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (finsupp.ext (λ n, show coeff p n = 0, from nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end theorem monic_X_sub_C (x : R) : monic (X - C x) := by simpa only [C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := monic_X_pow_add ((degree_neg p).symm ▸ H) theorem degree_mod_by_monic_le (p : polynomial R) {q : polynomial R} (hq : monic q) : degree (p %ₘ q) ≤ degree q := decidable.by_cases (assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq; have : (0:polynomial R) = 1 := (by rw [← C_0, ← C_1, hq]); rw [eq_zero_of_zero_eq_one _ this (p %ₘ q), eq_zero_of_zero_eq_one _ this q]; exact le_refl _) (assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H) lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] def nonzero_comm_ring.of_polynomial_ne (h : p ≠ q) : nonzero_comm_ring R := { zero := 0, one := 1, zero_ne_one := λ h01, h $ by rw [← one_mul p, ← one_mul q, ← C_1, ← h01, C_0, zero_mul, zero_mul], ..show comm_ring R, by apply_instance } end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring R] {p q : polynomial R} instance : nonzero_comm_ring (polynomial R) := { ..polynomial.nonzero_comm_semiring, ..polynomial.comm_ring } @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X R], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : polynomial R) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial R) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial R) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : polynomial R) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial R) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn; exact dec_trivial) end nonzero_comm_ring section comm_ring variables [comm_ring R] {p q : polynomial R} @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p %ₘ (X - C a) = C (p.eval a) := if h0 : (0 : R) = 1 then by letI := subsingleton_of_zero_eq_one R h0; exact subsingleton.elim _ _ else by letI : nonzero_comm_ring R := nonzero_comm_ring.of_ne h0; exact have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial R) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] section multiplicity def decidable_dvd_monic (p : polynomial R) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) open_locale classical lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : R) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact h0 (subsingleton.elim _ _)), by letI : nonzero_comm_ring R := { zero_ne_one := this, ..show comm_ring R, by apply_instance }; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 def root_multiplicity (a : R) (p : polynomial R) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial R) (a : R) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, roption.dom]; congr; funext; congr lemma pow_root_multiplicity_dvd (p : polynomial R) (a : R) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial R) (a : R) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial R} (a : R) (hp : p ≠ 0) : (p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 := begin letI : nonzero_comm_ring R := nonzero_comm_ring.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) _ hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring section integral_domain variables [integral_domain R] {p q : polynomial R} @[simp] lemma degree_mul_eq : 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_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow_eq (p : polynomial R) (n : ℕ) : degree (p ^ n) = add_monoid.smul n (degree p) := by induction n; [simp only [pow_zero, degree_one, add_monoid.zero_smul], simp only [*, pow_succ, succ_smul, degree_mul_eq]] @[simp] lemma leading_coeff_mul (p q : polynomial R) : 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 @[simp] lemma leading_coeff_pow (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := by induction n; [simp only [pow_zero, leading_coeff_one], simp only [*, pow_succ, leading_coeff_mul]] instance : integral_domain (polynomial R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, erw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero_comm_ring } lemma nat_degree_mul_eq (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul_eq] @[simp] lemma nat_degree_pow_eq (p : polynomial R) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow_eq' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul_eq, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) lemma exists_finset_roots : ∀ {p : polynomial R} (hp : p ≠ 0), ∃ s : finset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add' (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by simpa only [not_mem_empty, false_iff, not_exists] using h⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial R) : finset R := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ @[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : polynomial R) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots {R : Type*} [integral_domain R] (n : ℕ) (a : R) : finset R := roots ((X : polynomial R) ^ n - C a) @[simp] lemma mem_nth_roots {R : Type*} [integral_domain R] {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {R : Type*} [integral_domain R] (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : polynomial R) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← C_1, ← @is_ring_hom.map_sub _ _ _ _ (@C R _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa [← apply_eq_coeff, ← finsupp.mem_support_iff], dsimp [apply_eq_coeff], refine coeff_eq_zero_of_degree_lt _, rw [degree_mul_eq, degree_C this, degree_pow_eq, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_smul, add_monoid.smul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], exact (mul_lt_mul_right (nat.pos_of_ne_zero hqd0)).2 (lt_of_le_of_ne (with_bot.coe_le_coe.1 (by rw ← degree_eq_nat_degree hp0; exact le_sup hbs)) hbp) end (by rw [finsupp.mem_support_iff, apply_eq_coeff, ← leading_coeff, ne.def, leading_coeff_eq_zero, classical.not_not]; simp {contextual := tt}) ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow_eq], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial R) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul_eq hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial R)) : degree (u : polynomial R) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ @[simp] lemma nat_degree_coe_units (u : units (polynomial R)) : nat_degree (u : polynomial R) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) : coeff (u : polynomial R) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.coe_ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul_eq, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) end integral_domain section field variables [field R] {p q : polynomial R} instance : vector_space R (polynomial R) := finsupp.vector_space _ _ lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp; exact (hp $ is_unit.map' C $ is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))) lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := ⟨mt is_unit_iff_dvd_one.1 (λ ⟨q, hq⟩, absurd (congr_arg degree hq) (λ h, have degree q = 0, by rw [degree_one, degree_mul_eq, hp1, eq_comm, nat.with_bot.add_eq_zero_iff] at h; exact h.2, by simp [degree_mul_eq, this, degree_one, hp1] at h; exact absurd h dec_trivial)), λ q r hpqr, begin have := congr_arg degree hpqr, rw [hp1, degree_mul_eq, eq_comm, nat.with_bot.add_eq_one_iff] at this, rw [is_unit_iff_degree_eq_zero, is_unit_iff_degree_eq_zero]; tautology end⟩ lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial R) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq, degree_C h₁, add_zero] def div (p q : polynomial R) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) def mod (p q : polynomial R) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial R) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial R) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial R) := ⟨div⟩ instance : has_mod (polynomial R) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial R) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul_eq]} lemma degree_div_le (p q : polynomial R) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field k] (p : polynomial R) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective (is_ring_hom.injective f) @[simp] lemma nat_degree_map [field k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp [leading_coeff, coeff_map f] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [is_ring_hom.map_inv f, leading_coeff, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← is_ring_hom.map_inv f, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] @[simp] lemma map_eq_zero [field k] (f : R →+* k) : p.map f = 0 ↔ p = 0 := by simp [polynomial.ext_iff, is_ring_hom.map_eq_zero f, coeff_map] lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial R)) (n : ℕ) : ((↑u : polynomial R).coeff n)⁻¹ = ((↑u⁻¹ : polynomial R).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end instance : normalization_domain (polynomial R) := { norm_unit := λ p, if hp0 : p = 0 then 1 else ⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rw [← C_mul, inv_mul_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0, by rw [← C_mul, mul_inv_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0,⟩, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ p q hp0 hq0, begin rw [dif_neg hp0, dif_neg hq0, dif_neg (mul_ne_zero hp0 hq0)], apply units.ext, show C (leading_coeff (p * q))⁻¹ = C (leading_coeff p)⁻¹ * C (leading_coeff q)⁻¹, rw [leading_coeff_mul, mul_inv', C_mul, mul_comm] end, norm_unit_coe_units := λ u, have hu : degree ↑u⁻¹ = 0, from degree_eq_zero_of_is_unit ⟨u⁻¹, rfl⟩, begin apply units.ext, rw [dif_neg (units.coe_ne_zero u)], conv_rhs {rw eq_C_of_degree_eq_zero hu}, refine C_inj.2 _, rw [← nat_degree_eq_of_degree_eq_some hu, leading_coeff, coeff_inv_units], simp end, ..polynomial.integral_domain } lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := show leading_coeff (p * ↑(dite _ _ _)) = 1, by rw dif_neg hp0; exact monic_mul_leading_coeff_inv hp0 lemma coe_norm_unit (hp : p ≠ 0) : (norm_unit p : polynomial R) = C p.leading_coeff⁻¹ := show ↑(dite _ _ _) = C p.leading_coeff⁻¹, by rw dif_neg hp; refl end field section derivative variables [comm_semiring R] /-- `derivative p` is the formal derivative of the polynomial `p` -/ def derivative (p : polynomial R) : polynomial R := p.sum (λn a, C (a * n) * X^(n - 1)) lemma coeff_derivative (p : polynomial R) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [finsupp.sum, finset.sum_eq_single (n + 1), apply_eq_coeff], { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one] }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul] }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }, { intro H, rw [not_mem_support_iff.1 H, zero_mul, zero_mul] } end @[simp] lemma derivative_zero : derivative (0 : polynomial R) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X]; simp only [zero_mul, C_0]; refl @[simp] lemma derivative_C {a : R} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:R) * X ^ 0, by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero], derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial R) = 1 := suffices derivative (C (1:R) * X^1) = C (1 * (1:ℕ)) * X ^ 0, by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero], derivative_monomial 1 1 @[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial R} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; intros; simp only [add_mul, zero_mul, C_0, C_add, C_mul] /-- The formal derivative of polynomials, as additive homomorphism. -/ def derivative_hom (R : Type*) [comm_semiring R] : polynomial R →+ polynomial R := { to_fun := derivative, map_zero' := derivative_zero, map_add' := λ p q, derivative_add } @[simp] lemma derivative_neg {R : Type*} [comm_ring R] (f : polynomial R) : derivative (-f) = -derivative f := (derivative_hom R).map_neg f @[simp] lemma derivative_sub {R : Type*} [comm_ring R] (f g : polynomial R) : derivative (f - g) = derivative f - derivative g := (derivative_hom R).map_sub f g instance : is_add_monoid_hom (derivative : polynomial R → polynomial R) := (derivative_hom R).is_add_monoid_hom @[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} : derivative (s.sum f) = s.sum (λb, derivative (f b)) := (derivative_hom R).map_sum f s @[simp] lemma derivative_mul {f g : polynomial R} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, unfold derivative finsupp.sum, simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul] end lemma derivative_eval (p : polynomial R) (x : R) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp [derivative, eval_sum, eval_pow] @[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p := by { ext, simp only [coeff_derivative, mul_assoc, coeff_smul], } /-- The formal derivative of polynomials, as linear homomorphism. -/ def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R := { to_fun := derivative, add := λ p q, derivative_add, smul := λ r p, derivative_smul r p } /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : ideal.is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end end derivative section domain variables [integral_domain R] lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : R) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [coeff_derivative, apply_eq_coeff, mem_support_iff, ne.def, mul_eq_zero], by rw [nat.cast_eq_zero]; simp only [nat.succ_ne_zero, or_false] @[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn }, { assume h, simpa only [h, support_zero] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain section identities /- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials. These belong somewhere else. But not in group_power because they depend on tactic.ring Maybe use data.nat.choose to prove it. -/ def pow_add_expansion {R : Type*} [comm_semiring R] (x y : R) : ∀ (n : ℕ), {k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2} | 0 := ⟨0, by simp⟩ | 1 := ⟨0, by simp⟩ | (n+2) := begin cases pow_add_expansion (n+1) with z hz, existsi x*z + (n+1)*x^n+z*y, calc (x + y) ^ (n + 2) = (x + y) * (x + y) ^ (n + 1) : by ring_exp ... = (x + y) * (x ^ (n + 1) + ↑(n + 1) * x ^ (n + 1 - 1) * y + z * y ^ 2) : by rw hz ... = x ^ (n + 2) + ↑(n + 2) * x ^ (n + 1) * y + (x*z + (n+1)*x^n+z*y) * y ^ 2 : by { push_cast, ring_exp! } end variables [comm_ring R] private def poly_binom_aux1 (x y : R) (e : ℕ) (a : R) : {k : R // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} := begin existsi (pow_add_expansion x y e).val, congr, apply (pow_add_expansion _ _ _).property end private lemma poly_binom_aux2 (f : polynomial R) (x y : R) : f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) := begin unfold eval eval₂, congr, ext, apply (poly_binom_aux1 x y _ _).property end private lemma poly_binom_aux3 (f : polynomial R) (x y : R) : f.eval (x + y) = f.sum (λ e a, a * x^e) + f.sum (λ e a, (a * e * x^(e-1)) * y) + f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) := by rw poly_binom_aux2; simp [left_distrib, finsupp.sum_add, mul_assoc] def binom_expansion (f : polynomial R) (x y : R) : {k : R // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} := begin existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)), rw poly_binom_aux3, congr, { rw derivative_eval, symmetry, apply finsupp.sum_mul }, { symmetry, apply finsupp.sum_mul } end def pow_sub_pow_factor (x y : R) : Π {i : ℕ},{z : R // x^i - y^i = z*(x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases @pow_sub_pow_factor (k+1) with z hz, existsi z*x + y^(k+1), calc x ^ (k + 2) - y ^ (k + 2) = x * (x ^ (k + 1) - y ^ (k + 1)) + (x * y ^ (k + 1) - y ^ (k + 2)) : by ring_exp ... = x * (z * (x - y)) + (x * y ^ (k + 1) - y ^ (k + 2)) : by rw hz ... = (z * x + y ^ (k + 1)) * (x - y) : by ring_exp end def eval_sub_factor (f : polynomial R) (x y : R) : {z : R // f.eval x - f.eval y = z*(x - y)} := begin existsi f.sum (λ a b, b * (pow_sub_pow_factor x y).val), unfold eval eval₂, rw [←finsupp.sum_sub], have : finsupp.sum f (λ (a : ℕ) (b : R), b * (pow_sub_pow_factor x y).val) * (x - y) = finsupp.sum f (λ (a : ℕ) (b : R), b * (pow_sub_pow_factor x y).val * (x - y)), { apply finsupp.sum_mul }, rw this, congr, ext e a, rw [mul_assoc, ←(pow_sub_pow_factor x y).property], simp [mul_sub] end end identities end polynomial namespace is_integral_domain variables {R : Type*} [comm_ring R] /-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/ lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) := @integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _)) end is_integral_domain
3af0f5bd0fa7e82a4b07a78927f6f46396eb031f
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/complex/exponential.lean
f49c058ffa039659760a6abd4c9d88c53fb85603
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
45,833
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.archimedean import data.nat.choose data.complex.basic import tactic.linarith local attribute [instance, priority 0] classical.prop_decidable local notation `abs'` := _root_.abs open is_absolute_value section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - add_monoid.smul l ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - add_monoid.smul (k + (k + 1)) ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_monoid.add_smul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - add_monoid.smul l ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - add_monoid.smul (nat.pred l) ε : hi.2 ... = a - add_monoid.smul l ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_smul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, (range n).sum g) → is_cau_seq abv (λ n, (range n).sum f) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le ((range j).sum g) ((range i).sum g) ((range (max n i)).sum g), have := add_lt_add hi₁ hi₂, rw [abs_sub ((range (max n i)).sum g), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, rw [nat.succ_add, sum_range_succ, sum_range_succ, add_assoc, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) → is_cau_seq abv (λ m, (range m).sum f) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, (range n).sum (λ m, x ^ m)) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [_root_.pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), _root_.pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) := have is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, (range m).sum f) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, ← pow_inv _ _ r_ne_zero, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) = (range n).sum (λ m, (range (n - m)).sum (f m)) := have h₁ : ((range n).sigma (range ∘ nat.succ)).sum (λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) = (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) := sum_sigma, have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) = (range n).sum (λ m, sum (range (n - m)) (f m)) := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (s.sum f) ≤ s.sum (abv ∘ f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : (range m).sum f - (range n).sum f = ((range m).filter (λ k, n ≤ k)).sum f := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext.2 $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n)))) (hb : is_cau_seq abv (λ m, (range m).sum b)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((range j).sum a * (range j).sum b - (range j).sum (λ n, (range (n + 1)).sum (λ m, a m * b (n - m)))) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : sum (range K) (λ m, (range (m + 1)).sum (λ k, a k * b (m - k))) = sum (range K) (λ m, sum (range (K - m)) (λ n, a m * b n)), by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, (range (K - i)).sum (λ k, a i * b k)) = (λ i, a i * (range (K - i)).sum b), by simp [finset.mul_sum], have h₃ : (range K).sum (λ i, a i * (range (K - i)).sum b) = (range K).sum (λ i, a i * ((range (K - i)).sum b - (range K).sum b)) + (range K).sum (λ i, a i * (range K).sum b), by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : (range (max N M + 1)).sum (λ i, abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) ≤ (range (max N M + 1)).sum (λ i, abv (a i) * (ε / (2 * P))), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : sum (range (max N M + 1)) (λ n, abv (a n)) < P := calc sum (range (max N M + 1)) (λ n, abv (a n)) = abs (sum (range (max N M + 1)) (λ n, abv (a n))) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) + ((range K).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) -(range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b))) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc sum ((range K).filter (λ k, max N M + 1 ≤ k)) (λ i, abv (a i) * abv (sum (range (K - i)) b - sum (range K) b)) ≤ sum ((range K).filter (λ k, max N M + 1 ≤ k)) (λ i, abv (a i) * (2 * Q)) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs (z ^ m / nat.fact m))) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, z ^ m / nat.fact m)) := is_cau_series_of_abv_cau (is_cau_abs_exp z) def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, z ^ m / nat.fact m), is_cau_exp z⟩ def exp (z : ℂ) : ℂ := lim (exp' z) def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 def tan (z : ℂ) : ℂ := sin z / cos z def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex def exp (x : ℝ) : ℝ := (exp x).re def sin (x : ℝ) : ℝ := (sin x).re def cos (x : ℝ) : ℝ := (cos x).re def tan (x : ℝ) : ℝ := (tan x).re def sinh (x : ℝ) : ℝ := (sinh x).re def cosh (x : ℝ) : ℝ := (cosh x).re def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, (range j).sum (λ m, (x + y) ^ m / m.fact) = (range j).sum (λ i, (range (i + 1)).sum (λ k, x ^ k / k.fact * (y ^ (i - k) / (i - k).fact))), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (nat.choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (nat.choose m i : ℂ), mul_assoc, mul_left_comm (nat.choose m i : ℂ)⁻¹, mul_comm (nat.choose m i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, @zero_ne_one ℂ _ $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← domain.mul_left_inj (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw ← sum_hom conj, refine sum_congr rfl (λ n hn, _), rw [conj_div, conj_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj_neg, exp_conj, exp_conj, ← conj_sub, sinh, conj_div, conj_two] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := by rw [cosh, ← conj_neg, exp_conj, exp_conj, ← conj_add, cosh, conj_div, conj_two] @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← domain.mul_right_inj I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [cos_add, sin_neg, cos_neg] lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← domain.mul_right_inj I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj_mul, ← conj_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div_eq_inv] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [cos_add, sin_neg, cos_neg] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simpa using sin_sq_add_cos_sq x lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right' (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left' (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (sin x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply sin_sq_le_one lemma abs_cos_le_one : abs' (cos x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (cos x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply cos_sq_le_one lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ ((range j).sum (λ m, (x ^ m / m.fact : ℂ))).re, from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), dsimp [-nat.fact_succ], rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] end real namespace complex lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : (sum (filter (λ k, n ≤ k) (range j)) (λ m : ℕ, (1 / m.fact : α))) ≤ n.succ * (n.fact * n)⁻¹ := calc (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α)) = (range (j - n)).sum (λ m, 1 / (m + n).fact) : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_right_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ (range (j - n)).sum (λ m, (nat.fact n * n.succ ^ m)⁻¹) : begin refine sum_le_sum (assume m n, _), rw [one_div_eq_inv, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.fact_mul_pow_le_fact }, { exact nat.cast_pos.2 (nat.fact_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = (nat.fact n)⁻¹ * (range (j - n)).sum (λ m, n.succ⁻¹ ^ m) : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ_inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [geom_sum_inv h₁ h₂, eq_div_iff_mul_eq _ _ h₃, mul_comm _ (n.fact * n : α), ← mul_assoc (n.fact⁻¹ : α), ← mul_inv', h₄, ← mul_assoc (n.fact * n : α), mul_comm (n : α) n.fact, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n.fact * n) : begin refine (div_le_div_right (mul_pos _ _)).2 _, exact nat.cast_pos.2 (nat.fact_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) := begin rw [← lim_const ((range n).sum _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs ((range j).sum (λ m, x ^ m / m.fact) - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ m / m.fact : ℂ))) = abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ n * (x ^ (m - n) / m.fact) : ℂ))) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs (x ^ n * (_ / m.fact))) : abv_sum_le_sum_abv _ _ ... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs x ^ n * (1 / m.fact)) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.fact_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (1 / m.fact : ℝ))) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - (range 1).sum (λ m, x ^ m / m.fact)) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] end complex namespace real open complex finset lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) + ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) / 2) + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) - (complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) * I / 2) + abs (-((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
30b125968655f229e8006f8226cac5f7ac2ba520
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebra/lie/nilpotent.lean
f62bcc53a0c1d9c3ad2047890703f141f771beba
[ "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
7,521
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.solvable import linear_algebra.eigenspace /-! # Nilpotent Lie algebras Like groups, Lie algebras admit a natural concept of nilpotency. More generally, any Lie module carries a natural concept of nilpotency. We define these here via the lower central series. ## Main definitions * `lie_module.lower_central_series` * `lie_module.is_nilpotent` ## Tags lie algebra, lower central series, nilpotent -/ universes u v w w₁ w₂ namespace lie_module variables (R : Type u) (L : Type v) (M : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] /-- The lower central series of Lie submodules of a Lie module. -/ def lower_central_series (k : ℕ) : lie_submodule R L M := (λ I, ⁅(⊤ : lie_ideal R L), I⁆)^[k] ⊤ @[simp] lemma lower_central_series_zero : lower_central_series R L M 0 = ⊤ := rfl @[simp] lemma lower_central_series_succ (k : ℕ) : lower_central_series R L M (k + 1) = ⁅(⊤ : lie_ideal R L), lower_central_series R L M k⁆ := function.iterate_succ_apply' (λ I, ⁅(⊤ : lie_ideal R L), I⁆) k ⊤ lemma trivial_iff_lower_central_eq_bot : is_trivial L M ↔ lower_central_series R L M 1 = ⊥ := begin split; intros h, { erw [eq_bot_iff, lie_submodule.lie_span_le], rintros m ⟨x, n, hn⟩, rw [← hn, h.trivial], simp,}, { rw lie_submodule.eq_bot_iff at h, apply is_trivial.mk, intros x m, apply h, apply lie_submodule.subset_lie_span, use [x, m], refl, }, end lemma iterate_to_endomorphism_mem_lower_central_series (x : L) (m : M) (k : ℕ) : (to_endomorphism R L M x)^[k] m ∈ lower_central_series R L M k := begin induction k with k ih, { simp only [function.iterate_zero], }, { simp only [lower_central_series_succ, function.comp_app, function.iterate_succ', to_endomorphism_apply_apply], exact lie_submodule.lie_mem_lie _ _ (lie_submodule.mem_top x) ih, }, end open lie_algebra lemma derived_series_le_lower_central_series (k : ℕ) : derived_series R L k ≤ lower_central_series R L L k := begin induction k with k h, { rw [derived_series_def, derived_series_of_ideal_zero, lower_central_series_zero], exact le_refl _, }, { have h' : derived_series R L k ≤ ⊤, { by simp only [le_top], }, rw [derived_series_def, derived_series_of_ideal_succ, lower_central_series_succ], exact lie_submodule.mono_lie _ _ _ _ h' h, }, end /-- A Lie module is nilpotent if its lower central series reaches 0 (in a finite number of steps). -/ class is_nilpotent : Prop := (nilpotent : ∃ k, lower_central_series R L M k = ⊥) @[priority 100] instance trivial_is_nilpotent [is_trivial L M] : is_nilpotent R L M := ⟨by { use 1, change ⁅⊤, ⊤⁆ = ⊥, simp, }⟩ lemma nilpotent_endo_of_nilpotent_module [hM : is_nilpotent R L M] : ∃ (k : ℕ), ∀ (x : L), (to_endomorphism R L M x)^k = 0 := begin unfreezingI { obtain ⟨k, hM⟩ := hM, }, use k, intros x, ext m, rw [linear_map.pow_apply, linear_map.zero_apply, ← @lie_submodule.mem_bot R L M, ← hM], exact iterate_to_endomorphism_mem_lower_central_series R L M x m k, end /-- For a nilpotent Lie module, the weight space of the 0 weight is the whole module. This result will be used downstream to show that weight spaces are Lie submodules, at which time it will be possible to state it in the language of weight spaces. -/ lemma infi_max_gen_zero_eigenspace_eq_top_of_nilpotent [is_nilpotent R L M] : (⨅ (x : L), (to_endomorphism R L M x).maximal_generalized_eigenspace 0) = ⊤ := begin ext m, simp only [module.End.mem_maximal_generalized_eigenspace, submodule.mem_top, sub_zero, iff_true, zero_smul, submodule.mem_infi], intros x, obtain ⟨k, hk⟩ := nilpotent_endo_of_nilpotent_module R L M, use k, rw hk, exact linear_map.zero_apply m, end end lie_module @[priority 100] instance lie_algebra.is_solvable_of_is_nilpotent (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] [hL : lie_module.is_nilpotent R L L] : lie_algebra.is_solvable R L := begin obtain ⟨k, h⟩ : ∃ k, lie_module.lower_central_series R L L k = ⊥ := hL.nilpotent, use k, rw ← le_bot_iff at h ⊢, exact le_trans (lie_module.derived_series_le_lower_central_series R L k) h, end section nilpotent_algebras variables (R : Type u) (L : Type v) (L' : Type w) variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] /-- We say a Lie algebra is nilpotent when it is nilpotent as a Lie module over itself via the adjoint representation. -/ abbreviation lie_algebra.is_nilpotent (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : Prop := lie_module.is_nilpotent R L L open lie_algebra lemma lie_algebra.nilpotent_ad_of_nilpotent_algebra [is_nilpotent R L] : ∃ (k : ℕ), ∀ (x : L), (ad R L x)^k = 0 := lie_module.nilpotent_endo_of_nilpotent_module R L L lemma lie_algebra.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent [is_nilpotent R L] : (⨅ (x : L), (ad R L x).maximal_generalized_eigenspace 0) = ⊤ := lie_module.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L L -- TODO Generalise the below to Lie modules if / when we define morphisms, equivs of Lie modules -- covering a Lie algebra morphism of (possibly different) Lie algebras. variables {R L L'} open lie_module (lower_central_series) lemma lie_ideal.lower_central_series_map_le (k : ℕ) {f : L →ₗ⁅R⁆ L'} : lie_ideal.map f (lower_central_series R L L k) ≤ lower_central_series R L' L' k := begin induction k with k ih, { simp only [lie_module.lower_central_series_zero, le_top], }, { simp only [lie_module.lower_central_series_succ], exact le_trans (lie_ideal.map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ le_top ih), }, end lemma lie_ideal.lower_central_series_map_eq (k : ℕ) {f : L →ₗ⁅R⁆ L'} (h : function.surjective f) : lie_ideal.map f (lower_central_series R L L k) = lower_central_series R L' L' k := begin have h' : (⊤ : lie_ideal R L).map f = ⊤, { rw ←f.ideal_range_eq_map, exact f.ideal_range_eq_top_of_surjective h, }, induction k with k ih, { simp only [lie_module.lower_central_series_zero], exact h', }, { simp only [lie_module.lower_central_series_succ, lie_ideal.map_bracket_eq f h, ih, h'], }, end lemma function.injective.lie_algebra_is_nilpotent [h₁ : is_nilpotent R L'] {f : L →ₗ⁅R⁆ L'} (h₂ : function.injective f) : is_nilpotent R L := { nilpotent := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := h₁, use k, apply lie_ideal.bot_of_map_eq_bot h₂, rw [eq_bot_iff, ← hk], apply lie_ideal.lower_central_series_map_le, end, } lemma function.surjective.lie_algebra_is_nilpotent [h₁ : is_nilpotent R L] {f : L →ₗ⁅R⁆ L'} (h₂ : function.surjective f) : is_nilpotent R L' := { nilpotent := begin tactic.unfreeze_local_instances, obtain ⟨k, hk⟩ := h₁, use k, rw [← lie_ideal.lower_central_series_map_eq k h₂, hk], simp only [lie_ideal.map_eq_bot_iff, bot_le], end, } lemma lie_algebra.nilpotent_iff_equiv_nilpotent (e : L ≃ₗ⁅R⁆ L') : is_nilpotent R L ↔ is_nilpotent R L' := begin split; introsI h, { exact e.symm.injective.lie_algebra_is_nilpotent, }, { exact e.injective.lie_algebra_is_nilpotent, }, end end nilpotent_algebras
8a3da091cafdbd8d6f466b551a548d95470c4a2b
07c76fbd96ea1786cc6392fa834be62643cea420
/tests/lean/extra/755.hlean
95b3d75f738bd26d44740d71549e01596339e20a
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
1,724
hlean
import types.eq types.pi hit.colimit open eq is_trunc unit quotient seq_colim equiv axiom mysorry : ∀ {A : Type}, A namespace one_step_tr section parameters {A : Type} variables (a a' : A) protected definition R (a a' : A) : Type₀ := unit parameter (A) definition one_step_tr : Type := quotient R parameter {A} definition tr : one_step_tr := class_of R a definition tr_eq : tr a = tr a' := eq_of_rel _ star protected definition rec {P : one_step_tr → Type} (Pt : Π(a : A), P (tr a)) (Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') (x : one_step_tr) : P x := begin fapply (quotient.rec_on x), { intro a, apply Pt}, { intro a a' H, cases H, apply Pe} end protected definition elim {P : Type} (Pt : A → P) (Pe : Π(a a' : A), Pt a = Pt a') (x : one_step_tr) : P := rec Pt (λa a', pathover_of_eq _ (Pe a a')) x theorem rec_tr_eq {P : one_step_tr → Type} (Pt : Π(a : A), P (tr a)) (Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') (a a' : A) : apd (rec Pt Pe) (tr_eq a a') = Pe a a' := !rec_eq_of_rel theorem elim_tr_eq {P : Type} (Pt : A → P) (Pe : Π(a a' : A), Pt a = Pt a') (a a' : A) : ap (elim Pt Pe) (tr_eq a a') = Pe a a' := begin apply inj_inv !(pathover_constant (tr_eq a a')), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_tr_eq], end end end one_step_tr attribute one_step_tr.rec one_step_tr.elim [recursor 5] open one_step_tr definition one_step_tr_up (A B : Type) : (one_step_tr A → B) ≃ Σ(f : A → B), Π(x y : A), f x = f y := begin fapply equiv.MK, { intro f, fconstructor, intro a, exact f (tr a), intros, exact ap f !tr_eq}, { exact mysorry}, { exact mysorry}, { exact mysorry}, end
dbb376d67fdebaca923fcb648db64696adfbcc22
93b17e1ec33b7fd9fb0d8f958cdc9f2214b131a2
/src/cat/basic.lean
9adcc5cf53300153fc9668d5f5b65e1c2664b5c0
[]
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
2,079
lean
/- Categories - -/ namespace Cat universes ℓ ℓ₁ ℓ₂ ℓ₃ ℓ₄ structure Cat := (obj : Type.{ℓ₁}) (hom : obj → obj → Type.{ℓ₂}) (id : ∀ X, hom X X) (circ : ∀ {A B C}, hom B C → hom A B → hom A C) (circ_id_r : ∀ {A B} (f : hom A B), circ f (id _) = f) (circ_id_l : ∀ {A B} (f : hom A B), circ (id _) f = f) (circ_assoc : ∀ {A B C D} {h : hom C D} {g : hom B C} {f : hom A B} , circ h (circ g f) = circ (circ h g) f) def Cat.circ_congr {C : Cat.{ℓ₁ ℓ₂}} {X Y Z : C.obj} {g₁ g₂ : C.hom Y Z} {f₁ f₂ : C.hom X Y} (Eg : g₁ = g₂) (Ef : f₁ = f₂) : C.circ g₁ f₁ = C.circ g₂ f₂ := begin subst Eg, subst Ef end structure Cat.Prod (C : Cat.{ℓ₁ ℓ₂}) (I : Type.{ℓ}) (f : I → C.obj) := (obj : C.obj) (proj : ∀ (i : I), C.hom obj (f i)) structure Cat.Product (C : Cat.{ℓ₁ ℓ₂}) {I : Type.{ℓ}} {f : I → C.obj} (O : C.Prod I f) := (univ : ∀ (u : C.Prod I f) , C.hom u.obj O.obj) (eq : ∀ (u : C.Prod I f) (i : I) , u.proj i = C.circ (O.proj i) (univ u)) (uniq : ∀ (u : C.Prod I f) (h : C.hom u.obj O.obj) (Hh : ∀ (i : I), u.proj i = C.circ (O.proj i) h) , h = univ u) def Cat.HasProducts (C : Cat.{ℓ₁ ℓ₂}) := ∀ (I : Type.{ℓ}) (f : I → C.obj) , Σ (p : C.Prod I f), C.Product p structure Cat.Eql (C : Cat.{ℓ₁ ℓ₂}) {X Y : C.obj} (f g : C.hom X Y) := (obj : C.obj) (eq : C.hom obj X) (Eeq : C.circ f eq = C.circ g eq) structure Cat.Equalizer (C : Cat.{ℓ₁ ℓ₂}) {X Y : C.obj} {f g : C.hom X Y} (O : C.Eql f g) := (univ : ∀ (u : C.Eql f g) , C.hom u.obj O.obj) (eq : ∀ (u : C.Eql f g) , u.eq = C.circ O.eq (univ u)) (uniq : ∀ (u : C.Eql f g) (h : C.hom u.obj O.obj) (Hh : u.eq = C.circ O.eq h) , h = univ u) def Cat.HasEqualizers (C : Cat.{ℓ₁ ℓ₂}) := ∀ (X Y : C.obj) (f g : C.hom X Y) , Σ (e : C.Eql f g), C.Equalizer e end Cat
1fabe5c2310798ede3e4ef774f9e34b60e332675
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/yoneda.lean
e51d475f38bebd367c3651c8a7b1b75031222f90
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
6,897
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.opposites import category_theory.hom_functor /-! # The Yoneda embedding The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`, along with an instance that it is `fully_faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. -/ namespace category_theory open opposite universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 @[simps] def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop Y ⟶ X, map := λ Y Y' f g, f.unop ≫ g, map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext1, dsimp, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } } @[simps] def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext1, dsimp, erw [category.comp_id] end }, map := λ X X' f, { app := λ Y g, f.unop ≫ g }, map_comp' := λ _ _ _ f g, begin ext1, ext1, dsimp, erw [category.assoc] end, map_id' := λ X, begin ext1, ext1, dsimp, erw [category.id_comp] end } namespace yoneda lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) : ((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) := by obviously @[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) := begin erw [functor_to_types.naturality], refl end instance yoneda_full : full (@yoneda C _) := { preimage := λ X Y f, (f.app (op X)) (𝟙 X) } instance yoneda_faithful : faithful (@yoneda C _) := { injectivity' := λ X Y f g p, begin injection p with h, convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp, end } /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := @preimage_iso _ _ _ _ yoneda _ _ _ _ (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) def is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f := is_iso_of_fully_faithful yoneda f end yoneda namespace coyoneda @[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y) {Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) := begin erw [functor_to_types.naturality], refl end instance coyoneda_full : full (@coyoneda C _) := { preimage := λ X Y f, ((f.app (unop X)) (𝟙 _)).op } instance coyoneda_faithful : faithful (@coyoneda C _) := { injectivity' := λ X Y f g p, begin injection p with h, have t := (congr_fun (congr_fun h (unop X)) (𝟙 _)), simpa using congr_arg has_hom.hom.op t, end } def is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f := is_iso_of_fully_faithful coyoneda f end coyoneda class representable (F : Cᵒᵖ ⥤ Type v₁) := (X : C) (w : yoneda.obj X ≅ F) end category_theory namespace category_theory -- For the rest of the file, we are using product categories, -- so need to restrict to the case morphisms are in 'Type', not 'Sort'. universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation open opposite variables (C : Type u₁) [𝒞 : category.{v₁} C] include 𝒞 -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) := category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) := category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁) open yoneda def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁) @[simp] lemma yoneda_pairing_map (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))), naturality' := begin intros X Y f, ext1, ext1, cases f, cases Y, cases X, dsimp, erw [category.id_comp, ←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end }, inv := { app := λ F x, { app := λ X a, (F.2.map a.op) x.down, naturality' := begin intros X Y f, ext1, cases x, cases F, dsimp, erw [functor_to_types.map_comp] end }, naturality' := begin intros X Y f, ext1, ext1, ext1, cases x, cases f, cases Y, cases X, dsimp, erw [←functor_to_types.naturality, functor_to_types.map_comp] end }, hom_inv_id' := begin ext1, ext1, ext1, ext1, cases X, dsimp, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id], refl, end, inv_hom_id' := begin ext1, ext1, ext1, cases x, cases X, dsimp, erw [functor_to_types.map_id] end }. variables {C} @[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) := (yoneda_lemma C).app (op X, F) omit 𝒞 @[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟶ F) ≅ F.obj (op X) := yoneda_sections X F ≪≫ ulift_trivial _ end category_theory
a088ea245ecf604bbf7885c7fe7a94a4b39beec7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1907orig.lean
9979395a254ac469015114dd1836c63fa8e2170c
[ "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,230
lean
class One (α : Type u) where one : α instance One.toOfNat1 {α} [One α] : OfNat α (nat_lit 1) where ofNat := ‹One α›.1 class MulOneClass (M : Type u) extends One M, Mul M class FunLike (F : Sort _) (α : outParam (Sort _)) (β : outParam <| α → Sort _) where coe : F → ∀ a : α, β a instance (priority := 100) [FunLike F α β] : CoeFun F fun _ => ∀ a : α, β a where coe := FunLike.coe section One variable [One M] [One N] structure OneHom (M : Type _) (N : Type _) [One M] [One N] where toFun : M → N map_one' : toFun 1 = 1 class OneHomClass (F : Type _) (M N : outParam (Type _)) [outParam (One M)] [outParam (One N)] extends FunLike F M fun _ => N where map_one : ∀ f : F, f 1 = 1 @[simp] theorem map_one [OneHomClass F M N] (f : F) : f 1 = 1 := OneHomClass.map_one f end One section Mul variable [Mul M] [Mul N] structure MulHom (M : Type _) (N : Type _) [Mul M] [Mul N] where toFun : M → N map_mul' : ∀ x y, toFun (x * y) = toFun x * toFun y infixr:25 " →ₙ* " => MulHom class MulHomClass (F : Type _) (M N : outParam (Type _)) [outParam (Mul M)] [outParam (Mul N)] extends FunLike F M fun _ => N where map_mul : ∀ (f : F) (x y : M), f (x * y) = f x * f y @[simp] theorem map_mul [MulHomClass F M N] (f : F) (x y : M) : f (x * y) = f x * f y := MulHomClass.map_mul f x y end Mul section mul_one variable [MulOneClass M] [MulOneClass N] structure MonoidHom (M : Type _) (N : Type _) [MulOneClass M] [MulOneClass N] extends OneHom M N, M →ₙ* N infixr:25 " →* " => MonoidHom class MonoidHomClass (F : Type _) (M N : outParam (Type _)) [outParam (MulOneClass M)] [outParam (MulOneClass N)] extends MulHomClass F M N, OneHomClass F M N instance [MonoidHomClass F M N] : CoeTC F (M →* N) := ⟨fun f => { toFun := f, map_one' := map_one f, map_mul' := map_mul f }⟩ -- Now we reverse the order of the parents in the extends clause: class MonoidHomClass' (F : Type _) (M N : outParam (Type _)) [outParam (MulOneClass M)] [outParam (MulOneClass N)] extends OneHomClass F M N, MulHomClass F M N instance [MonoidHomClass' F M N] : CoeTC F (M →* N) := ⟨fun f => { toFun := f, map_one' := map_one f, map_mul' := map_mul f }⟩
4ade794df84d6a209b23905baa65484a015fb0f0
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/init/logic.lean
bc653e9ad66a10c52e7bcbcd30c8a963a9c41e41
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,131
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.datatypes init.reserved_notation init.tactic definition id [reducible] [unfold_full] {A : Type} (a : A) : A := a /- implication -/ definition implies (a b : Prop) := a → b lemma implies.trans [trans] {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) definition trivial := true.intro definition not (a : Prop) := a → false prefix `¬` := not definition absurd {a : Prop} {b : Type} (H1 : a) (H2 : ¬a) : b := false.rec b (H2 H1) theorem mt {a b : Prop} (H1 : a → b) (H2 : ¬b) : ¬a := assume Ha : a, absurd (H1 Ha) H2 /- not -/ theorem not_false : ¬false := assume H : false, H definition non_contradictory (a : Prop) : Prop := ¬¬a theorem non_contradictory_intro {a : Prop} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna /- false -/ theorem false.elim {c : Prop} (H : false) : c := false.rec c H /- eq -/ notation a = b := eq a b definition rfl {A : Type} {a : A} : a = a := eq.refl a -- proof irrelevance is built in theorem proof_irrel {a : Prop} (H₁ H₂ : a) : H₁ = H₂ := rfl -- Remark: we provide the universe levels explicitly to make sure `eq.drec` has the same type of `eq.rec` in the HoTT library protected theorem eq.drec.{l₁ l₂} {A : Type.{l₂}} {a : A} {C : Π (x : A), a = x → Type.{l₁}} (h₁ : C a (eq.refl a)) {b : A} (h₂ : a = b) : C b h₂ := eq.rec (λh₂ : a = a, show C a h₂, from h₁) h₂ h₂ namespace eq variables {A : Type} variables {a b c a': A} protected theorem drec_on {a : A} {C : Π (x : A), a = x → Type} {b : A} (h₂ : a = b) (h₁ : C a (refl a)) : C b h₂ := eq.drec h₁ h₂ theorem subst {P : A → Prop} (H₁ : a = b) (H₂ : P a) : P b := eq.rec H₂ H₁ theorem trans (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ theorem symm : a = b → b = a := eq.rec (refl a) theorem substr {P : A → Prop} (H₁ : b = a) : P a → P b := subst (symm H₁) theorem mp {a b : Type} : (a = b) → a → b := eq.rec_on theorem mpr {a b : Type} : (a = b) → b → a := assume H₁ H₂, eq.rec_on (eq.symm H₁) H₂ namespace ops notation H `⁻¹` := symm H --input with \sy or \-1 or \inv notation H1 ⬝ H2 := trans H1 H2 notation H1 ▸ H2 := subst H1 H2 notation H1 ▹ H2 := eq.rec H2 H1 end ops end eq theorem congr {A B : Type} {f₁ f₂ : A → B} {a₁ a₂ : A} (H₁ : f₁ = f₂) (H₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst H₁ (eq.subst H₂ rfl) theorem congr_fun {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a := eq.subst H (eq.refl (f a)) theorem congr_arg {A B : Type} {a₁ a₂ : A} (f : A → B) : a₁ = a₂ → f a₁ = f a₂ := congr rfl section variables {A : Type} {a b c: A} open eq.ops theorem trans_rel_left (R : A → A → Prop) (H₁ : R a b) (H₂ : b = c) : R a c := H₂ ▸ H₁ theorem trans_rel_right (R : A → A → Prop) (H₁ : a = b) (H₂ : R b c) : R a c := H₁⁻¹ ▸ H₂ end section variable {p : Prop} open eq.ops theorem of_eq_true (H : p = true) : p := H⁻¹ ▸ trivial theorem not_of_eq_false (H : p = false) : ¬p := assume Hp, H ▸ Hp end attribute eq.subst [subst] attribute eq.refl [refl] attribute eq.trans [trans] attribute eq.symm [symm] /- ne -/ definition ne [reducible] {A : Type} (a b : A) := ¬(a = b) notation a ≠ b := ne a b namespace ne open eq.ops variable {A : Type} variables {a b : A} theorem intro (H : a = b → false) : a ≠ b := H theorem elim (H : a ≠ b) : a = b → false := H theorem irrefl (H : a ≠ a) : false := H rfl theorem symm (H : a ≠ b) : b ≠ a := assume (H₁ : b = a), H (H₁⁻¹) end ne theorem false_of_ne {A : Type} {a : A} : a ≠ a → false := ne.irrefl section open eq.ops variables {p : Prop} theorem ne_false_of_self : p → p ≠ false := assume (Hp : p) (Heq : p = false), Heq ▸ Hp theorem ne_true_of_not : ¬p → p ≠ true := assume (Hnp : ¬p) (Heq : p = true), (Heq ▸ Hnp) trivial theorem true_ne_false : ¬true = false := ne_false_of_self trivial end infixl ` == `:50 := heq namespace heq universe variable u variables {A B C : Type.{u}} {a a' : A} {b b' : B} {c : C} theorem to_eq (H : a == a') : a = a' := have H₁ : ∀ (Ht : A = A), eq.rec a Ht = a, from λ Ht, eq.refl a, heq.rec H₁ H (eq.refl A) theorem elim {A : Type} {a : A} {P : A → Type} {b : A} (H₁ : a == b) : P a → P b := eq.rec_on (to_eq H₁) theorem subst {P : ∀T : Type, T → Prop} : a == b → P A a → P B b := heq.rec_on theorem symm (H : a == b) : b == a := heq.rec_on H (refl a) theorem of_eq (H : a = a') : a == a' := eq.subst H (refl a) theorem trans (H₁ : a == b) (H₂ : b == c) : a == c := subst H₂ H₁ theorem of_heq_of_eq (H₁ : a == b) (H₂ : b = b') : a == b' := trans H₁ (of_eq H₂) theorem of_eq_of_heq (H₁ : a = a') (H₂ : a' == b) : a == b := trans (of_eq H₁) H₂ definition type_eq (H : a == b) : A = B := heq.rec_on H (eq.refl A) end heq open eq.ops theorem eq_rec_heq {A : Type} {P : A → Type} {a a' : A} (H : a = a') (p : P a) : H ▹ p == p := eq.drec_on H !heq.refl theorem heq_of_eq_rec_left {A : Type} {P : A → Type} : ∀ {a a' : A} {p₁ : P a} {p₂ : P a'} (e : a = a') (h₂ : e ▹ p₁ = p₂), p₁ == p₂ | a a p₁ p₂ (eq.refl a) h := eq.rec_on h !heq.refl theorem heq_of_eq_rec_right {A : Type} {P : A → Type} : ∀ {a a' : A} {p₁ : P a} {p₂ : P a'} (e : a' = a) (h₂ : p₁ = e ▹ p₂), p₁ == p₂ | a a p₁ p₂ (eq.refl a) h := eq.rec_on h !heq.refl theorem of_heq_true {a : Prop} (H : a == true) : a := of_eq_true (heq.to_eq H) theorem eq_rec_compose : ∀ {A B C : Type} (p₁ : B = C) (p₂ : A = B) (a : A), p₁ ▹ (p₂ ▹ a : B) = (p₂ ⬝ p₁) ▹ a | A A A (eq.refl A) (eq.refl A) a := calc eq.refl A ▹ eq.refl A ▹ a = eq.refl A ▹ a : rfl ... = (eq.refl A ⬝ eq.refl A) ▹ a : {proof_irrel (eq.refl A) (eq.refl A ⬝ eq.refl A)} theorem eq_rec_eq_eq_rec {A₁ A₂ : Type} {p : A₁ = A₂} : ∀ {a₁ : A₁} {a₂ : A₂}, p ▹ a₁ = a₂ → a₁ = p⁻¹ ▹ a₂ := eq.drec_on p (λ a₁ a₂ h, eq.drec_on h rfl) theorem eq_rec_of_heq_left : ∀ {A₁ A₂ : Type} {a₁ : A₁} {a₂ : A₂} (h : a₁ == a₂), heq.type_eq h ▹ a₁ = a₂ | A A a a (heq.refl a) := rfl theorem eq_rec_of_heq_right {A₁ A₂ : Type} {a₁ : A₁} {a₂ : A₂} (h : a₁ == a₂) : a₁ = (heq.type_eq h)⁻¹ ▹ a₂ := eq_rec_eq_eq_rec (eq_rec_of_heq_left h) attribute heq.refl [refl] attribute heq.trans [trans] attribute heq.of_heq_of_eq [trans] attribute heq.of_eq_of_heq [trans] attribute heq.symm [symm] /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} theorem and.elim (H₁ : a ∧ b) (H₂ : a → b → c) : c := and.rec H₂ H₁ theorem and.swap : a ∧ b → b ∧ a := and.rec (λHa Hb, and.intro Hb Ha) /- or -/ notation a \/ b := or a b notation a ∨ b := or a b namespace or theorem elim (H₁ : a ∨ b) (H₂ : a → c) (H₃ : b → c) : c := or.rec H₂ H₃ H₁ end or theorem non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em theorem or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl /- iff -/ definition iff (a b : Prop) := (a → b) ∧ (b → a) notation a <-> b := iff a b notation a ↔ b := iff a b namespace iff theorem intro : (a → b) → (b → a) → (a ↔ b) := and.intro theorem elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := and.rec theorem elim_left : (a ↔ b) → a → b := and.left definition mp := @elim_left theorem elim_right : (a ↔ b) → b → a := and.right definition mpr := @elim_right theorem refl (a : Prop) : a ↔ a := intro (assume H, H) (assume H, H) theorem rfl {a : Prop} : a ↔ a := refl a theorem trans (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c := intro (assume Ha, mp H₂ (mp H₁ Ha)) (assume Hc, mpr H₁ (mpr H₂ Hc)) theorem symm (H : a ↔ b) : b ↔ a := intro (elim_right H) (elim_left H) theorem comm : (a ↔ b) ↔ (b ↔ a) := intro symm symm open eq.ops theorem of_eq {a b : Prop} (H : a = b) : a ↔ b := H ▸ rfl end iff theorem not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (Hna : ¬ a) (Hb : b), Hna (iff.elim_right H₁ Hb)) (assume (Hnb : ¬ b) (Ha : a), Hnb (iff.elim_left H₁ Ha)) theorem of_iff_true (H : a ↔ true) : a := iff.mp (iff.symm H) trivial theorem not_of_iff_false : (a ↔ false) → ¬a := iff.mp theorem iff_true_intro (H : a) : a ↔ true := iff.intro (λ Hl, trivial) (λ Hr, H) theorem iff_false_intro (H : ¬a) : a ↔ false := iff.intro H !false.rec theorem not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (Hl : ¬¬¬a) (Ha : a), Hl (non_contradictory_intro Ha)) absurd attribute iff.refl [refl] attribute iff.symm [symm] attribute iff.trans [trans] theorem imp_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λHab Hc, iff.mp H2 (Hab (iff.mpr H1 Hc))) (λHcd Ha, iff.mpr H2 (Hcd (iff.mp H1 Ha))) theorem not_not_intro (Ha : a) : ¬¬a := assume Hna : ¬a, Hna Ha theorem not_true [simp] : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) theorem not_false_iff [simp] : (¬ false) ↔ true := iff_true_intro not_false theorem not_congr [congr] (H : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ H₁ H₂, H₁ (iff.mpr H H₂)) (λ H₁ H₂, H₁ (iff.mp H H₂)) theorem ne_self_iff_false [simp] {A : Type} (a : A) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim theorem eq_self_iff_true [simp] {A : Type} (a : A) : (a = a) ↔ true := iff_true_intro rfl theorem heq_self_iff_true [simp] {A : Type} (a : A) : (a == a) ↔ true := iff_true_intro (heq.refl a) theorem iff_not_self [simp] (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ H, have H' : ¬a, from (λ Ha, (iff.mp H Ha) Ha), H' (iff.mpr H H')) theorem not_iff_self [simp] (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ H, have H' : ¬a, from (λ Ha, (iff.mpr H Ha) Ha), H' (iff.mp H H')) theorem true_iff_false [simp] : (true ↔ false) ↔ false := iff_false_intro (λ H, iff.mp H trivial) theorem false_iff_true [simp] : (false ↔ true) ↔ false := iff_false_intro (λ H, iff.mpr H trivial) theorem false_of_true_iff_false : (true ↔ false) → false := assume H, iff.mp H trivial /- and simp rules -/ theorem and.imp (H₂ : a → c) (H₃ : b → d) : a ∧ b → c ∧ d := and.rec (λHa Hb, and.intro (H₂ Ha) (H₃ Hb)) theorem and_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp H1) (iff.mp H2)) (and.imp (iff.mpr H1) (iff.mpr H2)) theorem and.comm [simp] : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap theorem and.assoc [simp] : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (and.rec (λ H' Hc, and.rec (λ Ha Hb, and.intro Ha (and.intro Hb Hc)) H')) (and.rec (λ Ha, and.rec (λ Hb Hc, and.intro (and.intro Ha Hb) Hc))) theorem and.left_comm [simp] : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm !and.assoc) (iff.trans (and_congr !and.comm !iff.refl) !and.assoc) theorem and_iff_left {a b : Prop} (Hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λHa, and.intro Ha Hb) theorem and_iff_right {a b : Prop} (Ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro Ha) theorem and_true [simp] (a : Prop) : a ∧ true ↔ a := and_iff_left trivial theorem true_and [simp] (a : Prop) : true ∧ a ↔ a := and_iff_right trivial theorem and_false [simp] (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right theorem false_and [simp] (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left theorem not_and_self [simp] (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ H, and.elim H (λ H₁ H₂, absurd H₂ H₁)) theorem and_not_self [simp] (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (λ H, and.elim H (λ H₁ H₂, absurd H₁ H₂)) theorem and_self [simp] (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume H, and.intro H H) /- or simp rules -/ theorem or.imp (H₂ : a → c) (H₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ H, or.inl (H₂ H)) (λ H, or.inr (H₃ H)) theorem or.imp_left (H : a → b) : a ∨ c → b ∨ c := or.imp H id theorem or.imp_right (H : a → b) : c ∨ a → c ∨ b := or.imp id H theorem or_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp H1) (iff.mp H2)) (or.imp (iff.mpr H1) (iff.mpr H2)) theorem or.comm [simp] : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap theorem or.assoc [simp] : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ H, or.inr (or.inr H))) (or.rec (λ H, or.inl (or.inl H)) (or.imp_left or.inr)) theorem or.left_comm [simp] : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm !or.assoc) (iff.trans (or_congr !or.comm !iff.refl) !or.assoc) theorem or_true [simp] (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) theorem true_or [simp] (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) theorem or_false [simp] (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl theorem false_or [simp] (a : Prop) : false ∨ a ↔ a := iff.trans or.comm !or_false theorem or_self [simp] (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl /- iff simp rules -/ theorem iff_true [simp] (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume H, iff.mpr H trivial) iff_true_intro theorem true_iff [simp] (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm !iff_true theorem iff_false [simp] (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro and.left iff_false_intro theorem false_iff [simp] (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm !iff_false theorem iff_self [simp] (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl theorem iff_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := and_congr (imp_congr H1 H2) (imp_congr H2 H1) /- exists -/ inductive Exists {A : Type} (P : A → Prop) : Prop := intro : ∀ (a : A), P a → Exists P definition exists.intro := @Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r theorem exists.elim {A : Type} {p : A → Prop} {B : Prop} (H1 : ∃x, p x) (H2 : ∀ (a : A), p a → B) : B := Exists.rec H2 H1 /- exists unique -/ definition exists_unique {A : Type} (p : A → Prop) := ∃x, p x ∧ ∀y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r theorem exists_unique.intro {A : Type} {p : A → Prop} (w : A) (H1 : p w) (H2 : ∀y, p y → y = w) : ∃!x, p x := exists.intro w (and.intro H1 H2) theorem exists_unique.elim {A : Type} {p : A → Prop} {b : Prop} (H2 : ∃!x, p x) (H1 : ∀x, p x → (∀y, p y → y = x) → b) : b := exists.elim H2 (λ w Hw, H1 w (and.left Hw) (and.right Hw)) theorem exists_unique_of_exists_of_unique {A : Type} {p : A → Prop} (Hex : ∃ x, p x) (Hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim Hex (λ x px, exists_unique.intro x px (take y, suppose p y, Hunique y x this px)) theorem exists_of_exists_unique {A : Type} {p : A → Prop} (H : ∃! x, p x) : ∃ x, p x := exists.elim H (λ x Hx, exists.intro x (and.left Hx)) theorem unique_of_exists_unique {A : Type} {p : A → Prop} (H : ∃! x, p x) {y₁ y₂ : A} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim H (take x, suppose p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ section variables {A : Type} {p₁ p₂ : A → Prop} theorem forall_congr [congr] {A : Type} {P Q : A → Prop} (H : ∀a, (P a ↔ Q a)) : (∀a, P a) ↔ ∀a, Q a := iff.intro (λp a, iff.mp (H a) (p a)) (λq a, iff.mpr (H a) (q a)) theorem exists_imp_exists {A : Type} {P Q : A → Prop} (H : ∀a, (P a → Q a)) (p : ∃a, P a) : ∃a, Q a := exists.elim p (λa Hp, exists.intro a (H a Hp)) theorem exists_congr [congr] {A : Type} {P Q : A → Prop} (H : ∀a, (P a ↔ Q a)) : (∃a, P a) ↔ ∃a, Q a := iff.intro (exists_imp_exists (λa, iff.mp (H a))) (exists_imp_exists (λa, iff.mpr (H a))) theorem exists_unique_congr [congr] (H : ∀ x, p₁ x ↔ p₂ x) : (∃! x, p₁ x) ↔ (∃! x, p₂ x) := exists_congr (λx, and_congr (H x) (forall_congr (λy, imp_congr (H y) iff.rfl))) end /- decidable -/ inductive decidable [class] (p : Prop) : Type := | inl : p → decidable p | inr : ¬p → decidable p definition decidable_true [instance] : decidable true := decidable.inl trivial definition decidable_false [instance] : decidable false := decidable.inr not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches definition dite (c : Prop) [H : decidable c] {A : Type} : (c → A) → (¬ c → A) → A := decidable.rec_on H /- if-then-else -/ definition ite (c : Prop) [H : decidable c] {A : Type} (t e : A) : A := decidable.rec_on H (λ Hc, t) (λ Hnc, e) namespace decidable variables {p q : Prop} definition rec_on_true [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : p) (H4 : H1 H3) : decidable.rec_on H H1 H2 := decidable.rec_on H (λh, H4) (λh, !false.rec (h H3)) definition rec_on_false [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} (H3 : ¬p) (H4 : H2 H3) : decidable.rec_on H H1 H2 := decidable.rec_on H (λh, false.rec _ (H3 h)) (λh, H4) definition by_cases {q : Type} [C : decidable p] : (p → q) → (¬p → q) → q := !dite theorem em (p : Prop) [H : decidable p] : p ∨ ¬p := by_cases or.inl or.inr theorem by_contradiction [Hp : decidable p] (H : ¬p → false) : p := if H1 : p then H1 else false.rec _ (H H1) end decidable section variables {p q : Prop} open decidable definition decidable_of_decidable_of_iff (Hp : decidable p) (H : p ↔ q) : decidable q := if Hp : p then inl (iff.mp H Hp) else inr (iff.mp (not_iff_not_of_iff H) Hp) definition decidable_of_decidable_of_eq (Hp : decidable p) (H : p = q) : decidable q := decidable_of_decidable_of_iff Hp (iff.of_eq H) protected definition or.by_cases [Hp : decidable p] [Hq : decidable q] {A : Type} (h : p ∨ q) (h₁ : p → A) (h₂ : q → A) : A := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} open decidable (rec_on inl inr) definition decidable_and [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then inl (and.intro hp hq) else inr (assume H : p ∧ q, hq (and.right H)) else inr (assume H : p ∧ q, hp (and.left H)) definition decidable_or [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ∨ q) := if hp : p then inl (or.inl hp) else if hq : q then inl (or.inr hq) else inr (or.rec hp hq) definition decidable_not [instance] [Hp : decidable p] : decidable (¬p) := if hp : p then inr (absurd hp) else inl hp definition decidable_implies [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p → q) := if hp : p then if hq : q then inl (assume H, hq) else inr (assume H : p → q, absurd (H hp) hq) else inl (assume Hp, absurd Hp hp) definition decidable_iff [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ↔ q) := decidable_and end definition decidable_pred [reducible] {A : Type} (R : A → Prop) := Π (a : A), decidable (R a) definition decidable_rel [reducible] {A : Type} (R : A → A → Prop) := Π (a b : A), decidable (R a b) definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A) definition decidable_ne [instance] {A : Type} [H : decidable_eq A] (a b : A) : decidable (a ≠ b) := decidable_implies namespace bool theorem ff_ne_tt : ff = tt → false | [none] end bool open bool definition is_dec_eq {A : Type} (p : A → A → bool) : Prop := ∀ ⦃x y : A⦄, p x y = tt → x = y definition is_dec_refl {A : Type} (p : A → A → bool) : Prop := ∀x, p x x = tt open decidable protected definition bool.has_decidable_eq [instance] : ∀a b : bool, decidable (a = b) | ff ff := inl rfl | ff tt := inr ff_ne_tt | tt ff := inr (ne.symm ff_ne_tt) | tt tt := inl rfl definition decidable_eq_of_bool_pred {A : Type} {p : A → A → bool} (H₁ : is_dec_eq p) (H₂ : is_dec_refl p) : decidable_eq A := take x y : A, if Hp : p x y = tt then inl (H₁ Hp) else inr (assume Hxy : x = y, (eq.subst Hxy Hp) (H₂ y)) theorem decidable_eq_inl_refl {A : Type} [H : decidable_eq A] (a : A) : H a a = inl (eq.refl a) := match H a a with | inl e := rfl | inr n := absurd rfl n end open eq.ops theorem decidable_eq_inr_neg {A : Type} [H : decidable_eq A] {a b : A} : Π n : a ≠ b, H a b = inr n := assume n, match H a b with | inl e := absurd e n | inr n₁ := proof_irrel n n₁ ▸ rfl end /- inhabited -/ inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A protected definition inhabited.value {A : Type} : inhabited A → A := inhabited.rec (λa, a) protected definition inhabited.destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B := inhabited.rec H2 H1 definition default (A : Type) [H : inhabited A] : A := inhabited.value H definition arbitrary [irreducible] (A : Type) [H : inhabited A] : A := inhabited.value H definition Prop.is_inhabited [instance] : inhabited Prop := inhabited.mk true definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) := inhabited.rec_on H (λb, inhabited.mk (λa, b)) definition inhabited_Pi [instance] (A : Type) {B : A → Type} [H : Πx, inhabited (B x)] : inhabited (Πx, B x) := inhabited.mk (λa, !default) protected definition bool.is_inhabited [instance] : inhabited bool := inhabited.mk ff protected definition pos_num.is_inhabited [instance] : inhabited pos_num := inhabited.mk pos_num.one protected definition num.is_inhabited [instance] : inhabited num := inhabited.mk num.zero inductive nonempty [class] (A : Type) : Prop := intro : A → nonempty A protected definition nonempty.elim {A : Type} {B : Prop} (H1 : nonempty A) (H2 : A → B) : B := nonempty.rec H2 H1 theorem nonempty_of_inhabited [instance] {A : Type} [H : inhabited A] : nonempty A := nonempty.intro !default theorem nonempty_of_exists {A : Type} {P : A → Prop} : (∃x, P x) → nonempty A := Exists.rec (λw H, nonempty.intro w) /- subsingleton -/ inductive subsingleton [class] (A : Type) : Prop := intro : (∀ a b : A, a = b) → subsingleton A protected definition subsingleton.elim {A : Type} [H : subsingleton A] : ∀(a b : A), a = b := subsingleton.rec (λp, p) H definition subsingleton_prop [instance] (p : Prop) : subsingleton p := subsingleton.intro (λa b, !proof_irrel) definition subsingleton_decidable [instance] (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | inl t₁ := (λ d₂, match d₂ with | inl t₂ := eq.rec_on (proof_irrel t₁ t₂) rfl | inr f₂ := absurd t₁ f₂ end) | inr f₁ := (λ d₂, match d₂ with | inl t₂ := absurd t₂ f₁ | inr f₂ := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected theorem rec_subsingleton {p : Prop} [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} [H3 : Π(h : p), subsingleton (H1 h)] [H4 : Π(h : ¬p), subsingleton (H2 h)] : subsingleton (decidable.rec_on H H1 H2) := decidable.rec_on H (λh, H3 h) (λh, H4 h) --this can be proven using dependent version of "by_cases" theorem if_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (ite c t e) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H theorem if_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (ite c t e) = e := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H theorem if_t_t [simp] (c : Prop) [H : decidable c] {A : Type} (t : A) : (ite c t t) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t)) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t)) H theorem implies_of_if_pos {c t e : Prop} [H : decidable c] (h : ite c t e) : c → t := assume Hc, eq.rec_on (if_pos Hc) h theorem implies_of_if_neg {c t e : Prop} [H : decidable c] (h : ite c t e) : ¬c → e := assume Hnc, eq.rec_on (if_neg Hnc) h theorem if_ctx_congr {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := decidable.rec_on dec_b (λ hp : b, calc ite b x y = x : if_pos hp ... = u : h_t (iff.mp h_c hp) ... = ite c u v : if_pos (iff.mp h_c hp)) (λ hn : ¬b, calc ite b x y = y : if_neg hn ... = v : h_e (iff.mp (not_iff_not_of_iff h_c) hn) ... = ite c u v : if_neg (iff.mp (not_iff_not_of_iff h_c) hn)) theorem if_congr [congr] {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr A b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) theorem if_ctx_simp_congr {A : Type} {b c : Prop} [dec_b : decidable b] {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @if_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x y u v h_c h_t h_e theorem if_simp_congr [congr] {A : Type} {b c : Prop} [dec_b : decidable b] {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @if_ctx_simp_congr A b c dec_b x y u v h_c (λ h, h_t) (λ h, h_e) definition if_true [simp] {A : Type} (t e : A) : (if true then t else e) = t := if_pos trivial definition if_false [simp] {A : Type} (t e : A) : (if false then t else e) = e := if_neg not_false theorem if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := decidable.rec_on dec_b (λ hp : b, calc ite b x y ↔ x : iff.of_eq (if_pos hp) ... ↔ u : h_t (iff.mp h_c hp) ... ↔ ite c u v : iff.of_eq (if_pos (iff.mp h_c hp))) (λ hn : ¬b, calc ite b x y ↔ y : iff.of_eq (if_neg hn) ... ↔ v : h_e (iff.mp (not_iff_not_of_iff h_c) hn) ... ↔ ite c u v : iff.of_eq (if_neg (iff.mp (not_iff_not_of_iff h_c) hn))) theorem if_congr_prop [congr] {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) theorem if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e theorem if_simp_congr_prop [congr] {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) theorem dif_pos {c : Prop} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : dite c t e = t Hc := decidable.rec (λ Hc : c, eq.refl (@dite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H theorem dif_neg {c : Prop} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : dite c t e = e Hnc := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@dite c (decidable.inr Hnc) A t e)) H theorem dif_ctx_congr {A : Type} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → A} {u : c → A} {y : ¬b → A} {v : ¬c → A} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b A x y) = (@dite c dec_c A u v) := decidable.rec_on dec_b (λ hp : b, calc dite b x y = x hp : dif_pos hp ... = x (iff.mpr h_c (iff.mp h_c hp)) : proof_irrel ... = u (iff.mp h_c hp) : h_t ... = dite c u v : dif_pos (iff.mp h_c hp)) (λ hn : ¬b, let h_nc : ¬b ↔ ¬c := not_iff_not_of_iff h_c in calc dite b x y = y hn : dif_neg hn ... = y (iff.mpr h_nc (iff.mp h_nc hn)) : proof_irrel ... = v (iff.mp h_nc hn) : h_e ... = dite c u v : dif_neg (iff.mp h_nc hn)) theorem dif_ctx_simp_congr {A : Type} {b c : Prop} [dec_b : decidable b] {x : b → A} {u : c → A} {y : ¬b → A} {v : ¬c → A} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b A x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @dif_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "definitionally equal" when we ignore the proofs. theorem dite_ite_eq (c : Prop) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e := rfl definition is_true (c : Prop) [H : decidable c] : Prop := if c then true else false definition is_false (c : Prop) [H : decidable c] : Prop := if c then false else true definition of_is_true {c : Prop} [H₁ : decidable c] (H₂ : is_true c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, !false.rec (if_neg Hnc ▸ H₂)) notation `dec_trivial` := of_is_true trivial theorem not_of_not_is_true {c : Prop} [H₁ : decidable c] (H₂ : ¬ is_true c) : ¬ c := if Hc : c then absurd trivial (if_pos Hc ▸ H₂) else Hc theorem not_of_is_false {c : Prop} [H₁ : decidable c] (H₂ : is_false c) : ¬ c := if Hc : c then !false.rec (if_pos Hc ▸ H₂) else Hc theorem of_not_is_false {c : Prop} [H₁ : decidable c] (H₂ : ¬ is_false c) : c := if Hc : c then Hc else absurd trivial (if_neg Hc ▸ H₂) -- The following symbols should not be considered in the pattern inference procedure used by -- heuristic instantiation. attribute and or not iff ite dite eq ne heq [no_pattern] -- namespace used to collect congruence rules for "contextual simplification" namespace contextual attribute if_ctx_simp_congr [congr] attribute if_ctx_simp_congr_prop [congr] attribute dif_ctx_simp_congr [congr] end contextual
e2f844f6f5d21960ae44dfbe34d162b0ef3bd26a
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/int/comp_lemmas.lean
eb836d969eaf992ad700732b81a85e918bf00408
[ "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
5,000
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.int.order namespace int /-! # Auxiliary lemmas for proving that two int numerals are differen -/ /-! 1. Lemmas for reducing the problem to the case where the numerals are positive -/ protected lemma ne_neg_of_ne {a b : ℤ} : a ≠ b → -a ≠ -b := λ h₁ h₂, absurd (int.neg_inj h₂) h₁ protected lemma neg_ne_zero_of_ne {a : ℤ} : a ≠ 0 → -a ≠ 0 := λ h₁ h₂, have -a = -0, by rwa int.neg_zero, have a = 0, from int.neg_inj this, by contradiction protected lemma zero_ne_neg_of_ne {a : ℤ} (h : 0 ≠ a) : 0 ≠ -a := ne.symm (int.neg_ne_zero_of_ne (ne.symm h)) protected lemma neg_ne_of_pos {a b : ℤ} : 0 < a → 0 < b → -a ≠ b := λ h₁ h₂ h, begin rw [← h] at h₂, change 0 < a at h₁, have := le_of_lt h₁, exact absurd (le_of_lt h₁) (not_le_of_gt (int.neg_of_neg_pos h₂)) end protected lemma ne_neg_of_pos {a b : ℤ} : 0 < a → 0 < b → a ≠ -b := λ h₁ h₂, ne.symm (int.neg_ne_of_pos h₂ h₁) /-! 2. Lemmas for proving that positive int numerals are nonneg and positive -/ protected lemma one_pos : 0 < (1:int) := int.zero_lt_one protected lemma bit0_pos {a : ℤ} : 0 < a → 0 < bit0 a := λ h, int.add_pos h h protected lemma bit1_pos {a : ℤ} : 0 ≤ a → 0 < bit1 a := λ h, int.lt_add_of_le_of_pos (int.add_nonneg h h) int.zero_lt_one protected lemma zero_nonneg : 0 ≤ (0 : ℤ) := le_refl 0 protected lemma one_nonneg : 0 ≤ (1 : ℤ) := le_of_lt (int.zero_lt_one) protected lemma bit0_nonneg {a : ℤ} : 0 ≤ a → 0 ≤ bit0 a := λ h, int.add_nonneg h h protected lemma bit1_nonneg {a : ℤ} : 0 ≤ a → 0 ≤ bit1 a := λ h, le_of_lt (int.bit1_pos h) protected lemma nonneg_of_pos {a : ℤ} : 0 < a → 0 ≤ a := le_of_lt /-! 3. nat_abs auxiliary lemmas -/ lemma neg_succ_of_nat_lt_zero (n : ℕ) : neg_succ_of_nat n < 0 := @lt.intro _ _ n (by simp [neg_succ_of_nat_coe, int.coe_nat_succ, int.coe_nat_add, int.coe_nat_one, int.add_comm, int.add_left_comm, int.neg_add, int.add_right_neg, int.zero_add]) lemma zero_le_of_nat (n : ℕ) : 0 ≤ of_nat n := @le.intro _ _ n (by rw [int.zero_add, int.coe_nat_eq]) lemma of_nat_nat_abs_eq_of_nonneg : ∀ {a : ℤ}, 0 ≤ a → of_nat (nat_abs a) = a | (of_nat n) h := rfl | (neg_succ_of_nat n) h := absurd (neg_succ_of_nat_lt_zero n) (not_lt_of_ge h) lemma ne_of_nat_abs_ne_nat_abs_of_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) (h : nat_abs a ≠ nat_abs b) : a ≠ b := assume h, have of_nat (nat_abs a) = of_nat (nat_abs b), by rwa [of_nat_nat_abs_eq_of_nonneg ha, of_nat_nat_abs_eq_of_nonneg hb], begin injection this, contradiction end protected lemma ne_of_nat_ne_nonneg_case {a b : ℤ} {n m : nat} (ha : 0 ≤ a) (hb : 0 ≤ b) (e1 : nat_abs a = n) (e2 : nat_abs b = m) (h : n ≠ m) : a ≠ b := have nat_abs a ≠ nat_abs b, by rwa [e1, e2], ne_of_nat_abs_ne_nat_abs_of_nonneg ha hb this /-! 4. Aux lemmas for pushing nat_abs inside numerals nat_abs_zero and nat_abs_one are defined at init/data/int/basic.lean -/ lemma nat_abs_of_nat_core (n : ℕ) : nat_abs (of_nat n) = n := rfl lemma nat_abs_of_neg_succ_of_nat (n : ℕ) : nat_abs (neg_succ_of_nat n) = nat.succ n := rfl protected lemma nat_abs_add_nonneg : ∀ {a b : int}, 0 ≤ a → 0 ≤ b → nat_abs (a + b) = nat_abs a + nat_abs b | (of_nat n) (of_nat m) h₁ h₂ := have of_nat n + of_nat m = of_nat (n + m), from rfl, by simp [nat_abs_of_nat_core, this] | _ (neg_succ_of_nat m) h₁ h₂ := absurd (neg_succ_of_nat_lt_zero m) (not_lt_of_ge h₂) | (neg_succ_of_nat n) _ h₁ h₂ := absurd (neg_succ_of_nat_lt_zero n) (not_lt_of_ge h₁) protected lemma nat_abs_add_neg : ∀ {a b : int}, a < 0 → b < 0 → nat_abs (a + b) = nat_abs a + nat_abs b | (neg_succ_of_nat n) (neg_succ_of_nat m) h₁ h₂ := have -[1+ n] + -[1+ m] = -[1+ nat.succ (n + m)], from rfl, begin simp [nat_abs_of_neg_succ_of_nat, this, nat.succ_add, nat.add_succ] end protected lemma nat_abs_bit0 : ∀ (a : int), nat_abs (bit0 a) = bit0 (nat_abs a) | (of_nat n) := int.nat_abs_add_nonneg (zero_le_of_nat n) (zero_le_of_nat n) | (neg_succ_of_nat n) := int.nat_abs_add_neg (neg_succ_of_nat_lt_zero n) (neg_succ_of_nat_lt_zero n) protected lemma nat_abs_bit0_step {a : int} {n : nat} (h : nat_abs a = n) : nat_abs (bit0 a) = bit0 n := begin rw [← h], apply int.nat_abs_bit0 end protected lemma nat_abs_bit1_nonneg {a : int} (h : 0 ≤ a) : nat_abs (bit1 a) = bit1 (nat_abs a) := show nat_abs (bit0 a + 1) = bit0 (nat_abs a) + nat_abs 1, from by rw [int.nat_abs_add_nonneg (int.bit0_nonneg h) (le_of_lt (int.zero_lt_one)), int.nat_abs_bit0] protected lemma nat_abs_bit1_nonneg_step {a : int} {n : nat} (h₁ : 0 ≤ a) (h₂ : nat_abs a = n) : nat_abs (bit1 a) = bit1 n := begin rw [← h₂], apply int.nat_abs_bit1_nonneg h₁ end end int
d2ee7fb0dee19de11ab9a798783ef96d0aaab757
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/eq19.lean
2e526ec2115314c7c424717b641d210d73495806
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
458
lean
import data.vector data.prod open nat vector prod variables {A B : Type} definition unzip : Π {n}, vector (A × B) n → vector A n × vector B n, unzip nil := (nil, nil), unzip ((a, b) :: t) := (a :: pr₁ (unzip t), b :: pr₂ (unzip t)) theorem unzip_nil : unzip nil = (@nil A, @nil B) := rfl theorem unzip_cons {n : nat} (a : A) (b : B) (t : vector (A × B) n) : unzip ((a, b) :: t) = (a :: pr₁ (unzip t), b :: pr₂ (unzip t)) := rfl
bbfa4ebbdde379f70daf6594e74ea319d1209c34
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/upto.lean
13391db98aa328ee07174cdab42ef198ba610826
[ "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,380
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.nat.basic /-! # `nat.upto` `nat.upto p`, with `p` a predicate on `ℕ`, is a subtype of elements `n : ℕ` such that no value (strictly) below `n` satisfies `p`. This type has the property that `>` is well-founded when `∃ i, p i`, which allows us to implement searches on `ℕ`, starting at `0` and with an unknown upper-bound. It is similar to the well founded relation constructed to define `nat.find` with the difference that, in `nat.upto p`, `p` does not need to be decidable. In fact, `nat.find` could be slightly altered to factor decidability out of its well founded relation and would then fulfill the same purpose as this file. -/ namespace nat /-- The subtype of natural numbers `i` which have the property that no `j` less than `i` satisfies `p`. This is an initial segment of the natural numbers, up to and including the first value satisfying `p`. We will be particularly interested in the case where there exists a value satisfying `p`, because in this case the `>` relation is well-founded. -/ @[reducible] def upto (p : ℕ → Prop) : Type := {i : ℕ // ∀ j < i, ¬ p j} namespace upto variable {p : ℕ → Prop} /-- Lift the "greater than" relation on natural numbers to `nat.upto`. -/ protected def gt (p) (x y : upto p) : Prop := x.1 > y.1 instance : has_lt (upto p) := ⟨λ x y, x.1 < y.1⟩ /-- The "greater than" relation on `upto p` is well founded if (and only if) there exists a value satisfying `p`. -/ protected lemma wf : (∃ x, p x) → well_founded (upto.gt p) | ⟨x, h⟩ := begin suffices : upto.gt p = measure (λ y : nat.upto p, x - y.val), { rw this, apply measure_wf }, ext ⟨a, ha⟩ ⟨b, _⟩, dsimp [measure, inv_image, upto.gt], rw tsub_lt_tsub_iff_left_of_le, exact le_of_not_lt (λ h', ha _ h' h), end /-- Zero is always a member of `nat.upto p` because it has no predecessors. -/ def zero : nat.upto p := ⟨0, λ j h, false.elim (nat.not_lt_zero _ h)⟩ /-- The successor of `n` is in `nat.upto p` provided that `n` doesn't satisfy `p`. -/ def succ (x : nat.upto p) (h : ¬ p x.val) : nat.upto p := ⟨x.val.succ, λ j h', begin rcases nat.lt_succ_iff_lt_or_eq.1 h' with h' | rfl; [exact x.2 _ h', exact h] end⟩ end upto end nat
a573732eef2ff7d38eccca61db49bab305069e41
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/triangulated/rotate.lean
f649eab584c1f9f3505f922be617e491c80a2042
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,214
lean
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw -/ import category_theory.preadditive.additive_functor import category_theory.triangulated.basic /-! # Rotate This file adds the ability to rotate triangles and triangle morphisms. It also shows that rotation gives an equivalence on the category of triangles. -/ noncomputable theory open category_theory open category_theory.preadditive open category_theory.limits universes v v₀ v₁ v₂ u u₀ u₁ u₂ namespace category_theory.triangulated open category_theory.category /-- We work in an preadditive category `C` equipped with an additive shift. -/ variables {C : Type u} [category.{v} C] [preadditive C] variables [has_shift C ℤ] variables (X : C) /-- If you rotate a triangle, you get another triangle. Given a triangle of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` applying `rotate` gives a triangle of the form: ``` g h -f⟦1⟧' Y ───> Z ───> X⟦1⟧ ───> Y⟦1⟧ ``` -/ @[simps] def triangle.rotate (T : triangle C) : triangle C := triangle.mk _ T.mor₂ T.mor₃ (-T.mor₁⟦1⟧') section local attribute [semireducible] shift_shift_neg shift_neg_shift /-- Given a triangle of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` applying `inv_rotate` gives a triangle that can be thought of as: ``` -h⟦-1⟧' f g Z⟦-1⟧ ───> X ───> Y ───> Z ``` (note that this diagram doesn't technically fit the definition of triangle, as `Z⟦-1⟧⟦1⟧` is not necessarily equal to `Z`, but it is isomorphic, by the `counit_iso` of `shift C`) -/ @[simps] def triangle.inv_rotate (T : triangle C) : triangle C := triangle.mk _ (-T.mor₃⟦(-1:ℤ)⟧' ≫ (shift_shift_neg _ _).hom) T.mor₁ (T.mor₂ ≫ (shift_neg_shift _ _).inv) end namespace triangle_morphism variables {T₁ T₂ T₃ T₄: triangle C} open triangle /-- You can also rotate a triangle morphism to get a morphism between the two rotated triangles. Given a triangle morphism of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │ │a │b │c │a⟦1⟧ V V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` applying `rotate` gives a triangle morphism of the form: ``` g h -f⟦1⟧ Y ───> Z ───> X⟦1⟧ ───> Y⟦1⟧ │ │ │ │ │b │c │a⟦1⟧ │b⟦1⟧' V V V V Y' ───> Z' ───> X'⟦1⟧ ───> Y'⟦1⟧ g' h' -f'⟦1⟧ ``` -/ @[simps] def rotate (f : triangle_morphism T₁ T₂) : triangle_morphism (T₁.rotate) (T₂.rotate):= { hom₁ := f.hom₂, hom₂ := f.hom₃, hom₃ := f.hom₁⟦1⟧', comm₃' := begin dsimp, simp only [rotate_mor₃, comp_neg, neg_comp, ← functor.map_comp, f.comm₁] end } /-- Given a triangle morphism of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │ │a │b │c │a⟦1⟧ V V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` applying `inv_rotate` gives a triangle morphism that can be thought of as: ``` -h⟦-1⟧ f g Z⟦-1⟧ ───> X ───> Y ───> Z │ │ │ │ │c⟦-1⟧' │a │b │c V V V V Z'⟦-1⟧ ───> X' ───> Y' ───> Z' -h'⟦-1⟧ f' g' ``` (note that this diagram doesn't technically fit the definition of triangle morphism, as `Z⟦-1⟧⟦1⟧` is not necessarily equal to `Z`, and `Z'⟦-1⟧⟦1⟧` is not necessarily equal to `Z'`, but they are isomorphic, by the `counit_iso` of `shift C`) -/ @[simps] def inv_rotate (f : triangle_morphism T₁ T₂) : triangle_morphism (T₁.inv_rotate) (T₂.inv_rotate) := { hom₁ := f.hom₃⟦-1⟧', hom₂ := f.hom₁, hom₃ := f.hom₂, comm₁' := begin dsimp [inv_rotate_mor₁], simp only [discrete.functor_map_id, id_comp, preadditive.comp_neg, assoc, neg_inj, nat_trans.id_app, preadditive.neg_comp], rw [← functor.map_comp_assoc, ← f.comm₃, functor.map_comp_assoc, μ_naturality_assoc, nat_trans.naturality, functor.id_map], end, comm₃' := begin dsimp, simp only [discrete.functor_map_id, id_comp, opaque_eq_to_iso_inv, μ_inv_naturality, category.assoc, nat_trans.id_app, unit_of_tensor_iso_unit_inv_app], erw ε_naturality_assoc, rw comm₂_assoc end } end triangle_morphism variables (C) /-- Rotating triangles gives an endofunctor on the category of triangles in `C`. -/ @[simps] def rotate : triangle C ⥤ triangle C := { obj := triangle.rotate, map := λ _ _ f, f.rotate } /-- The inverse rotation of triangles gives an endofunctor on the category of triangles in `C`. -/ @[simps] def inv_rotate : triangle C ⥤ triangle C := { obj := triangle.inv_rotate, map := λ _ _ f, f.inv_rotate } variables {C} variables [∀ n : ℤ, functor.additive (shift_functor C n)] /-- There is a natural map from a triangle to the `inv_rotate` of its `rotate`. -/ @[simps] def to_inv_rotate_rotate (T : triangle C) : T ⟶ (inv_rotate C).obj ((rotate C).obj T) := { hom₁ := (shift_shift_neg _ _).inv, hom₂ := 𝟙 T.obj₂, hom₃ := 𝟙 T.obj₃, comm₃' := begin dsimp, simp only [ε_app_obj, eq_to_iso.hom, discrete.functor_map_id, id_comp, eq_to_iso.inv, opaque_eq_to_iso_inv, category.assoc, obj_μ_inv_app, functor.map_comp, nat_trans.id_app, obj_ε_app, unit_of_tensor_iso_unit_inv_app], erw μ_inv_hom_app_assoc, refl end } /-- There is a natural transformation between the identity functor on triangles in `C`, and the composition of a rotation with an inverse rotation. -/ @[simps] def rot_comp_inv_rot_hom : 𝟭 (triangle C) ⟶ rotate C ⋙ inv_rotate C := { app := to_inv_rotate_rotate, naturality' := begin introv, ext, { dsimp, simp only [nat_iso.cancel_nat_iso_inv_right_assoc, discrete.functor_map_id, id_comp, opaque_eq_to_iso_inv, μ_inv_naturality, assoc, nat_trans.id_app, unit_of_tensor_iso_unit_inv_app], erw ε_naturality }, { dsimp, rw [comp_id, id_comp] }, { dsimp, rw [comp_id, id_comp] }, end } /-- There is a natural map from the `inv_rotate` of the `rotate` of a triangle to itself. -/ @[simps] def from_inv_rotate_rotate (T : triangle C) : (inv_rotate C).obj ((rotate C).obj T) ⟶ T := { hom₁ := (shift_equiv C 1).unit_inv.app T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := 𝟙 T.obj₃, comm₃' := begin dsimp, rw [unit_of_tensor_iso_unit_inv_app, ε_app_obj], simp only [discrete.functor_map_id, nat_trans.id_app, id_comp, assoc, functor.map_comp, obj_μ_app, obj_ε_inv_app, comp_id, μ_inv_hom_app_assoc], erw [μ_inv_hom_app, μ_inv_hom_app_assoc, category.comp_id] end } /-- There is a natural transformation between the composition of a rotation with an inverse rotation on triangles in `C`, and the identity functor. -/ @[simps] def rot_comp_inv_rot_inv : rotate C ⋙ inv_rotate C ⟶ 𝟭 (triangle C) := { app := from_inv_rotate_rotate } /-- The natural transformations between the identity functor on triangles in `C` and the composition of a rotation with an inverse rotation are natural isomorphisms (they are isomorphisms in the category of functors). -/ @[simps] def rot_comp_inv_rot : 𝟭 (triangle C) ≅ rotate C ⋙ inv_rotate C := { hom := rot_comp_inv_rot_hom, inv := rot_comp_inv_rot_inv } /-- There is a natural map from the `rotate` of the `inv_rotate` of a triangle to itself. -/ @[simps] def from_rotate_inv_rotate (T : triangle C) : (rotate C).obj ((inv_rotate C).obj T) ⟶ T := { hom₁ := 𝟙 T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := (shift_equiv C 1).counit.app T.obj₃, comm₂' := begin dsimp, rw unit_of_tensor_iso_unit_inv_app, simp only [discrete.functor_map_id, nat_trans.id_app, id_comp, add_neg_equiv_counit_iso_hom, eq_to_hom_refl, nat_trans.comp_app, assoc, μ_inv_hom_app_assoc, ε_hom_inv_app], exact category.comp_id _, end, comm₃' := begin dsimp, simp only [discrete.functor_map_id, nat_trans.id_app, id_comp, functor.map_neg, functor.map_comp, obj_μ_app, obj_ε_inv_app, comp_id, assoc, μ_naturality_assoc, neg_neg, category_theory.functor.map_id, add_neg_equiv_counit_iso_hom, eq_to_hom_refl, nat_trans.comp_app], erw [μ_inv_hom_app, category.comp_id, obj_zero_map_μ_app], rw [discrete.functor_map_id, nat_trans.id_app, comp_id], end } /-- There is a natural transformation between the composition of an inverse rotation with a rotation on triangles in `C`, and the identity functor. -/ @[simps] def inv_rot_comp_rot_hom : inv_rotate C ⋙ rotate C ⟶ 𝟭 (triangle C) := { app := from_rotate_inv_rotate } /-- There is a natural map from a triangle to the `rotate` of its `inv_rotate`. -/ @[simps] def to_rotate_inv_rotate (T : triangle C) : T ⟶ (rotate C).obj ((inv_rotate C).obj T) := { hom₁ := 𝟙 T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := (shift_equiv C 1).counit_inv.app T.obj₃, comm₃' := begin dsimp, rw category_theory.functor.map_id, simp only [comp_id, add_neg_equiv_counit_iso_inv, eq_to_hom_refl, id_comp, nat_trans.comp_app, discrete.functor_map_id, nat_trans.id_app, functor.map_neg, functor.map_comp, obj_μ_app, obj_ε_inv_app, assoc, μ_naturality_assoc, neg_neg, μ_inv_hom_app_assoc], erw [μ_inv_hom_app, category.comp_id, obj_zero_map_μ_app], simp only [discrete.functor_map_id, nat_trans.id_app, comp_id, ε_hom_inv_app_assoc], end } /-- There is a natural transformation between the identity functor on triangles in `C`, and the composition of an inverse rotation with a rotation. -/ @[simps] def inv_rot_comp_rot_inv : 𝟭 (triangle C) ⟶ inv_rotate C ⋙ rotate C := { app := to_rotate_inv_rotate, naturality' := begin introv, ext, { dsimp, rw [comp_id, id_comp] }, { dsimp, rw [comp_id, id_comp] }, { dsimp, rw [add_neg_equiv_counit_iso_inv, eq_to_hom_refl, id_comp], simp only [nat_trans.comp_app, assoc], erw [μ_inv_naturality, ε_naturality_assoc] }, end } /-- The natural transformations between the composition of a rotation with an inverse rotation on triangles in `C`, and the identity functor on triangles are natural isomorphisms (they are isomorphisms in the category of functors). -/ @[simps] def inv_rot_comp_rot : inv_rotate C ⋙ rotate C ≅ 𝟭 (triangle C) := { hom := inv_rot_comp_rot_hom, inv := inv_rot_comp_rot_inv } variables (C) /-- Rotating triangles gives an auto-equivalence on the category of triangles in `C`. -/ @[simps] def triangle_rotation : equivalence (triangle C) (triangle C) := { functor := rotate C, inverse := inv_rotate C, unit_iso := rot_comp_inv_rot, counit_iso := inv_rot_comp_rot, functor_unit_iso_comp' := begin introv, ext, { dsimp, rw comp_id }, { dsimp, rw comp_id }, { dsimp, rw unit_of_tensor_iso_unit_inv_app, simp only [discrete.functor_map_id, nat_trans.id_app, id_comp, functor.map_comp, obj_ε_app, obj_μ_inv_app, assoc, add_neg_equiv_counit_iso_hom, eq_to_hom_refl, nat_trans.comp_app, ε_inv_app_obj, comp_id, μ_inv_hom_app_assoc], erw [μ_inv_hom_app_assoc, μ_inv_hom_app], refl } end } variables {C} instance : is_equivalence (rotate C) := by { change is_equivalence (triangle_rotation C).functor, apply_instance, } instance : is_equivalence (inv_rotate C) := by { change is_equivalence (triangle_rotation C).inverse, apply_instance, } end category_theory.triangulated
fd44fdbd3bc148ee86cdfa45355a1acc01247e9c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/semiconj_Sup_auto.lean
fcfeebcabad973c099a95a14daacbd3e9a81bce3
[]
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,029
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.conditionally_complete_lattice import Mathlib.logic.function.conjugate import Mathlib.order.ord_continuous import Mathlib.data.equiv.mul_add import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Semiconjugate by `Sup` In this file we prove two facts about semiconjugate (families of) functions. First, if an order isomorphism `fa : α → α` is semiconjugate to an order embedding `fb : β → β` by `g : α → β`, then `fb` is semiconjugate to `fa` by `y ↦ Sup {x | g x ≤ y}`, see `semiconj.symm_adjoint`. Second, consider two actions `f₁ f₂ : G → α → α` of a group on a complete lattice by order isomorphisms. Then the map `x ↦ ⨆ g : G, (f₁ g)⁻¹ (f₂ g x)` semiconjugates each `f₁ g'` to `f₂ g'`, see `function.Sup_div_semiconj`. In the case of a conditionally complete lattice, a similar statement holds true under an additional assumption that each set `{(f₁ g)⁻¹ (f₂ g x) | g : G}` is bounded above, see `function.cSup_div_semiconj`. The lemmas come from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes], Proposition 2.1 and 5.4 respectively. In the paper they are formulated for homeomorphisms of the circle, so in order to apply results from this file one has to lift these homeomorphisms to the real line first. -/ /-- We say that `g : β → α` is an order right adjoint function for `f : α → β` if it sends each `y` to a least upper bound for `{x | f x ≤ y}`. If `α` is a partial order, and `f : α → β` has a right adjoint, then this right adjoint is unique. -/ def is_order_right_adjoint {α : Type u_1} {β : Type u_2} [preorder α] [preorder β] (f : α → β) (g : β → α) := ∀ (y : β), is_lub (set_of fun (x : α) => f x ≤ y) (g y) theorem is_order_right_adjoint_Sup {α : Type u_1} {β : Type u_2} [complete_lattice α] [preorder β] (f : α → β) : is_order_right_adjoint f fun (y : β) => Sup (set_of fun (x : α) => f x ≤ y) := fun (y : β) => is_lub_Sup (set_of fun (x : α) => f x ≤ y) theorem is_order_right_adjoint_cSup {α : Type u_1} {β : Type u_2} [conditionally_complete_lattice α] [preorder β] (f : α → β) (hne : ∀ (y : β), ∃ (x : α), f x ≤ y) (hbdd : ∀ (y : β), ∃ (b : α), ∀ (x : α), f x ≤ y → x ≤ b) : is_order_right_adjoint f fun (y : β) => Sup (set_of fun (x : α) => f x ≤ y) := fun (y : β) => is_lub_cSup (hne y) (hbdd y) theorem is_order_right_adjoint.unique {α : Type u_1} {β : Type u_2} [partial_order α] [preorder β] {f : α → β} {g₁ : β → α} {g₂ : β → α} (h₁ : is_order_right_adjoint f g₁) (h₂ : is_order_right_adjoint f g₂) : g₁ = g₂ := funext fun (y : β) => is_lub.unique (h₁ y) (h₂ y) theorem is_order_right_adjoint.right_mono {α : Type u_1} {β : Type u_2} [preorder α] [preorder β] {f : α → β} {g : β → α} (h : is_order_right_adjoint f g) : monotone g := fun (y₁ y₂ : β) (hy : y₁ ≤ y₂) => is_lub.mono (h y₁) (h y₂) fun (x : α) (hx : x ∈ set_of fun (x : α) => f x ≤ y₁) => le_trans hx hy namespace function /-- If an order automorphism `fa` is semiconjugate to an order embedding `fb` by a function `g` and `g'` is an order right adjoint of `g` (i.e. `g' y = Sup {x | f x ≤ y}`), then `fb` is semiconjugate to `fa` by `g'`. This is a version of Proposition 2.1 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ theorem semiconj.symm_adjoint {α : Type u_1} {β : Type u_2} [partial_order α] [preorder β] {fa : α ≃o α} {fb : β ↪o β} {g : α → β} (h : semiconj g ⇑fa ⇑fb) {g' : β → α} (hg' : is_order_right_adjoint g g') : semiconj g' ⇑fb ⇑fa := sorry theorem semiconj_of_is_lub {α : Type u_1} {G : Type u_3} [partial_order α] [group G] (f₁ : G →* α ≃o α) (f₂ : G →* α ≃o α) {h : α → α} (H : ∀ (x : α), is_lub (set.range fun (g' : G) => coe_fn (coe_fn f₁ g'⁻¹) (coe_fn (coe_fn f₂ g') x)) (h x)) (g : G) : semiconj h ⇑(coe_fn f₂ g) ⇑(coe_fn f₁ g) := sorry /-- Consider two actions `f₁ f₂ : G → α → α` of a group on a complete lattice by order isomorphisms. Then the map `x ↦ ⨆ g : G, (f₁ g)⁻¹ (f₂ g x)` semiconjugates each `f₁ g'` to `f₂ g'`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ theorem Sup_div_semiconj {α : Type u_1} {G : Type u_3} [complete_lattice α] [group G] (f₁ : G →* α ≃o α) (f₂ : G →* α ≃o α) (g : G) : semiconj (fun (x : α) => supr fun (g' : G) => coe_fn (coe_fn f₁ g'⁻¹) (coe_fn (coe_fn f₂ g') x)) ⇑(coe_fn f₂ g) ⇑(coe_fn f₁ g) := semiconj_of_is_lub f₁ f₂ (fun (x : α) => is_lub_supr) g /-- Consider two actions `f₁ f₂ : G → α → α` of a group on a conditionally complete lattice by order isomorphisms. Suppose that each set $s(x)=\{f_1(g)^{-1} (f_2(g)(x)) | g \in G\}$ is bounded above. Then the map `x ↦ Sup s(x)` semiconjugates each `f₁ g'` to `f₂ g'`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ theorem cSup_div_semiconj {α : Type u_1} {G : Type u_3} [conditionally_complete_lattice α] [group G] (f₁ : G →* α ≃o α) (f₂ : G →* α ≃o α) (hbdd : ∀ (x : α), bdd_above (set.range fun (g : G) => coe_fn (coe_fn f₁ g⁻¹) (coe_fn (coe_fn f₂ g) x))) (g : G) : semiconj (fun (x : α) => supr fun (g' : G) => coe_fn (coe_fn f₁ g'⁻¹) (coe_fn (coe_fn f₂ g') x)) ⇑(coe_fn f₂ g) ⇑(coe_fn f₁ g) := sorry end Mathlib
4a8a0d9bbc03b4ff747d8f85b2339cc65243fb63
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/tools/super/misc_preprocessing.lean
7ad73972727d529d850e4051b35c2f8c77846ac9
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,156
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state open expr list monad namespace super meta def is_taut (c : clause) : tactic bool := do qf ← c^.open_constn c^.num_quants, return $ list.bor $ do l1 ← qf^.1^.get_lits, guard l1^.is_neg, l2 ← qf^.1^.get_lits, guard l2^.is_pos, [decidable.to_bool $ l1^.formula = l2^.formula] meta def tautology_removal_pre : prover unit := preprocessing_rule $ λnew, filter (λc, lift bnot $ is_taut c^.c) new meta def remove_duplicates : list derived_clause → list derived_clause | [] := [] | (c :: cs) := let (same_type, other_type) := partition (λc' : derived_clause, c'^.c^.type = c^.c^.type) cs in { c with sc := foldl score.min c^.sc (same_type^.map $ λc, c^.sc) } :: remove_duplicates other_type meta def remove_duplicates_pre : prover unit := preprocessing_rule $ λnew, return $ remove_duplicates new meta def clause_normalize_pre : prover unit := preprocessing_rule $ λnew, for new $ λdc, do c' ← dc^.c^.normalize, return { dc with c := c' } end super
6ba079d10bc3a0f75d051b6c730a7b70c9d2aa1d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/protected.lean
83edc46a884c5afd3553a47c071ef1f37d972835
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,812
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import tactic.core /-! ## `protected` and `protect_proj` user attributes `protected` is an attribute to protect a declaration. If a declaration `foo.bar` is marked protected, then it must be referred to by its full name `foo.bar`, even when the `foo` namespace is open. `protect_proj` attribute to protect the projections of a structure. If a structure `foo` is marked with the `protect_proj` user attribute, then all of the projections become protected. `protect_proj without bar baz` will protect all projections except for `bar` and `baz`. # Examples In this example all of `foo.bar`, `foo.baz` and `foo.qux` will be protected. ``` @[protect_proj] structure foo : Type := (bar : unit) (baz : unit) (qux : unit) ``` The following code example define the structure `foo`, and the projections `foo.qux` will be protected, but not `foo.baz` or `foo.bar` ``` @[protect_proj without baz bar] structure foo : Type := (bar : unit) (baz : unit) (qux : unit) ``` -/ namespace tactic /-- Attribute to protect a declaration. If a declaration `foo.bar` is marked protected, then it must be referred to by its full name `foo.bar`, even when the `foo` namespace is open. Protectedness is a built in parser feature that is independent of this attribute. A declaration may be protected even if it does not have the `@[protected]` attribute. This provides a convenient way to protect many declarations at once. -/ @[user_attribute] meta def protected_attr : user_attribute := { name := "protected", descr := "Attribute to protect a declaration If a declaration `foo.bar` is marked protected, then it must be referred to by its full name `foo.bar`, even when the `foo` namespace is open.", after_set := some (λ n _ _, mk_protected n) } add_tactic_doc { name := "protected", category := doc_category.attr, decl_names := [`tactic.protected_attr], tags := ["parsing", "environment"] } /-- Tactic that is executed when a structure is marked with the `protect_proj` attribute -/ meta def protect_proj_tac (n : name) (l : list name) : tactic unit := do env ← get_env, match env.structure_fields_full n with | none := fail "protect_proj failed: declaration is not a structure" | some fields := fields.mmap' $ λ field, when (l.all $ λ m, bnot $ m.is_suffix_of field) $ mk_protected field end /-- Attribute to protect the projections of a structure. If a structure `foo` is marked with the `protect_proj` user attribute, then all of the projections become protected, meaning they must always be referred to by their full name `foo.bar`, even when the `foo` namespace is open. `protect_proj without bar baz` will protect all projections except for `bar` and `baz`. ```lean @[protect_proj without baz bar] structure foo : Type := (bar : unit) (baz : unit) (qux : unit) ``` -/ @[user_attribute] meta def protect_proj_attr : user_attribute unit (list name) := { name := "protect_proj", descr := "Attribute to protect the projections of a structure. If a structure `foo` is marked with the `protect_proj` user attribute, then all of the projections become protected, meaning they must always be referred to by their full name `foo.bar`, even when the `foo` namespace is open. `protect_proj without bar baz` will protect all projections except for bar and baz", after_set := some (λ n _ _, do l ← protect_proj_attr.get_param n, protect_proj_tac n l), parser := interactive.types.without_ident_list } add_tactic_doc { name := "protect_proj", category := doc_category.attr, decl_names := [`tactic.protect_proj_attr], tags := ["parsing", "environment", "structures"] } end tactic
d4811fc491ff23d4682e871e929402e91afccc34
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/infoTree.lean
9d50fa347e9038ffce5c4894f34947eaa0ca4d19
[ "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
838
lean
import Lean open Lean.Elab structure A where val : Nat → Nat structure B where pair : A × A set_option trace.Elab.info true def f (x : Nat) : Nat × Nat := let y := ⟨x, x⟩ id y def h : (x y : Nat) → (b : Bool) → x + 0 = x := fun x y b => by simp def f2 : (x y : Nat) → (b : Bool) → Nat := fun x y b => let (z, w) := (x + y, x - y) let z1 := z + w z + z1 def f3 (s : Nat × Array (Array Nat)) : Array Nat := s.2[1].push s.1 def f4 (arg : B) : Nat := arg.pair.fst.val 0 def f5 (x : Nat) : B := { pair := ({ val := id }, { val := id }) } open Nat in #print xor instance : Inhabited Nat where macro -- `x` and `y` should both have a signature and a body binder definition set_option pp.raw true def f6 (x y : Nat) : x = x := let rec f7 (x y : Nat) : x = x := Eq.refl x f7 x y
115a9d47c56647c3f32076996706d211b46c550c
f7315930643edc12e76c229a742d5446dad77097
/tests/lean/run/tactic27.lean
6eff6ea7fc0064a50b286789a03f6e0e99d0247c
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
189
lean
import logic open tactic definition my_tac := repeat (apply @and.intro | apply @eq.refl) tactic_hint my_tac theorem T1 {A : Type} {B : Type} (a : A) (b c : B) : a = a ∧ b = b ∧ c = c
e166c566aa26e351ff702febdf7a535679332b40
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Compiler/IR/Basic.lean
8931dcb1211e26d6402b28fee132c9bf42bd5c82
[ "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
26,212
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Data.Name import Lean.Data.Format import Lean.Compiler.ExternAttr /- Implements (extended) λPure and λRc proposed in the article "Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura. The Lean to IR transformation produces λPure code, and this part is implemented in C++. The procedures described in the paper above are implemented in Lean. -/ namespace Lean.IR /- Function identifier -/ abbrev FunId := Name abbrev Index := Nat /- Variable identifier -/ structure VarId where idx : Index deriving Inhabited /- Join point identifier -/ structure JoinPointId where idx : Index deriving Inhabited abbrev Index.lt (a b : Index) : Bool := a < b instance : BEq VarId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩ instance : ToFormat VarId := ⟨fun a => toString a⟩ instance : Hashable VarId := ⟨fun a => hash a.idx⟩ instance : BEq JoinPointId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩ instance : ToFormat JoinPointId := ⟨fun a => toString a⟩ instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩ abbrev MData := KVMap abbrev MData.empty : MData := {} /- Low Level IR types. Most are self explanatory. - `usize` represents the C++ `size_t` Type. We have it here because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines, and we want the C++ backend for our Compiler to generate platform independent code. - `irrelevant` for Lean types, propositions and proofs. - `object` a pointer to a value in the heap. - `tobject` a pointer to a value in the heap or tagged pointer (i.e., the least significant bit is 1) storing a scalar value. - `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`) on the stack. Remark: the RC operations for `tobject` are slightly more expensive because we first need to test whether the `tobject` is really a pointer or not. Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT). Lean cannot be compiled on old platforms where this is not True. Since values of type `struct` and `union` are only used to return values, We assume they must be used/consumed "linearly". We use the term "linear" here to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct, then one of the following must hold in each (execution) branch. 1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned. 2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`. 3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union fields that do not contain object fields. -/ inductive IRType where | float | uint8 | uint16 | uint32 | uint64 | usize | irrelevant | object | tobject | struct (leanTypeName : Option Name) (types : Array IRType) : IRType | union (leanTypeName : Name) (types : Array IRType) : IRType deriving Inhabited namespace IRType partial def beq : IRType → IRType → Bool | float, float => true | uint8, uint8 => true | uint16, uint16 => true | uint32, uint32 => true | uint64, uint64 => true | usize, usize => true | irrelevant, irrelevant => true | object, object => true | tobject, tobject => true | struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | _, _ => false instance : BEq IRType := ⟨beq⟩ def isScalar : IRType → Bool | float => true | uint8 => true | uint16 => true | uint32 => true | uint64 => true | usize => true | _ => false def isObj : IRType → Bool | object => true | tobject => true | _ => false def isIrrelevant : IRType → Bool | irrelevant => true | _ => false def isStruct : IRType → Bool | struct _ _ => true | _ => false def isUnion : IRType → Bool | union _ _ => true | _ => false end IRType /- Arguments to applications, constructors, etc. We use `irrelevant` for Lean types, propositions and proofs that have been erased. Recall that for a Function `f`, we also generate `f._rarg` which does not take `irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/ inductive Arg where | var (id : VarId) | irrelevant deriving Inhabited protected def Arg.beq : Arg → Arg → Bool | var x, var y => x == y | irrelevant, irrelevant => true | _, _ => false instance : BEq Arg := ⟨Arg.beq⟩ @[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id inductive LitVal where | num (v : Nat) | str (v : String) def LitVal.beq : LitVal → LitVal → Bool | num v₁, num v₂ => v₁ == v₂ | str v₁, str v₂ => v₁ == v₂ | _, _ => false instance : BEq LitVal := ⟨LitVal.beq⟩ /- Constructor information. - `name` is the Name of the Constructor in Lean. - `cidx` is the Constructor index (aka tag). - `size` is the number of arguments of type `object/tobject`. - `usize` is the number of arguments of type `usize`. - `ssize` is the number of bytes used to store scalar values. Recall that a Constructor object contains a header, then a sequence of pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`) scalar values, and a sequence of other scalar values. -/ structure CtorInfo where name : Name cidx : Nat size : Nat usize : Nat ssize : Nat def CtorInfo.beq : CtorInfo → CtorInfo → Bool | ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ => n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂ instance : BEq CtorInfo := ⟨CtorInfo.beq⟩ def CtorInfo.isRef (info : CtorInfo) : Bool := info.size > 0 || info.usize > 0 || info.ssize > 0 def CtorInfo.isScalar (info : CtorInfo) : Bool := !info.isRef inductive Expr where /- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime. This instruction is also used to creat `struct` and `union` return values. For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/ | ctor (i : CtorInfo) (ys : Array Arg) | reset (n : Nat) (x : VarId) /- `reuse x in ctor_i ys` instruction in the paper. -/ | reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg) /- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`. We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/ | proj (i : Nat) (x : VarId) /- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/ | uproj (i : Nat) (x : VarId) /- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/ | sproj (n : Nat) (offset : Nat) (x : VarId) /- Full application. -/ | fap (c : FunId) (ys : Array Arg) /- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/ | pap (c : FunId) (ys : Array Arg) /- Application. `x` must be a `pap` value. -/ | ap (x : VarId) (ys : Array Arg) /- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`. For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/ | box (ty : IRType) (x : VarId) /- Given `x : [t]object`, obtain the scalar value. -/ | unbox (x : VarId) | lit (v : LitVal) /- Return `1 : uint8` Iff `RC(x) > 1` -/ | isShared (x : VarId) /- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/ | isTaggedPtr (x : VarId) @[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr := Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys @[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x @[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x @[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x @[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys @[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys @[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys @[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v) @[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v) structure Param where x : VarId borrow : Bool ty : IRType deriving Inhabited @[export lean_ir_mk_param] def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩ inductive AltCore (FnBody : Type) : Type where | ctor (info : CtorInfo) (b : FnBody) : AltCore FnBody | default (b : FnBody) : AltCore FnBody inductive FnBody where /- `let x : ty := e; b` -/ | vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) /- Join point Declaration `block_j (xs) := e; b` -/ | jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) /- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. This operation is not part of λPure is only used during optimization. -/ | set (x : VarId) (i : Nat) (y : Arg) (b : FnBody) | setTag (x : VarId) (cidx : Nat) (b : FnBody) /- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/ | uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody) /- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. `ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/ | sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) /- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) /- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) | del (x : VarId) (b : FnBody) | mdata (d : MData) (b : FnBody) | case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody)) | ret (x : Arg) /- Jump to join point `j` -/ | jmp (j : JoinPointId) (ys : Array Arg) | unreachable instance : Inhabited FnBody := ⟨FnBody.unreachable⟩ abbrev FnBody.nil := FnBody.unreachable @[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b @[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b @[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b @[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b @[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody := -- Type field `xType` is set by `explicitBoxing` compiler pass. FnBody.case tid x IRType.object cs @[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x @[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys @[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable abbrev Alt := AltCore FnBody @[matchPattern] abbrev Alt.ctor := @AltCore.ctor FnBody @[matchPattern] abbrev Alt.default := @AltCore.default FnBody instance : Inhabited Alt := ⟨Alt.default arbitrary⟩ def FnBody.isTerminal : FnBody → Bool | FnBody.case _ _ _ _ => true | FnBody.ret _ => true | FnBody.jmp _ _ => true | FnBody.unreachable => true | _ => false def FnBody.body : FnBody → FnBody | FnBody.vdecl _ _ _ b => b | FnBody.jdecl _ _ _ b => b | FnBody.set _ _ _ b => b | FnBody.uset _ _ _ b => b | FnBody.sset _ _ _ _ _ b => b | FnBody.setTag _ _ b => b | FnBody.inc _ _ _ _ b => b | FnBody.dec _ _ _ _ b => b | FnBody.del _ b => b | FnBody.mdata _ b => b | other => other def FnBody.setBody : FnBody → FnBody → FnBody | FnBody.vdecl x t v _, b => FnBody.vdecl x t v b | FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b | FnBody.set x i y _, b => FnBody.set x i y b | FnBody.uset x i y _, b => FnBody.uset x i y b | FnBody.sset x i o y t _, b => FnBody.sset x i o y t b | FnBody.setTag x i _, b => FnBody.setTag x i b | FnBody.inc x n c p _, b => FnBody.inc x n c p b | FnBody.dec x n c p _, b => FnBody.dec x n c p b | FnBody.del x _, b => FnBody.del x b | FnBody.mdata d _, b => FnBody.mdata d b | other, b => other @[inline] def FnBody.resetBody (b : FnBody) : FnBody := b.setBody FnBody.nil /- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`, and c.body == FnBody.nil -/ @[inline] def FnBody.split (b : FnBody) : FnBody × FnBody := let b' := b.body let c := b.resetBody (c, b') def AltCore.body : Alt → FnBody | Alt.ctor _ b => b | Alt.default b => b def AltCore.setBody : Alt → FnBody → Alt | Alt.ctor c _, b => Alt.ctor c b | Alt.default _, b => Alt.default b @[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt | Alt.ctor c b => Alt.ctor c (f b) | Alt.default b => Alt.default (f b) @[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt | Alt.ctor c b => Alt.ctor c <$> f b | Alt.default b => Alt.default <$> f b def Alt.isDefault : Alt → Bool | Alt.ctor _ _ => false | Alt.default _ => true def push (bs : Array FnBody) (b : FnBody) : Array FnBody := let b := b.resetBody bs.push b partial def flattenAux (b : FnBody) (r : Array FnBody) : (Array FnBody) × FnBody := if b.isTerminal then (r, b) else flattenAux b.body (push r b) def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody := flattenAux b #[] partial def reshapeAux (a : Array FnBody) (i : Nat) (b : FnBody) : FnBody := if i == 0 then b else let i := i - 1 let (curr, a) := a.swapAt! i arbitrary let b := curr.setBody b reshapeAux a i b def reshape (bs : Array FnBody) (term : FnBody) : FnBody := reshapeAux bs bs.size term @[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody := bs.map fun b => match b with | FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k | other => other @[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) := bs.mapM fun b => match b with | FnBody.jdecl j xs v k => do let v ← f v; pure $ FnBody.jdecl j xs v k | other => pure other @[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt := Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b /-- Extra information associated with a declaration. -/ structure DeclInfo where /-- If `some <blame>`, then declaration depends on `<blame>` which uses a `sorry` axiom. -/ sorryDep? : Option Name := none inductive Decl where | fdecl (f : FunId) (xs : Array Param) (type : IRType) (body : FnBody) (info : DeclInfo) | extern (f : FunId) (xs : Array Param) (type : IRType) (ext : ExternAttrData) deriving Inhabited namespace Decl def name : Decl → FunId | Decl.fdecl f .. => f | Decl.extern f .. => f def params : Decl → Array Param | Decl.fdecl (xs := xs) .. => xs | Decl.extern (xs := xs) .. => xs def resultType : Decl → IRType | Decl.fdecl (type := t) .. => t | Decl.extern (type := t) .. => t def isExtern : Decl → Bool | Decl.extern .. => true | _ => false def getInfo : Decl → DeclInfo | Decl.fdecl (info := info) .. => info | _ => {} def updateBody! (d : Decl) (bNew : FnBody) : Decl := match d with | Decl.fdecl f xs t b info => Decl.fdecl f xs t bNew info | _ => panic! "expected definition" end Decl @[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl := Decl.fdecl f xs ty b {} @[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl := Decl.extern f xs ty e open Std (RBTree RBTree.empty RBMap) /-- Set of variable and join point names -/ abbrev IndexSet := RBTree Index compare instance : Inhabited IndexSet := ⟨{}⟩ def mkIndexSet (idx : Index) : IndexSet := RBTree.empty.insert idx inductive LocalContextEntry where | param : IRType → LocalContextEntry | localVar : IRType → Expr → LocalContextEntry | joinPoint : Array Param → FnBody → LocalContextEntry abbrev LocalContext := RBMap Index LocalContextEntry compare def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext := ctx.insert x.idx (LocalContextEntry.localVar t v) def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext := ctx.insert j.idx (LocalContextEntry.joinPoint xs b) def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext := ctx.insert p.x.idx (LocalContextEntry.param p.ty) def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext := ps.foldl LocalContext.addParam ctx def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.joinPoint _ _) => true | other => false def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint _ b) => some b | other => none def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint ys _) => some ys | other => none def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.param _) => true | other => false def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.localVar _ _) => true | other => false def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool := Std.RBMap.contains ctx idx def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext := ctx.erase j.idx def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType := match ctx.find? x.idx with | some (LocalContextEntry.param t) => some t | some (LocalContextEntry.localVar t _) => some t | other => none def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr := match ctx.find? x.idx with | some (LocalContextEntry.localVar _ v) => some v | other => none abbrev IndexRenaming := RBMap Index Index compare class AlphaEqv (α : Type) where aeqv : IndexRenaming → α → α → Bool export AlphaEqv (aeqv) def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool := match ρ.find? v₁.idx with | some v => v == v₂.idx | none => v₁ == v₂ instance : AlphaEqv VarId := ⟨VarId.alphaEqv⟩ def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool | Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂ | Arg.irrelevant, Arg.irrelevant => true | _, _ => false instance : AlphaEqv Arg := ⟨Arg.alphaEqv⟩ def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool := Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b) instance: AlphaEqv (Array Arg) := ⟨args.alphaEqv⟩ def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool | Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂ | Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂ | Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂ | Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂ | Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂ | Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂ | Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂ | Expr.lit v₁, Expr.lit v₂ => v₁ == v₂ | Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂ | Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂ | _, _ => false instance : AlphaEqv Expr:= ⟨Expr.alphaEqv⟩ def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) := if x₁ == x₂ then ρ else ρ.insert x₁ x₂ def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming := if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then some (addVarRename ρ p₁.x.idx p₂.x.idx) else none def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := OptionM.run do if ps₁.size != ps₂.size then failure else let mut ρ := ρ for i in [:ps₁.size] do ρ ← addParamRename ρ ps₁[i] ps₂[i] pure ρ partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool | ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂ | ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with | some ρ' => alphaEqv ρ' v₁ v₂ && alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂ | none => false | ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ => aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ => match alt₁, alt₂ with | Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && alphaEqv ρ b₁ b₂ | Alt.default b₁, Alt.default b₂ => alphaEqv ρ b₁ b₂ | _, _ => false) | ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂ | ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂ | _, FnBody.unreachable, FnBody.unreachable => true | _, _, _ => false def FnBody.beq (b₁ b₂ : FnBody) : Bool := FnBody.alphaEqv ∅ b₁ b₂ instance : BEq FnBody := ⟨FnBody.beq⟩ abbrev VarIdSet := RBTree VarId (fun x y => compare x.idx y.idx) instance : Inhabited VarIdSet := ⟨{}⟩ def mkIf (x : VarId) (t e : FnBody) : FnBody := FnBody.case `Bool x IRType.uint8 #[ Alt.ctor {name := `Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e, Alt.ctor {name := `Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t ] end Lean.IR
88a67037a76df9a9bdbb94ffb682c89dbe778a66
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_lean_summary/unnamed_379.lean
4b8ea6f911eff7f22083bf98702e13fdcef5433d
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
293
lean
variables p q r : Prop -- BEGIN example (h₁ : (p ∧ r) ∨ (r ∧ q)) : r := begin cases h₁ with h₂ h₂, { exact h₂.right, }, -- In this subproof, `h₂ : p ∧ r`. The subgoal is `r`. { exact h₂.left, }, -- In this subproof, `h₂ : r ∧ q`. The subgoal is `r`. end -- END
3f404c1b22dce083a40bd02a80eb7a94edab95ec
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/list/join.lean
969f0086bddacb921d8c0e856f26d642a3edc039
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
5,697
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Floris van Doorn, Mario Carneiro -/ import data.list.big_operators /-! # Join of a list of lists This file proves basic properties of `list.join`, which concatenates a list of lists. It is defined in [`data.list.defs`](./data/list/defs). -/ variables {α β : Type*} namespace list attribute [simp] join @[simp] lemma join_nil : [([] : list α)].join = [] := rfl @[simp] lemma join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l :: L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] lemma join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] @[simp] lemma join_filter_empty_eq_ff [decidable_pred (λ l : list α, l.empty = ff)] : ∀ {L : list (list α)}, join (L.filter (λ l, l.empty = ff)) = L.join | [] := rfl | ([] :: L) := by simp [@join_filter_empty_eq_ff L] | ((a :: l) :: L) := by simp [@join_filter_empty_eq_ff L] @[simp] lemma join_filter_ne_nil [decidable_pred (λ l : list α, l ≠ [])] {L : list (list α)} : join (L.filter (λ l, l ≠ [])) = L.join := by simp [join_filter_empty_eq_ff, ← empty_iff_eq_nil] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } @[simp] lemma length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] lemma length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end end list
7539688b8f60e6805e8e3f40884128f7b4eb0e00
ce89339993655da64b6ccb555c837ce6c10f9ef4
/bluejam/topprover/27.lean
3f5e1ccc0d97126e99d658a803f0597c2aba00e3
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
395
lean
inductive two | c21 | c22 inductive three | c31 | c32 | c33 lemma two_has_two_elements (a b c: two): a = b ∨ b = c ∨ c = a := begin cases a; cases b; cases c; repeat {refl <|> {left, refl} <|> right }, end example : two ≠ three := begin intro, have h := two_has_two_elements, rw a at h, have := h three.c31 three.c32 three.c33, simp at this, assumption, end
efce2cb7ddaa70523d5161d148a2bff634d7296f
63abd62053d479eae5abf4951554e1064a4c45b4
/src/number_theory/quadratic_reciprocity.lean
a5a9326cffc74f197b6b9e6bdcb27f078412b04e
[ "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
25,028
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import field_theory.finite.basic import data.zmod.basic import data.nat.parity /-! # Quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_pow_two_eq_prime_iff_of_mod_four_eq_one`, and `exists_pow_two_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_pow_two_eq_neg_one_iff_mod_four_ne_three` and `exists_pow_two_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmod open_locale big_operators nat namespace zmod variables (p q : ℕ) [fact p.prime] [fact q.prime] /-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion_units (x : units (zmod p)) : (∃ y : units (zmod p), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := begin cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd, { substI p, refine iff_of_true ⟨1, _⟩ _; apply subsingleton.elim }, obtain ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmod p)), obtain ⟨n, hn⟩ : x ∈ submonoid.powers g, { rw mem_powers_iff_mem_gpowers, apply hg }, split, { rintro ⟨y, rfl⟩, rw [← pow_mul, two_mul_odd_div_two hp_odd, units_pow_card_sub_one_eq_one], }, { subst x, assume h, have key : 2 * (p / 2) ∣ n * (p / 2), { rw [← pow_mul] at h, rw [two_mul_odd_div_two hp_odd, ← card_units, ← order_of_eq_card_of_forall_mem_gpowers hg], apply order_of_dvd_of_pow_eq_one h }, have : 0 < p / 2 := nat.div_pos (show fact (1 < p), by apply_instance) dec_trivial, obtain ⟨m, rfl⟩ := dvd_of_mul_dvd_mul_right this key, refine ⟨g ^ m, _⟩, rw [mul_comm, pow_mul], }, end /-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion {a : zmod p} (ha : a ≠ 0) : (∃ y : zmod p, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := begin apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)), simp only [units.ext_iff, pow_two, units.coe_mk0, units.coe_mul], split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ }, { rintro ⟨y, rfl⟩, have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, }, refine ⟨units.mk0 y hy, _⟩, simp, } end lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmod p, y ^ 2 = -1) ↔ p % 4 ≠ 3 := begin cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd, { substI p, exact dec_trivial }, change fact (p % 2 = 1) at hp_odd, resetI, have neg_one_ne_zero : (-1 : zmod p) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, rw [euler_criterion p neg_one_ne_zero, neg_one_pow_eq_pow_mod_two], cases mod_two_eq_zero_or_one (p / 2) with p_half_even p_half_odd, { rw [p_half_even, pow_zero, eq_self_iff_true, true_iff], contrapose! p_half_even with hp, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp], exact dec_trivial }, { rw [p_half_odd, pow_one, iff_false_intro (ne_neg_self p one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at p_half_odd, rw [_root_.fact, ← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp_odd, have hp : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp hp_odd p_half_odd, generalize : p % 4 = k, dec_trivial! } end lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := begin cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd, { substI p, revert a ha, exact dec_trivial }, rw [← mul_self_eq_one_iff, ← pow_add, ← two_mul, two_mul_odd_div_two hp_odd], exact pow_card_sub_one_eq_one ha end /-- Wilson's Lemma: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/ @[simp] lemma wilsons_lemma : ((p - 1)! : zmod p) = -1 := begin refine calc ((p - 1)! : zmod p) = (∏ x in Ico 1 (succ (p - 1)), x) : by rw [← finset.prod_Ico_id_eq_factorial, prod_nat_cast] ... = (∏ x : units (zmod p), x) : _ ... = -1 : by rw [prod_hom _ (coe : units (zmod p) → zmod p), prod_univ_units_id_eq_neg_one, units.coe_neg, units.coe_one], have hp : 0 < p := nat.prime.pos ‹p.prime›, symmetry, refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _, { intros a ha, rw [Ico.mem, ← nat.succ_sub hp, nat.succ_sub_one], split, { apply nat.pos_of_ne_zero, rw ← @val_zero p, assume h, apply units.ne_zero a (val_injective p h) }, { exact val_lt _ } }, { intros a ha, simp only [cast_id, nat_cast_val], }, { intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h }, { intros b hb, rw [Ico.mem, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, nat.pos_iff_ne_zero] at hb, refine ⟨units.mk0 b _, finset.mem_univ _, _⟩, { assume h, apply hb.1, apply_fun val at h, simpa only [val_cast_of_lt hb.right, val_zero] using h }, { simp only [val_cast_of_lt hb.right, units.coe_mk0], } } end @[simp] lemma prod_Ico_one_prime : (∏ x in Ico 1 p, (x : zmod p)) = -1 := begin conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (nat.prime.pos ‹p.prime›)] }, rw [← prod_nat_cast, finset.prod_Ico_id_eq_factorial, wilsons_lemma] end end zmod /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id (p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := begin have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, nat.pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ), (a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, { assume x hx, simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff, nat.pos_iff_ne_zero, nat_abs_val_min_abs_le _], }, have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ), ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs, { assume b hb, refine ⟨(b / a : zmod p).val_min_abs.nat_abs, Ico.mem.mpr ⟨_, _⟩, _⟩, { apply nat.pos_of_ne_zero, simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff, val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero, or_self] }, { apply lt_succ_of_le, apply nat_abs_val_min_abs_le }, { rw cast_nat_abs_val_min_abs, split_ifs, { erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat] } } }, exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj end private lemma gauss_lemma_aux₁ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) * (p / 2)! : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! := calc (a ^ (p / 2) * (p / 2)! : zmod p) = (∏ x in Ico 1 (p / 2).succ, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_factorial, prod_const, Ico.card, succ_sub_one]; simp ... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp ... = (∏ x in Ico 1 (p / 2).succ, (if (a * x : zmod p).val ≤ p / 2 then 1 else -1) * (a * x : zmod p).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : have (∏ x in Ico 1 (p / 2).succ, if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) = (∏ x in (Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_factorial] private lemma gauss_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := (mul_left_inj' (show ((p / 2)! : zmod p) ≠ 0, by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.dvd_factorial, not_le]; exact nat.div_lt_self hp.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ p hap private lemma eisenstein_lemma_aux₁ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card + ∑ x in Ico 1 (p / 2).succ, x + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2, calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) : by simp only [val_cast_nat]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, sum_nat_cast, hp2] ... = _ : congr_arg2 (+) (calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2) = ∑ x in Ico 1 (p / 2).succ, ((((a * x : zmod p).val_min_abs + (if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) : by simp only [(val_eq_ite_val_min_abs _).symm]; simp [sum_nat_cast] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card + ((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) : by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, sum_nat_cast], } ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.sum_eq_multiset_sum]; simp [sum_nat_cast]) rfl private lemma eisenstein_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card ≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2, (eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, sum_nat_cast, add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc] using eq.symm (eisenstein_lemma_aux₁ p hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _ $ finset.ext $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto /-- The given sum is the number of integer points in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : ∑ a in Ico 1 (p / 2).succ, (a * q) / p = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card := if hp0 : p = 0 then by simp [hp0, finset.ext_iff] else calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ∑ a in Ico 1 (p / 2).succ, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ by finish) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp only [mem_filter, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, heq_iff_eq, forall_true_iff] {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp only [mem_filter, eq_self_iff_true, exists_prop_of_true, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ private lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime] (hq0 : (q : zmod p) ≠ 0) : ∑ a in Ico 1 (p / 2).succ, (a * q) / p + ∑ a in Ico 1 (q / 2).succ, (a * p) / q = (p / 2) * (q / 2) := begin have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp only [mem_filter, and_self, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, prod.swap_prod_mk, forall_true_iff] {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp only [mem_filter, eq_self_iff_true, and_self, exists_prop_of_true, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}⟩), have hdisj : disjoint (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), { apply disjoint_filter.2 (λ x hx hpq hqp, _), have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp only [*, lt_succ_iff, Ico.mem, mem_product] at *; tauto) (nat.div_lt_self hp.pos dec_trivial), have : (x.1 : zmod p) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) }, apply_fun zmod.val at this, rw [val_cast_of_lt hxp, val_zero] at this, simpa only [this, le_zero_iff_eq, Ico.mem, one_ne_zero, false_and, mem_product] using hx }, have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)), from finset.ext (λ x, by have := le_total (x.2 * p) (x.1 * q); simp only [mem_union, mem_filter, Ico.mem, mem_product]; tauto), rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product], simp only [Ico.card, nat.sub_zero, succ_sub_succ_eq_sub] end variables (p q : ℕ) [fact p.prime] [fact q.prime] namespace zmod /-- The Legendre symbol of `a` and `p` is an integer defined as * `0` if `a` is `0` modulo `p`; * `1` if `a ^ (p / 2)` is `1` modulo `p` (by `euler_criterion` this is equivalent to “`a` is a square modulo `p`”); * `-1` otherwise. -/ def legendre_sym (a p : ℕ) : ℤ := if (a : zmod p) = 0 then 0 else if (a : zmod p) ^ (p / 2) = 1 then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) [hp : fact p.prime] : (legendre_sym a p : zmod p) = (a ^ (p / 2)) := begin rw legendre_sym, by_cases ha : (a : zmod p) = 0, { simp only [if_pos, ha, zero_pow (nat.div_pos (hp.two_le) (succ_pos 1)), int.cast_zero] }, cases hp.eq_two_or_odd with hp2 hp_odd, { substI p, generalize : (a : (zmod 2)) = b, revert b, dec_trivial, }, { change fact (p % 2 = 1) at hp_odd, resetI, rw if_neg ha, have : (-1 : zmod p) ≠ 1, from (ne_neg_self p one_ne_zero).symm, cases pow_div_two_eq_neg_one_or_one p ha with h h, { rw [if_pos h, h, int.cast_one], }, { rw [h, if_neg this, int.cast_neg, int.cast_one], } } end lemma legendre_sym_eq_one_or_neg_one (a p : ℕ) (ha : (a : zmod p) ≠ 0) : legendre_sym a p = -1 ∨ legendre_sym a p = 1 := by unfold legendre_sym; split_ifs; simp only [*, eq_self_iff_true, or_true, true_or] at * lemma legendre_sym_eq_zero_iff (a p : ℕ) : legendre_sym a p = 0 ↔ (a : zmod p) = 0 := begin split, { classical, contrapose, assume ha, cases legendre_sym_eq_one_or_neg_one a p ha with h h, all_goals { rw h, norm_num } }, { assume ha, rw [legendre_sym, if_pos ha] } end /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℕ} [hp1 : fact (p % 2 = 1)] (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := have (legendre_sym a p : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ p ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a p ha0; cases @neg_one_pow_eq_or ℤ _ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = 1 ↔ (∃ b : zmod p, b ^ 2 = a) := begin rw [euler_criterion p ha0, legendre_sym, if_neg ha0], split_ifs, { simp only [h, eq_self_iff_true] }, finish -- this is quite slow. I'm actually surprised that it can close the goal at all! end lemma eisenstein_lemma [hp1 : fact (p % 2 = 1)] {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ p ha1 ha0] theorem quadratic_reciprocity [hp1 : fact (p % 2 = 1)] [hq1 : fact (q % 2 = 1)] (hpq : p ≠ q) : legendre_sym p q * legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm, have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq, by rw [eisenstein_lemma q hp1 hpq0, eisenstein_lemma p hq1 hqp0, ← pow_add, sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm] -- move this instance fact_prime_two : fact (nat.prime 2) := nat.prime_two lemma legendre_sym_two [hp1 : fact (p % 2 = 1)] : legendre_sym 2 p = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simpa using hp1), have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ by finish) dec_trivial ... < _ : by conv_rhs {rw [← mod_add_div p 2, add_comm, show p % 2 = 1, from hp1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, begin rw [gauss_lemma p (prime_ne_zero p 2 hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_pow_two_eq_two_iff [hp1 : fact (p % 2 = 1)] : (∃ a : zmod p, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmod p) ≠ 0, from prime_ne_zero p 2 (λ h, by simpa [h] using hp1), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, begin rw [show (2 : zmod p) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff p hp2, legendre_sym_two p, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), resetI, rw _root_.fact at hp1, revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, unfreezingI {clear_dependent p}, dec_trivial!, end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) [hq1 : fact (q % 2 = 1)] : (∃ a : zmod p, a ^ 2 = q) ↔ ∃ b : zmod q, b ^ 2 = p := if hpq : p = q then by substI hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin haveI hp_odd : fact (p % 2 = 1) := odd_of_mod_four_eq_one hp1, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hqp0, if_neg hpq0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction, end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmod p, a ^ 2 = q) ↔ ¬∃ b : zmod q, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin haveI hp_odd : fact (p % 2 = 1) := odd_of_mod_four_eq_three hp3, haveI hq_odd : fact (q % 2 = 1) := odd_of_mod_four_eq_three hq3, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hpq0, if_neg hqp0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction end end zmod
d13dbb8e464b1bcb337681d56be8bc6b40e515d7
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/stateRef.lean
c8cdf23aa2d262f77d857fdc3ef02fc2f72e06fc
[ "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
1,529
lean
def f (v : Nat) : StateRefT Nat IO Nat := do IO.println "hello"; modify fun s => s - v; get def g : IO Nat := (f 5).run' 20 #eval (f 5).run' 20 #eval (do set 100; f 5).run' 0 def f2 : ReaderT Nat (StateRefT Nat IO) Nat := do v ← read; IO.println $ "context " ++ toString v; modify fun s => s + v; get #eval (f2.run 10).run' 20 def f3 : StateT String (StateRefT Nat IO) Nat := do s ← get; n ← getThe Nat; set (s ++ ", " ++ toString n); s ← get; IO.println s; set (n+1); getThe Nat #eval (f3.run' "test").run' 10 structure Label {β : Type} (v : β) (α : Type) := (val : α) class HasGetAt {β : Type} (v : β) (α : outParam Type) (m : Type → Type) := (getAt : m α) instance monadState.hasGetAt (β : Type) (v : β) (α : Type) (m : Type → Type) [Monad m] [MonadStateOf (Label v α) m] : HasGetAt v α m := { getAt := do a ← getThe (Label v α); pure a.val } export HasGetAt (getAt) abbrev M := StateRefT (Label 0 Nat) $ StateRefT (Label 1 Nat) $ StateRefT (Label 2 Nat) IO def f4 : M Nat := do a0 : Nat ← getAt 0; a1 ← getAt 1; a2 ← getAt 2; IO.println $ "state0 " ++ toString a0; IO.println $ "state1 " ++ toString a1; IO.println $ "state1 " ++ toString a2; pure (a0 + a1 + a2) #eval ((f4.run' ⟨10⟩).run' ⟨20⟩).run' ⟨30⟩ abbrev S (ω : Type) := StateRefT Nat $ StateRefT String $ ST ω def f5 {ω} : S ω Unit := do s ← getThe String; modify fun n => n + s.length; pure () def f5Pure (n : Nat) (s : String) := runST (fun _ => (f5.run n).run s) #eval f5Pure 10 "hello world"
2dcabb939d1623d490b626d2735a68b848989fe4
1cc8cf59a317bf12d71a5a8ed03bfc1948c66f10
/src/limits.lean
e375f506fe297b2224704fe7dea5869c0fe9ff8b
[ "Apache-2.0" ]
permissive
kckennylau/M1P1-lean
1e4fabf513539669f86a439af6844aa078c239ad
c92e524f3e4e7aec5dc09e05fb8923cc9720dd34
refs/heads/master
1,587,503,976,663
1,549,715,955,000
1,549,715,955,000
169,875,735
1
0
Apache-2.0
1,549,722,917,000
1,549,722,917,000
null
UTF-8
Lean
false
false
15,467
lean
/- limits.lean Limits of sequences. Part of the M1P1 Lean project. This file contains the basic definition of the limit of a sequence, and proves basic properties about it. It is full of comments in an attempt to make it more comprehensible to mathematicians with little Lean experience, although by far the best way to understand what is going on is to open the file within Lean 3.4.2 so you can check out the goal at each line -- this really helps understanding. -/ -- The import below gives us a working copy of the real numbers ℝ, -- and functions such as abs : ℝ → ℝ import data.real.basic -- This import has addition of functions, which we need for sums of limits. import algebra.pi_instances -- This next import gives us several tactics of use to mathematicians: -- (1) norm_num [to prove basic facts about reals like 2+2 = 4] -- (2) ring [to prove basic algebra identities like (a+b)^2 = a^2+2ab+b^2] -- (3) linarith [to prove basic inequalities like x > 0 -> x/2 > 0] import tactic.linarith import topology.basic import analysis.exponential -- These lines switch Lean into "maths proof mode" -- don't worry about them. -- Basically they tell Lean to use the axiom of choice and the -- law of the excluded middle, two standard maths facts which we -- assume all the time in maths, usually without comment. -- This imports Patrick's extension obv_ineq of linarith which solves -- "obvious inequalities", and maybe other things too. import xenalib.M1P1 noncomputable theory local attribute [instance, priority 0] classical.prop_decidable -- Let's also put things into an M1P1 namespace so we can define -- stuff which is already defined in mathlib without breaking anything. namespace M1P1 -- the maths starts here. -- We introduce the usual mathematical notation for absolute value local notation `|` x `|` := abs x -- We model a sequence a₀, a₁, a₂,... of real numbers as a function -- from ℕ := {0,1,2,...} to ℝ, sending n to aₙ . So in the below -- definition of the limit of a sequence, a : ℕ → ℝ is the sequence. -- We first formalise the definition of "aₙ → l as n → ∞" definition is_limit (a : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε -- A sequence converges if and only if it has a limit. The difference -- with this definition is that we don't specify the limit, we just -- claim that it exists. definition has_limit (a : ℕ → ℝ) : Prop := ∃ l : ℝ, is_limit a l -- We now start on the proof of the theorem that if a sequence has -- two limits, they are equal. We start with a lemma. theorem triangle' (x y z : ℝ) : | x - y | ≤ | z - y | + | z - x | := begin -- See the solution to sheet 1 Q1a for a more detailed explanation of this argument. -- We start by unfolding the definitions. unfold abs, unfold max, -- The value of | x - y | depends on whether x - y ≥ 0 or < 0. -- The `split_ifs` tactic splits into these 8 = 2^3 cases split_ifs, -- Each case is trivial by easy inequality arguments, and the `linarith` -- tactic solves them all. repeat {linarith}, end -- We're ready to prove the theorem. theorem limits_are_unique (a : ℕ → ℝ) (l m : ℝ) (hl : is_limit a l) (hm : is_limit a m) : l = m := begin -- WLOG l ≤ m. wlog h : l ≤ m, -- We're trying to prove l = m, so it suffices to prove l < m is false. suffices : ¬ (l < m), linarith, -- don't need h any more clear h, -- Let's prove it by contradiction. So let's assume l < m. intro hlm, -- Our goal is now "⊢ false" and hlm is the assumption l < m. -- Situation so far: aₙ → l, aₙ → m, hlm is the assumption l < m -- and we're looking for a contradiction. let ε := (m - l) / 2, -- This is a standard trick. -- First note that ε is positive, because l > m. have Hε : ε > 0 := by {show (m - l) / 2 > 0, linarith}, -- Because aₙ → l, there exists N₁ such that n ≥ N₁ → |aₙ - l| < ε cases hl ε Hε with N₁ HN₁, -- Because bₙ → m, there exists N₂ such that n ≥ N₂ → |bₙ - m| < ε cases hm ε Hε with N₂ HN₂, -- The trick is to let N be the max of N₁ and N₂ let N := max N₁ N₂, -- Now clearly N ≥ N₁... have H₁ : N₁ ≤ N := le_max_left _ _, -- ... so |a_N - l| < ε have Ha : | a N - l| < ε := HN₁ N H₁, -- similarly N ≥ N₂... have H₂ : N₂ ≤ N := le_max_right _ _, -- ... so |a_N - m| < ε too have H₂ : | a N - m| < ε := HN₂ N H₂, -- So now a basic calculation shows 2ε < 2ε. Let's go through it. have weird : 2 * ε < 2 * ε, calc 2 * ε = 2 * ((m - l) / 2) : by refl -- by definition -- and this is obviously m - l ... = m - l : by ring -- which is at most its own absolute value ... ≤ | m - l | : le_abs_self _ -- and now use the triangle inequality ... ≤ |a N - l| + |a N - m| : triangle' _ _ _ -- and stuff we proved already ... < ε + ε : by linarith -- to deduce this is less than 2ε ... = 2 * ε : by ring, -- That's the contradiction we seek! linarith -- (it's an easy inequality argument) end -- We now prove that if aₙ → l and bₙ → m then aₙ + bₙ → l + m. theorem tendsto_add (a : ℕ → ℝ) (b : ℕ → ℝ) (l m : ℝ) (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a + b) (l + m) := begin -- let epsilon be a positive real intros ε Hε, -- We now need to come up with N such that n >= N implies -- |aₙ + bₙ - (l + m)| < ε. -- Well, note first that epsilon / 2 is also positive. have Hε2 : ε / 2 > 0 := by linarith, -- Choose large M₁ such that n ≥ M₁ implies |a n - l| < ε /2 cases (h1 (ε / 2) Hε2) with M₁ HM₁, -- similarly choose M₂ for the b sequence. cases (h2 (ε / 2) Hε2) with M₂ HM₂, -- let N be the max of M1 and M2 let N := max M₁ M₂, -- and let's use that use N, -- Of course N ≥ M₁ and N ≥ M₂ have H₁ : N ≥ M₁ := le_max_left _ _, have H₂ : N ≥ M₂ := le_max_right _ _, -- Now say n ≥ N. intros n Hn, -- Then obviously n ≥ M₁... have Hn₁ : n ≥ M₁ := by linarith, -- ...so |aₙ - l| < ε /2 have H3 : |a n - l| < ε / 2 := HM₁ n Hn₁, -- and similarly n ≥ M₂, so |bₙ - l| < ε / 2 have H4 : |b n - m| < ε / 2 := HM₂ n (by linarith), -- And now what we want (|aₙ + bₙ - (l + m)| < ε) -- follows from a calculation. -- First do some obvious algebra calc |(a + b) n - (l + m)| = |(a n - l) + (b n - m)| : by ring -- now use the triangle inequality ... ≤ |(a n - l)| + |(b n - m)| : abs_add _ _ -- and our assumptions ... < ε / 2 + ε / 2 : by linarith -- and a bit more algebra ... = ε : by ring end -- A sequence (aₙ) is *bounded* if there exists some real number B such that |aₙ| ≤ B for all n≥0. definition has_bound (a : ℕ → ℝ) (B : ℝ) := ∀ n, |a n| ≤ B definition is_bounded (a : ℕ → ℝ) := ∃ B, has_bound a B -- A convergent sequence is bounded. open finset theorem bounded_of_convergent (a : ℕ → ℝ) (Ha : has_limit a) : is_bounded a := begin -- let l be the limit of the sequence. cases Ha with l Hl, -- By definition, there exist some N such that n ≥ N → |aₙ - l| < 1 cases Hl 1 (zero_lt_one) with N HN, -- Let X be {|a₀|, |a₁|, ... , |a_N|}... let X := image (abs ∘ a) (range (N + 1)), -- ...let's remark that |a₀| ∈ X so X ≠ ∅ while we're here... have H2 : |a 0| ∈ X := mem_image_of_mem _ (mem_range.2 (nat.zero_lt_succ _)), have H3 : X ≠ ∅ := ne_empty_of_mem H2, -- ...and let B₀ be the max of X. let B₀ := max' X H3, -- If n ≤ N then |aₙ| ≤ B₀. have HB₀ : ∀ n ≤ N, |a n| ≤ B₀ := λ n Hn, le_max' X H3 _ (mem_image_of_mem _ (mem_range.2 (nat.lt_succ_of_le Hn))), -- So now let B = max {B₀, |l| + 1} let B := max B₀ ( |l| + 1), -- and we claim this bound works, i.e. |aₙ| ≤ B for all n ∈ ℕ. use B, -- Because if n ∈ ℕ, intro n, -- then either n ≤ N or n > N. cases le_or_gt n N with Hle Hgt, { -- if n ≤ N, then |aₙ| ≤ B₀ have h : |a n| ≤ B₀ := HB₀ n Hle, -- and B₀ ≤ B have h2 : B₀ ≤ B := le_max_left _ _, -- so we're done linarith }, { -- and if n > N, then |aₙ - l| < 1... have h : |a n - l| < 1 := HN n (le_of_lt Hgt), -- ...so |aₙ| < 1 + |l|... have h2 : |a n| < |l| + 1, -- todo (kmb) -- remove linarith bug workaround revert h,unfold abs,unfold max,split_ifs;intros;linarith {restrict_type := ℝ}, -- ...which is ≤ B have h3 : |l| + 1 ≤ B := le_max_right _ _, -- ...so we're done in this case too linarith } end -- more convenient theorem: a sequence with a limit -- is bounded in absolute value by a positive real. theorem bounded_pos_of_convergent (a : ℕ → ℝ) (Ha : has_limit a) : ∃ B : ℝ, B > 0 ∧ has_bound a B := begin -- We know the sequence is bounded. Say it's bounded by B₀. cases bounded_of_convergent a Ha with B₀ HB₀, -- let B = |B₀| + 1; this bound works. let B := |B₀| + 1, use B, -- B is obviously positive split, { -- (because 1 > 0... apply lt_of_lt_of_le zero_lt_one, show 1 ≤ |B₀| + 1, apply le_add_of_nonneg_left', -- ... and |B₀| ≥ 0) exact abs_nonneg _ }, -- so it suffices to prove B is a bound. -- If n is a natural intro n, -- then |aₙ| ≤ B₀ apply le_trans (HB₀ n), -- so it suffices to show B₀ ≤ |B₀| + 1 show B₀ ≤ |B₀| + 1, -- which is obvious. apply le_trans (le_abs_self B₀), simp [zero_le_one], end -- If a convergent sequence is bounded in absolute value by B, -- then the limit is also bounded in absolute value by B. theorem limit_bounded_of_bounded {a : ℕ → ℝ} {l : ℝ} (Ha : is_limit a l) {B : ℝ} (HB : has_bound a B) : |l| ≤ B := begin -- Suppose it's not true. apply le_of_not_gt, -- Then |l| > B. intro HlB, -- Set ε = (|l| - B) / 2, let ε := ( |l| - B) / 2, -- noting that it's positive have Hε : ε > 0 := div_pos (by linarith) (by linarith), -- and choose N such that |a_N - l| < ε cases Ha ε Hε with N HN, have HN2 := HN N (le_refl _), -- Now |a_N| ≤ B have HB2 : |a N| ≤ B := HB N, -- so now we get a contradiction have Hcontra := calc |l| ≤ |a N - l| + |a N| : by unfold abs;unfold max;split_ifs;linarith ... < ε + B : add_lt_add_of_lt_of_le HN2 HB2 ... = ( |l| - B) / 2 + B : rfl ... < |l| : by linarith, linarith, end -- The limit of the product is the product of the limits. -- If aₙ → l and bₙ → m then aₙ * bₙ → l * m. theorem tendsto_mul (a : ℕ → ℝ) (b : ℕ → ℝ) (l m : ℝ) (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a * b) (l * m) := begin -- let epsilon be a positive real intros ε Hε, -- Now aₙ has a limit, have ha : has_limit a := ⟨l,h1⟩, -- so it's bounded in absolute value by a positive real A rcases bounded_pos_of_convergent a ha with ⟨A,HApos,HAbd⟩, -- Similarly bₙ is bounded by B. rcases bounded_pos_of_convergent b ⟨m,h2⟩ with ⟨B,HBpos,HBbd⟩, -- Now chose N_A such that n ≥ N_A -> |aₙ - l| < ε / 2B cases h1 (ε / (2 * B)) (div_pos Hε (by linarith)) with NA HNA, -- and choose N_B such that n ≥ N_B -> |bₙ - m| < ε /2A cases h2 (ε / (2 * A)) (div_pos Hε (by linarith)) with NB HNB, -- Let N be the max of N_A and N_B; this N works. let N := max NA NB, use N, -- For if n ≥ N intros n Hn, -- then |aₙ bₙ - l m| ... calc |a n * b n - l * m| -- equals |aₙ (bₙ - m) + (aₙ - l) m|, = |a n * (b n - m) + (a n - l) * m | : by ring -- which by the triangle inequality and multiplicativy of |.| ... ≤ |a n * (b n - m)| + |(a n - l) * m| : abs_add _ _ -- is at most |aₙ| |bₙ - m| + |aₙ - l| |m|, ... ≤ |a n| * |b n - m| + |a n - l| * |m| : by simp [abs_mul] -- which is at most A(ε / 2A) + B(ε / 2B), by a very tedious calculation in Lean ... ≤ A * |b n - m| + |a n - l| * |m| : add_le_add_right (mul_le_mul_of_nonneg_right (HAbd n) (abs_nonneg _)) _ ... < A * (ε / (2 * A)) + |a n - l| * |m| : add_lt_add_right (mul_lt_mul_of_pos_left (HNB n (le_trans (le_max_right _ _) Hn)) HApos) _ ... ≤ A * (ε / (2 * A)) + (ε / (2 * B)) * |m| : add_le_add_left (mul_le_mul_of_nonneg_right (le_of_lt $ HNA n $ le_trans (le_max_left _ _) Hn) (abs_nonneg _)) _ ... ≤ A * (ε / (2 * A)) + (ε / (2 * B)) * B : add_le_add_left (mul_le_mul_of_nonneg_left (limit_bounded_of_bounded h2 HBbd) $ le_of_lt $ div_pos Hε (by linarith)) _ -- which is at most ε by some easy algebra. ... = ε / 2 + (ε / (2 * B)) * B : by rw [←div_div_eq_div_mul,mul_div_cancel' _ (show A ≠ 0, by intro h;rw h at HApos;linarith)] ... = ε / 2 + ε / 2 : by rw [←div_div_eq_div_mul,div_mul_cancel _ (show B ≠ 0, by intro h;rw h at HBpos;linarith)] ... = ε : by ring end -- If aₙ → l and bₙ → m, and aₙ ≤ bₙ for all n, then l ≤ m theorem tendsto_le_of_le (a : ℕ → ℝ) (b : ℕ → ℝ) (l : ℝ) (m : ℝ) (hl : is_limit a l) (hm : is_limit b m) (hle : ∀ n, a n ≤ b n) : l ≤ m := begin -- Assume for a contradiction that m < l apply le_of_not_lt, intro hlt, -- Let ε be (l - m) / 2... let ε := (l - m) /2, -- ...and note that it's positive have Hε : ε > 0 := show (l - m) / 2 > 0 , by linarith, -- Choose Na s.t. |aₙ - l| < ε for n ≥ Na cases hl ε Hε with Na HNa, have Hε : ε > 0 := show (l - m) / 2 > 0 , by linarith, -- Choose Nb s.t. |bₙ - m| < ε for n ≥ Nb cases hm ε Hε with Nb HNb, -- let N be the max of Na and Nb... let N := max Na Nb, -- ...and note N ≥ Na and N ≥ Nb, have HNa' : Na ≤ N := le_max_left _ _, have HNb' : Nb ≤ N := le_max_right _ _, -- ... so |a_N - l| < ε and |b_N - m| < ε have Hl' : |a N - l| < ε := HNa N HNa', have Hm' : |b N - m| < ε := HNb N HNb', -- ... and also a_N ≤ b_N. have HN : a N ≤ b N := hle N, -- This is probably a contradiction. have Hε : ε = (l - m) / 2 := rfl, revert Hl' Hm', unfold abs,unfold max,split_ifs;intros;linarith end theorem sandwich (a b c : ℕ → ℝ) (l : ℝ) (ha : is_limit a l) (hc : is_limit c l) (hab : ∀ n, a n ≤ b n) (hbc : ∀ n, b n ≤ c n) : is_limit b l := begin -- Choose ε > 0 intros ε Hε, -- we now need an N. This is a standard ε/2 argument. -- Choose Na and Nc such that |aₙ - l| < ε for n ≥ Na and |cₙ - l| < ε for n ≥ Nc. cases ha ε Hε with Na Ha, cases hc ε Hε with Nc Hc, -- and as usual let N be the max. let N := max Na Nc, use N, -- Now for n ≥ N, note n ≥ Na and N ≥ Nc, have HNa : Na ≤ N := by obvineq, have HNc : Nc ≤ N := by obvineq, intros n Hn, have h1 : a n ≤ b n := hab n, have h2 : b n ≤ c n := hbc n, have h3 : |a n - l| < ε := Ha n (le_trans HNa Hn), have h4 : |c n - l| < ε := Hc n (le_trans HNc Hn), revert h3,revert h4, unfold abs,unfold max, split_ifs;intros;linarith, end end M1P1
ac65dfd3fc50026a50866ce92e0836add84f3a94
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Data/Array/Mem.lean
d3faebb330e023aaf72c2bdb4bdc320cb46e4f61
[ "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,185
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 -/ prelude import Init.Data.Array.Basic import Init.Data.Nat.Linear import Init.Data.List.BasicAux theorem List.sizeOf_get_lt [SizeOf α] (as : List α) (i : Fin as.length) : sizeOf (as.get i) < sizeOf as := by match as, i with | [], i => apply Fin.elim0 i | a::as, ⟨0, _⟩ => simp_arith [get] | a::as, ⟨i+1, h⟩ => simp [get] have h : i < as.length := Nat.lt_of_succ_lt_succ h have ih := sizeOf_get_lt as ⟨i, h⟩ exact Nat.lt_of_lt_of_le ih (Nat.le_add_left ..) namespace Array instance [DecidableEq α] : Membership α (Array α) where mem a as := as.contains a theorem sizeOf_get_lt [SizeOf α] (as : Array α) (i : Fin as.size) : sizeOf (as.get i) < sizeOf as := by cases as; rename_i as simp [get] have ih := List.sizeOf_get_lt as i exact Nat.lt_trans ih (by simp_arith) theorem sizeOf_lt_of_mem [DecidableEq α] [SizeOf α] {as : Array α} (h : a ∈ as) : sizeOf a < sizeOf as := by simp [Membership.mem, contains, any, Id.run, BEq.beq, anyM] at h let rec aux (j : Nat) (h : anyM.loop (m := Id) (fun b => decide (a = b)) as as.size (Nat.le_refl ..) j = true) : sizeOf a < sizeOf as := by unfold anyM.loop at h split at h · simp [Bind.bind, pure] at h; split at h next he => subst a; apply sizeOf_get_lt next => have ih := aux (j+1) h; assumption · contradiction apply aux 0 h termination_by aux j _ => as.size - j @[simp] theorem sizeOf_get [SizeOf α] (as : Array α) (i : Fin as.size) : sizeOf (as.get i) < sizeOf as := by cases as simp [get] apply Nat.lt_trans (List.sizeOf_get ..) simp_arith /-- This tactic, added to the `decreasing_trivial` toolbox, proves that `sizeOf arr[i] < sizeOf arr`, which is useful for well founded recursions over a nested inductive like `inductive T | mk : Array T → T`. -/ macro "array_get_dec" : tactic => `(first | apply sizeOf_get | apply Nat.lt_trans (sizeOf_get ..); simp_arith) macro_rules | `(tactic| decreasing_trivial) => `(tactic| array_get_dec) end Array
feafa02acb91f87fdecf913731b328e0eb0daee5
367134ba5a65885e863bdc4507601606690974c1
/src/data/char.lean
13e889fcfd390952ed1a74fa37ad761a4839bf6e
[ "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
642
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Supplementary theorems about the `char` type. -/ instance : linear_order char := { le_refl := λ a, @le_refl ℕ _ _, le_trans := λ a b c, @le_trans ℕ _ _ _ _, le_antisymm := λ a b h₁ h₂, char.eq_of_veq $ le_antisymm h₁ h₂, le_total := λ a b, @le_total ℕ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ℕ _ _ _, decidable_le := char.decidable_le, decidable_eq := char.decidable_eq, decidable_lt := char.decidable_lt, ..char.has_le, ..char.has_lt }
95ac81d4e984b4c6204348328beff2d6396c788c
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/fin_cases.lean
20f9ac445c3835257a4ca01bb16d13a14be240c9
[ "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
4,017
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison Case bashing: * on `x ∈ A`, for `A : finset α` or `A : list α`, or * on `x : A`, with `[fintype A]`. -/ import data.fintype import tactic.norm_num namespace tactic open lean.parser open interactive interactive.types expr open conv.interactive /-- Checks that the expression looks like `x ∈ A` for `A : finset α`, `multiset α` or `A : list α`, and returns the type α. -/ meta def guard_mem_fin (e : expr) : tactic expr := do t ← infer_type e, α ← mk_mvar, to_expr ``(_ ∈ (_ : finset %%α)) tt ff >>= unify t <|> to_expr ``(_ ∈ (_ : multiset %%α)) tt ff >>= unify t <|> to_expr ``(_ ∈ (_ : list %%α)) tt ff >>= unify t, instantiate_mvars α meta def expr_list_to_list_expr : Π (e : expr), tactic (list expr) | `(list.cons %%h %%t) := list.cons h <$> expr_list_to_list_expr t | `([]) := return [] | _ := failed meta def fin_cases_at_aux : Π (with_list : list expr) (e : expr) (ty_numeric : bool), tactic unit | with_list e ty_numeric := (do result ← cases_core e, match result with -- We have a goal with an equation `s`, and a second goal with a smaller `e : x ∈ _`. | [(_, [s], _), (_, [e], _)] := do let sn := local_pp_name s, ng ← num_goals, -- tidy up the new value tactic.interactive.conv (some sn) none (to_rhs >> match with_list.nth 0 with | (some h) := conv.interactive.change (to_pexpr h) | _ := `[try { conv.interactive.simp ff [] [] }] >> when ty_numeric `[try { conv.interactive.norm_num [] }] end), s ← get_local sn, try `[subst %%s], ng' ← num_goals, when (ng = ng') (rotate_left 1), fin_cases_at_aux with_list.tail e ty_numeric -- No cases; we're done. | [] := skip | _ := failed end) meta def fin_cases_at : Π (with_list : option pexpr) (e : expr), tactic unit | with_list e := do ty ← try_core $ guard_mem_fin e, match ty with | none := -- Deal with `x : A`, where `[fintype A]` is available: (do ty ← infer_type e, i ← to_expr ``(fintype %%ty) >>= mk_instance <|> fail "Failed to find `fintype` instance.", t ← to_expr ``(%%e ∈ @fintype.elems %%ty %%i), v ← to_expr ``(@fintype.complete %%ty %%i %%e), h ← assertv `h t v, fin_cases_at with_list h) | (some ty) := -- Deal with `x ∈ A` hypotheses: (do with_list ← match with_list with | (some e) := do e ← to_expr ``(%%e : list %%ty), expr_list_to_list_expr e | none := return [] end, ty_numeric ← succeeds (unify ty `(ℕ) <|> unify ty `(ℤ) <|> unify ty `(ℚ)), fin_cases_at_aux with_list e ty_numeric) end namespace interactive private meta def hyp := tk "*" *> return none <|> some <$> ident local postfix `?`:9001 := optional /-- `fin_cases h` performs case analysis on a hypothesis of the form `h : A`, where `[fintype A]` is available, or `h ∈ A`, where `A : finset X`, `A : multiset X` or `A : list X`. `fin_cases *` performs case analysis on all suitable hypotheses. As an example, in ``` example (f : ℕ → Prop) (p : fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := begin fin_cases *; simp, all_goals { assumption } end ``` after `fin_cases p; simp`, there are three goals, `f 0`, `f 1`, and `f 2`. -/ meta def fin_cases : parse hyp → parse (tk "with" *> texpr)? → tactic unit | none none := focus1 $ do ctx ← local_context, ctx.mfirst (fin_cases_at none) <|> fail "No hypothesis of the forms `x ∈ A`, where `A : finset X`, `A : list X`, or `A : multiset X`, or `x : A`, with `[fintype A]`." | none (some _) := fail "Specify a single hypothesis when using a `with` argument." | (some n) with_list := do h ← get_local n, focus1 $ fin_cases_at with_list h end interactive end tactic
661df7f774c64fc8e2544321c500caef173df851
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/group_theory/quotient_group.lean
a1f7104eed7a4db5efd21dc1ec70febcafa2b26a
[ "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
10,811
lean
/- Copyright (c) 2018 Kevin Buzzard, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl. -/ import group_theory.coset /-! # Quotients of groups by normal subgroups This files develops the basic theory of quotients of groups by normal subgroups. In particular it proves Noether's first and second isomorphism theorems. ## Main definitions * `mk'`: the canonical group homomorphism `G →* G/N` given a normal subgroup `N` of `G`. * `lift φ`: the group homomorphism `G/N →* H` given a group homomorphism `φ : G →* H` such that `N ⊆ ker φ`. * `map f`: the group homomorphism `G/N →* H/M` given a group homomorphism `f : G →* H` such that `N ⊆ f⁻¹(M)`. ## Main statements * `quotient_ker_equiv_range`: Noether's first isomorphism theorem, an explicit isomorphism `G/ker φ → range φ` for every group homomorphism `φ : G →* H`. * `quotient_inf_equiv_prod_normal_quotient`: Noether's second isomorphism theorem, an explicit isomorphism between `H/(H ∩ N)` and `(HN)/N` given a subgroup `H` and a normal subgroup `N` of a group `G`. ## Tags isomorphism theorems, quotient groups ## TODO Noether's third isomorphism theorem -/ universes u v namespace quotient_group variables {G : Type u} [group G] (N : subgroup G) [nN : N.normal] {H : Type v} [group H] include nN -- Define the `div_inv_monoid` before the `group` structure, -- to make sure we have `inv` fully defined before we show `mul_left_inv`. -- TODO: is there a non-invasive way of defining this in one declaration? @[to_additive quotient_add_group.div_inv_monoid] instance : div_inv_monoid (quotient N) := { one := (1 : G), mul := quotient.map₂' (*) (λ a₁ b₁ hab₁ a₂ b₂ hab₂, ((N.mul_mem_cancel_right (N.inv_mem hab₂)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact nN.conj_mem _ hab₁ _))), mul_assoc := λ a b c, quotient.induction_on₃' a b c (λ a b c, congr_arg mk (mul_assoc a b c)), one_mul := λ a, quotient.induction_on' a (λ a, congr_arg mk (one_mul a)), mul_one := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_one a)), inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N)) (λ a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact N.inv_mem (nN.mem_comm hab) end) } @[to_additive quotient_add_group.add_group] instance : group (quotient N) := { mul_left_inv := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_left_inv a)), .. quotient.div_inv_monoid _ } /-- The group homomorphism from `G` to `G/N`. -/ @[to_additive quotient_add_group.mk' "The additive group homomorphism from `G` to `G/N`."] def mk' : G →* quotient N := monoid_hom.mk' (quotient_group.mk) (λ _ _, rfl) @[simp, to_additive quotient_add_group.ker_mk] lemma ker_mk : monoid_hom.ker (quotient_group.mk' N : G →* quotient_group.quotient N) = N := begin ext g, rw [monoid_hom.mem_ker, eq_comm], show (((1 : G) : quotient_group.quotient N)) = g ↔ _, rw [quotient_group.eq, one_inv, one_mul], end -- for commutative groups we don't need normality assumption omit nN @[to_additive quotient_add_group.add_comm_group] instance {G : Type*} [comm_group G] (N : subgroup G) : comm_group (quotient N) := { mul_comm := λ a b, quotient.induction_on₂' a b (λ a b, congr_arg mk (mul_comm a b)), .. @quotient_group.quotient.group _ _ N N.normal_of_comm } include nN local notation ` Q ` := quotient N @[simp, to_additive quotient_add_group.coe_zero] lemma coe_one : ((1 : G) : Q) = 1 := rfl @[simp, to_additive quotient_add_group.coe_add] lemma coe_mul (a b : G) : ((a * b : G) : Q) = a * b := rfl @[simp, to_additive quotient_add_group.coe_neg] lemma coe_inv (a : G) : ((a⁻¹ : G) : Q) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : Q) = a ^ n := (mk' N).map_pow a n @[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : Q) = a ^ n := (mk' N).map_gpow a n /-- A group homomorphism `φ : G →* H` with `N ⊆ ker(φ)` descends (i.e. `lift`s) to a group homomorphism `G/N →* H`. -/ @[to_additive quotient_add_group.lift "An `add_group` homomorphism `φ : G →+ H` with `N ⊆ ker(φ)` descends (i.e. `lift`s) to a group homomorphism `G/N →* H`."] def lift (φ : G →* H) (HN : ∀x∈N, φ x = 1) : Q →* H := monoid_hom.mk' (λ q : Q, q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N), (calc φ a = φ a * 1 : (mul_one _).symm ... = φ a * φ (a⁻¹ * b) : HN (a⁻¹ * b) hab ▸ rfl ... = φ (a * (a⁻¹ * b)) : (is_mul_hom.map_mul φ a (a⁻¹ * b)).symm ... = φ b : by rw mul_inv_cancel_left)) (λ q r, quotient.induction_on₂' q r $ is_mul_hom.map_mul φ) @[simp, to_additive quotient_add_group.lift_mk] lemma lift_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (g : Q) = φ g := rfl @[simp, to_additive quotient_add_group.lift_mk'] lemma lift_mk' {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (mk g : Q) = φ g := rfl @[simp, to_additive quotient_add_group.lift_quot_mk] lemma lift_quot_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (quot.mk _ g : Q) = φ g := rfl /-- A group homomorphism `f : G →* H` induces a map `G/N →* H/M` if `N ⊆ f⁻¹(M)`. -/ @[to_additive quotient_add_group.map "An `add_group` homomorphism `f : G →+ H` induces a map `G/N →+ H/M` if `N ⊆ f⁻¹(M)`."] def map (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) : quotient N →* quotient M := begin refine quotient_group.lift N ((mk' M).comp f) _, assume x hx, refine quotient_group.eq.2 _, rw [mul_one, subgroup.inv_mem_iff], exact h hx, end omit nN variables (φ : G →* H) open function monoid_hom /-- The induced map from the quotient by the kernel to the codomain. -/ @[to_additive quotient_add_group.ker_lift "The induced map from the quotient by the kernel to the codomain."] def ker_lift : quotient (ker φ) →* H := lift _ φ $ λ g, φ.mem_ker.mp @[simp, to_additive quotient_add_group.ker_lift_mk] lemma ker_lift_mk (g : G) : (ker_lift φ) g = φ g := lift_mk _ _ _ @[simp, to_additive quotient_add_group.ker_lift_mk'] lemma ker_lift_mk' (g : G) : (ker_lift φ) (mk g) = φ g := lift_mk' _ _ _ @[to_additive quotient_add_group.injective_ker_lift] lemma ker_lift_injective : injective (ker_lift φ) := assume a b, quotient.induction_on₂' a b $ assume a b (h : φ a = φ b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [mem_ker, is_mul_hom.map_mul φ, ← h, is_group_hom.map_inv φ, inv_mul_self] -- Note that `ker φ` isn't definitionally `ker (φ.range_restrict)` -- so there is a bit of annoying code duplication here /-- The induced map from the quotient by the kernel to the range. -/ @[to_additive quotient_add_group.range_ker_lift "The induced map from the quotient by the kernel to the range."] def range_ker_lift : quotient (ker φ) →* φ.range := lift _ φ.range_restrict $ λ g hg, (mem_ker _).mp $ by rwa range_restrict_ker @[to_additive quotient_add_group.range_ker_lift_injective] lemma range_ker_lift_injective : injective (range_ker_lift φ) := assume a b, quotient.induction_on₂' a b $ assume a b (h : φ.range_restrict a = φ.range_restrict b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [←range_restrict_ker, mem_ker, φ.range_restrict.map_mul, ← h, φ.range_restrict.map_inv, inv_mul_self] @[to_additive quotient_add_group.range_ker_lift_surjective] lemma range_ker_lift_surjective : surjective (range_ker_lift φ) := begin rintro ⟨_, g, rfl⟩, use mk g, refl, end /-- The first isomorphism theorem (a definition): the canonical isomorphism between `G/(ker φ)` to `range φ`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_range "The first isomorphism theorem (a definition): the canonical isomorphism between `G/(ker φ)` to `range φ`."] noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃* range φ := mul_equiv.of_bijective (range_ker_lift φ) ⟨range_ker_lift_injective φ, range_ker_lift_surjective φ⟩ /-- The canonical isomorphism `G/(ker φ) ≃* H` induced by a surjection `φ : G →* H`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_surjective "The canonical isomorphism `G/(ker φ) ≃+ H` induced by a surjection `φ : G →+ H`."] noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) : (quotient (ker φ)) ≃* H := mul_equiv.of_bijective (ker_lift φ) ⟨ker_lift_injective φ, λ h, begin rcases hφ h with ⟨g, rfl⟩, use mk g, refl end⟩ /-- If two normal subgroups `M` and `N` of `G` are the same, their quotient groups are isomorphic. -/ @[to_additive "If two normal subgroups `M` and `N` of `G` are the same, their quotient groups are isomorphic."] def equiv_quotient_of_eq {M N : subgroup G} [M.normal] [N.normal] (h : M = N) : quotient M ≃* quotient N := { to_fun := (lift M (mk' N) (λ m hm, quotient_group.eq.mpr (by simpa [← h] using M.inv_mem hm))), inv_fun := (lift N (mk' M) (λ n hn, quotient_group.eq.mpr (by simpa [← h] using N.inv_mem hn))), left_inv := λ x, x.induction_on' $ by { intro, refl }, right_inv := λ x, x.induction_on' $ by { intro, refl }, map_mul' := λ x y, by rw map_mul } section snd_isomorphism_thm open subgroup /-- The second isomorphism theorem: given two subgroups `H` and `N` of a group `G`, where `N` is normal, defines an isomorphism between `H/(H ∩ N)` and `(HN)/N`. -/ @[to_additive "The second isomorphism theorem: given two subgroups `H` and `N` of a group `G`, where `N` is normal, defines an isomorphism between `H/(H ∩ N)` and `(H + N)/N`"] noncomputable def quotient_inf_equiv_prod_normal_quotient (H N : subgroup G) [N.normal] : quotient ((H ⊓ N).comap H.subtype) ≃* quotient (N.comap (H ⊔ N).subtype) := /- φ is the natural homomorphism H →* (HN)/N. -/ let φ : H →* quotient (N.comap (H ⊔ N).subtype) := (mk' $ N.comap (H ⊔ N).subtype).comp (inclusion le_sup_left) in have φ_surjective : function.surjective φ := λ x, x.induction_on' $ begin rintro ⟨y, (hy : y ∈ ↑(H ⊔ N))⟩, rw mul_normal H N at hy, rcases hy with ⟨h, n, hh, hn, rfl⟩, use [h, hh], apply quotient.eq.mpr, change h⁻¹ * (h * n) ∈ N, rwa [←mul_assoc, inv_mul_self, one_mul], end, (equiv_quotient_of_eq (by simp [comap_comap, ←comap_ker])).trans (quotient_ker_equiv_of_surjective φ φ_surjective) end snd_isomorphism_thm end quotient_group
61fda9c3abb204718528eae79a83edad7cde1edc
618003631150032a5676f229d13a079ac875ff77
/src/algebra/category/Group/Z_Module_equivalence.lean
b66ef5da699b8766c82bcd168f5e8987deaf50fd
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,237
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Module.basic /-! The forgetful functor from ℤ-modules to additive commutative groups is an equivalence of categories. TODO: either use this equivalence to transport the monoidal structure from `Module ℤ` to `Ab`, or, having constructed that monoidal structure directly, show this functor is monoidal. -/ open category_theory open category_theory.equivalence /-- The forgetful functor from `ℤ` modules to `AddCommGroup` is full. -/ instance : full (forget₂ (Module ℤ) AddCommGroup) := { preimage := λ A B f, { to_fun := f, add := λ x y, add_monoid_hom.map_add f x y, smul := λ n x, by convert add_monoid_hom.map_int_module_smul f n x } } /-- The forgetful functor from `ℤ` modules to `AddCommGroup` is essentially surjective. -/ instance : ess_surj (forget₂ (Module ℤ) AddCommGroup) := { obj_preimage := λ A, Module.of ℤ A, iso' := λ A, { hom := 𝟙 A, inv := 𝟙 A, } } instance : is_equivalence (forget₂ (Module ℤ) AddCommGroup) := equivalence_of_fully_faithfully_ess_surj (forget₂ (Module ℤ) AddCommGroup)
2d80fe3b0b2c1c719f0f313ed7beb53b600a7b82
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast_ematch2.lean
1888269e975dd9a84619b6b4b878fca58b089940
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
219
lean
import data.nat open nat constant f : nat → nat constant g : nat → nat definition lemma1 [forward] : ∀ x, g (f x) = x := sorry set_option blast.ematch true example (a b : nat) : f a = f b → a = b := by blast
a9d3c014599d0b08b93c2e10cdc7792352ad007a
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Server/FileWorker.lean
776fbbc0657fb88f85f1530b6611c52d01fe1285
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
37,549
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Std.Data.RBMap import Lean.Environment import Lean.PrettyPrinter import Lean.DeclarationRange import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Server.Snapshots import Lean.Server.Utils import Lean.Server.AsyncList import Lean.Server.InfoUtils import Lean.Server.Completion /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open Lean.Parser.Command open Std (RBMap RBMap.empty) open JsonRpc section Utils private def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit := IO.eprintln s!"[{s.beginPos}, {s.endPos}]: `{text.source.extract s.beginPos (s.endPos-1)}`" inductive ElabTaskError where | aborted | eof | ioError (e : IO.Error) instance : Coe IO.Error ElabTaskError := ⟨ElabTaskError.ioError⟩ structure CancelToken where ref : IO.Ref Bool deriving Inhabited namespace CancelToken def new : IO CancelToken := CancelToken.mk <$> IO.mkRef false def check [MonadExceptOf ElabTaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do let c ← tk.ref.get if c then throw ElabTaskError.aborted def set (tk : CancelToken) : IO Unit := tk.ref.set true end CancelToken /-- A document editable in the sense that we track the environment and parser state after each command so that edits can be applied without recompiling code appearing earlier in the file. -/ structure EditableDocument where meta : DocumentMeta /- The first snapshot is that after the header. -/ headerSnap : Snapshot /- Subsequent snapshots occur after each command. -/ cmdSnaps : AsyncList ElabTaskError Snapshot cancelTk : CancelToken deriving Inhabited end Utils /- Asynchronous snapshot elaboration. -/ section Elab /-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/ private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream) : ExceptT ElabTaskError IO Snapshot := do cancelTk.check publishProgressAtPos m parentSnap.endPos hOut let maybeSnap ← compileNextCmd m.text.source parentSnap -- TODO(MH): check for interrupt with increased precision cancelTk.check match maybeSnap with | Sum.inl snap => /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ publishMessages m snap.msgLog hOut snap | Sum.inr msgLog => publishMessages m msgLog hOut publishProgressDone m hOut throw ElabTaskError.eof /-- Elaborates all commands after `initSnap`, emitting the diagnostics into `hOut`. -/ def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream) (initial : Bool) : IO (AsyncList ElabTaskError Snapshot) := do if initial && initSnap.msgLog.hasErrors then -- treat header processing errors as fatal so users aren't swamped with followup errors AsyncList.nil else AsyncList.unfoldAsync (nextCmdSnap m . cancelTk hOut) initSnap end Elab -- Pending requests are tracked so they can be cancelled abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) compare structure ServerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream srcSearchPath : SearchPath docRef : IO.Ref EditableDocument pendingRequestsRef : IO.Ref PendingRequestMap abbrev ServerM := ReaderT ServerContext IO /- Worker initialization sequence. -/ section Initialization /-- Use `leanpkg print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`. Compilation progress is reported to `hOut` via LSP notifications. Return the search path for source files. -/ partial def leanpkgSetupSearchPath (leanpkgPath : System.FilePath) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do let leanpkgProc ← Process.spawn { stdin := Process.Stdio.null stdout := Process.Stdio.piped stderr := Process.Stdio.piped cmd := leanpkgPath.toString args := #["print-paths"] ++ imports.map (toString ·.module) } -- progress notification: report latest stderr line let rec processStderr (acc : String) : IO String := do let line ← leanpkgProc.stderr.getLine if line == "" then return acc else publishDiagnostics m #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }] hOut processStderr (acc ++ line) let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated let stdout := String.trim (← leanpkgProc.stdout.readToEnd) let stderr ← IO.ofExcept stderr.get if (← leanpkgProc.wait) == 0 then let leanpkgLines := stdout.split (· == '\n') -- ignore any output up to the last two lines -- TODO: leanpkg should instead redirect nested stdout output to stderr let leanpkgLines := leanpkgLines.drop (leanpkgLines.length - 2) match leanpkgLines with | [""] => pure [] -- e.g. no leanpkg.toml | [leanPath, leanSrcPath] => let sp ← getBuiltinSearchPath let sp ← addSearchPathFromEnv sp let sp := System.SearchPath.parse leanPath ++ sp searchPathRef.set sp let srcPath := System.SearchPath.parse leanSrcPath srcPath.mapM realPathNormalized | _ => throw <| IO.userError s!"unexpected output from `leanpkg print-paths`:\n{stdout}\nstderr:\n{stderr}" else throw <| IO.userError s!"`leanpkg print-paths` failed:\n{stdout}\nstderr:\n{stderr}" def compileHeader (m : DocumentMeta) (hOut : FS.Stream) : IO (Snapshot × SearchPath) := do let opts := {} -- TODO let inputCtx := Parser.mkInputContext m.text.source "<input>" let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx let leanpkgPath ← match ← IO.getEnv "LEAN_SYSROOT" with | some path => pure <| System.FilePath.mk path / "bin" / "leanpkg" | _ => pure <| (← appDir) / "leanpkg" let leanpkgPath := leanpkgPath.withExtension System.FilePath.exeExtension let mut srcSearchPath := [(← appDir) / ".." / "lib" / "lean" / "src"] if let some p := (← IO.getEnv "LEAN_SRC_PATH") then srcSearchPath := srcSearchPath ++ System.SearchPath.parse p let (headerEnv, msgLog) ← try -- NOTE: leanpkg does not exist in stage 0 (yet?) if (← System.FilePath.pathExists leanpkgPath) then let pkgSearchPath ← leanpkgSetupSearchPath leanpkgPath m (Lean.Elab.headerToImports headerStx).toArray hOut srcSearchPath := srcSearchPath ++ pkgSearchPath Elab.processHeader headerStx opts msgLog inputCtx catch e => -- should be from `leanpkg print-paths` let msgs := MessageLog.empty.add { fileName := "<ignored>", pos := ⟨0, 0⟩, data := e.toString } pure (← mkEmptyEnvironment, msgs) publishMessages m msgLog hOut let cmdState := Elab.Command.mkState headerEnv msgLog opts let cmdState := { cmdState with infoState.enabled := true, scopes := [{ header := "", opts := opts }] } let headerSnap := { beginPos := 0 stx := headerStx mpState := headerParserState cmdState := cmdState } return (headerSnap, srcSearchPath) def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream) : IO ServerContext := do /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ let (headerSnap, srcSearchPath) ← compileHeader meta o let cancelTk ← CancelToken.new let cmdSnaps ← unfoldCmdSnaps meta headerSnap cancelTk o (initial := true) let doc : EditableDocument := ⟨meta, headerSnap, cmdSnaps, cancelTk⟩ return { hIn := i hOut := o hLog := e srcSearchPath := srcSearchPath docRef := ←IO.mkRef doc pendingRequestsRef := ←IO.mkRef RBMap.empty } end Initialization section Updates def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : ServerM Unit := do (←read).pendingRequestsRef.modify map /-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : ServerM Unit := do -- The watchdog only restarts the file worker when the syntax tree of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let st ← read let oldDoc ← st.docRef.get let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap if newHeaderSnap.stx != oldDoc.headerSnap.stx then throwServerError "Internal server error: header changed but worker wasn't restarted." let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix match e? with -- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks -- do not show up in `snapshots` of an EditableDocument. | some ElabTaskError.aborted => throwServerError "Internal server error: elab task was aborted while still in use." | some (ElabTaskError.ioError ioError) => throw ioError | _ => -- No error or EOF oldDoc.cancelTk.set -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos) if validSnaps.length = 0 then let cancelTk ← CancelToken.new let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.hOut (initial := true) st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.text.source preLastSnap if newLastStx != lastSnap.stx then validSnaps ← validSnaps.dropLast lastSnap ← preLastSnap let cancelTk ← CancelToken.new let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk st.hOut (initial := false) let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ end Updates /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ section NotificationHandling def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc ← (←read).docRef.get let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff def handleCancelRequest (p : CancelParams) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) end NotificationHandling /- Request handlers are given by `Task`s executed asynchronously. They may be cancelled at any time, so they should check the cancellation token when possible to handle this cooperatively. Any exceptions thrown in a handler will be reported to the client as LSP error responses. -/ section RequestHandling structure RequestError where code : ErrorCode message : String namespace RequestError def fileChanged : RequestError := { code := ErrorCode.contentModified message := "File changed." } end RequestError -- TODO(WN): the type is too complicated abbrev RequestM α := ServerM $ Task $ Except IO.Error $ Except RequestError α def mapTask (t : Task α) (f : α → ExceptT RequestError ServerM β) : RequestM β := fun st => (IO.mapTask · t) fun a => f a st /-- Create a task which waits for a snapshot matching `p`, handles various errors, and if a matching snapshot was found executes `x` with it. If not found, the task executes `notFoundX`. -/ def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool) (notFoundX : ExceptT RequestError ServerM β) (x : Snapshot → ExceptT RequestError ServerM β) : ServerM (Task (Except IO.Error (Except RequestError β))) := do let findTask ← doc.cmdSnaps.waitFind? p mapTask findTask fun | Except.error ElabTaskError.aborted => throwThe RequestError RequestError.fileChanged | Except.error (ElabTaskError.ioError e) => throwThe IO.Error e | Except.error ElabTaskError.eof => notFoundX | Except.ok none => notFoundX | Except.ok (some snap) => x snap /- Requests that need data from a certain command should traverse the snapshots by successively getting the next task, meaning that we might need to wait for elaboration. When that happens, the request should send a "content changed" error to the user (this way, the server doesn't get bogged down in requests for an old state of the document). Requests need to manually check for whether their task has been cancelled, so that they can reply with a RequestCancelled error. -/ partial def handleCompletion (p : CompletionParams) : ServerM (Task (Except IO.Error (Except RequestError CompletionList))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let pos := text.lspPosToUtf8Pos p.position -- dbg_trace ">> handleCompletion invoked {pos}" -- NOTE: use `>=` since the cursor can be *after* the input withWaitFindSnap doc (fun s => s.endPos >= pos) (notFoundX := pure { items := #[], isIncomplete := true }) fun snap => do for infoTree in snap.cmdState.infoState.trees do -- for (ctx, info) in infoTree.getCompletionInfos do -- dbg_trace "{← info.format ctx}" if let some r ← Completion.find? doc.meta.text pos infoTree then return r return { items := #[ ], isIncomplete := true } open Elab in partial def handleHover (p : HoverParams) : ServerM (Task (Except IO.Error (Except RequestError (Option Hover)))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let mkHover (s : String) (f : String.Pos) (t : String.Pos) : Hover := { contents := { kind := MarkupKind.markdown value := s } range? := some { start := text.utf8PosToLspPos f «end» := text.utf8PosToLspPos t } } let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure none) fun snap => do for t in snap.cmdState.infoState.trees do if let some (ci, i) := t.hoverableInfoAt? hoverPos then if let some hoverFmt ← i.fmtHover? ci then return some <| mkHover (toString hoverFmt) i.pos?.get! i.tailPos?.get! return none open Elab in partial def handleDefinition (goToType? : Bool) (p : TextDocumentPositionParams) : ServerM (Task (Except IO.Error (Except RequestError (Array LocationLink)))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure #[]) fun snap => do for t in snap.cmdState.infoState.trees do if let some (ci, Info.ofTermInfo i) := t.hoverableInfoAt? hoverPos then let mut expr := i.expr if goToType? then expr ← ci.runMetaM i.lctx do Meta.instantiateMVars (← Meta.inferType expr) if let some n := expr.constName? then let mod? ← ci.runMetaM i.lctx <| findModuleOf? n let modUri? ← match mod? with | some modName => let modFname? ← st.srcSearchPath.findWithExt "lean" modName pure <| modFname?.map toFileUri | none => pure <| some doc.meta.uri let ranges? ← ci.runMetaM i.lctx <| findDeclarationRanges? n if let (some ranges, some modUri) := (ranges?, modUri?) then let declRangeToLspRange (r : DeclarationRange) : Lsp.Range := { start := ⟨r.pos.line - 1, r.charUtf16⟩ «end» := ⟨r.endPos.line - 1, r.endCharUtf16⟩ } let ll : LocationLink := { originSelectionRange? := some ⟨text.utf8PosToLspPos i.stx.getPos?.get!, text.utf8PosToLspPos i.stx.getTailPos?.get!⟩ targetUri := modUri targetRange := declRangeToLspRange ranges.range targetSelectionRange := declRangeToLspRange ranges.selectionRange } return #[ll] return #[] open Elab in partial def handlePlainGoal (p : PlainGoalParams) : ServerM (Task (Except IO.Error (Except RequestError (Option PlainGoal)))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position -- NOTE: use `>=` since the cursor can be *after* the input withWaitFindSnap doc (fun s => s.endPos >= hoverPos) (notFoundX := return none) fun snap => do for t in snap.cmdState.infoState.trees do if let rs@(_ :: _) := t.goalsAt? doc.meta.text hoverPos then let goals ← List.join <$> rs.mapM fun { ctxInfo := ci, tacticInfo := ti, useAfter := useAfter } => let ci := if useAfter then { ci with mctx := ti.mctxAfter } else { ci with mctx := ti.mctxBefore } let goals := if useAfter then ti.goalsAfter else ti.goalsBefore ci.runMetaM {} <| goals.mapM (fun g => Meta.withPPInaccessibleNames (Meta.ppGoal g)) let md := if goals.isEmpty then "no goals" else let goals := goals.map fun goal => s!"```lean {goal} ```" String.intercalate "\n---\n" goals return some { goals := goals.map toString |>.toArray, rendered := md } return none def hasRange (stx : Syntax) : Bool := stx.getPos?.isSome && stx.getTailPos?.isSome def rangeOfSyntax! (text : FileMap) (stx : Syntax) : Range := ⟨text.utf8PosToLspPos <| stx.getPos?.get!, text.utf8PosToLspPos <| stx.getTailPos?.get!⟩ open Elab in partial def handlePlainTermGoal (p : PlainTermGoalParams) : ServerM (Task (Except IO.Error (Except RequestError (Option PlainTermGoal)))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure none) fun snap => do for t in snap.cmdState.infoState.trees do if let some (ci, Info.ofTermInfo i) := t.termGoalAt? hoverPos then let goal ← ci.runMetaM i.lctx <| open Meta in do let ty ← instantiateMVars <| i.expectedType?.getD (← inferType i.expr) withPPInaccessibleNames <| Meta.ppGoal (← mkFreshExprMVar ty).mvarId! let range := if hasRange i.stx then rangeOfSyntax! text i.stx else ⟨p.position, p.position⟩ return some { goal := toString goal, range } return none partial def handleDocumentHighlight (p : DocumentHighlightParams) : ServerM (Task (Except IO.Error (Except RequestError (Array DocumentHighlight)))) := do let doc ← (← read).docRef.get let text := doc.meta.text let pos := text.lspPosToUtf8Pos p.position let rec highlightReturn? (doRange? : Option Range) : Syntax → Option DocumentHighlight | stx@`(doElem|return%$i $e) => if stx.getPos?.get! <= pos && pos < stx.getTailPos?.get! then some { range := doRange?.getD (rangeOfSyntax! text i), kind? := DocumentHighlightKind.text } else highlightReturn? doRange? e | `(do%$i $elems) => highlightReturn? (rangeOfSyntax! text i) elems | stx => stx.getArgs.findSome? (highlightReturn? doRange?) withWaitFindSnap doc (fun s => s.endPos > pos) (notFoundX := pure #[]) fun snap => do if let some hi := highlightReturn? none snap.stx then return #[hi] return #[] partial def handleDocumentSymbol (p : DocumentSymbolParams) : ServerM (Task (Except IO.Error (Except RequestError DocumentSymbolResult))) := do let st ← read asTask do let doc ← st.docRef.get let ⟨cmdSnaps, e?⟩ ← doc.cmdSnaps.updateFinishedPrefix let mut stxs := cmdSnaps.finishedPrefix.map Snapshot.stx match e? with | some ElabTaskError.aborted => return Except.error RequestError.fileChanged | some _ => pure () -- TODO(WN): what to do on ioError? | none => let lastSnap := cmdSnaps.finishedPrefix.getLastD doc.headerSnap stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList let (syms, _) := toDocumentSymbols doc.meta.text stxs return Except.ok { syms := syms.toArray } where toDocumentSymbols (text : FileMap) | [] => ([], []) | stx::stxs => match stx with | `(namespace $id) => sectionLikeToDocumentSymbols text stx stxs (id.getId.toString) SymbolKind.namespace id | `(section $(id)?) => sectionLikeToDocumentSymbols text stx stxs ((·.getId.toString) <$> id |>.getD "<section>") SymbolKind.namespace (id.getD stx) | `(end $(id)?) => ([], stx::stxs) | _ => let (syms, stxs') := toDocumentSymbols text stxs if stx.isOfKind ``Lean.Parser.Command.declaration && hasRange stx then let (name, selection) := match stx with | `($dm:declModifiers $ak:attrKind instance $[$np:namedPrio]? $[$id:ident$[.{$ls,*}]?]? $sig:declSig $val) => ((·.getId.toString) <$> id |>.getD s!"instance {sig.reprint.getD ""}", id.getD sig) | _ => match stx[1][1] with | `(declId|$id:ident$[.{$ls,*}]?) => (id.getId.toString, id) | _ => (stx[1][0].isIdOrAtom?.getD "<unknown>", stx[1][0]) if hasRange selection then (DocumentSymbol.mk { name := name kind := SymbolKind.method range := rangeOfSyntax! text stx selectionRange := rangeOfSyntax! text selection } :: syms, stxs') else (syms, stxs') else (syms, stxs') sectionLikeToDocumentSymbols (text : FileMap) (stx : Syntax) (stxs : List Syntax) (name : String) (kind : SymbolKind) (selection : Syntax) := let (syms, stxs') := toDocumentSymbols text stxs -- discard `end` let (syms', stxs'') := toDocumentSymbols text (stxs'.drop 1) let endStx := match stxs' with | endStx::_ => endStx | [] => (stx::stxs').getLast! -- we can assume that commands always have at least one position (see `parseCommand`) let range := rangeOfSyntax! text (mkNullNode #[stx, endStx]) (DocumentSymbol.mk { name kind range selectionRange := if hasRange selection then rangeOfSyntax! text selection else range children? := syms.toArray } :: syms', stxs'') def noHighlightKinds : Array SyntaxNodeKind := #[ -- usually have special highlighting by the client ``Lean.Parser.Term.sorry, ``Lean.Parser.Term.type, ``Lean.Parser.Term.prop, -- not really keywords `antiquotName, ``Lean.Parser.Command.docComment] structure SemanticTokensContext where beginPos : String.Pos endPos : String.Pos text : FileMap infoState : Elab.InfoState structure SemanticTokensState where data : Array Nat lastLspPos : Lsp.Position partial def handleSemanticTokens (beginPos endPos : String.Pos) : ServerM (Task (Except IO.Error (Except RequestError SemanticTokens))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let t ← doc.cmdSnaps.waitAll (·.beginPos < endPos) IO.mapTask (t := t) fun (snaps, _) => StateT.run' (s := { data := #[], lastLspPos := ⟨0, 0⟩ : SemanticTokensState }) do for s in snaps do if s.endPos <= beginPos then continue ReaderT.run (r := SemanticTokensContext.mk beginPos endPos text s.cmdState.infoState) <| go s.stx return Except.ok { data := (← get).data } where go (stx : Syntax) := do match stx with | `($e.$id:ident) => go e; addToken id SemanticTokenType.property -- indistinguishable from next pattern --| `(level|$id:ident) => addToken id SemanticTokenType.variable | `($id:ident) => highlightId id | _ => if !noHighlightKinds.contains stx.getKind then highlightKeyword stx if stx.isOfKind choiceKind then go stx[0] else stx.getArgs.forM go highlightId (stx : Syntax) : ReaderT SemanticTokensContext (StateT SemanticTokensState IO) _ := do if let (some pos, some tailPos) := (stx.getPos?, stx.getTailPos?) then for t in (← read).infoState.trees do for ti in t.deepestNodes (fun | _, i@(Elab.Info.ofTermInfo ti), _ => match i.pos? with | some ipos => if pos <= ipos && ipos < tailPos then some ti else none | _ => none | _, _, _ => none) do match ti.expr with | Expr.fvar .. => addToken ti.stx SemanticTokenType.variable | _ => if ti.stx.getPos?.get! > pos then addToken ti.stx SemanticTokenType.property highlightKeyword stx := do if let Syntax.atom info val := stx then if val.bsize > 0 && val[0].isAlpha then addToken stx SemanticTokenType.keyword addToken stx type := do let ⟨beginPos, endPos, text, _⟩ ← read if let (some pos, some tailPos) := (stx.getPos?, stx.getTailPos?) then if beginPos <= pos && pos < endPos then let lspPos := (← get).lastLspPos let lspPos' := text.utf8PosToLspPos pos let deltaLine := lspPos'.line - lspPos.line let deltaStart := lspPos'.character - (if lspPos'.line == lspPos.line then lspPos.character else 0) let length := (text.utf8PosToLspPos tailPos).character - lspPos'.character let tokenType := type.toNat let tokenModifiers := 0 modify fun st => { data := st.data ++ #[deltaLine, deltaStart, length, tokenType, tokenModifiers] lastLspPos := lspPos' } def handleSemanticTokensFull (p : SemanticTokensParams) : ServerM (Task (Except IO.Error (Except RequestError SemanticTokens))) := do handleSemanticTokens 0 (1 <<< 16) def handleSemanticTokensRange (p : SemanticTokensRangeParams) : ServerM (Task (Except IO.Error (Except RequestError SemanticTokens))) := do let st ← read let doc ← st.docRef.get let text := doc.meta.text let beginPos := text.lspPosToUtf8Pos p.range.start let endPos := text.lspPosToUtf8Pos p.range.end handleSemanticTokens beginPos endPos partial def handleWaitForDiagnostics (p : WaitForDiagnosticsParams) : ServerM (Task (Except IO.Error (Except RequestError WaitForDiagnostics))) := do let st ← read let rec waitLoop : IO EditableDocument := do let doc ← st.docRef.get if p.version ≤ doc.meta.version then return doc else IO.sleep 50 waitLoop let t ← IO.asTask waitLoop let t ← IO.bindTask t fun | Except.error e => unreachable! | Except.ok doc => do let t₁ ← doc.cmdSnaps.waitAll return t₁.map fun _ => Except.ok WaitForDiagnostics.mk return t.map fun _ => Except.ok <| Except.ok WaitForDiagnostics.mk end RequestHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | some parsed => pure parsed | none => throwServerError s!"Got param with wrong structure: {params.compress}" def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → ServerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] respType [ToJson respType] (handler : paramType → RequestM respType) => do let st ← read let p ← parseParams paramType params let t ← handler p let t₁ ← (IO.mapTask · t) fun | Except.ok (Except.ok resp) => st.hOut.writeLspResponse ⟨id, resp⟩ | Except.ok (Except.error e) => st.hOut.writeLspResponseError { id := id, code := e.code, message := e.message } | Except.error e => st.hOut.writeLspResponseError { id := id, code := ErrorCode.internalError, message := toString e } queueRequest id t₁ match method with | "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParams WaitForDiagnostics handleWaitForDiagnostics | "textDocument/completion" => handle CompletionParams CompletionList handleCompletion | "textDocument/hover" => handle HoverParams (Option Hover) handleHover | "textDocument/declaration" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := false) | "textDocument/definition" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := false) | "textDocument/typeDefinition" => handle TextDocumentPositionParams (Array LocationLink) <| handleDefinition (goToType? := true) | "textDocument/documentHighlight" => handle DocumentHighlightParams DocumentHighlightResult handleDocumentHighlight | "textDocument/documentSymbol" => handle DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol | "textDocument/semanticTokens/full" => handle SemanticTokensParams SemanticTokens handleSemanticTokensFull | "textDocument/semanticTokens/range" => handle SemanticTokensRangeParams SemanticTokens handleSemanticTokensRange | "$/lean/plainGoal" => handle PlainGoalParams (Option PlainGoal) handlePlainGoal | "$/lean/plainTermGoal" => handle PlainTermGoalParams (Option PlainTermGoal) handlePlainTermGoal | _ => throwServerError s!"Got unsupported request: {method}" end MessageHandling section MainLoop partial def mainLoop : ServerM Unit := do let st ← read let msg ← st.hIn.readLspMessage let pendingRequests ← st.pendingRequestsRef.get let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : ServerM PendingRequestMap := do if (←hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" acc.erase id else acc let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests st.pendingRequestsRef.set pendingRequests match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => let doc ← st.docRef.get doc.cancelTk.set return () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) : IO UInt32 := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o -- TODO(WN): act in accordance with InitializeParams let _ ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let doc := param.textDocument let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩ let e ← e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e try let ctx ← initializeWorker meta i o e ReaderT.run (r := ctx) mainLoop return 0 catch e => IO.eprintln e publishDiagnostics meta #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }] o return 1 @[export lean_server_worker_main] def workerMain : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWorker i o e catch err => e.putStrLn s!"worker initialization error: {err}" return (1 : UInt32) end Lean.Server.FileWorker
d3644b499ca02cbe8528ef3be12477ad555103fe
9a208b2f36ebdb9b100b123c6aa00063414860a7
/src/widget.lean
760b89a34e116bcf74dd51c549ab4c44162440a9
[ "Apache-2.0" ]
permissive
SnobbyDragon/sudoku
67b0dc46ff3484e29b0d99e1b82d66896ce13ff0
3aa976818a7c950c85d6e7f1a70d329125fcea9b
refs/heads/master
1,675,441,677,467
1,609,123,194,000
1,609,123,194,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,180
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import init.meta.widget.tactic_component import stactic section tac open tactic widget tactic.sudoku meta def list.iota' : ℕ → list ℕ := list.map (λ n, n - 1) ∘ list.reverse ∘ list.iota meta def get_numbers (n m : ℕ) : list cell_data → list ℕ := list.erase_dup ∘ list.filter_map (λ cd : cell_data, if cd.row.1 = n ∧ cd.col.1 = m then some ( if cd.val.1 = 0 then 9 else cd.val.1) else none) meta def get_outer_marks (n m : ℕ) : list outer_pencil_data → list ℕ := list.erase_dup ∘ list.filter_map (λ op : outer_pencil_data, if (op.row₀.1 = n ∧ op.col₀.1 = m) ∨ (op.row₁.1 = n ∧ op.col₁.1 = m) then some ( if op.val.1 = 0 then 9 else op.val.1) else none) meta def get_inner_marks (n m : ℕ) : list inner_pencil_data → list ℕ := list.head ∘ list.filter_map (λ ip : inner_pencil_data, if ip.row.1 = n ∧ ip.col.1 = m then some (list.map (λ k : fin 9, if k.1 = 0 then 9 else k.1) ip.vals) else none) meta def format_marks (n m : ℕ) (bi : board_info) : list (html empty) := match get_inner_marks n m bi.ip with | [] := let os := get_outer_marks n m bi.op in [h "div" [cn "dtc", cn "mw3", cn "flex", cn "flex-wrap"] (list.map (λ k : ℕ, h "span" [cn "f5", cn "ph1"] (to_string k)) os)] | l := [h "span" [cn "dtc", cn "tc", cn "v-mid", cn "f5"] (list.map (λ l : ℕ, to_string l) l)] end meta def mk_table_entry (n m : ℕ) (bi : board_info) : tactic (html empty) := do let attrs : list (attr empty) := [cn "bw2"], let attrs := if n % 3 = 0 then attrs ++ [cn "bt"] else attrs, let attrs := if m % 3 = 0 then attrs ++ [cn "bl"] else attrs, let attrs := if n % 3 = 2 then attrs ++ [cn "bb"] else attrs, let attrs := if m % 3 = 2 then attrs ++ [cn "br"] else attrs, let ns := get_numbers n m bi.cd, let s : list (html empty) := match ns with | [] := format_marks n m bi | (a::[]) := [h "span" [cn "dtc", cn "v-mid", cn "tc", cn "f2"] (to_string a)] | (a::as) := [h "span" [cn "dtc", cn "v-mid", cn "tc", cn "f2"] "💥"] end, return $ h "td" attrs [ h "div" [cn "dt", cn "ba", cn "b--light-silver", cn "w3", cn "mw3", cn "h3"] s ] meta def mk_table_row (n : ℕ) (bi : board_info) : tactic (html empty) := do a ← list.mmap (λ m, mk_table_entry n m bi) (list.iota' 9), return $ h "tr" [] a meta def mk_table (bi : board_info) : tactic (html empty) := do a ← list.mmap (λ n, mk_table_row n bi) (list.iota' 9), return $ h "table" [cn "collapse"] a meta def sudoku_widget : tactic (list (html empty)) := (do s ← get_sudoku, bi ← get_board_info s, u ← mk_table bi, return [u]) <|> return [] end tac section tc open widget meta def sudoku_component : tc unit empty := tc.stateless $ λ _, sudoku_widget meta def combined_component : tc unit empty := tc.stateless $ λ _, do s ← tactic.read, return [ h "div" [] [html.of_component s (tc.to_component sudoku_component)], h "hr" [] [], h "div" [] [html.of_component s tactic_state_widget] ] end tc @[reducible] meta def show_sudoku := tactic open tactic -- The following two functions are taken from the natural number game and are written by Rob Lewis meta def copy_decl (d : declaration) : tactic unit := add_decl $ d.update_name $ d.to_name.update_prefix `show_sudoku.interactive meta def copy_decls : tactic unit := do env ← get_env, let ls := env.fold [] list.cons, ls.mmap' $ λ dec, when (dec.to_name.get_prefix = `tactic.interactive) (copy_decl dec) namespace show_sudoku meta def step {α : Type} (t : show_sudoku α) : show_sudoku unit := t >> return () meta def istep := @tactic.istep meta def solve1 := @tactic.solve1 meta def save_info (p : pos) : show_sudoku unit := do s ← tactic.read, tactic.save_info_thunk p (λ _, tactic_state.to_format s), tactic.save_widget p (widget.tc.to_component combined_component) end show_sudoku run_cmd copy_decls example (P Q : Prop) (i : P → Q) (j : P) : Q := begin [show_sudoku] apply i, have : true := trivial, exact j, end
ce267760f8de8ae0f89ad49316d5a44ecf31e1bf
a44280b79dc85615010e3fbda46abf82c6730fa3
/tests/playground/task_test3.lean
e7754f82c472ea19f2dfdeae945d8d6977b915e2
[ "Apache-2.0" ]
permissive
kodyvajjha/lean4
8e1c613248b531d47367ca6e8d97ee1046645aa1
c8a045d69fac152fd5e3a577f718615cecb9c53d
refs/heads/master
1,589,684,450,102
1,555,200,447,000
1,556,139,945,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
436
lean
def run1 (i : Nat) (n : Nat) (xs : List Nat) : Nat := n.repeat (λ _ r, -- dbgTrace (">> [" ++ toString i ++ "] " ++ toString r) $ λ _, xs.foldl (+) (r+i)) 0 def main (xs : List String) : IO UInt32 := let ys := (List.repeat 1 xs.head.toNat) in let ts : List (Task Nat) := (List.iota 10).map (λ i, Task.mk $ λ _, run1 (i+1) xs.head.toNat ys) in let ns : List Nat := ts.map Task.get in IO.println (">> " ++ toString ns) *> pure 0
ee253c6c49085676a574baa3d8e36ea93a8a191e
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/holor.lean
d20fbc71cef5c81424cd7753632b87f116293d0e
[ "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
13,421
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp Basic properties of holors. Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. Based on the tensor library found in https://www.isa-afp.org/entries/Deep_Learning.html. -/ import data.list.basic import algebra.module import algebra.pi_instances import tactic.interactive import tactic.tidy import tactic.pi_instances universes u open list /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimenstions `ds` -/ def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds} namespace holor_index variables {ds₁ ds₂ ds₃ : list ℕ} def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩ def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂ | ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩ lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm) lemma take_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left]) lemma drop_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds:list ℕ) := holor_index ds → α namespace holor variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ} instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩ instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩ instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩ instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩ instance [add_semigroup α] : add_semigroup (holor α ds) := by pi_instance instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by pi_instance instance [add_monoid α] : add_monoid (holor α ds) := by pi_instance instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by pi_instance instance [add_group α] : add_group (holor α ds) := by pi_instance instance [add_comm_group α] : add_comm_group (holor α ds) := by pi_instance /- scalar product -/ instance [has_mul α] : has_scalar α (holor α ds) := ⟨λ a x, λ t, a * x t⟩ instance [ring α] : module α (holor α ds) := pi.module α instance [discrete_field α] : vector_space α (holor α ds) := ⟨α, holor α ds⟩ /- tensor product -/ def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := λ t, x (t.take) * y (t.drop) local infix ` ⊗ ` : 70 := mul lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm) lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left := funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃): mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext (λt, right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))) @[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) : (0 : holor α ds₁) ⊗ x = 0 := funext (λ t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) : x ⊗ (0 :holor α ds₂) = 0 := funext (λ t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) : x ⊗ y = x ⟨[], forall₂.nil⟩ • y := by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := (λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩) def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := λ ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop): Π (t : holor_index (d :: ds)), (∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t | ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨(i :: is), hforall₂⟩ hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis, have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forall₂_cons.1 hiisdds).1, have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 := funext $ λ t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)): slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)]) lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) : slice (0 : holor α (d :: ds)) i hid = 0 := funext (λ t, by simp [slice]; refl) lemma slice_sum [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)): finset.sum s (λ x, slice (f x) i hid) = slice (finset.sum s f) i hid := begin letI := classical.dec_eq β, refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) : (finset.range d).attach.sum (λ i, unit_vec d i.1 ⊗ slice x i.1 (nat.succ_le_of_lt (finset.mem_range.1 i.2))) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i _), { simp, refl }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩), have hbi' : i ≠ b.val, { apply not.imp hbi, { assume h0 : i = b.val, apply subtype.eq, simp only [h0] }, { exact finset.mem_range.2 hid } }, simp [hbi']}, { assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop | nil (x : holor α []) : cprank_max1 x | cons {d} {ds} (x : holor α [d]) (y : holor α ds) : cprank_max1 y → cprank_max1 (x ⊗ y) inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop | zero {ds} : cprank_max 0 (0 : holor α ds) | succ n {ds} (x : holor α ds) (y : holor α ds) : cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid α] [add_monoid α]: ∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds}, cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hx₂ hy } end lemma cprank_max_mul [ring α] : ∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x y₂ hy₂ } end lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (finset.sum s f) := by letI := classical.dec_eq β; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x ∉ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (finset.sum s f), { apply ih, assume (x : β) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Π (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)), from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end noncomputable def cprank [ring α] (x : holor α ds) : nat := @nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod := λ ds (x : holor α ds), by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
8a863d0573d12e5434c965e24ebc98077a21cd1d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/field_division.lean
c5fe4b557756ac49ec73e222ab8102577589d608
[]
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
11,523
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.ring_division import Mathlib.data.polynomial.derivative import Mathlib.algebra.gcd_monoid import Mathlib.PostPort universes u y v u_1 namespace Mathlib /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ namespace polynomial protected instance normalization_monoid {R : Type u} [integral_domain R] [normalization_monoid R] : normalization_monoid (polynomial R) := normalization_monoid.mk (fun (p : polynomial R) => units.mk (coe_fn C ↑(norm_unit (leading_coeff p))) (coe_fn C ↑(norm_unit (leading_coeff p)⁻¹)) sorry sorry) sorry sorry sorry @[simp] theorem coe_norm_unit {R : Type u} [integral_domain R] [normalization_monoid R] {p : polynomial R} : ↑(norm_unit p) = coe_fn C ↑(norm_unit (leading_coeff p)) := sorry theorem leading_coeff_normalize {R : Type u} [integral_domain R] [normalization_monoid R] (p : polynomial R) : leading_coeff (coe_fn normalize p) = coe_fn normalize (leading_coeff p) := sorry theorem is_unit_iff_degree_eq_zero {R : Type u} [field R] {p : polynomial R} : is_unit p ↔ degree p = 0 := sorry theorem degree_pos_of_ne_zero_of_nonunit {R : Type u} [field R] {p : polynomial R} (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := sorry theorem monic_mul_leading_coeff_inv {R : Type u} [field R] {p : polynomial R} (h : p ≠ 0) : monic (p * coe_fn C (leading_coeff p⁻¹)) := sorry theorem degree_mul_leading_coeff_inv {R : Type u} [field R] {q : polynomial R} (p : polynomial R) (h : q ≠ 0) : degree (p * coe_fn C (leading_coeff q⁻¹)) = degree p := sorry theorem irreducible_of_monic {R : Type u} [field R] {p : polynomial R} (hp1 : monic p) (hp2 : p ≠ 1) : irreducible p ↔ ∀ (f g : polynomial R), monic f → monic g → f * g = p → f = 1 ∨ g = 1 := sorry /-- Division of polynomials. See polynomial.div_by_monic for more details.-/ def div {R : Type u} [field R] (p : polynomial R) (q : polynomial R) : polynomial R := coe_fn C (leading_coeff q⁻¹) * (p /ₘ (q * coe_fn C (leading_coeff q⁻¹))) /-- Remainder of polynomial division, see the lemma `quotient_mul_add_remainder_eq_aux`. See polynomial.mod_by_monic for more details. -/ def mod {R : Type u} [field R] (p : polynomial R) (q : polynomial R) : polynomial R := p %ₘ (q * coe_fn C (leading_coeff q⁻¹)) protected instance has_div {R : Type u} [field R] : Div (polynomial R) := { div := div } protected instance has_mod {R : Type u} [field R] : Mod (polynomial R) := { mod := mod } theorem div_def {R : Type u} [field R] {p : polynomial R} {q : polynomial R} : p / q = coe_fn C (leading_coeff q⁻¹) * (p /ₘ (q * coe_fn C (leading_coeff q⁻¹))) := rfl theorem mod_def {R : Type u} [field R] {p : polynomial R} {q : polynomial R} : p % q = p %ₘ (q * coe_fn C (leading_coeff q⁻¹)) := rfl theorem mod_by_monic_eq_mod {R : Type u} [field R] {q : polynomial R} (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := sorry theorem div_by_monic_eq_div {R : Type u} [field R] {q : polynomial R} (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := sorry theorem mod_X_sub_C_eq_C_eval {R : Type u} [field R] (p : polynomial R) (a : R) : p % (X - coe_fn C a) = coe_fn C (eval a p) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval p a theorem mul_div_eq_iff_is_root {R : Type u} {a : R} [field R] {p : polynomial R} : (X - coe_fn C a) * (p / (X - coe_fn C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root protected instance euclidean_domain {R : Type u} [field R] : euclidean_domain (polynomial R) := euclidean_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry sorry Div.div sorry Mod.mod quotient_mul_add_remainder_eq_aux (fun (p q : polynomial R) => degree p < degree q) sorry sorry sorry theorem mod_eq_self_iff {R : Type u} [field R] {p : polynomial R} {q : polynomial R} (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := sorry theorem div_eq_zero_iff {R : Type u} [field R] {p : polynomial R} {q : polynomial R} (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := sorry theorem degree_add_div {R : Type u} [field R] {p : polynomial R} {q : polynomial R} (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := sorry theorem degree_div_le {R : Type u} [field R] (p : polynomial R) (q : polynomial R) : degree (p / q) ≤ degree p := sorry theorem degree_div_lt {R : Type u} [field R] {p : polynomial R} {q : polynomial R} (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := sorry @[simp] theorem degree_map {R : Type u} {k : Type y} [field R] [field k] (p : polynomial R) (f : R →+* k) : degree (map f p) = degree p := degree_map_eq_of_injective (ring_hom.injective f) p @[simp] theorem nat_degree_map {R : Type u} {k : Type y} [field R] {p : polynomial R} [field k] (f : R →+* k) : nat_degree (map f p) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map p f) @[simp] theorem leading_coeff_map {R : Type u} {k : Type y} [field R] {p : polynomial R} [field k] (f : R →+* k) : leading_coeff (map f p) = coe_fn f (leading_coeff p) := sorry theorem monic_map_iff {R : Type u} {k : Type y} [field R] [field k] {f : R →+* k} {p : polynomial R} : monic (map f p) ↔ monic p := sorry theorem is_unit_map {R : Type u} {k : Type y} [field R] {p : polynomial R} [field k] (f : R →+* k) : is_unit (map f p) ↔ is_unit p := sorry theorem map_div {R : Type u} {k : Type y} [field R] {p : polynomial R} {q : polynomial R} [field k] (f : R →+* k) : map f (p / q) = map f p / map f q := sorry theorem map_mod {R : Type u} {k : Type y} [field R] {p : polynomial R} {q : polynomial R} [field k] (f : R →+* k) : map f (p % q) = map f p % map f q := sorry theorem gcd_map {R : Type u} {k : Type y} [field R] {p : polynomial R} {q : polynomial R} [field k] (f : R →+* k) : euclidean_domain.gcd (map f p) (map f q) = map f (euclidean_domain.gcd p q) := sorry theorem eval₂_gcd_eq_zero {R : Type u} {k : Type y} [field R] [comm_semiring k] {ϕ : R →+* k} {f : polynomial R} {g : polynomial R} {α : k} (hf : eval₂ ϕ α f = 0) (hg : eval₂ ϕ α g = 0) : eval₂ ϕ α (euclidean_domain.gcd f g) = 0 := sorry theorem eval_gcd_eq_zero {R : Type u} [field R] {f : polynomial R} {g : polynomial R} {α : R} (hf : eval α f = 0) (hg : eval α g = 0) : eval α (euclidean_domain.gcd f g) = 0 := eval₂_gcd_eq_zero hf hg theorem root_left_of_root_gcd {R : Type u} {k : Type y} [field R] [comm_semiring k] {ϕ : R →+* k} {f : polynomial R} {g : polynomial R} {α : k} (hα : eval₂ ϕ α (euclidean_domain.gcd f g) = 0) : eval₂ ϕ α f = 0 := sorry theorem root_right_of_root_gcd {R : Type u} {k : Type y} [field R] [comm_semiring k] {ϕ : R →+* k} {f : polynomial R} {g : polynomial R} {α : k} (hα : eval₂ ϕ α (euclidean_domain.gcd f g) = 0) : eval₂ ϕ α g = 0 := sorry theorem root_gcd_iff_root_left_right {R : Type u} {k : Type y} [field R] [comm_semiring k] {ϕ : R →+* k} {f : polynomial R} {g : polynomial R} {α : k} : eval₂ ϕ α (euclidean_domain.gcd f g) = 0 ↔ eval₂ ϕ α f = 0 ∧ eval₂ ϕ α g = 0 := sorry theorem is_root_gcd_iff_is_root_left_right {R : Type u} [field R] {f : polynomial R} {g : polynomial R} {α : R} : is_root (euclidean_domain.gcd f g) α ↔ is_root f α ∧ is_root g α := root_gcd_iff_root_left_right theorem is_coprime_map {R : Type u} {k : Type y} [field R] {p : polynomial R} {q : polynomial R} [field k] (f : R →+* k) : is_coprime (map f p) (map f q) ↔ is_coprime p q := sorry @[simp] theorem map_eq_zero {R : Type u} {S : Type v} [field R] {p : polynomial R} [semiring S] [nontrivial S] (f : R →+* S) : map f p = 0 ↔ p = 0 := sorry theorem map_ne_zero {R : Type u} {S : Type v} [field R] {p : polynomial R} [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : map f p ≠ 0 := mt (iff.mp (map_eq_zero f)) hp theorem mem_roots_map {R : Type u} {k : Type y} [field R] {p : polynomial R} [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ roots (map f p) ↔ eval₂ f x p = 0 := sorry theorem exists_root_of_degree_eq_one {R : Type u} [field R] {p : polynomial R} (h : degree p = 1) : ∃ (x : R), is_root p x := sorry theorem coeff_inv_units {R : Type u} [field R] (u : units (polynomial R)) (n : ℕ) : coeff (↑u) n⁻¹ = coeff (↑(u⁻¹)) n := sorry theorem monic_normalize {R : Type u} [field R] {p : polynomial R} (hp0 : p ≠ 0) : monic (coe_fn normalize p) := sorry theorem coe_norm_unit_of_ne_zero {R : Type u} [field R] {p : polynomial R} (hp : p ≠ 0) : ↑(norm_unit p) = coe_fn C (leading_coeff p⁻¹) := sorry theorem normalize_monic {R : Type u} [field R] {p : polynomial R} (h : monic p) : coe_fn normalize p = p := sorry theorem map_dvd_map' {R : Type u} {k : Type y} [field R] [field k] (f : R →+* k) {x : polynomial R} {y : polynomial R} : map f x ∣ map f y ↔ x ∣ y := sorry theorem degree_normalize {R : Type u} [field R] {p : polynomial R} : degree (coe_fn normalize p) = degree p := sorry theorem prime_of_degree_eq_one {R : Type u} [field R] {p : polynomial R} (hp1 : degree p = 1) : prime p := sorry theorem irreducible_of_degree_eq_one {R : Type u} [field R] {p : polynomial R} (hp1 : degree p = 1) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one hp1) theorem not_irreducible_C {R : Type u} [field R] (x : R) : ¬irreducible (coe_fn C x) := sorry theorem degree_pos_of_irreducible {R : Type u} [field R] {p : polynomial R} (hp : irreducible p) : 0 < degree p := lt_of_not_ge fun (hp0 : 0 ≥ degree p) => (fun (this : p = coe_fn C (coeff p 0)) => not_irreducible_C (coeff p 0) (this ▸ hp)) (eq_C_of_degree_le_zero hp0) theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on fun (i : I) => X - coe_fn C (s i)) := sorry /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ theorem is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type u_1} [field K] (f : polynomial K) (a : K) (hf' : eval a (coe_fn derivative f) ≠ 0) : is_coprime (X - coe_fn C a) (f /ₘ (X - coe_fn C a)) := sorry theorem prod_multiset_root_eq_finset_root {R : Type u} [field R] {p : polynomial R} (hzero : p ≠ 0) : multiset.prod (multiset.map (fun (a : R) => X - coe_fn C a) (roots p)) = finset.prod (multiset.to_finset (roots p)) fun (a : R) => (fun (a : R) => (X - coe_fn C a) ^ root_multiplicity a p) a := sorry /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ theorem prod_multiset_X_sub_C_dvd {R : Type u} [field R] (p : polynomial R) : multiset.prod (multiset.map (fun (a : R) => X - coe_fn C a) (roots p)) ∣ p := sorry theorem roots_C_mul {R : Type u} [field R] (p : polynomial R) {a : R} (hzero : a ≠ 0) : roots (coe_fn C a * p) = roots p := sorry theorem roots_normalize {R : Type u} [field R] {p : polynomial R} : roots (coe_fn normalize p) = roots p := sorry
d54b4949a7475ef64adf4060e0e990c036b03acf
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/contradiction_tactic.lean
4b42d7bd12d7a5eef37eb7904800ce63ca1b14b1
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,597
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.function namespace tactic open expr tactic decidable environment private meta def contra_p_not_p : list expr → list expr → tactic unit | [] Hs := failed | (H1 :: Rs) Hs := do t ← infer_type H1 >>= whnf, (do a ← match_not t, H2 ← find_same_type a Hs, tgt ← target, pr ← mk_app `absurd [tgt, H2, H1], exact pr) <|> contra_p_not_p Rs Hs private meta def contra_false : list expr → tactic unit | [] := failed | (H :: Hs) := do t ← infer_type H, if is_false t then do tgt ← target, pr ← mk_app `false.rec [tgt, H], exact pr else contra_false Hs private meta def contra_not_a_refl_rel_a : list expr → tactic unit | [] := failed | (H :: Hs) := do t ← infer_type H, (do (lhs, rhs) ← match_ne t, unify lhs rhs, tgt ← target, refl_pr ← mk_app `eq.refl [lhs], mk_app `absurd [tgt, refl_pr, H] >>= exact) <|> (do p ← match_not t, (refl_lemma, lhs, rhs) ← match_refl_app p, unify lhs rhs, tgt ← target, refl_pr ← mk_app refl_lemma [lhs], mk_app `absurd [tgt, refl_pr, H] >>= exact) <|> contra_not_a_refl_rel_a Hs private meta def contra_constructor_eq : list expr → tactic unit | [] := failed | (H :: Hs) := do t ← infer_type H >>= whnf, match (is_eq t) with | (some (lhs_0, rhs_0)) := do env ← get_env, lhs ← whnf lhs_0, rhs ← whnf rhs_0, if is_constructor_app env lhs ∧ is_constructor_app env rhs ∧ const_name (get_app_fn lhs) ≠ const_name (get_app_fn rhs) then do tgt ← target, I_name ← return $ name.get_prefix (const_name (get_app_fn lhs)), pr ← mk_app (I_name <.> "no_confusion") [tgt, lhs, rhs, H], exact pr else contra_constructor_eq Hs | none := contra_constructor_eq Hs end meta def contradiction : tactic unit := do ctx ← local_context, (contra_false ctx <|> contra_not_a_refl_rel_a ctx <|> contra_p_not_p ctx ctx <|> contra_constructor_eq ctx <|> fail "contradiction tactic failed") meta def exfalso : tactic unit := do fail_if_no_goals, assert `Hfalse (expr.const `false []), swap, contradiction end tactic
b7bfa74f9866518c2252e0858933571facc4ed0c
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/topology/basic.lean
a4508908da6e7a7d725cddb1f9ac6bcb74421263
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
68,811
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, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial import algebra.support /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `α`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ noncomputable theory open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (set.compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} @[ext] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space α] include t /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t lemma is_open.inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter t s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma topological_space_eq_iff {t t' : topological_space α} : t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s := ⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩ lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open.union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open.inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open.inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open.and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open.inter /-- A set is closed if its complement is open -/ class is_closed (s : set α) : Prop := (is_open_compl : is_open sᶜ) @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := ⟨λ h, ⟨h⟩, λ h, h.is_open_compl⟩ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ } @[simp] lemma is_closed_univ : is_closed (univ : set α) := by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty } lemma is_closed.union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by { rw [← is_open_compl_iff] at *, rw compl_union, exact is_open.inter h₁ h₂ } lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i lemma is_closed_bInter {s : set β} {f : β → set α} (h : ∀ i ∈ s, is_closed (f i)) : is_closed (⋂ i ∈ s, f i) := is_closed_Inter $ λ i, is_closed_Inter $ h i @[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open.is_closed_compl {s : set α} (hs : is_open s) : is_closed sᶜ := is_closed_compl_iff.2 hs lemma is_open.sdiff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open.inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed.inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by { rw [← is_open_compl_iff] at *, rw compl_inter, exact is_open.union h₁ h₂ } lemma is_closed.sdiff {s t : set α} (h₁ : is_closed s) (h₂ : is_open t) : is_closed (s \ t) := is_closed.inter h₁ (is_closed_compl_iff.mpr h₂) lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed.union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed.union (is_closed_compl_iff.mpr hp) hq lemma is_closed.not : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ @[mono] lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set α) = univ := is_open_univ.interior_eq @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := is_open_interior.interior_eq @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open.inter is_open_interior is_open_interior) @[simp] lemma finset.interior_Inter {ι : Type*} (s : finset ι) (f : ι → set α) : interior (⋂ i ∈ s, f i) = ⋂ i ∈ s, interior (f i) := begin classical, refine s.induction_on (by simp) _, intros i s h₁ h₂, simp [h₂], end @[simp] lemma interior_Inter_of_fintype {ι : Type*} [fintype ι] (f : ι → set α) : interior (⋂ i, f i) = ⋂ i, interior (f i) := by { convert finset.univ.interior_Inter f; simp, } lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa subset_interior_iff_subset_of_open (is_open.sdiff hu₁ h₁), have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] lemma interior_Inter_subset (s : ι → set α) : interior (⋂ i, s i) ⊆ ⋂ i, interior (s i) := subset_Inter $ λ i, interior_mono $ Inter_subset _ _ lemma interior_bInter_subset (p : ι → Sort*) (s : Π i, p i → set α) : interior (⋂ i (hi : p i), s i hi) ⊆ ⋂ i (hi : p i), interior (s i hi) := (interior_Inter_subset _).trans $ Inter_subset_Inter $ λ i, interior_Inter_subset _ lemma interior_sInter_subset (S : set (set α)) : interior (⋂₀ S) ⊆ ⋂ s ∈ S, interior s := calc interior (⋂₀ S) = interior (⋂ s ∈ S, s) : by rw sInter_eq_bInter ... ⊆ ⋂ s ∈ S, interior s : interior_bInter_subset _ _ /-! ### Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma not_mem_of_not_mem_closure {s : set α} {P : α} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ @[mono] lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma diff_subset_closure_iff {s t : set α} : s \ t ⊆ closure t ↔ s ⊆ closure t := by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure] lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ @[simp] lemma closure_nonempty_iff {s : set α} : (closure s).nonempty ↔ s.nonempty := by simp only [← ne_empty_iff_nonempty, ne.def, closure_empty_iff] alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed.union is_closed_closure is_closed_closure) ((monotone_closure α).le_map_sup s t) @[simp] lemma finset.closure_Union {ι : Type*} (s : finset ι) (f : ι → set α) : closure (⋃ i ∈ s, f i) = ⋃ i ∈ s, closure (f i) := begin classical, refine s.induction_on (by simp) _, intros i s h₁ h₂, simp [h₂], end @[simp] lemma closure_Union_of_fintype {ι : Type*} [fintype ι] (f : ι → set α) : closure (⋃ i, f i) = ⋃ i, closure (f i) := by { convert finset.univ.closure_Union f; simp, } lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ := begin rw [interior, closure, compl_sUnion, compl_image_set_of], simp only [compl_subset_compl, is_open_compl_iff], end @[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (h₂ hs)⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set α) : Prop := ∀ x, x ∈ closure s lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h lemma interior_eq_empty_iff_dense_compl {s : set α} : interior s = ∅ ↔ dense sᶜ := by rw [dense_iff_closure_eq, closure_compl, compl_univ_iff] lemma dense.interior_compl {s : set α} (h : dense s) : interior sᶜ = ∅ := interior_eq_empty_iff_dense_compl.2 $ by rwa compl_compl /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set α} : dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.exists_mem_open {s : set α} (hs : dense s) {U : set α} (ho : is_open U) (hne : U.nonempty) : ∃ x ∈ s, x ∈ U := let ⟨x, hx⟩ := hs.inter_open_nonempty U ho hne in ⟨x, hx.2, hx.1⟩ lemma dense.nonempty_iff {s : set α} (hs : dense s) : s.nonempty ↔ nonempty α := ⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ := λ x, closure_mono h (hd x) /-- Complement to a singleton is dense if and only if the singleton is not an open set. -/ lemma dense_compl_singleton_iff_not_open {x : α} : dense ({x}ᶜ : set α) ↔ ¬is_open ({x} : set α) := begin fsplit, { intros hd ho, exact (hd.inter_open_nonempty _ ho (singleton_nonempty _)).ne_empty (inter_compl_self _) }, { refine λ ho, dense_iff_inter_open.2 (λ U hU hne, inter_compl_nonempty_iff.2 $ λ hUx, _), obtain rfl : U = {x}, from eq_singleton_iff_nonempty_unique_mem.2 ⟨hne, hUx⟩, exact ho hU } end /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] lemma frontier_subset_closure {s : set α} : frontier s ⊆ closure s := diff_subset _ _ /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] @[simp] lemma frontier_univ : frontier (univ : set α) = ∅ := by simp [frontier] @[simp] lemma frontier_empty : frontier (∅ : set α) = ∅ := by simp [frontier] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] lemma is_open.inter_frontier_eq {s : set α} (hs : is_open s) : s ∩ frontier s = ∅ := by rw [hs.frontier_eq, inter_diff_self] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed.inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm lemma is_open.inter_frontier_eq_empty_of_disjoint {s t : set α} (ht : is_open t) (hd : disjoint s t) : t ∩ frontier s = ∅ := begin rw [inter_comm, ← subset_compl_iff_disjoint], exact subset.trans frontier_subset_closure (closure_minimal (λ _, disjoint_left.1 hd) (is_closed_compl_iff.2 ht)) end lemma frontier_eq_inter_compl_interior {s : set α} : frontier s = (interior s)ᶜ ∩ (interior (sᶜ))ᶜ := by { rw [←frontier_compl, ←closure_compl], refl } lemma compl_frontier_eq_union_interior {s : set α} : (frontier s)ᶜ = interior s ∪ interior sᶜ := begin rw frontier_eq_inter_compl_interior, simp only [compl_inter, compl_compl], end /-! ### Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ @[irreducible] def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation `𝓝` := nhds" in topological_space /-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s localized "notation `𝓝[` s `] ` x:100 := nhds_within x s" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := by rw nhds /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) := begin rw nhds_def, exact has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open.inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ end /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : α} {p : α → Prop} : (∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi lemma mem_of_mem_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_mem_nhds h lemma is_open.mem_nhds {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_closed.compl_mem_nhds {a : α} {s : set α} (hs : is_closed s) (ha : a ∉ s) : sᶜ ∈ 𝓝 a := hs.is_open_compl.mem_nhds (mem_compl ha) lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : ∀ᶠ x in 𝓝 a, x ∈ s := is_open.mem_nhds hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) := begin convert nhds_basis_opens a, ext s, split, { rintros ⟨s_in, s_op⟩, exact ⟨mem_of_mem_nhds s_in, s_op⟩ }, { rintros ⟨a_in, s_op⟩, exact ⟨is_open.mem_nhds s_op a_in, s_op⟩ }, end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`: it contains an open set containing `s`. -/ lemma exists_open_set_nhds {s U : set α} (h : ∀ x ∈ s, U ∈ 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := begin have := λ x hx, (nhds_basis_opens x).mem_iff.1 (h x hx), choose! Z hZ hZ' using this, refine ⟨⋃ x ∈ s, Z x, _, _, bUnion_subset hZ'⟩, { intros x hx, simp only [mem_Union], exact ⟨x, hx, (hZ x hx).1⟩ }, { apply is_open_Union, intros x, by_cases hx : x ∈ s ; simp [hx], exact (hZ x hx).2 } end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s: it contains an open set containing `s`. -/ lemma exists_open_set_nhds' {s U : set α} (h : U ∈ ⨆ x ∈ s, 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := exists_open_set_nhds (by simpa using h) /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : ∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩ @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≤ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem' $ assume _, ha lemma tendsto_at_top_of_eventually_const {ι : Type*} [semilattice_sup ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≥ i₀, u i = x) : tendsto u at_top (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_top.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma tendsto_at_bot_of_eventually_const {ι : Type*} [semilattice_inf ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≤ i₀, u i = x) : tendsto u at_bot (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_bot.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure.2 $ mem_of_mem_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {α : Type*} [order_top α] [topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F) lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h lemma filter.has_basis.cluster_pt_iff {ιa ιF} {pa : ιa → Prop} {sa : ιa → set α} {pF : ιF → Prop} {sF : ιF → set α} {F : filter α} (ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) : cluster_pt a F ↔ ∀ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty := ha.inf_basis_ne_bot_iff hF lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. -/ lemma cluster_pt_principal_iff {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩ lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x := ⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩ /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} := set.ext $ λ x, by simp only [mem_interior, mem_nhds_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] @[simp] lemma interior_mem_nhds {s : set α} {a : α} : interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a := ⟨λ h, mem_of_superset h interior_subset, λ h, is_open.mem_nhds is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩ lemma interior_set_of_eq {p : α → Prop} : interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff theorem is_open_iff_ultrafilter {s : set α} : is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) := by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter] lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (λ p, is_closed.union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma mem_closure_iff_nhds_ne_bot {s : set α} : a ∈ closure s ↔ 𝓝 a ⊓ 𝓟 s ≠ ⊥ := mem_closure_iff_cluster_pt.trans ne_bot_iff lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} : x ∈ closure s ↔ ne_bot (𝓝[s] x) := mem_closure_iff_cluster_pt /-- If `x` is not an isolated point of a topological space, then `{x}ᶜ` is dense in the whole space. -/ lemma dense_compl_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] : dense ({x}ᶜ : set α) := begin intro y, unfreezingI { rcases eq_or_ne y x with rfl|hne }, { rwa mem_closure_iff_nhds_within_ne_bot }, { exact subset_closure hne } end /-- If `x` is not an isolated point of a topological space, then the closure of `{x}ᶜ` is the whole space. -/ @[simp] lemma closure_compl_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] : closure {x}ᶜ = (univ : set α) := (dense_compl_singleton x).closure_eq /-- If `x` is not an isolated point of a topological space, then the interior of `{x}ᶜ` is empty. -/ @[simp] lemma interior_singleton (x : α) [ne_bot (𝓝[{x}ᶜ] x)] : interior {x} = (∅ : set α) := interior_eq_empty_iff_dense_compl.2 (dense_compl_singleton x) lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := set.ext $ λ x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} : x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_nhds_basis' {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → (s i ∩ t).nonempty := mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $ by simp only [exists_prop, forall_const] theorem mem_closure_iff_nhds_basis {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans $ by simp only [set.nonempty, mem_inter_eq, exists_prop, and_comm] /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x := by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm] lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := begin rintro a ⟨hs, ht⟩, have : s ∈ 𝓝 a := is_open.mem_nhds h hs, rw mem_closure_iff_nhds_ne_bot at ht ⊢, rwa [← inf_principal, ← inf_assoc, inf_eq_left.2 (le_principal_iff.2 this)], end lemma closure_inter_open' {s t : set α} (h : is_open t) : closure s ∩ t ⊆ closure (s ∩ t) := by simpa only [inter_comm] using closure_inter_open h lemma dense.open_subset_closure_inter {s t : set α} (hs : dense s) (ht : is_open t) : t ⊆ closure (t ∩ s) := calc t = t ∩ closure s : by rw [hs.closure_eq, inter_univ] ... ⊆ closure (t ∩ s) : closure_inter_open ht lemma mem_closure_of_mem_closure_union {s₁ s₂ : set α} {x : α} (h : x ∈ closure (s₁ ∪ s₂)) (h₁ : s₁ᶜ ∈ 𝓝 x) : x ∈ closure s₂ := begin rw mem_closure_iff_nhds_ne_bot at *, rwa ← calc 𝓝 x ⊓ principal (s₁ ∪ s₂) = 𝓝 x ⊓ (principal s₁ ⊔ principal s₂) : by rw sup_principal ... = (𝓝 x ⊓ principal s₁) ⊔ (𝓝 x ⊓ principal s₂) : inf_sup_left ... = ⊥ ⊔ 𝓝 x ⊓ principal s₂ : by rw inf_principal_eq_bot.mpr h₁ ... = 𝓝 x ⊓ principal s₂ : bot_sup_eq end /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := λ x, (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_open_left hs hto lemma dense.inter_nhds_nonempty {s t : set α} (hs : dense s) {x : α} (ht : t ∈ 𝓝 x) : (s ∩ t).nonempty := let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht in (hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ λ y hy, ⟨hy.2, hsub hy.1⟩ lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := is_closed_closure.mem_of_tendsto hf $ h.mono (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_mem_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter α`. -/ def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim /-! ### Locally finite families -/ /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty } lemma locally_finite.point_finite {f : β → set α} (hf : locally_finite f) (x : α) : finite {b | x ∈ f b} := let ⟨t, hxt, ht⟩ := hf x in ht.subset $ λ b hb, ⟨x, hb, mem_of_mem_nhds hxt⟩ lemma locally_finite_of_fintype [fintype β] (f : β → set α) : locally_finite f := assume x, ⟨univ, univ_mem, finite.of_fintype _⟩ lemma locally_finite.subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma locally_finite.comp_injective {ι} {f : β → set α} {g : ι → β} (hf : locally_finite f) (hg : function.injective g) : locally_finite (f ∘ g) := λ x, let ⟨t, htx, htf⟩ := hf x in ⟨t, htx, htf.preimage (hg.inj_on _)⟩ lemma locally_finite.closure {f : β → set α} (hf : locally_finite f) : locally_finite (λ i, closure (f i)) := begin intro x, rcases hf x with ⟨s, hsx, hsf⟩, refine ⟨interior s, interior_mem_nhds.2 hsx, hsf.subset $ λ i hi, _⟩, exact (hi.mono (closure_inter_open' is_open_interior)).of_closure.mono (inter_subset_inter_right _ interior_subset) end lemma locally_finite.is_closed_Union {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := begin simp only [← is_open_compl_iff, compl_Union, is_open_iff_mem_nhds, mem_Inter], intros a ha, replace ha : ∀ i, (f i)ᶜ ∈ 𝓝 a := λ i, (h₂ i).is_open_compl.mem_nhds (ha i), rcases h₁ a with ⟨t, h_nhds, h_fin⟩, have : t ∩ (⋂ i ∈ {i | (f i ∩ t).nonempty}, (f i)ᶜ) ∈ 𝓝 a, from inter_mem h_nhds ((bInter_mem h_fin).2 (λ i _, ha i)), filter_upwards [this], simp only [mem_inter_eq, mem_Inter], rintros b ⟨hbt, hn⟩ i hfb, exact hn i ⟨b, hfb, hbt⟩ hfb end lemma locally_finite.closure_Union {f : β → set α} (h : locally_finite f) : closure (⋃ i, f i) = ⋃ i, closure (f i) := subset.antisymm (closure_minimal (Union_subset_Union $ λ _, subset_closure) $ h.closure.is_closed_Union $ λ _, is_closed_closure) (Union_subset $ λ i, closure_mono $ subset_Union _ _) end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ structure continuous (f : α → β) : Prop := (is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s)) lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) := ⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩ lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) : is_open (f ⁻¹' s) := hf.is_open_preimage s h /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at_congr {f g : α → β} {x : α} (h : f =ᶠ[𝓝 x] g) : continuous_at f x ↔ continuous_at g x := by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds] lemma continuous_at.congr {f g : α → β} {x : α} (hf : continuous_at f x) (h : f =ᶠ[𝓝 x] g) : continuous_at g x := (continuous_at_congr h).1 hf lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma eventually_eq_zero_nhds {M₀} [has_zero M₀] {a : α} {f : α → M₀} : f =ᶠ[𝓝 a] 0 ↔ a ∉ closure (function.support f) := by rw [← mem_compl_eq, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la) {f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) : cluster_pt (f x) lb := ⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩ /-- See also `interior_preimage_subset_preimage_interior`. -/ lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf) lemma continuous_id : continuous (id : α → α) := continuous_def.2 $ assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := continuous_def.2 $ assume s h, (h.preimage hg).preimage hf lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩ /-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) : tendsto f (𝓝 x) (𝓝 y) := h ▸ hf.tendsto x lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), continuous_def.2 $ assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, is_open.mem_nhds hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := tendsto_const_nhds lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, continuous_at_const lemma filter.eventually_eq.continuous_at {x : α} {f : α → β} {y : β} (h : f =ᶠ[𝓝 x] (λ _, y)) : continuous_at f x := (continuous_at_congr h).2 tendsto_const_nhds lemma continuous_of_const {f : α → β} (h : ∀ x y, f x = f y) : continuous f := continuous_iff_continuous_at.mpr $ λ x, filter.eventually_eq.continuous_at $ eventually_of_forall (λ y, h y x) lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, by simpa using (continuous_def.1 hf sᶜ hs.is_open_compl).is_closed_compl, assume hf, continuous_def.2 $ assume s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma mem_closure_image {f : α → β} {x : α} {s : set α} (hf : continuous_at f x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := begin rw [mem_closure_iff_nhds_ne_bot] at hx ⊢, rw ← bot_lt_iff_ne_bot, haveI : ne_bot _ := ⟨hx⟩, calc ⊥ < map f (𝓝 x ⊓ principal s) : bot_lt_iff_ne_bot.mpr ne_bot.ne' ... ≤ (map f $ 𝓝 x) ⊓ (map f $ principal s) : map_inf_le ... = (map f $ 𝓝 x) ⊓ (principal $ f '' s) : by rw map_principal ... ≤ 𝓝 (f x) ⊓ (principal $ f '' s) : inf_le_inf hf le_rfl end lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔ ∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] lemma continuous.closure_preimage_subset {f : α → β} (hf : continuous f) (t : set β) : closure (f ⁻¹' t) ⊆ f ⁻¹' (closure t) := begin rw ← (is_closed_closure.preimage hf).closure_eq, exact closure_mono (preimage_mono subset_closure), end lemma continuous.frontier_preimage_subset {f : α → β} (hf : continuous f) (t : set β) : frontier (f ⁻¹' t) ⊆ f ⁻¹' (frontier t) := diff_subset_diff (hf.closure_preimage_subset t) (preimage_interior_subset_interior_preimage hf) /-! ### Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) (hc : continuous f) : maps_to f (closure s) (closure t) := begin simp only [maps_to, mem_closure_iff_cluster_pt], exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h) end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := ((maps_to_image f s).closure h).image_subset lemma closure_subset_preimage_closure_image {f : α → β} {s : set α} (h : continuous f) : closure s ⊆ f ⁻¹' (closure (f '' s)) := by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h } lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t := set.maps_to.closure ht hf ha /-! ### Function with dense range -/ section dense_range variables {κ ι : Type*} (f : κ → β) (g : β → γ) /-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := λ x, by simp [hf.range_eq] lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma dense.dense_range_coe {s : set α} (h : dense s) : dense_range (coe : s → α) := by simpa only [dense_range, subtype.range_coe_subtype] lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f) {s : set α} (hs : dense s) : range f ⊆ closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If `f` has dense range and `s` is an open set in the codomain of `f`, then the image of the preimage of `s` under `f` is dense in `s`. -/ lemma dense_range.subset_closure_image_preimage_of_is_open (hf : dense_range f) {s : set β} (hs : is_open s) : s ⊆ closure (f '' (f ⁻¹' s)) := by { rw image_preimage_eq_inter_range, exact hf.open_subset_closure_inter hs } /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ := hf.nonempty_iff.mpr h /-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/ def dense_range.some (hf : dense_range f) (b : β) : κ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ lemma dense_range.exists_mem_open (hf : dense_range f) {s : set β} (ho : is_open s) (hs : s.nonempty) : ∃ a, f a ∈ s := exists_range_iff.1 $ hf.exists_mem_open ho hs lemma dense_range.mem_nhds {f : κ → β} (h : dense_range f) {b : β} {U : set β} (U_in : U ∈ nhds b) : ∃ a, f a ∈ U := begin rcases (mem_closure_iff_nhds.mp ((dense_range_iff_closure_range.mp h).symm ▸ mem_univ b : b ∈ closure (range f)) U U_in) with ⟨_, h, a, rfl⟩, exact ⟨a, h⟩ end end dense_range end continuous /-- The library contains many lemmas stating that functions/operations are continuous. There are many ways to formulate the continuity of operations. Some are more convenient than others. Note: for the most part this note also applies to other properties (`measurable`, `differentiable`, `continuous_on`, ...). ### The traditional way As an example, let's look at addition `(+) : M → M → M`. We can state that this is continuous in different definitionally equal ways (omitting some typing information) * `continuous (λ p, p.1 + p.2)`; * `continuous (function.uncurry (+))`; * `continuous ↿(+)`. (`↿` is notation for recursively uncurrying a function) However, lemmas with this conclusion are not nice to use in practice because 1. They confuse the elaborator. The following two examples fail, because of limitations in the elaboration process. ``` variables {M : Type*} [has_mul M] [topological_space M] [has_continuous_mul M] example : continuous (λ x : M, x + x) := continuous_add.comp _ example : continuous (λ x : M, x + x) := continuous_add.comp (continuous_id.prod_mk continuous_id) ``` The second is a valid proof, which is accepted if you write it as `continuous_add.comp (continuous_id.prod_mk continuous_id : _)` 2. If the operation has more than 2 arguments, they are impractical to use, because in your application the arguments in the domain might be in a different order or associated differently. ### The convenient way A much more convenient way to write continuity lemmas is like `continuous.add`: ``` continuous.add {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λ x, f x + g x) ``` The conclusion can be `continuous (f + g)`, which is definitionally equal. This has the following advantages * It supports projection notation, so is shorter to write. * `continuous.add _ _` is recognized correctly by the elaborator and gives useful new goals. * It works generally, since the domain is a variable. As an example for an unary operation, we have `continuous.neg`. ``` continuous.neg {f : α → G} (hf : continuous f) : continuous (λ x, -f x) ``` For unary functions, the elaborator is not confused when applying the traditional lemma (like `continuous_neg`), but it's still convenient to have the short version available (compare `hf.neg.neg.neg` with `continuous_neg.comp $ continuous_neg.comp $ continuous_neg.comp hf`). As a harder example, consider an operation of the following type: ``` def strans {x : F} (γ γ' : path x x) (t₀ : I) : path x x ``` The precise definition is not important, only its type. The correct continuity principle for this operation is something like this: ``` {f : X → F} {γ γ' : ∀ x, path (f x) (f x)} {t₀ s : X → I} (hγ : continuous ↿γ) (hγ' : continuous ↿γ') (ht : continuous t₀) (hs : continuous s) : continuous (λ x, strans (γ x) (γ' x) (t x) (s x)) ``` Note that *all* arguments of `strans` are indexed over `X`, even the basepoint `x`, and the last argument `s` that arises since `path x x` has a coercion to `I → F`. The paths `γ` and `γ'` (which are unary functions from `I`) become binary functions in the continuity lemma. ### Summary * Make sure that your continuity lemmas are stated in the most general way, and in a convenient form. That means that: - The conclusion has a variable `X` as domain (not something like `Y × Z`); - Wherever possible, all point arguments `c : Y` are replaced by functions `c : X → Y`; - All `n`-ary function arguments are replaced by `n+1`-ary functions (`f : Y → Z` becomes `f : X → Y → Z`); - All (relevant) arguments have continuity assumptions, and perhaps there are additional assumptions needed to make the operation continuous; - The function in the conclusion is fully applied. * These remarks are mostly about the format of the *conclusion* of a continuity lemma. In assumptions it's fine to state that a function with more than 1 argument is continuous using `↿` or `function.uncurry`. ### Functions with discontinuities In some cases, you want to work with discontinuous functions, and in certain expressions they are still continuous. For example, consider the fractional part of a number, `fract : ℝ → ℝ`. In this case, you want to add conditions to when a function involving `fract` is continuous, so you get something like this: (assumption `hf` could be weakened, but the important thing is the shape of the conclusion) ``` lemma continuous_on.comp_fract {X Y : Type*} [topological_space X] [topological_space Y] {f : X → ℝ → Y} {g : X → ℝ} (hf : continuous ↿f) (hg : continuous g) (h : ∀ s, f s 0 = f s 1) : continuous (λ x, f x (fract (g x))) ``` With `continuous_at` you can be even more precise about what to prove in case of discontinuities, see e.g. `continuous_at.comp_div_cases`. -/ library_note "continuity lemma statement"