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
35f7e85ccb4827aa3329edb032cf99bf980aec3c
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/12_Axioms.org.24.lean
c21f8c4da166ebedf8fd602ad06359c918bda0c5
[]
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
674
lean
import standard import logic.eq open classical eq.ops section parameter p : Prop definition U (x : Prop) : Prop := x = true ∨ p definition V (x : Prop) : Prop := x = false ∨ p noncomputable definition u := epsilon U noncomputable definition v := epsilon V lemma u_def : U u := epsilon_spec (exists.intro true (or.inl rfl)) lemma v_def : V v := epsilon_spec (exists.intro false (or.inl rfl)) -- BEGIN lemma not_uv_or_p : ¬(u = v) ∨ p := or.elim u_def (assume Hut : u = true, or.elim v_def (assume Hvf : v = false, have Hne : ¬(u = v), from Hvf⁻¹ ▸ Hut⁻¹ ▸ true_ne_false, or.inl Hne) (assume Hp : p, or.inr Hp)) (assume Hp : p, or.inr Hp) -- END end
5e0831f66dc51795dca5851791719c82290e103d
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/docStr.lean
5d7d5b1e878da8d2ba440d28b35c8a82ba55a6cd
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,676
lean
import Lean /-- Foo structure is just a test -/ structure Foo where /-- main name -/ name : String := "hello" /-- documentation for the second field -/ val : Nat := 0 /-- documenting test axiom -/ axiom myAxiom : Nat structure Boo (α : Type) where /-- Boo constructor has a custom name -/ makeBoo :: /-- Boo.x docString -/ x : Nat y : Bool /-- inductive datatype Tree documentation -/ inductive Tree (α : Type) where | /-- Tree.node documentation -/ node : List (Tree α) → Tree α | /-- Tree.leaf stores the values -/ leaf : α → Tree α namespace Bla /-- documenting definition in namespace -/ def test (x : Nat) : Nat := aux x + 1 where /-- We can document 'where' functions too -/ aux x := x + 2 end Bla def f (x : Nat) : IO Nat := do let rec /-- let rec documentation at f -/ foo | 0 => 1 | x+1 => foo x + 2 return foo x def g (x : Nat) : Nat := let rec /-- let rec documentation at g -/ foo | 0 => 1 | x+1 => foo x + 2 foo x open Lean def printDocString (declName : Name) : MetaM Unit := do match (← findDocString? declName) with | some docStr => IO.println (repr docStr) | none => IO.println s!"doc string for '{declName}' is not available" def printDocStringTest : MetaM Unit := do printDocString `Foo printDocString `Foo.name printDocString `Foo.val printDocString `myAxiom printDocString `Boo printDocString `Boo.makeBoo printDocString `Boo.x printDocString `Boo.y printDocString `Tree printDocString `Tree.node printDocString `Tree.leaf printDocString `Bla.test printDocString `Bla.test.aux printDocString `f printDocString `f.foo printDocString `g printDocString `g.foo printDocString `optParam printDocString `namedPattern printDocString `Lean.Meta.forallTelescopeReducing #eval printDocStringTest def printRanges (declName : Name) : MetaM Unit := do match (← findDeclarationRanges? declName) with | some range => IO.println f!"{declName} :={Std.Format.indentD <| repr range}" | none => IO.println s!"range for '{declName}' is not available" def printRangesTest : MetaM Unit := do printRanges `Foo printRanges `Foo.name printRanges `Foo.val printRanges `myAxiom printRanges `Boo printRanges `Boo.makeBoo printRanges `Boo.x printRanges `Boo.y printRanges `Tree printRanges `Tree.rec printRanges `Tree.casesOn printRanges `Tree.node printRanges `Tree.leaf printRanges `Bla.test printRanges `Bla.test.aux printRanges `f printRanges `f.foo printRanges `g printRanges `g.foo printRanges `optParam printRanges `namedPattern printRanges `Lean.Meta.forallTelescopeReducing #eval printRangesTest
a4c5ac6e67479567a4fc08e0216018aad6916006
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/t3.lean
4c151017ab68cb60142e7221e6f6dc1bd6d6fbe4
[ "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
361
lean
prelude constant int : Type.{1} constant nat : Type.{1} namespace int constant plus : int → int → int end int namespace nat constant plus : nat → nat → nat end nat open int nat constants a b : int #check plus a b constant f : int → int → int constant g : nat → nat → int notation A `+`:65 B:65 := f A (g B B) constant n : nat #check a + n
a6211b39337b66b7f3118a2ad92ff308a104207b
59a4b050600ed7b3d5826a8478db0a9bdc190252
/src/category_theory/universal/complete/default.lean
15a466c2b52fc4f250a9ab65ad5ccd5e265fd60a
[]
no_license
rwbarton/lean-category-theory
f720268d800b62a25d69842ca7b5d27822f00652
00df814d463406b7a13a56f5dcda67758ba1b419
refs/heads/master
1,585,366,296,767
1,536,151,349,000
1,536,151,349,000
147,652,096
0
0
null
1,536,226,960,000
1,536,226,960,000
null
UTF-8
Lean
false
false
1,008
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.universal.cones open category_theory namespace category_theory.limits universes u v variables {C : Type u} [category.{u v} C] {J : Type v} [small_category J] [has_limits.{u v} C] def lim : (J ⥤ C) ⥤ C := { obj := limit, map' := λ F F' t, limit.lift F' $ { X := limit F, π := λ j, limit.π F j ≫ t j } }. -- boilerplate @[simp] lemma lim_map [has_limits.{u v} C] {F F' : J ⥤ C} (t : F ⟹ F') : lim.map t = (limit.lift F' $ { X := limit F, π := λ j, limit.π F j ≫ t j }) := rfl -- def colim : (J ⥤ C) ⥤ C := -- { obj := colimit, -- map' := λ F F' t, (colimit.universal_property F').desc $ -- { X := colimit F, π := λ j, t j ≫ colimit.ι F j}, -- map_id' := begin tidy, erw colimit.desc_ι, dsimp, simp, end }. -- FIXME why doesn't simp work here? end category_theory.limits
7dd5304a506fdc3ff176241ac79038a8e3078019
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/data/complex/exponential.lean
3e746a01392e5a60c0bf56f7feac41a9f6e826df
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
60,450
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.geom_sum import data.nat.choose.sum import data.complex.basic /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file contains the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := _root_.abs open is_absolute_value open_locale classical big_operators nat 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 section variables {α : Type*} {β : Type*} [ring β] [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 - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (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_nsmul], 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 - 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 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 - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', 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 end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := 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 (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub (∑ k in range (max n i), g k), 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 *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, simp only [sub_eq_add_neg] at hi, 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, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) end no_archimedean section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, 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] {eta := ff}, have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) = λ m, geom_series (abv x) m := rfl, simp only [this, 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 (le_of_lt $ sub_pos.2 hx1) (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)), refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1), clear hn, induction n with n ih, { simp }, { rw [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 (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _), rw [← one_mul (_ ^ n), 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, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, 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, ∑ n in range m, f n) := 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, inv_pow' _ _, ← 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 : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := have h₁ : ∑ a in (range n).sigma (range ∘ nat.succ), f (a.2) (a.1 - a.2) = ∑ m in range n, ∑ k in range (m + 1), f k (m - k) := sum_sigma, have h₂ : ∑ a in (range n).sigma (λ m, range (n - m)), f (a.1) (a.2) = ∑ m in range n, ∑ k in range (n - m), f m k := 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 sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k = ∑ k in (range m).filter (λ k, n ≤ k), f k := 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 $ λ 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 end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := 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 cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), 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₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, 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 : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), 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 : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = abs (∑ n in range (max N M + 1), 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 : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (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 ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), 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 no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, ∑ m in range n, abs (z ^ m / 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 (complex.abs_nonneg _) (le_of_lt hn0)) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.factorial_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, ∑ m in range n, z ^ m / m!) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] 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 : ℕ, ∑ m in range j, (x + y) ^ m / m! = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!), 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₁ : (m.choose 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_factorial_mul_factorial (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 (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose 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_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s 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 [← mul_right_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 [sub_eq_add_neg, 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 conj.map_sum, refine sum_congr rfl (λ n hn, _), rw [conj.map_div, conj.map_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, norm_cast] 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 [← mul_right_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, ← mul_right_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 [add_comm, 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 [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← mul_right_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 [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_sub, sinh, conj.map_div, conj_bit0, conj.map_one] @[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, norm_cast] 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) := begin rw [cosh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_add, cosh, conj.map_div, conj_bit0, conj.map_one] end @[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, norm_cast] 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.map_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, norm_cast] 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 [← mul_right_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 [← mul_right_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] lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [two_mul, cosh_add, pow_two, pow_two] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := begin rw [two_mul, sinh_add], ring end lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cosh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring, rw [h2, sinh_square], ring end lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sinh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring, rw [h2, cosh_square], ring, end @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, 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 [← mul_right_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 [← mul_right_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 [← mul_left_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, sub_eq_add_neg, exp_neg, add_comm] 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 [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin have s1 := sin_add ((x + y) / 2) ((x - y) / 2), have s2 := sin_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin have s1 := cos_add ((x + y) / 2) ((x - y) / 2), have s2 := cos_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin have h2 : (2:ℂ) ≠ 0 := by norm_num, calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _ ... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2)) + (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _ ... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _, { congr; field_simp [h2]; ring }, { rw [cos_add, cos_sub] }, ring, end lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj.map_mul, ← conj.map_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, norm_cast] 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.map_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, norm_cast] 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 lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[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.map_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, norm_cast] 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] @[simp] 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)) @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] 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] lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel] lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx, by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] } lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cos_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, pow_two], have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring, rw [h2, cos_square'], ring end lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sin_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, cos_square'], have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring, rw [h2, cos_square'], ring end 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] /-- De Moivre's formula -/ 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_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s 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 [sub_eq_add_neg, 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 [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin rw ← of_real_inj, simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert sin_sub_sin _ _; norm_cast end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin rw ← of_real_inj, simp only [cos, neg_mul_eq_neg_mul_symm, of_real_sin, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0], convert cos_sub_cos _ _, ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin rw ← of_real_inj, simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert cos_add_cos _ _; norm_cast, end 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 lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simp @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] 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 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← pow_two, sin_sq_le_one] lemma abs_cos_le_one : abs' (cos x) ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← pow_two, 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 cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := 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 cos_square' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have complex.cos x ≠ 0, from mt (congr_arg re) hx, of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : (sqrt (1 + tan x ^ 2))⁻¹ = cos x := by rw [← sqrt_sqr hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne'] lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : tan x / sqrt (1 + tan x ^ 2) = sin x := by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by rw ← of_real_inj; simp [cos_three_mul] lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by rw ← of_real_inj; simp [sin_three_mul] /-- The definition of `sinh` in terms of `exp`. -/ lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re] @[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] /-- The definition of `cosh` in terms of `exp`. -/ lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re] @[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 [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, 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] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw ← of_real_inj; simp [cosh_add_sinh] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw ← of_real_inj; simp [sinh_add_cosh] lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw ← of_real_inj; simp [cosh_sq_sub_sinh_sq] lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw ← of_real_inj; simp [cosh_square] lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw ← of_real_inj; simp [sinh_square] lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw ← of_real_inj; simp [cosh_two_mul] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw ← of_real_inj; simp [sinh_two_mul] lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by rw ← of_real_inj; simp [cosh_three_mul] lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by rw ← of_real_inj; simp [sinh_three_mul] 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 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / 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 _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _), 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.2 (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))) @[mono] lemma exp_monotone : ∀ {x y : ℝ}, x ≤ y → exp x ≤ exp y := exp_strict_mono.monotone @[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt @[simp] 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_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] @[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 := exp_zero ▸ exp_le_exp @[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x := exp_zero ▸ exp_le_exp /-- `real.cosh` is always positive -/ lemma cosh_pos (x : ℝ) : 0 < real.cosh x := (cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x))) end real namespace complex lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ * (n! * n)⁻¹ := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) = ∑ m in range (j - n), 1 / (m + n)! : 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_left_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⟩) ... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.factorial_mul_pow_le_factorial }, { exact nat.cast_pos.2 (nat.factorial_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * 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! * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.factorial_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev', h₄, ← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n! * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.factorial_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 - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw ← sub_eq_add_neg, show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) : 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.factorial_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_factorial_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 - ∑ m in range 1, x ^ m / m!) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma exp_bound {x : ℝ} (hx : abs' x ≤ 1) {n : ℕ} (hn : 0 < n) : abs' (exp x - ∑ m in range n, x ^ m / m!) ≤ abs' x ^ n * (n.succ / (n! * n)) := begin have hxc : complex.abs x ≤ 1, by exact_mod_cast hx, convert exp_bound hxc hn; norm_cast end /-- A finite initial segment of the exponential series, followed by an arbitrary tail. For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`, for any `r`. -/ def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r @[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near] @[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) := by { simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ], field_simp [mul_assoc, mul_left_comm] } theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) := by simp [exp_near, mul_sub] lemma exp_approx_end (n m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : abs' x ≤ 1) : abs' (exp x - exp_near m x 0) ≤ abs' x ^ m / m! * ((m+1)/m) := by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith } lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ b₂ : ℝ) (e : abs' (1 + x / m * a₂ - a₁) ≤ b₁ - abs' x / m * b₂) (h : abs' (exp x - exp_near m x a₂) ≤ abs' x ^ m / m! * b₂) : abs' (exp x - exp_near n x a₁) ≤ abs' x ^ n / n! * b₁ := begin refine le_trans (_root_.abs_sub_le _ _ _) (le_trans (add_le_add_right h _) _), subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul], convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _, { simp [mul_add, pow_succ', _root_.abs_div, ← pow_abs], field_simp [mul_assoc] }, { simp [_root_.div_nonneg, _root_.abs_nonneg] } end lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : abs' x ≤ 1) (e : abs' (1 - a) ≤ b - abs' x / rm * ((rm+1)/rm)) : abs' (exp x - exp_near n x a) ≤ abs' x ^ n / n! * b := by subst er; exact exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h) lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : abs' (exp 1 - exp_near m 1 ((a₁ - 1) * rm)) ≤ abs' 1 ^ m / m! * (b₁ * rm)) : abs' (exp 1 - exp_near n 1 a₁) ≤ abs' 1 ^ n / n! * b₁ := begin subst er, refine exp_approx_succ _ en _ _ _ h, field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith], end lemma exp_approx_start (x a b : ℝ) (h : abs' (exp x - exp_near 0 x a) ≤ abs' x ^ 0 / 0! * b) : abs' (exp x - a) ≤ b := by simpa using h 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) - ∑ m in range 4, (x * I) ^ m / m!) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 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) - ∑ m in range 4, (x * I) ^ m / m!) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.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) - ∑ m in range 4, (-x * I) ^ m / m!) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * 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) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.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_iff (by norm_num)).mpr (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 [add_comm, 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
34db237bb5e2fd7819ffe2764100e668646592d8
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/measure_theory/integral/interval_integral.lean
12f491acf92b70564119f8fa0ef08154f4f6ae96
[ "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
124,734
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot, Sébastien Gouëzel -/ import analysis.calculus.extend_deriv import analysis.calculus.fderiv_measurable import analysis.normed_space.dual import measure_theory.integral.set_integral import measure_theory.integral.vitali_caratheodory import measure_theory.measure.lebesgue /-! # Integral over an interval In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and `-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. We prove a few simple properties and several versions of the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). Recall that its first version states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`, and its second version states that, if `f` has an integrable derivative on `[a, b]`, then `∫ x in a..b, f' x = f b - f a`. ## Main statements ### FTC-1 for Lebesgue measure We prove several versions of FTC-1, all in the `interval_integral` namespace. Many of them follow the naming scheme `integral_has(_strict?)_(f?)deriv(_within?)_at(_of_tendsto_ae?)(_right|_left?)`. They formulate FTC in terms of `has(_strict?)_(f?)deriv(_within?)_at`. Let us explain the meaning of each part of the name: * `_strict` means that the theorem is about strict differentiability; * `f` means that the theorem is about differentiability in both endpoints; incompatible with `_right|_left`; * `_within` means that the theorem is about one-sided derivatives, see below for details; * `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit almost surely as `x` tends to `a` and/or `b`; * `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left) endpoint. We also reformulate these theorems in terms of `(f?)deriv(_within?)`. These theorems are named `(f?)deriv(_within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the name. ### One-sided derivatives Theorem `integral_has_fderiv_within_at_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and corresponding filters `la`, `lb` are given in the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | We use a typeclass `FTC_filter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered by `integral_has_deriv_within_at_of_tendsto_ae_(left|right)` and `integral_has_fderiv_at_of_tendsto_ae`). Similarly, `integral_has_deriv_within_at_of_tendsto_ae_right` works for both one-sided derivatives using the same typeclass to find an appropriate filter. ### FTC for a locally finite measure Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for any measure. The most general of them, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae`, states the following. Let `(la, la')` be an `FTC_filter` pair of filters around `a` (i.e., `FTC_filter a la la'`) and let `(lb, lb')` be an `FTC_filter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. ### FTC-2 and corollaries We use FTC-1 to prove several versions of FTC-2 for the Lebesgue measure, using a similar naming scheme as for the versions of FTC-1. They include: * `interval_integral.integral_eq_sub_of_has_deriv_right_of_le` - most general version, for functions with a right derivative * `interval_integral.integral_eq_sub_of_has_deriv_at'` - version for functions with a derivative on an open set * `interval_integral.integral_deriv_eq_sub'` - version that is easiest to use when computing the integral of a specific function We then derive additional integration techniques from FTC-2: * `interval_integral.integral_mul_deriv_eq_deriv_mul` - integration by parts * `interval_integral.integral_comp_mul_deriv''` - integration by substitution Many applications of these theorems can be found in the file `analysis.special_functions.integrals`. Note that the assumptions of FTC-2 are formulated in the form that `f'` is integrable. To use it in a context with the stronger assumption that `f'` is continuous, one can use `continuous_on.interval_integrable` or `continuous_on.integrable_on_Icc` or `continuous_on.integrable_on_interval`. ## Implementation notes ### Avoiding `if`, `min`, and `max` In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as `integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these intervals is empty and the other coincides with `Ioc (min a b) (max a b)`. Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result. This way some properties can be translated from integrals over sets without dealing with the cases `a ≤ b` and `b ≤ a` separately. ### Choice of the interval We use integral over `Ioc (min a b) (max a b)` instead of one of the other three possible intervals with the same endpoints for two reasons: * this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever `f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom at `b`; this rules out `Ioo` and `Icc` intervals; * with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of `μ`. ### `FTC_filter` class As explained above, many theorems in this file rely on the typeclass `FTC_filter (a : α) (l l' : filter α)` to avoid code duplication. This typeclass combines four assumptions: - `pure a ≤ l`; - `l' ≤ 𝓝 a`; - `l'` has a basis of measurable sets; - if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included in `s`. This typeclass has the following “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`. Furthermore, we have the following instances that are equal to the previously mentioned instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure, it becomes important in the versions of FTC about any locally finite measure if this measure has an atom at one of the endpoints. ### Combining one-sided and two-sided derivatives There are some `FTC_filter` instances where the fact that it is one-sided or two-sided depends on the point, namely `(x, 𝓝[Icc a b] x, 𝓝[Icc a b] x)` (resp. `(x, 𝓝[[a, b]] x, 𝓝[[a, b]] x)`, where `[a, b] = set.interval a b`), with `x ∈ Icc a b` (resp. `x ∈ [a, b]`). This results in a two-sided derivatives for `x ∈ Ioo a b` and one-sided derivatives for `x ∈ {a, b}`. Other instances could be added when needed (in that case, one also needs to add instances for `filter.is_measurably_generated` and `filter.tendsto_Ixx_class`). ## Tags integral, fundamental theorem of calculus, FTC-1, FTC-2, change of variables in integrals -/ noncomputable theory open topological_space (second_countable_topology) open measure_theory set classical filter function open_locale classical topological_space filter ennreal big_operators interval variables {α β 𝕜 E F : Type*} [linear_order α] [measurable_space α] [measurable_space E] [normed_group E] /-! ### Almost everywhere on an interval -/ section variables {μ : measure α} {a b : α} {P : α → Prop} lemma ae_interval_oc_iff : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂μ, x ∈ Ioc a b → P x) ∧ (∀ᵐ x ∂μ, x ∈ Ioc b a → P x) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } lemma ae_measurable_interval_oc_iff {μ : measure α} {β : Type*} [measurable_space β] {f : α → β} : (ae_measurable f $ μ.restrict $ Ι a b) ↔ (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } variables [topological_space α] [opens_measurable_space α] [order_closed_topology α] lemma ae_interval_oc_iff' : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂ (μ.restrict $ Ioc a b), P x) ∧ (∀ᵐ x ∂ (μ.restrict $ Ioc b a), P x) := begin simp_rw ae_interval_oc_iff, rw [ae_restrict_eq, eventually_inf_principal, ae_restrict_eq, eventually_inf_principal] ; exact measurable_set_Ioc end end /-! ### Integrability at an interval -/ /-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these intervals is always empty, so this property is equivalent to `f` being integrable on `(min a b, max a b]`. -/ def interval_integrable (f : α → E) (μ : measure α) (a b : α) := integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ /-- A function is interval integrable with respect to a given measure `μ` on `interval a b` if and only if it is integrable on `Ioc (min a b) (max a b)` with respect to `μ`. This is an equivalent defintion of `interval_integrable`. -/ lemma interval_integrable_iff {f : α → E} {a b : α} {μ : measure α} : interval_integrable f μ a b ↔ integrable_on f (Ioc (min a b) (max a b)) μ := by cases le_total a b; simp [h, interval_integrable] /-- If a function is interval integrable with respect to a given measure `μ` on `interval a b` then it is integrable on `Ioc (min a b) (max a b)` with respect to `μ`. -/ lemma interval_integrable.def {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) : integrable_on f (Ioc (min a b) (max a b)) μ := interval_integrable_iff.mp h lemma interval_integrable_iff_integrable_Ioc_of_le {f : α → E} {a b : α} (hab : a ≤ b) {μ : measure α} : interval_integrable f μ a b ↔ integrable_on f (Ioc a b) μ := by simp [interval_integrable_iff, hab] /-- If a function is integrable with respect to a given measure `μ` then it is interval integrable with respect to `μ` on `interval a b`. -/ lemma measure_theory.integrable.interval_integrable {f : α → E} {a b : α} {μ : measure α} (hf : integrable f μ) : interval_integrable f μ a b := ⟨hf.integrable_on, hf.integrable_on⟩ lemma measure_theory.integrable_on.interval_integrable {f : α → E} {a b : α} {μ : measure α} (hf : integrable_on f (interval a b) μ) : interval_integrable f μ a b := ⟨measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_interval), measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_interval')⟩ namespace interval_integrable section variables {f : α → E} {a b c d : α} {μ ν : measure α} @[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a := h.symm @[refl] lemma refl : interval_integrable f μ a a := by split; simp @[trans] lemma trans (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : interval_integrable f μ a c := ⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc, (hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩ lemma trans_iterate {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : interval_integrable f μ (a 0) (a n) := begin induction n with n hn, { simp }, { exact (hn (λ k hk, hint k (hk.trans n.lt_succ_self))).trans (hint n n.lt_succ_self) } end lemma neg [borel_space E] (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ lemma norm [opens_measurable_space E] (h : interval_integrable f μ a b) : interval_integrable (λ x, ∥f x∥) μ a b := ⟨h.1.norm, h.2.norm⟩ lemma abs {f : α → ℝ} (h : interval_integrable f μ a b) : interval_integrable (λ x, |f x|) μ a b := h.norm lemma mono (hf : interval_integrable f ν a b) (h1 : interval c d ⊆ interval a b) (h2 : μ ≤ ν) : interval_integrable f μ c d := let ⟨h1₁, h1₂⟩ := interval_subset_interval_iff_le.mp h1 in interval_integrable_iff.mpr $ hf.def.mono (Ioc_subset_Ioc h1₁ h1₂) h2 lemma mono_set (hf : interval_integrable f μ a b) (h : interval c d ⊆ interval a b) : interval_integrable f μ c d := hf.mono h rfl.le lemma mono_measure (hf : interval_integrable f ν a b) (h : μ ≤ ν) : interval_integrable f μ a b := hf.mono rfl.subset h lemma mono_set_ae (hf : interval_integrable f μ a b) (h : Ioc (min c d) (max c d) ≤ᵐ[μ] Ioc (min a b) (max a b)) : interval_integrable f μ c d := interval_integrable_iff.mpr $ hf.def.mono_set_ae h protected lemma ae_measurable (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc a b)):= h.1.ae_measurable protected lemma ae_measurable' (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc b a)):= h.2.ae_measurable end variables [borel_space E] {f g : α → E} {a b : α} {μ : measure α} lemma smul [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) (r : 𝕜) : interval_integrable (r • f) μ a b := ⟨h.1.smul r, h.2.smul r⟩ @[simp] lemma add [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x + g x) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ @[simp] lemma sub [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x - g x) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ lemma mul_continuous_on {α : Type*} [conditionally_complete_linear_order α] [measurable_space α] [topological_space α] [order_topology α] [opens_measurable_space α] {μ : measure α} {a b : α} {f g : α → ℝ} (hf : interval_integrable f μ a b) (hg : continuous_on g (interval a b)) : interval_integrable (λ x, f x * g x) μ a b := begin rcases le_total a b with hab|hab, { rw interval_integrable_iff_integrable_Ioc_of_le hab at hf ⊢, apply hf.mul_continuous_on_of_subset hg measurable_set_Ioc is_compact_interval, rw interval_of_le hab, exact Ioc_subset_Icc_self }, { apply interval_integrable.symm, rw interval_integrable_iff_integrable_Ioc_of_le hab, have := (interval_integrable_iff_integrable_Ioc_of_le hab).1 hf.symm, apply this.mul_continuous_on_of_subset hg measurable_set_Ioc is_compact_interval, rw interval_of_ge hab, exact Ioc_subset_Icc_self }, end lemma continuous_on_mul {α : Type*} [conditionally_complete_linear_order α] [measurable_space α] [topological_space α] [order_topology α] [opens_measurable_space α] {μ : measure α} {a b : α} {f g : α → ℝ} (hf : interval_integrable f μ a b) (hg : continuous_on g (interval a b)) : interval_integrable (λ x, g x * f x) μ a b := by simpa [mul_comm] using hf.mul_continuous_on hg end interval_integrable section variables {μ : measure ℝ} [is_locally_finite_measure μ] lemma continuous_on.interval_integrable [borel_space E] {u : ℝ → E} {a b : ℝ} (hu : continuous_on u (interval a b)) : interval_integrable u μ a b := (continuous_on.integrable_on_Icc hu).interval_integrable lemma continuous_on.interval_integrable_of_Icc [borel_space E] {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : continuous_on u (Icc a b)) : interval_integrable u μ a b := continuous_on.interval_integrable ((interval_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure `ν` on ℝ. -/ lemma continuous.interval_integrable [borel_space E] {u : ℝ → E} (hu : continuous u) (a b : ℝ) : interval_integrable u μ a b := hu.continuous_on.interval_integrable end section variables {ι : Type*} [topological_space ι] [conditionally_complete_linear_order ι] [order_topology ι] [measurable_space ι] [borel_space ι] {μ : measure ι} [is_locally_finite_measure μ] [conditionally_complete_linear_order E] [order_topology E] [second_countable_topology E] [borel_space E] lemma monotone_on.interval_integrable {u : ι → E} {a b : ι} (hu : monotone_on u (interval a b)) : interval_integrable u μ a b := begin rw interval_integrable_iff, exact (monotone_on.integrable_on_compact is_compact_interval hu).mono_set Ioc_subset_Icc_self, end lemma antitone_on.interval_integrable {u : ι → E} {a b : ι} (hu : antitone_on u (interval a b)) : interval_integrable u μ a b := @monotone_on.interval_integrable (order_dual E) _ ‹_› ι _ _ _ _ _ _ _ _ _ ‹_› ‹_› u a b hu lemma monotone.interval_integrable {u : ι → E} {a b : ι} (hu : monotone u) : interval_integrable u μ a b := (hu.monotone_on _).interval_integrable lemma antitone.interval_integrable {u : ι → E} {a b : ι} (hu :antitone u) : interval_integrable u μ a b := (hu.antitone_on _).interval_integrable end /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable_ae {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := have _ := (hf.integrable_at_filter_ae hfm hμ).eventually, ((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := (hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv /-! ### Interval integral: definition and basic properties In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ` and prove some basic properties. -/ variables [second_countable_topology E] [complete_space E] [normed_space ℝ E] [borel_space E] /-- The interval integral `∫ x in a..b, f x ∂μ` is defined as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/ def interval_integral (f : α → E) (a b : α) (μ : measure α) := ∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r namespace interval_integral section basic variables {a b : α} {f g : α → E} {μ : measure α} @[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 := by simp [interval_integral] lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ := by simp [interval_integral, h] @[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 := sub_self _ lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [interval_integral, neg_sub] lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ := by simp only [integral_symm b, integral_of_le h] lemma integral_cases (f : α → E) (a b) : ∫ x in a..b, f x ∂μ ∈ ({∫ x in Ioc (min a b) (max a b), f x ∂μ, -∫ x in Ioc (min a b) (max a b), f x ∂μ} : set E) := (le_total a b).imp (λ h, by simp [h, integral_of_le]) (λ h, by simp [h, integral_of_ge]) lemma integral_undef (h : ¬ interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b with hab hab; simp only [integral_of_le, integral_of_ge, hab, neg_eq_zero]; refine integral_undef (not_imp_not.mpr integrable.integrable_on' _); simpa [hab] using not_and_distrib.mp h lemma integral_non_ae_measurable (hf : ¬ ae_measurable f (μ.restrict (Ioc (min a b) (max a b)))) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b; simpa [integral_of_le, integral_of_ge, h] using integral_non_ae_measurable hf lemma integral_non_ae_measurable_of_le (h : a ≤ b) (hf : ¬ ae_measurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := integral_non_ae_measurable $ by simpa [h] using hf lemma norm_integral_eq_norm_integral_Ioc : ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ := (integral_cases f a b).elim (congr_arg _) (λ h, (congr_arg _ h).trans (norm_neg _)) lemma norm_integral_le_integral_norm_Ioc : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ := calc ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ : norm_integral_eq_norm_integral_Ioc ... ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ : norm_integral_le_integral_norm f lemma norm_integral_le_abs_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ |∫ x in a..b, ∥f x∥ ∂μ| := begin simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc], exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _) end lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ioc (min a b) (max a b) → ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * |b - a| := begin rw [norm_integral_eq_norm_integral_Ioc], convert norm_set_integral_le_of_norm_le_const_ae'' _ measurable_set_Ioc h, { rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] }, { simp only [real.volume_Ioc, ennreal.of_real_lt_top] }, end lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E} (h : ∀ x ∈ Ioc (min a b) (max a b), ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * |b - a| := norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h @[simp] lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ := by { simp only [interval_integral, integral_add hf.1 hg.1, integral_add hf.2 hg.2], abel } @[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by { simp only [interval_integral, integral_neg], abel } @[simp] lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ := by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg) @[simp] lemma integral_smul {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] (r : 𝕜) (f : α → E) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, integral_smul, smul_sub] lemma integral_const' (c : E) : ∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c := by simp only [interval_integral, set_integral_const, sub_smul] @[simp] lemma integral_const {a b : ℝ} (c : E) : ∫ x in a..b, c = (b - a) • c := by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b, max_zero_sub_eq_self] lemma integral_smul_measure (c : ℝ≥0∞) : ∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub] variables [normed_group F] [second_countable_topology F] [complete_space F] [normed_space ℝ F] [measurable_space F] [borel_space F] lemma _root_.continuous_linear_map.interval_integral_comp_comm (L : E →L[ℝ] F) (hf : interval_integrable f μ a b) : ∫ x in a..b, L (f x) ∂μ = L (∫ x in a..b, f x ∂μ) := begin rw [interval_integral, interval_integral, L.integral_comp_comm, L.integral_comp_comm, L.map_sub], exacts [hf.2, hf.1] end end basic section comp variables {a b c d : ℝ} (f : ℝ → E) @[simp] lemma integral_comp_mul_right (hc : c ≠ 0) : ∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x := begin have A : closed_embedding (λ x, x * c) := (homeomorph.mul_right₀ c hc).closed_embedding, conv_rhs { rw [← real.smul_map_volume_mul_right hc] }, simp_rw [integral_smul_measure, interval_integral, set_integral_map_of_closed_embedding measurable_set_Ioc A, ennreal.to_real_of_real (abs_nonneg c)], cases lt_or_gt_of_ne hc, { simp [h, mul_div_cancel, hc, abs_of_neg, restrict_congr_set Ico_ae_eq_Ioc] }, { simp [(show 0 < c, from h), mul_div_cancel, hc, abs_of_pos] } end @[simp] lemma smul_integral_comp_mul_right (c) : c • ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_left (hc : c ≠ 0) : ∫ x in a..b, f (c * x) = c⁻¹ • ∫ x in c*a..c*b, f x := by simpa only [mul_comm c] using integral_comp_mul_right f hc @[simp] lemma smul_integral_comp_mul_left (c) : c • ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div (hc : c ≠ 0) : ∫ x in a..b, f (x / c) = c • ∫ x in a/c..b/c, f x := by simpa only [inv_inv₀] using integral_comp_mul_right f (inv_ne_zero hc) @[simp] lemma inv_smul_integral_comp_div (c) : c⁻¹ • ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_right (d) : ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x := have A : closed_embedding (λ x, x + d) := (homeomorph.add_right d).closed_embedding, calc ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x ∂(measure.map (λ x, x + d) volume) : by simp [interval_integral, set_integral_map_of_closed_embedding _ A] ... = ∫ x in a+d..b+d, f x : by rw [real.map_volume_add_right] @[simp] lemma integral_comp_add_left (d) : ∫ x in a..b, f (d + x) = ∫ x in d+a..d+b, f x := by simpa only [add_comm] using integral_comp_add_right f d @[simp] lemma integral_comp_mul_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x + d) = c⁻¹ • ∫ x in c*a+d..c*b+d, f x := by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_mul_add (c d) : c • ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + c * x) = c⁻¹ • ∫ x in d+c*a..d+c*b, f x := by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_add_mul (c d) : c • ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c + d) = c • ∫ x in a/c+d..b/c+d, f x := by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_mul_add f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_add (c d) : c⁻¹ • ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + x / c) = c • ∫ x in d+a/c..d+b/c, f x := by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_add_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_add_div (c d) : c⁻¹ • ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x - d) = c⁻¹ • ∫ x in c*a-d..c*b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d) @[simp] lemma smul_integral_comp_mul_sub (c d) : c • ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - c * x) = c⁻¹ • ∫ x in d-c*b..d-c*a, f x := begin simp only [sub_eq_add_neg, neg_mul_eq_neg_mul], rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm], simp only [inv_neg, smul_neg, neg_neg, neg_smul], end @[simp] lemma smul_integral_comp_sub_mul (c d) : c • ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c - d) = c • ∫ x in a/c-d..b/c-d, f x := by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_mul_sub f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_sub (c d) : c⁻¹ • ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - x / c) = c • ∫ x in d-b/c..d-a/c, f x := by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_sub_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_sub_div (c d) : c⁻¹ • ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_right (d) : ∫ x in a..b, f (x - d) = ∫ x in a-d..b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d) @[simp] lemma integral_comp_sub_left (d) : ∫ x in a..b, f (d - x) = ∫ x in d-b..d-a, f x := by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d @[simp] lemma integral_comp_neg : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x := by simpa only [zero_sub] using integral_comp_sub_left f 0 end comp /-! ### Integral is an additive function of the interval In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` as well as a few other identities trivially equivalent to this one. We also prove that `∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`. -/ section order_closed_topology variables [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b c d : α} {f g : α → E} {μ : measure α} lemma integrable_on_Icc_iff_integrable_on_Ioc' {E : Type*} [measurable_space E] [normed_group E] {f : α → E} {a b : α} (ha : μ {a} ≠ ⊤) : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ := begin cases le_or_lt a b with hab hab, { have : Icc a b = Icc a a ∪ Ioc a b := (Icc_union_Ioc_eq_Icc le_rfl hab).symm, rw [this, integrable_on_union], simp [lt_top_iff_ne_top.2 ha] }, { simp [hab, hab.le] }, end lemma integrable_on_Icc_iff_integrable_on_Ioc {E : Type*} [measurable_space E] [normed_group E] [has_no_atoms μ] {f : α → E} {a b : α} : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ := integrable_on_Icc_iff_integrable_on_Ioc' (by simp) lemma interval_integrable_iff_integrable_Icc_of_le {E : Type*} [measurable_space E] [normed_group E] {f : α → E} {a b : α} (hab : a ≤ b) {μ : measure α} [has_no_atoms μ] : interval_integrable f μ a b ↔ integrable_on f (Icc a b) μ := by rw [interval_integrable_iff_integrable_Ioc_of_le hab, integrable_on_Icc_iff_integrable_on_Ioc] lemma integral_Icc_eq_integral_Ioc' {f : α → E} {a b : α} (ha : μ {a} = 0) : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := begin cases le_or_lt a b with hab hab, { have : μ.restrict (Icc a b) = μ.restrict (Ioc a b), { rw [← Ioc_union_left hab, measure_theory.measure.restrict_union _ measurable_set_Ioc (measurable_set_singleton a)], { simp [measure_theory.measure.restrict_zero_set ha] }, { simp } }, rw this }, { simp [hab, hab.le] } end lemma integral_Icc_eq_integral_Ioc {f : α → E} {a b : α} [has_no_atoms μ] : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := integral_Icc_eq_integral_Ioc' $ measure_singleton a /-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/ lemma integral_congr {a b : α} (h : eq_on f g (interval a b)) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by cases le_total a b with hab hab; simpa [hab, integral_of_le, integral_of_ge] using set_integral_congr measurable_set_Ioc (h.mono Ioc_subset_Icc_self) lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 := begin have hac := hab.trans hbc, simp only [interval_integral, ← add_sub_comm, sub_eq_zero], iterate 4 { rw ← integral_union }, { suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this, rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle, min_left_comm, max_left_comm] }, all_goals { simp [*, measurable_set.union, measurable_set_Ioc, Ioc_disjoint_Ioc_same, Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] } end lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ := by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc] lemma sum_integral_adjacent_intervals {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : ∑ (k : ℕ) in finset.range n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ := begin induction n with n hn, { simp }, { rw [finset.sum_range_succ, hn (λ k hk, hint k (hk.trans n.lt_succ_self))], exact integral_add_adjacent_intervals (interval_integrable.trans_iterate $ λ k hk, hint k (hk.trans n.lt_succ_self)) (hint n n.lt_succ_self) } end lemma integral_interval_sub_left (hab : interval_integrable f μ a b) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ := sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab) lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ := by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm, integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm] lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ := by simp only [sub_eq_add_neg, ← integral_symm, integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)] lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ := by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c, sub_neg_eq_add, sub_eq_neg_add], } lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) : ∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ := begin wlog hab : a ≤ b using [a b] tactic.skip, { rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc (le_refl _)), Iic_union_Ioc_eq_Iic hab], exacts [measurable_set_Iic, measurable_set_Ioc, ha, hb.mono_set (λ _, and.right)] }, { intros ha hb, rw [integral_symm, ← this hb ha, neg_sub] } end /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ lemma integral_const_of_cdf [is_finite_measure μ] (c : E) : ∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c := begin simp only [sub_smul, ← set_integral_const], refine (integral_Iic_sub_Iic _ _).symm; simp only [integrable_on_const, measure_lt_top, or_true] end lemma integral_eq_integral_of_support_subset {f : α → E} {a b} (h : support f ⊆ Ioc a b) : ∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ := begin cases le_total a b with hab hab, { rw [integral_of_le hab, ← integral_indicator measurable_set_Ioc, indicator_eq_self.2 h]; apply_instance }, { rw [Ioc_eq_empty hab.not_lt, subset_empty_iff, support_eq_empty_iff] at h, simp [h] } end lemma integral_congr_ae' {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x) (h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) : ∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ := by simp only [interval_integral, set_integral_congr_ae (measurable_set_Ioc) h, set_integral_congr_ae (measurable_set_Ioc) h'] lemma integral_congr_ae {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) : ∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ := integral_congr_ae' (ae_interval_oc_iff.mp h).1 (ae_interval_oc_iff.mp h).2 lemma integral_zero_ae {f : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) : ∫ (x : α) in a..b, f x ∂μ = 0 := calc ∫ x in a..b, f x ∂μ = ∫ x in a..b, 0 ∂μ : integral_congr_ae h ... = 0 : integral_zero lemma integral_indicator {a₁ a₂ a₃ : α} (h : a₂ ∈ Icc a₁ a₃) {f : α → E} : ∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂ μ = ∫ x in a₁..a₂, f x ∂ μ := begin have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂, from Iic_inter_Ioc_of_le h.2, rw [integral_of_le h.1, integral_of_le (h.1.trans h.2), integral_indicator, measure.restrict_restrict, this], exact measurable_set_Iic, all_goals { apply measurable_set_Iic }, end end order_closed_topology section continuity_wrt_parameter open topological_space variables {X : Type*} [topological_space X] [first_countable_topology X] variables {μ : measure α} /-- Continuity of interval integral with respect to a parameter, at a point within a set. Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀` within `s` and at `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀` within `s`. If `(λ x, F x t)` is continuous at `x₀` within `s` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_within_at_of_dominated_interval {F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} {s : set X} (hF_meas : ∀ᶠ x in 𝓝[s] x₀, ae_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_within_at (λ x, F x t) s x₀) : continuous_within_at (λ x, ∫ t in a..b, F x t ∂μ) s x₀ := begin cases bound_integrable, cases le_or_lt a b with hab hab; [{ rw interval_oc_of_le hab at *, simp_rw interval_integral.integral_of_le hab }, { rw interval_oc_of_lt hab at *, simp_rw interval_integral.integral_of_ge hab.le, refine tendsto.neg _ }]; apply tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound, exacts [bound_integrable_left, h_cont, bound_integrable_right, h_cont] end /-- Continuity of interval integral with respect to a parameter at a point. Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀`. If `(λ x, F x t)` is continuous at `x₀` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_at_of_dominated_interval {F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_at (λ x, F x t) x₀) : continuous_at (λ x, ∫ t in a..b, F x t ∂μ) x₀ := begin rw ← continuous_within_at_univ, apply continuous_within_at_of_dominated_interval ; try { rw nhds_within_univ}, exacts [hF_meas, h_bound, bound_integrable, h_cont.mono (λ a, (continuous_within_at_univ (λ x, F x a) x₀).mpr)] end /-- Continuity of interval integral with respect to a parameter. Given `F : X → α → E`, assume each `F x` is ae-measurable on `[a, b]`, and assume it is bounded by a function integrable on `[a, b]` independent of `x`. If `(λ x, F x t)` is continuous for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_of_dominated_interval {F : X → α → E} {bound : α → ℝ} {a b : α} (hF_meas : ∀ x, ae_measurable (F x) $ μ.restrict $ Ι a b) (h_bound : ∀ x, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous (λ x, F x t)) : continuous (λ x, ∫ t in a..b, F x t ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated_interval (eventually_of_forall hF_meas) (eventually_of_forall h_bound) bound_integrable $ h_cont.mono $ λ _, continuous.continuous_at) end continuity_wrt_parameter section continuous_primitive open topological_space variables [topological_space α] [order_topology α] [opens_measurable_space α] [first_countable_topology α] {a b : α} {μ : measure α} lemma continuous_within_at_primitive {f : α → E} {a b₀ b₁ b₂ : α} (hb₀ : μ {b₀} = 0) (h_int : interval_integrable f μ (min a b₁) (max a b₂)) : continuous_within_at (λ b, ∫ x in a .. b, f x ∂ μ) (Icc b₁ b₂) b₀ := begin by_cases h₀ : b₀ ∈ Icc b₁ b₂, { have h₁₂ : b₁ ≤ b₂ := h₀.1.trans h₀.2, have min₁₂ : min b₁ b₂ = b₁ := min_eq_left h₁₂, have h_int' : ∀ {x}, x ∈ Icc b₁ b₂ → interval_integrable f μ b₁ x, { rintros x ⟨h₁, h₂⟩, apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_right a b₁), h₁.trans (h₂.trans $ le_max_of_le_right $ le_max_right _ _)⟩ }, { exact ⟨min_le_of_left_le $ (min_le_right _ _).trans h₁, le_max_of_le_right $ h₂.trans $ le_max_right _ _⟩ } }, have : ∀ b ∈ Icc b₁ b₂, ∫ x in a..b, f x ∂μ = ∫ x in a..b₁, f x ∂μ + ∫ x in b₁..b, f x ∂μ, { rintros b ⟨h₁, h₂⟩, rw ← integral_add_adjacent_intervals _ (h_int' ⟨h₁, h₂⟩), apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_left a b₁), le_max_of_le_right (le_max_left _ _)⟩ }, { exact ⟨min_le_of_left_le (min_le_right _ _), le_max_of_le_right (h₁.trans $ h₂.trans (le_max_right a b₂))⟩ } }, apply continuous_within_at.congr _ this (this _ h₀), clear this, refine continuous_within_at_const.add _, have : (λ b, ∫ x in b₁..b, f x ∂μ) =ᶠ[𝓝[Icc b₁ b₂] b₀] λ b, ∫ x in b₁..b₂, indicator {x | x ≤ b} f x ∂ μ, { apply eventually_eq_of_mem self_mem_nhds_within, exact λ b b_in, (integral_indicator b_in).symm }, apply continuous_within_at.congr_of_eventually_eq _ this (integral_indicator h₀).symm, have : interval_integrable (λ x, ∥f x∥) μ b₁ b₂, from interval_integrable.norm (h_int' $ right_mem_Icc.mpr h₁₂), refine continuous_within_at_of_dominated_interval _ _ this _ ; clear this, { apply eventually.mono (self_mem_nhds_within), intros x hx, erw [ae_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' hx).1.ae_measurable }, { exact le_max_of_le_right hx.2 }, exacts [measurable_set_Iic, measurable_set_Iic] }, { refine eventually_of_forall (λ (x : α), eventually_of_forall (λ (t : α), _)), dsimp [indicator], split_ifs ; simp }, { have : ∀ᵐ t ∂μ.restrict (Ι b₁ b₂), t < b₀ ∨ b₀ < t, { apply ae_restrict_of_ae, apply eventually.mono (compl_mem_ae_iff.mpr hb₀), intros x hx, exact ne.lt_or_lt hx }, apply this.mono, rintros x₀ (hx₀ | hx₀), { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = f x₀, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Ioi_mem_nhds hx₀), intros x hx, simp [hx.le] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀.le] }, { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = 0, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Iio_mem_nhds hx₀), intros x hx, simp [hx] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀] } } }, { apply continuous_within_at_of_not_mem_closure, rwa [closure_Icc] } end lemma continuous_on_primitive {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Ioc a x, f t ∂ μ) (Icc a b) := begin by_cases h : a ≤ b, { have : ∀ x ∈ Icc a b, ∫ (t : α) in Ioc a x, f t ∂μ = ∫ (t : α) in a..x, f t ∂μ, { intros x x_in, simp_rw [← interval_oc_of_le h, integral_of_le x_in.1] }, rw continuous_on_congr this, intros x₀ hx₀, refine continuous_within_at_primitive (measure_singleton x₀) _, rw interval_integrable_iff, simp only [h, max_eq_right, min_eq_left], exact h_int.mono Ioc_subset_Icc_self le_rfl }, { rw Icc_eq_empty h, exact continuous_on_empty _ }, end lemma continuous_on_primitive_Icc {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Icc a x, f t ∂ μ) (Icc a b) := begin rw show (λ x, ∫ t in Icc a x, f t ∂μ) = λ x, ∫ t in Ioc a x, f t ∂μ, by { ext x, exact integral_Icc_eq_integral_Ioc }, exact continuous_on_primitive h_int end /-- Note: this assumes that `f` is `interval_integrable`, in contrast to some other lemmas here. -/ lemma continuous_on_primitive_interval' {f : α → E} {a b₁ b₂ : α} [has_no_atoms μ] (h_int : interval_integrable f μ b₁ b₂) (ha : a ∈ [b₁, b₂]) : continuous_on (λ b, ∫ x in a..b, f x ∂ μ) [b₁, b₂] := begin intros b₀ hb₀, refine continuous_within_at_primitive (measure_singleton _) _, rw [min_eq_right ha.1, max_eq_right ha.2], simpa [interval_integrable_iff] using h_int, end lemma continuous_on_primitive_interval {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (interval a b) μ) : continuous_on (λ x, ∫ t in a..x, f t ∂ μ) (interval a b) := continuous_on_primitive_interval' h_int.interval_integrable left_mem_interval lemma continuous_on_primitive_interval_left {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (interval a b) μ) : continuous_on (λ x, ∫ t in x..b, f t ∂ μ) (interval a b) := begin rw interval_swap a b at h_int ⊢, simp only [integral_symm b], exact (continuous_on_primitive_interval h_int).neg, end variables [no_bot_order α] [no_top_order α] [has_no_atoms μ] lemma continuous_primitive {f : α → E} (h_int : ∀ a b : α, interval_integrable f μ a b) (a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := begin rw continuous_iff_continuous_at, intro b₀, cases no_bot b₀ with b₁ hb₁, cases no_top b₀ with b₂ hb₂, apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₁ hb₂), exact continuous_within_at_primitive (measure_singleton b₀) (h_int _ _) end lemma _root_.measure_theory.integrable.continuous_primitive {f : α → E} (h_int : integrable f μ) (a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := continuous_primitive (λ _ _, h_int.interval_integrable) a end continuous_primitive section variables {f g : α → ℝ} {a b : α} {μ : measure α} lemma integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b)] 0 := by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1] lemma integral_eq_zero_iff_of_nonneg_ae (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 := begin cases le_total a b with hab hab; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi }, { rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] } end lemma integral_pos_iff_support_of_nonneg_ae' (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := begin obtain hab | hab := le_total b a; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { rw [←not_iff_not, not_and_distrib, not_lt, not_lt, integral_of_ge hab, neg_nonpos], exact iff_of_true (integral_nonneg_of_ae hf) (or.intro_left _ hab) }, rw [integral_of_le hab, set_integral_pos_iff_support_of_nonneg_ae hf hfi.1, iff.comm, and_iff_right_iff_imp], contrapose!, intro h, rw [Ioc_eq_empty h.not_lt, inter_empty, measure_empty], exact le_refl 0, end lemma integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi variable (hab : a ≤ b) include hab lemma integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf in by simpa only [integral_of_le hab] using set_integral_nonneg_of_ae_restrict H lemma integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ ae_restrict_of_ae hf lemma integral_nonneg_of_forall (hf : ∀ u, 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae hab $ eventually_of_forall hf lemma integral_nonneg [topological_space α] [opens_measurable_space α] [order_closed_topology α] (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ (ae_restrict_iff' measurable_set_Icc).mpr $ ae_of_all μ hf lemma norm_integral_le_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in a..b, ∥f x∥ ∂μ := norm_integral_le_abs_integral_norm.trans_eq $ abs_of_nonneg $ integral_nonneg_of_forall hab $ λ x, norm_nonneg _ lemma abs_integral_le_integral_abs : |∫ x in a..b, f x ∂μ| ≤ ∫ x in a..b, |f x| ∂μ := norm_integral_le_integral_norm hab section mono variables (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) include hf hg lemma integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := h.filter_mono $ ae_mono $ measure.restrict_mono Ioc_subset_Icc_self $ le_refl μ in by simpa only [integral_of_le hab] using set_integral_mono_ae_restrict hf.1 hg.1 H lemma integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := by simpa only [integral_of_le hab] using set_integral_mono_ae hf.1 hg.1 h lemma integral_mono_on [topological_space α] [opens_measurable_space α] [order_closed_topology α] (h : ∀ x ∈ Icc a b, f x ≤ g x) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := λ x hx, h x $ Ioc_subset_Icc_self hx in by simpa only [integral_of_le hab] using set_integral_mono_on hf.1 hg.1 measurable_set_Ioc H lemma integral_mono (h : f ≤ g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := integral_mono_ae hab hf hg $ ae_of_all _ h end mono end /-! ### Fundamental theorem of calculus, part 1, for any measure In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by `FTC_filter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar cases. Lean can automatically find both `a` and `l'` based on `l`. The most general theorem `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` can be seen as a generalization of lemma `integral_has_strict_fderiv_at` below which states strict differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three directions: first, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` deals with any locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes only that `f` has finite limits almost surely at `a` and `b`. Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This theorem is formulated with integral of constants instead of measures in the right hand sides for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is possible to write better `simp` lemmas for these integrals, see `integral_const` and `integral_const_of_cdf`. In the next subsection we apply this theorem to prove various theorems about differentiability of the integral w.r.t. Lebesgue measure. -/ /-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. -/ class FTC_filter {β : Type*} [linear_order β] [measurable_space β] [topological_space β] (a : out_param β) (outer : filter β) (inner : out_param $ filter β) extends tendsto_Ixx_class Ioc outer inner : Prop := (pure_le : pure a ≤ outer) (le_nhds : inner ≤ 𝓝 a) [meas_gen : is_measurably_generated inner] /- The `dangerous_instance` linter doesn't take `out_param`s into account, so it thinks that `FTC_filter.to_tendsto_Ixx_class` is dangerous. Disable this linter using `nolint`. -/ attribute [nolint dangerous_instance] FTC_filter.to_tendsto_Ixx_class namespace FTC_filter variables [linear_order β] [measurable_space β] [topological_space β] instance pure (a : β) : FTC_filter a (pure a) ⊥ := { pure_le := le_refl _, le_nhds := bot_le } instance nhds_within_singleton (a : β) : FTC_filter a (𝓝[{a}] a) ⊥ := by { rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)], apply_instance } lemma finite_at_inner {a : β} (l : filter β) {l'} [h : FTC_filter a l l'] {μ : measure β} [is_locally_finite_measure μ] : μ.finite_at_filter l' := (μ.finite_at_nhds a).filter_mono h.le_nhds variables [opens_measurable_space β] [order_topology β] instance nhds (a : β) : FTC_filter a (𝓝 a) (𝓝 a) := { pure_le := pure_le_nhds a, le_nhds := le_refl _ } instance nhds_univ (a : β) : FTC_filter a (𝓝[univ] a) (𝓝 a) := by { rw nhds_within_univ, apply_instance } instance nhds_left (a : β) : FTC_filter a (𝓝[Iic a] a) (𝓝[Iic a] a) := { pure_le := pure_le_nhds_within right_mem_Iic, le_nhds := inf_le_left } instance nhds_right (a : β) : FTC_filter a (𝓝[Ici a] a) (𝓝[Ioi a] a) := { pure_le := pure_le_nhds_within left_mem_Ici, le_nhds := inf_le_left } instance nhds_Icc {x a b : β} [h : fact (x ∈ Icc a b)] : FTC_filter x (𝓝[Icc a b] x) (𝓝[Icc a b] x) := { pure_le := pure_le_nhds_within h.out, le_nhds := inf_le_left } instance nhds_interval {x a b : β} [h : fact (x ∈ [a, b])] : FTC_filter x (𝓝[[a, b]] x) (𝓝[[a, b]] x) := by { haveI : fact (x ∈ set.Icc (min a b) (max a b)) := h, exact FTC_filter.nhds_Icc } end FTC_filter open asymptotics section variables {f : α → E} {a b : α} {c ca cb : E} {l l' la la' lb lb' : filter α} {lt : filter β} {μ : measure α} {u v ua va ub vb : β → α} /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, where `μ` is a measure finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := begin have A := hf.integral_sub_linear_is_o_ae hfm hl (hu.Ioc hv), have B := hf.integral_sub_linear_is_o_ae hfm hl (hv.Ioc hu), simp only [integral_const'], convert (A.trans_le _).sub (B.trans_le _), { ext t, simp_rw [interval_integral, sub_smul], abel }, all_goals { intro t, cases le_total (u t) (v t) with huv huv; simp [huv] } end /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l` so that `u ≤ v`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf hl hu hv).congr' (huv.mono $ λ x hx, by simp [integral_const', hx]) (huv.mono $ λ x hx, by simp [integral_const', hx]) /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l` so that `v ≤ u`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left $ λ t, by simp [integral_symm (u t), add_comm] variables [topological_space α] section variables [is_locally_finite_measure μ] [FTC_filter a l l'] include a local attribute [instance] FTC_filter.meas_gen /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae'` for a version that also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf (FTC_filter.finite_at_inner l) hu hv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf (FTC_filter.finite_at_inner l) hu hv huv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' hfm hf (FTC_filter.finite_at_inner l) hu hv huv end variables [order_topology α] [borel_space α] local attribute [instance] FTC_filter.meas_gen variables [FTC_filter a la la'] [FTC_filter b lb lb'] [is_locally_finite_measure μ] /-- Fundamental theorem of calculus-1, strict derivative in both limits for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f μ a b) (hmeas_a : measurable_at_filter f la' μ) (hmeas_b : measurable_at_filter f lb' μ) (ha_lim : tendsto f (la' ⊓ μ.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ μ.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x ∂μ) - (∫ x in ua t..ub t, f x ∂μ) - (∫ x in ub t..vb t, cb ∂μ - ∫ x in ua t..va t, ca ∂μ)) (λ t, ∥∫ x in ua t..va t, (1:ℝ) ∂μ∥ + ∥∫ x in ub t..vb t, (1:ℝ) ∂μ∥) lt := begin refine ((measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add (measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr' _ eventually_eq.rfl, have A : ∀ᶠ t in lt, interval_integrable f μ (ua t) (va t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) hua hva, have A' : ∀ᶠ t in lt, interval_integrable f μ a (ua t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) (tendsto_const_pure.mono_right FTC_filter.pure_le) hua, have B : ∀ᶠ t in lt, interval_integrable f μ (ub t) (vb t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) hub hvb, have B' : ∀ᶠ t in lt, interval_integrable f μ b (ub t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) (tendsto_const_pure.mono_right FTC_filter.pure_le) hub, filter_upwards [A, A', B, B'], intros t ua_va a_ua ub_vb b_ub, rw [← integral_interval_sub_interval_comm'], { dsimp only [], abel }, exacts [ub_vb, ua_va, b_ub.symm.trans $ hab.symm.trans a_ua] end /-- Fundamental theorem of calculus-1, strict derivative in right endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ μ.ae`. Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f lb' μ) (hf : tendsto f (lb' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, ∫ x in a..v t, f x ∂μ - ∫ x in a..u t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab measurable_at_bot hmeas ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hf (tendsto_const_pure : tendsto _ _ (pure a)) tendsto_const_pure hu hv /-- Fundamental theorem of calculus-1, strict derivative in left endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ μ.ae`. Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `la`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f la' μ) (hf : tendsto f (la' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, ∫ x in v t..b, f x ∂μ - ∫ x in u t..b, f x ∂μ + ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas measurable_at_bot hf ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hu hv (tendsto_const_pure : tendsto _ _ (pure b)) tendsto_const_pure end /-! ### Fundamental theorem of calculus-1 for Lebesgue measure In this section we restate theorems from the previous section for Lebesgue measure. In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)` at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`. -/ variables {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter β} {a b z : ℝ} {u v ua ub va vb : β → ℝ} [FTC_filter a la la'] [FTC_filter b lb lb'] /-! #### Auxiliary `is_o` statements In this section we prove several lemmas that can be interpreted as strict differentiability of `(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `is_o` because we have no definition of `has_strict_(f)deriv_at_filter` in the library. -/ /-- Fundamental theorem of calculus-1, local version. If `f` has a finite limit `c` almost surely at `l'`, where `(l, l')` is an `FTC_filter` pair around `a`, then `∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/ lemma integral_sub_linear_is_o_of_tendsto_ae [FTC_filter a l l'] (hfm : measurable_at_filter f l') (hf : tendsto f (l' ⊓ volume.ae) (𝓝 c)) {u v : β → ℝ} (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, (∫ x in u t..v t, f x) - (v t - u t) • c) (v - u) lt := by simpa [integral_const] using measure_integral_sub_linear_is_o_of_tendsto_ae hfm hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca + o(∥va - ua∥ + ∥vb - ub∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This lemma could've been formulated using `has_strict_fderiv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la') (hmeas_b : measurable_at_filter f lb') (ha_lim : tendsto f (la' ⊓ volume.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ volume.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x) - (∫ x in ua t..ub t, f x) - ((vb t - ub t) • cb - (va t - ua t) • ca)) (λ t, ∥va t - ua t∥ + ∥vb t - ub t∥) lt := by simpa [integral_const] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas_a hmeas_b ha_lim hb_lim hua hva hub hvb /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then `(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `lb`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f lb') (hf : tendsto f (lb' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, (∫ x in a..v t, f x) - (∫ x in a..u t, f x) - (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hab hmeas hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `f` has a finite limit `c` almost surely at `la'`, then `(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `la`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f la') (hf : tendsto f (la' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, (∫ x in v t..b, f x) - (∫ x in u t..b, f x) + (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left hab hmeas hf hu hv open continuous_linear_map (fst snd smul_right sub_apply smul_right_apply coe_fst' coe_snd' map_sub) /-! #### Strict differentiability In this section we prove that for a measurable function `f` integrable on `a..b`, * `integral_has_strict_fderiv_at_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`, respectively; * `integral_has_strict_fderiv_at`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability provided that `f` is continuous at `a` and `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `b`; * `integral_has_strict_deriv_at_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability provided that `f` is continuous at `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `a`; * `integral_has_strict_deriv_at_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability provided that `f` is continuous at `a`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := begin have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb ((continuous_fst.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_fst.comp continuous_fst).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_fst).tendsto ((a, b), (a, b))), refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- **First Fundamental Theorem of Calculus**: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) c b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb continuous_at_snd continuous_at_fst /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_of_tendsto_ae_right hf.symm hmeas ha).neg /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_right hf.symm hmeas ha).neg /-! #### Fréchet differentiability In this subsection we restate results from the previous subsection in terms of `has_fderiv_at`, `has_deriv_at`, `fderiv`, and `deriv`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := (integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := (integral_has_strict_fderiv_at hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca := (integral_has_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a) := (integral_has_fderiv_at hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/ lemma integral_has_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in a..u, f x) c b := (integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/ lemma integral_has_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := (integral_has_strict_deriv_at_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in a..u, f x) b = c := (integral_has_deriv_at_of_tendsto_ae_right hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_integral_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : deriv (λ u, ∫ x in a..u, f x) b = f b := (integral_has_deriv_at_right hf hmeas hb).deriv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/ lemma integral_has_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := (integral_has_strict_deriv_at_of_tendsto_ae_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/ lemma integral_has_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := (integral_has_strict_deriv_at_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in u..b, f x) a = -c := (integral_has_deriv_at_of_tendsto_ae_left hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_integral_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : continuous_at f a) : deriv (λ u, ∫ x in u..b, f x) a = -f a := (integral_has_deriv_at_left hf hmeas hb).deriv /-! #### One-sided derivatives -/ /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at_of_tendsto_ae (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (s.prod t) (a, b) := begin rw [has_fderiv_within_at, nhds_within_prod_eq], have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[s] a)) tendsto_fst (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[t] b)) tendsto_snd, refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption is definitionally equal `continuous_at f _` or `continuous_within_at f _ _`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f la (𝓝 $ f a)) (hb : tendsto f lb (𝓝 $ f b)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (s.prod t) (a, b) := integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- An auxiliary tactic closing goals `unique_diff_within_at ℝ s a` where `s ∈ {Iic a, Ici a, univ}`. -/ meta def unique_diff_within_at_Ici_Iic_univ : tactic unit := `[apply_rules [unique_diff_on.unique_diff_within_at, unique_diff_on_Ici, unique_diff_on_Iic, left_mem_Ici, right_mem_Iic, unique_diff_within_at_univ]] /-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}` and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the table below. Then `fderiv_within ℝ (λ p, ∫ x in p.1..p.2, f x) (s.prod t)` is equal to `(u, v) ↦ u • cb - v • ca`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma fderiv_within_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) (ht : unique_diff_within_at ℝ t b . unique_diff_within_at_Ici_Iic_univ) : fderiv_within ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (s.prod t) (a, b) = ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) := (integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv_within $ hs.prod ht /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in a..u, f x) c s b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb (tendsto_const_pure.mono_right FTC_filter.pure_le) tendsto_id /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right) derivative `f b` at `b`. -/ lemma integral_has_deriv_within_at_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) : has_deriv_within_at (λ u, ∫ x in a..u, f x) (f b) s b := integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_within_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas: measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = c := (integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `b`, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_within_integral_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = f b := (integral_has_deriv_within_at_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-c) s a := by { simp only [integral_symm b], exact (integral_has_deriv_within_at_of_tendsto_ae_right hf.symm hmeas ha).neg } /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right) derivative `-f a` at `a`. -/ lemma integral_has_deriv_within_at_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-f a) s a := integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_within_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -c := (integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas ha).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `a`, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_within_integral_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -f a := (integral_has_deriv_within_at_left hf hmeas ha).deriv_within hs /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiable_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : differentiable_on ℝ (λ u, ∫ x in a..u, f x) s := λ y hy, (integral_has_deriv_at_right (hintg y hy) hcont.measurable.ae_measurable.measurable_at_filter hcont.continuous_at) .differentiable_at.differentiable_within_at /-! ### Fundamental theorem of calculus, part 2 This section contains theorems pertaining to FTC-2 for interval integrals, i.e., the assertion that `∫ x in a..b, f' x = f b - f a` under suitable assumptions. The most classical version of this theorem assumes that `f'` is continuous. However, this is unnecessarily strong: the result holds if `f'` is just integrable. We prove the strong version, following [Rudin, *Real and Complex Analysis* (Theorem 7.21)][rudin2006real]. The proof is first given for real-valued functions, and then deduced for functions with a general target space. For a real-valued function `g`, it suffices to show that `g b - g a ≤ (∫ x in a..b, g' x) + ε` for all positive `ε`. To prove this, choose a lower-semicontinuous function `G'` with `g' < G'` and with integral close to that of `g'` (its existence is guaranteed by the Vitali-Carathéodory theorem). It satisfies `g t - g a ≤ ∫ x in a..t, G' x` for all `t ∈ [a, b]`: this inequality holds at `a`, and if it holds at `t` then it holds for `u` close to `t` on its right, as the left hand side increases by `g u - g t ∼ (u -t) g' t`, while the right hand side increases by `∫ x in t..u, G' x` which is roughly at least `∫ x in t..u, G' t = (u - t) G' t`, by lower semicontinuity. As `g' t < G' t`, this gives the conclusion. One can therefore push progressively this inequality to the right until the point `b`, where it gives the desired conclusion. -/ variables {g' g : ℝ → ℝ} /-- Hard part of FTC-2 for integrable derivatives, real-valued functions: one has `g b - g a ≤ ∫ y in a..b, g' y`. Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`. -/ lemma sub_le_integral_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : g b - g a ≤ ∫ y in a..b, g' y := begin refine le_of_forall_pos_le_add (λ ε εpos, _), -- Bound from above `g'` by a lower-semicontinuous function `G'`. rcases exists_lt_lower_semicontinuous_integral_lt g' g'int εpos with ⟨G', g'_lt_G', G'cont, G'int, G'lt_top, hG'⟩, -- we will show by "induction" that `g t - g a ≤ ∫ u in a..t, G' u` for all `t ∈ [a, b]`. set s := {t | g t - g a ≤ ∫ u in a..t, (G' u).to_real} ∩ Icc a b, -- the set `s` of points where this property holds is closed. have s_closed : is_closed s, { have : continuous_on (λ t, (g t - g a, ∫ u in a..t, (G' u).to_real)) (Icc a b), { rw ← interval_of_le hab at G'int ⊢ hcont, exact (hcont.sub continuous_on_const).prod (continuous_on_primitive_interval G'int) }, simp only [s, inter_comm], exact this.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, have main : Icc a b ⊆ {t | g t - g a ≤ ∫ u in a..t, (G' u).to_real }, { -- to show that the set `s` is all `[a, b]`, it suffices to show that any point `t` in `s` -- with `t < b` admits another point in `s` slightly to its right -- (this is a sort of real induction). apply s_closed.Icc_subset_of_forall_exists_gt (by simp only [integral_same, mem_set_of_eq, sub_self]) (λ t ht v t_lt_v, _), obtain ⟨y, g'_lt_y', y_lt_G'⟩ : ∃ (y : ℝ), (g' t : ereal) < y ∧ (y : ereal) < G' t := ereal.lt_iff_exists_real_btwn.1 (g'_lt_G' t), -- bound from below the increase of `∫ x in a..u, G' x` on the right of `t`, using the lower -- semicontinuity of `G'`. have I1 : ∀ᶠ u in 𝓝[Ioi t] t, (u - t) * y ≤ ∫ w in t..u, (G' w).to_real, { have B : ∀ᶠ u in 𝓝 t, (y : ereal) < G' u := G'cont.lower_semicontinuous_at _ _ y_lt_G', rcases mem_nhds_iff_exists_Ioo_subset.1 B with ⟨m, M, ⟨hm, hM⟩, H⟩, have : Ioo t (min M b) ∈ 𝓝[Ioi t] t := mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨min M b, by simp only [hM, ht.right.right, lt_min_iff, mem_Ioi, and_self], subset.refl _⟩, filter_upwards [this], assume u hu, have I : Icc t u ⊆ Icc a b := Icc_subset_Icc ht.2.1 (hu.2.le.trans (min_le_right _ _)), calc (u - t) * y = ∫ v in Icc t u, y : by simp only [hu.left.le, measure_theory.integral_const, algebra.id.smul_eq_mul, sub_nonneg, measurable_set.univ, real.volume_Icc, measure.restrict_apply, univ_inter, ennreal.to_real_of_real] ... ≤ ∫ w in t..u, (G' w).to_real : begin rw [interval_integral.integral_of_le hu.1.le, ← integral_Icc_eq_integral_Ioc], apply set_integral_mono_ae_restrict, { simp only [integrable_on_const, real.volume_Icc, ennreal.of_real_lt_top, or_true] }, { exact integrable_on.mono_set G'int I }, { have C1 : ∀ᵐ (x : ℝ) ∂volume.restrict (Icc t u), G' x < ⊤ := ae_mono (measure.restrict_mono I (le_refl _)) G'lt_top, have C2 : ∀ᵐ (x : ℝ) ∂volume.restrict (Icc t u), x ∈ Icc t u := ae_restrict_mem measurable_set_Icc, filter_upwards [C1, C2], assume x G'x hx, apply ereal.coe_le_coe_iff.1, have : x ∈ Ioo m M, by simp only [hm.trans_le hx.left, (hx.right.trans_lt hu.right).trans_le (min_le_left M b), mem_Ioo, and_self], convert le_of_lt (H this), exact ereal.coe_to_real G'x.ne (ne_bot_of_gt (g'_lt_G' x)) } end }, -- bound from above the increase of `g u - g a` on the right of `t`, using the derivative at `t` have I2 : ∀ᶠ u in 𝓝[Ioi t] t, g u - g t ≤ (u - t) * y, { have g'_lt_y : g' t < y := ereal.coe_lt_coe_iff.1 g'_lt_y', filter_upwards [(hderiv t ⟨ht.2.1, ht.2.2⟩).limsup_slope_le' (not_mem_Ioi.2 le_rfl) g'_lt_y, self_mem_nhds_within], assume u hu t_lt_u, have := hu.le, rwa [← div_eq_inv_mul, div_le_iff'] at this, exact sub_pos.2 t_lt_u }, -- combine the previous two bounds to show that `g u - g a` increases less quickly than -- `∫ x in a..u, G' x`. have I3 : ∀ᶠ u in 𝓝[Ioi t] t, g u - g t ≤ ∫ w in t..u, (G' w).to_real, { filter_upwards [I1, I2], assume u hu1 hu2, exact hu2.trans hu1 }, have I4 : ∀ᶠ u in 𝓝[Ioi t] t, u ∈ Ioc t (min v b), { refine mem_nhds_within_Ioi_iff_exists_Ioc_subset.2 ⟨min v b, _, subset.refl _⟩, simp only [lt_min_iff, mem_Ioi], exact ⟨t_lt_v, ht.2.2⟩ }, -- choose a point `x` slightly to the right of `t` which satisfies the above bound rcases (I3.and I4).exists with ⟨x, hx, h'x⟩, -- we check that it belongs to `s`, essentially by construction refine ⟨x, _, Ioc_subset_Ioc (le_refl _) (min_le_left _ _) h'x⟩, calc g x - g a = (g t - g a) + (g x - g t) : by abel ... ≤ (∫ w in a..t, (G' w).to_real) + ∫ w in t..x, (G' w).to_real : add_le_add ht.1 hx ... = ∫ w in a..x, (G' w).to_real : begin apply integral_add_adjacent_intervals, { rw interval_integrable_iff_integrable_Ioc_of_le ht.2.1, exact integrable_on.mono_set G'int (Ioc_subset_Icc_self.trans (Icc_subset_Icc le_rfl ht.2.2.le)) }, { rw interval_integrable_iff_integrable_Ioc_of_le h'x.1.le, apply integrable_on.mono_set G'int, refine Ioc_subset_Icc_self.trans (Icc_subset_Icc ht.2.1 (h'x.2.trans (min_le_right _ _))) } end }, -- now that we know that `s` contains `[a, b]`, we get the desired result by applying this to `b`. calc g b - g a ≤ ∫ y in a..b, (G' y).to_real : main (right_mem_Icc.2 hab) ... ≤ (∫ y in a..b, g' y) + ε : begin convert hG'.le; { rw interval_integral.integral_of_le hab, simp only [integral_Icc_eq_integral_Ioc', real.volume_singleton] }, end end /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`. -/ lemma integral_le_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y ≤ g b - g a := begin rw ← neg_le_neg_iff, convert sub_le_integral_of_has_deriv_right_of_le hab hcont.neg (λ x hx, (hderiv x hx).neg) g'int.neg, { abel }, { simp only [integral_neg] } end /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`: real version -/ lemma integral_eq_sub_of_has_deriv_right_of_le_real (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y = g b - g a := le_antisymm (integral_le_sub_of_has_deriv_right_of_le hab hcont hderiv g'int) (sub_le_integral_of_has_deriv_right_of_le hab hcont hderiv g'int) /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`: real version, not requiring differentiability as the left endpoint of the interval. Follows from `integral_eq_sub_of_has_deriv_right_of_le_real` together with a continuity argument. -/ lemma integral_eq_sub_of_has_deriv_right_of_le_real' (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y = g b - g a := begin obtain rfl|a_lt_b := hab.eq_or_lt, { simp }, set s := {t | ∫ u in t..b, g' u = g b - g t} ∩ Icc a b, have s_closed : is_closed s, { have : continuous_on (λ t, (∫ u in t..b, g' u, g b - g t)) (Icc a b), { rw ← interval_of_le hab at ⊢ hcont g'int, exact (continuous_on_primitive_interval_left g'int).prod (continuous_on_const.sub hcont) }, simp only [s, inter_comm], exact this.preimage_closed_of_closed is_closed_Icc is_closed_diagonal, }, have A : closure (Ioc a b) ⊆ s, { apply s_closed.closure_subset_iff.2, assume t ht, refine ⟨_, ⟨ht.1.le, ht.2⟩⟩, exact integral_eq_sub_of_has_deriv_right_of_le_real ht.2 (hcont.mono (Icc_subset_Icc ht.1.le (le_refl _))) (λ x hx, hderiv x ⟨ht.1.trans_le hx.1, hx.2⟩) (g'int.mono_set (Icc_subset_Icc ht.1.le (le_refl _))) }, rw closure_Ioc a_lt_b at A, exact (A (left_mem_Icc.2 hab)).1, end variable {f' : ℝ → E} /-- **Fundamental theorem of calculus-2**: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a right derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_within_at f (f' x) (Ioi x) x) (f'int : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := begin refine (normed_space.eq_iff_forall_dual_eq ℝ).2 (λ g, _), rw [← g.interval_integral_comp_comm f'int, g.map_sub], exact integral_eq_sub_of_has_deriv_right_of_le_real' hab (g.continuous.comp_continuous_on hcont) (λ x hx, g.has_fderiv_at.comp_has_deriv_within_at x (hderiv x hx)) (g.integrable_comp ((interval_integrable_iff_integrable_Icc_of_le hab).1 f'int)) end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is integrable on `[a, b]` then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := begin cases le_total a b with hab hab, { simp only [interval_of_le, min_eq_left, max_eq_right, hab] at hcont hderiv hint, apply integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hint }, { simp only [interval_of_ge, min_eq_right, max_eq_left, hab] at hcont hderiv, rw [integral_symm, integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hint.symm, neg_sub] } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_right_of_le hab hcont (λ x hx, (hderiv x hx).has_deriv_within_at) hint /-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in `[a, b]` and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at (hderiv : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_right (has_deriv_at.continuous_on hderiv) (λ x hx, (hderiv _ (mem_Icc_of_Ioo hx)).has_deriv_within_at) hint theorem integral_eq_sub_of_has_deriv_at_of_tendsto (hab : a < b) {fa fb} (hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) (ha : tendsto f (𝓝[Ioi a] a) (𝓝 fa)) (hb : tendsto f (𝓝[Iio b] b) (𝓝 fb)) : ∫ y in a..b, f' y = fb - fa := begin set F : ℝ → E := update (update f a fa) b fb, have Fderiv : ∀ x ∈ Ioo a b, has_deriv_at F (f' x) x, { refine λ x hx, (hderiv x hx).congr_of_eventually_eq _, filter_upwards [Ioo_mem_nhds hx.1 hx.2], intros y hy, simp only [F], rw [update_noteq hy.2.ne, update_noteq hy.1.ne'] }, have hcont : continuous_on F (Icc a b), { rw [continuous_on_update_iff, continuous_on_update_iff, Icc_diff_right, Ico_diff_left], refine ⟨⟨λ z hz, (hderiv z hz).continuous_at.continuous_within_at, _⟩, _⟩, { exact λ _, ha.mono_left (nhds_within_mono _ Ioo_subset_Ioi_self) }, { rintro -, refine (hb.congr' _).mono_left (nhds_within_mono _ Ico_subset_Iio_self), filter_upwards [Ioo_mem_nhds_within_Iio (right_mem_Ioc.2 hab)], exact λ z hz, (update_noteq hz.1.ne' _ _).symm } }, simpa [F, hab.ne, hab.ne'] using integral_eq_sub_of_has_deriv_at_of_le hab.le hcont Fderiv hint end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and its derivative is integrable on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hint : interval_integrable (deriv f) volume a b) : ∫ y in a..b, deriv f y = f b - f a := integral_eq_sub_of_has_deriv_at (λ x hx, (hderiv x hx).has_deriv_at) hint theorem integral_deriv_eq_sub' (f) (hderiv : deriv f = f') (hdiff : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin rw [← hderiv, integral_deriv_eq_sub hdiff], rw hderiv, exact hcont.interval_integrable end /-! ### Integration by parts -/ theorem integral_deriv_mul_eq_sub {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hu' : interval_integrable u' volume a b) (hv' : interval_integrable v' volume a b) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := integral_eq_sub_of_has_deriv_at (λ x hx, (hu x hx).mul (hv x hx)) $ (hu'.mul_continuous_on (has_deriv_at.continuous_on hv)).add (hv'.continuous_on_mul ((has_deriv_at.continuous_on hu))) theorem integral_mul_deriv_eq_deriv_mul {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hu' : interval_integrable u' volume a b) (hv' : interval_integrable v' volume a b) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, v x * u' x := begin rw [← integral_deriv_mul_eq_sub hu hv hu' hv', ← integral_sub], { exact integral_congr (λ x hx, by simp only [mul_comm, add_sub_cancel']) }, { exact ((hu'.mul_continuous_on (has_deriv_at.continuous_on hv)).add (hv'.continuous_on_mul (has_deriv_at.continuous_on hu))) }, { exact hu'.continuous_on_mul (has_deriv_at.continuous_on hv) }, end /-! ### Integration by substitution / Change of variables -/ section smul /-- Change of variables, general form. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. We could potentially slightly weaken the conditions, by not requiring that `f'` and `g` are continuous on the endpoints of these intervals, but in that case we need to additionally assume that the functions are integrable on that interval. -/ theorem integral_comp_smul_deriv'' {f f' : ℝ → ℝ} {g : ℝ → E} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, f' x • (g ∘ f) x= ∫ u in f a..f b, g u := begin have h_cont : continuous_on (λ u, ∫ t in f a..f u, g t) [a, b], { rw [hf.image_interval] at hg, refine (continuous_on_primitive_interval' hg.interval_integrable _).comp hf _, { rw [← hf.image_interval], exact mem_image_of_mem f left_mem_interval }, { rw [← image_subset_iff], exact hf.image_interval.subset } }, have h_der : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at (λ u, ∫ t in f a..f u, g t) (f' x • ((g ∘ f) x)) (Ioi x) x, { intros x hx, let I := [Inf (f '' [a, b]), Sup (f '' [a, b])], have hI : f '' [a, b] = I := hf.image_interval, have h2x : f x ∈ I, { rw [← hI], exact mem_image_of_mem f (Ioo_subset_Icc_self hx) }, have h2g : interval_integrable g volume (f a) (f x), { refine (hg.mono $ _).interval_integrable, exact hf.surj_on_interval left_mem_interval (Ioo_subset_Icc_self hx) }, rw [hI] at hg, have h3g : measurable_at_filter g (𝓝[I] f x) volume := hg.measurable_at_filter_nhds_within measurable_set_Icc (f x), haveI : fact (f x ∈ I) := ⟨h2x⟩, have : has_deriv_within_at (λ u, ∫ x in f a..u, g x) (g (f x)) I (f x) := integral_has_deriv_within_at_right h2g h3g (hg (f x) h2x), refine (this.scomp x ((hff' x hx).Ioo_of_Ioi hx.2) _).Ioi_of_Ioo hx.2, dsimp only [I], rw [← image_subset_iff, ← hf.image_interval], refine image_subset f (Ioo_subset_Icc_self.trans $ Icc_subset_Icc_left hx.1.le) }, have h_int : interval_integrable (λ (x : ℝ), f' x • (g ∘ f) x) volume a b := (hf'.smul (hg.comp hf $ subset_preimage_image f _)).interval_integrable, simp_rw [integral_eq_sub_of_has_deriv_right h_cont h_der h_int, integral_same, sub_zero], end /-- Change of variables. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. Compared to `interval_integral.integral_comp_smul_deriv` we only require that `g` is continuous on `f '' [a, b]`. -/ theorem integral_comp_smul_deriv' {f f' : ℝ → ℝ} {g : ℝ → E} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, f' x • (g ∘ f) x = ∫ x in f a..f b, g x := integral_comp_smul_deriv'' (λ x hx, (h x hx).continuous_at.continuous_within_at) (λ x hx, (h x $ Ioo_subset_Icc_self hx).has_deriv_within_at) h' hg /-- Change of variables, most common version. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_smul_deriv {f f' : ℝ → ℝ} {g : ℝ → E} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous g) : ∫ x in a..b, f' x • (g ∘ f) x = ∫ x in f a..f b, g x := integral_comp_smul_deriv' h h' hg.continuous_on theorem integral_deriv_comp_smul_deriv' {f f' : ℝ → ℝ} {g g' : ℝ → E} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g [f a, f b]) (hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), has_deriv_within_at g (g' x) (Ioi x) x) (hg' : continuous_on g' (f '' [a, b])) : ∫ x in a..b, f' x • (g' ∘ f) x = (g ∘ f) b - (g ∘ f) a := begin rw [integral_comp_smul_deriv'' hf hff' hf' hg', integral_eq_sub_of_has_deriv_right hg hgg' (hg'.mono _).interval_integrable], exact intermediate_value_interval hf end theorem integral_deriv_comp_smul_deriv {f f' : ℝ → ℝ} {g g' : ℝ → E} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x)) (hf' : continuous_on f' (interval a b)) (hg' : continuous g') : ∫ x in a..b, f' x • (g' ∘ f) x = (g ∘ f) b - (g ∘ f) a := integral_eq_sub_of_has_deriv_at (λ x hx, (hg x hx).scomp x $ hf x hx) (hf'.smul (hg'.comp_continuous_on $ has_deriv_at.continuous_on hf)).interval_integrable end smul section mul /-- Change of variables, general form for scalar functions. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv'' {f f' g : ℝ → ℝ} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u := by simpa [mul_comm] using integral_comp_smul_deriv'' hf hff' hf' hg /-- Change of variables. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. Compared to `interval_integral.integral_comp_mul_deriv` we only require that `g` is continuous on `f '' [a, b]`. -/ theorem integral_comp_mul_deriv' {f f' g : ℝ → ℝ} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := by simpa [mul_comm] using integral_comp_smul_deriv' h h' hg /-- Change of variables, most common version. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv {f f' g : ℝ → ℝ} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous g) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := integral_comp_mul_deriv' h h' hg.continuous_on theorem integral_deriv_comp_mul_deriv' {f f' g g' : ℝ → ℝ} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g [f a, f b]) (hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), has_deriv_within_at g (g' x) (Ioi x) x) (hg' : continuous_on g' (f '' [a, b])) : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := by simpa [mul_comm] using integral_deriv_comp_smul_deriv' hf hff' hf' hg hgg' hg' theorem integral_deriv_comp_mul_deriv {f f' g g' : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x)) (hf' : continuous_on f' (interval a b)) (hg' : continuous g') : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := by simpa [mul_comm] using integral_deriv_comp_smul_deriv hf hg hf' hg' end mul end interval_integral
7962698624114b3c77b2787abc9f66605b8f115e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/closed/functor.lean
82b1442a9e7da6a9439bc72d23d1503b1b7a0f46
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,500
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.closed.cartesian import Mathlib.category_theory.limits.preserves.shapes.binary_products import Mathlib.category_theory.adjunction.fully_faithful import Mathlib.PostPort universes v u u' l namespace Mathlib /-! # Cartesian closed functors Define the exponential comparison morphisms for a functor which preserves binary products, and use them to define a cartesian closed functor: one which (naturally) preserves exponentials. Define the Frobenius morphism, and show it is an isomorphism iff the exponential comparison is an isomorphism. ## TODO Some of the results here are true more generally for closed objects and for closed monoidal categories, and these could be generalised. ## References https://ncatlab.org/nlab/show/cartesian+closed+functor https://ncatlab.org/nlab/show/Frobenius+reciprocity ## Tags Frobenius reciprocity, cartesian closed functor -/ namespace category_theory /-- The Frobenius morphism for an adjunction `L ⊣ F` at `A` is given by the morphism L(FA ⨯ B) ⟶ LFA ⨯ LB ⟶ A ⨯ LB natural in `B`, where the first morphism is the product comparison and the latter uses the counit of the adjunction. We will show that if `C` and `D` are cartesian closed, then this morphism is an isomorphism for all `A` iff `F` is a cartesian closed functor, i.e. it preserves exponentials. -/ def frobenius_morphism {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) {L : D ⥤ C} (h : L ⊣ F) (A : C) : functor.obj limits.prod.functor (functor.obj F A) ⋙ L ⟶ L ⋙ functor.obj limits.prod.functor A := limits.prod_comparison_nat_trans L (functor.obj F A) ≫ whisker_left L (functor.map limits.prod.functor (nat_trans.app (adjunction.counit h) A)) /-- If `F` is full and faithful and has a left adjoint `L` which preserves binary products, then the Frobenius morphism is an isomorphism. -/ protected instance frobenius_morphism_iso_of_preserves_binary_products {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) {L : D ⥤ C} (h : L ⊣ F) (A : C) [limits.preserves_limits_of_shape (discrete limits.walking_pair) L] [full F] [faithful F] : is_iso (frobenius_morphism F h A) := nat_iso.is_iso_of_is_iso_app (frobenius_morphism F h A) /-- The exponential comparison map. `F` is a cartesian closed functor if this is an iso for all `A`. -/ def exp_comparison {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] (A : C) : exp A ⋙ F ⟶ F ⋙ exp (functor.obj F A) := coe_fn (transfer_nat_trans (exp.adjunction A) (exp.adjunction (functor.obj F A))) (iso.inv (limits.prod_comparison_nat_iso F A)) theorem exp_comparison_ev {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] (A : C) (B : C) : limits.prod.map 𝟙 (nat_trans.app (exp_comparison F A) B) ≫ nat_trans.app (ev (functor.obj F A)) (functor.obj F B) = inv (limits.prod_comparison F A (functor.obj (exp A) B)) ≫ functor.map F (nat_trans.app (ev A) B) := sorry theorem coev_exp_comparison {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] (A : C) (B : C) : functor.map F (nat_trans.app (coev A) B) ≫ nat_trans.app (exp_comparison F A) (A ⨯ B) = nat_trans.app (coev (functor.obj F A)) (functor.obj F B) ≫ functor.map (exp (functor.obj F A)) (inv (limits.prod_comparison F A B)) := sorry theorem uncurry_exp_comparison {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] (A : C) (B : C) : cartesian_closed.uncurry (nat_trans.app (exp_comparison F A) B) = inv (limits.prod_comparison F A (functor.obj (exp A) B)) ≫ functor.map F (nat_trans.app (ev A) B) := sorry /-- The exponential comparison map is natural in `A`. -/ theorem exp_comparison_whisker_left {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] {A : C} {A' : C} (f : A' ⟶ A) : exp_comparison F A ≫ whisker_left F (pre (functor.map F f)) = whisker_right (pre f) F ≫ exp_comparison F A' := sorry /-- The functor `F` is cartesian closed (ie preserves exponentials) if each natural transformation `exp_comparison F A` is an isomorphism -/ class cartesian_closed_functor {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] where comparison_iso : (A : C) → is_iso (exp_comparison F A) theorem frobenius_morphism_mate {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) {L : D ⥤ C} [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] (h : L ⊣ F) (A : C) : coe_fn (transfer_nat_trans_self (adjunction.comp (functor.obj limits.prod.functor A) (exp A) h (exp.adjunction A)) (adjunction.comp L F (exp.adjunction (functor.obj F A)) h)) (frobenius_morphism F h A) = exp_comparison F A := sorry /-- If the exponential comparison transformation (at `A`) is an isomorphism, then the Frobenius morphism at `A` is an isomorphism. -/ def frobenius_morphism_iso_of_exp_comparison_iso {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) {L : D ⥤ C} [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] (h : L ⊣ F) (A : C) [i : is_iso (exp_comparison F A)] : is_iso (frobenius_morphism F h A) := transfer_nat_trans_self_of_iso (adjunction.comp (functor.obj limits.prod.functor A) (exp A) h (exp.adjunction A)) (adjunction.comp L F (exp.adjunction (functor.obj F A)) h) (frobenius_morphism F h A) /-- If the Frobenius morphism at `A` is an isomorphism, then the exponential comparison transformation (at `A`) is an isomorphism. -/ def exp_comparison_iso_of_frobenius_morphism_iso {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) {L : D ⥤ C} [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] (h : L ⊣ F) (A : C) [i : is_iso (frobenius_morphism F h A)] : is_iso (exp_comparison F A) := eq.mpr sorry (category_theory.transfer_nat_trans_self_iso (adjunction.comp (functor.obj limits.prod.functor A) (exp A) h (exp.adjunction A)) (adjunction.comp L F (exp.adjunction (functor.obj F A)) h) (frobenius_morphism F h A)) /-- If `F` is full and faithful, and has a left adjoint which preserves binary products, then it is cartesian closed. TODO: Show the converse, that if `F` is cartesian closed and its left adjoint preserves binary products, then it is full and faithful. -/ def cartesian_closed_functor_of_left_adjoint_preserves_binary_products {C : Type u} [category C] {D : Type u'} [category D] [limits.has_finite_products C] [limits.has_finite_products D] (F : C ⥤ D) {L : D ⥤ C} [cartesian_closed C] [cartesian_closed D] [limits.preserves_limits_of_shape (discrete limits.walking_pair) F] (h : L ⊣ F) [full F] [faithful F] [limits.preserves_limits_of_shape (discrete limits.walking_pair) L] : cartesian_closed_functor F := cartesian_closed_functor.mk fun (A : C) => exp_comparison_iso_of_frobenius_morphism_iso F h A
c18650bf506715852e044a707a700fb0429abfd2
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/data/cpi/species/default.lean
d23d37a94ca1060ed4484e556cafcc8f5bae783f
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
111
lean
import data.cpi.species.basic import data.cpi.species.congruence_prime import data.cpi.species.normalise_prime
3eabd529dd9b6ed4319f1bc349643bade50ad480
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/user_attribute.lean
bf10dcbab9123f02bcc41e173071343bb4511d48
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
866
lean
definition foo_attr : user_attribute := { name := `foo, descr := "bar" } run_command attribute.register `foo_attr attribute [foo] eq.refl print [foo] print eq.refl run_command attribute.get_instances `foo >>= tactic.pp >>= tactic.trace print "---" -- compound names definition foo_baz_attr : user_attribute := ⟨`foo.baz, "bar"⟩ run_command attribute.register `foo_baz_attr attribute [foo.baz] eq.refl print [foo.baz] print eq.refl run_command attribute.get_instances `foo.baz >>= tactic.pp >>= tactic.trace -- can't redeclare attributes definition duplicate : user_attribute := ⟨`reducible, "bar"⟩ run_command attribute.register `duplicate -- wrong type definition bar := "bar" run_command attribute.register `bar section variable x : string definition baz_attr : user_attribute := ⟨`baz, x⟩ run_command attribute.register `baz_attr end
b69186f17925107789d0605f04567a4ede992337
4727251e0cd73359b15b664c3170e5d754078599
/src/data/seq/computation.lean
06bd8c3c010087dc796b1b97766a8d5bb601b48a
[ "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
37,961
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Coinductive formalization of unbounded computations. -/ import tactic.basic import data.stream.init import logic.relator open function universes u v w /- coinductive computation (α : Type u) : Type u | return : α → computation α | think : computation α → computation α -/ /-- `computation α` is the type of unbounded computations returning `α`. An element of `computation α` is an infinite sequence of `option α` such that if `f n = some a` for some `n` then it is constantly `some a` after that. -/ def computation (α : Type u) : Type u := { f : stream (option α) // ∀ {n a}, f n = some a → f (n+1) = some a } namespace computation variables {α : Type u} {β : Type v} {γ : Type w} -- constructors /-- `return a` is the computation that immediately terminates with result `a`. -/ def return (a : α) : computation α := ⟨stream.const (some a), λn a', id⟩ instance : has_coe_t α (computation α) := ⟨return⟩ -- note [use has_coe_t] /-- `think c` is the computation that delays for one "tick" and then performs computation `c`. -/ def think (c : computation α) : computation α := ⟨none :: c.1, λn a h, by {cases n with n, contradiction, exact c.2 h}⟩ /-- `thinkN c n` is the computation that delays for `n` ticks and then performs computation `c`. -/ def thinkN (c : computation α) : ℕ → computation α | 0 := c | (n+1) := think (thinkN n) -- check for immediate result /-- `head c` is the first step of computation, either `some a` if `c = return a` or `none` if `c = think c'`. -/ def head (c : computation α) : option α := c.1.head -- one step of computation /-- `tail c` is the remainder of computation, either `c` if `c = return a` or `c'` if `c = think c'`. -/ def tail (c : computation α) : computation α := ⟨c.1.tail, λ n a, let t := c.2 in t⟩ /-- `empty α` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (α) : computation α := ⟨stream.const none, λn a', id⟩ instance : inhabited (computation α) := ⟨empty _⟩ /-- `run_for c n` evaluates `c` for `n` steps and returns the result, or `none` if it did not terminate after `n` steps. -/ def run_for : computation α → ℕ → option α := subtype.val /-- `destruct c` is the destructor for `computation α` as a coinductive type. It returns `inl a` if `c = return a` and `inr c'` if `c = think c'`. -/ def destruct (c : computation α) : α ⊕ computation α := match c.1 0 with | none := sum.inr (tail c) | some a := sum.inl a end /-- `run c` is an unsound meta function that runs `c` to completion, possibly resulting in an infinite loop in the VM. -/ meta def run : computation α → α | c := match destruct c with | sum.inl a := a | sum.inr ca := run ca end theorem destruct_eq_ret {s : computation α} {a : α} : destruct s = sum.inl a → s = return a := begin dsimp [destruct], induction f0 : s.1 0; intro h, { contradiction }, { apply subtype.eq, funext n, induction n with n IH, { injection h with h', rwa h' at f0 }, { exact s.2 IH } } end theorem destruct_eq_think {s : computation α} {s'} : destruct s = sum.inr s' → s = think s' := begin dsimp [destruct], induction f0 : s.1 0 with a'; intro h, { injection h with h', rw ←h', cases s with f al, apply subtype.eq, dsimp [think, tail], rw ←f0, exact (stream.eta f).symm }, { contradiction } end @[simp] theorem destruct_ret (a : α) : destruct (return a) = sum.inl a := rfl @[simp] theorem destruct_think : ∀ s : computation α, destruct (think s) = sum.inr s | ⟨f, al⟩ := rfl @[simp] theorem destruct_empty : destruct (empty α) = sum.inr (empty α) := rfl @[simp] theorem head_ret (a : α) : head (return a) = some a := rfl @[simp] theorem head_think (s : computation α) : head (think s) = none := rfl @[simp] theorem head_empty : head (empty α) = none := rfl @[simp] theorem tail_ret (a : α) : tail (return a) = return a := rfl @[simp] theorem tail_think (s : computation α) : tail (think s) = s := by cases s with f al; apply subtype.eq; dsimp [tail, think]; rw [stream.tail_cons] @[simp] theorem tail_empty : tail (empty α) = empty α := rfl theorem think_empty : empty α = think (empty α) := destruct_eq_think destruct_empty def cases_on {C : computation α → Sort v} (s : computation α) (h1 : ∀ a, C (return a)) (h2 : ∀ s, C (think s)) : C s := begin induction H : destruct s with v v, { rw destruct_eq_ret H, apply h1 }, { cases v with a s', rw destruct_eq_think H, apply h2 } end def corec.F (f : β → α ⊕ β) : α ⊕ β → option α × (α ⊕ β) | (sum.inl a) := (some a, sum.inl a) | (sum.inr b) := (match f b with | sum.inl a := some a | sum.inr b' := none end, f b) /-- `corec f b` is the corecursor for `computation α` as a coinductive type. If `f b = inl a` then `corec f b = return a`, and if `f b = inl b'` then `corec f b = think (corec f b')`. -/ def corec (f : β → α ⊕ β) (b : β) : computation α := begin refine ⟨stream.corec' (corec.F f) (sum.inr b), λn a' h, _⟩, rw stream.corec'_eq, change stream.corec' (corec.F f) (corec.F f (sum.inr b)).2 n = some a', revert h, generalize : sum.inr b = o, revert o, induction n with n IH; intro o, { change (corec.F f o).1 = some a' → (corec.F f (corec.F f o).2).1 = some a', cases o with a b; intro h, { exact h }, dsimp [corec.F] at h, dsimp [corec.F], cases f b with a b', { exact h }, { contradiction } }, { rw [stream.corec'_eq (corec.F f) (corec.F f o).2, stream.corec'_eq (corec.F f) o], exact IH (corec.F f o).2 } end /-- left map of `⊕` -/ def lmap (f : α → β) : α ⊕ γ → β ⊕ γ | (sum.inl a) := sum.inl (f a) | (sum.inr b) := sum.inr b /-- right map of `⊕` -/ def rmap (f : β → γ) : α ⊕ β → α ⊕ γ | (sum.inl a) := sum.inl a | (sum.inr b) := sum.inr (f b) attribute [simp] lmap rmap @[simp] lemma corec_eq (f : β → α ⊕ β) (b : β) : destruct (corec f b) = rmap (corec f) (f b) := begin dsimp [corec, destruct], change stream.corec' (corec.F f) (sum.inr b) 0 with corec.F._match_1 (f b), induction h : f b with a b', { refl }, dsimp [corec.F, destruct], apply congr_arg, apply subtype.eq, dsimp [corec, tail], rw [stream.corec'_eq, stream.tail_cons], dsimp [corec.F], rw h end section bisim variable (R : computation α → computation α → Prop) local infix ` ~ `:50 := R def bisim_o : α ⊕ computation α → α ⊕ computation α → Prop | (sum.inl a) (sum.inl a') := a = a' | (sum.inr s) (sum.inr s') := R s s' | _ _ := false attribute [simp] bisim_o def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂) -- If two computations are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := begin apply subtype.eq, apply stream.eq_of_bisim (λx y, ∃ s s' : computation α, s.1 = x ∧ s'.1 = y ∧ R s s'), dsimp [stream.is_bisimulation], intros t₁ t₂ e, exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ := suffices head s = head s' ∧ R (tail s) (tail s'), from and.imp id (λr, ⟨tail s, tail s', by cases s; refl, by cases s'; refl, r⟩) this, begin have := bisim r, revert r this, apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this, { constructor, dsimp at this, rw this, assumption }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { rw [destruct_ret, destruct_think] at this, exact false.elim this }, { simp at this, simp [*] } end end, exact ⟨s₁, s₂, rfl, rfl, r⟩ end end bisim -- It's more of a stretch to use ∈ for this relation, but it -- asserts that the computation limits to the given value. protected def mem (a : α) (s : computation α) := some a ∈ s.1 instance : has_mem α (computation α) := ⟨computation.mem⟩ theorem le_stable (s : computation α) {a m n} (h : m ≤ n) : s.1 m = some a → s.1 n = some a := by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]} theorem mem_unique {s : computation α} {a b : α} : a ∈ s → b ∈ s → a = b | ⟨m, ha⟩ ⟨n, hb⟩ := by injection (le_stable s (le_max_left m n) ha.symm).symm.trans (le_stable s (le_max_right m n) hb.symm) theorem mem.left_unique : relator.left_unique ((∈) : α → computation α → Prop) := λ a s b, mem_unique /-- `terminates s` asserts that the computation `s` eventually terminates with some value. -/ class terminates (s : computation α) : Prop := (term : ∃ a, a ∈ s) theorem terminates_iff (s : computation α) : terminates s ↔ ∃ a, a ∈ s := ⟨λ h, h.1, terminates.mk⟩ theorem terminates_of_mem {s : computation α} {a : α} (h : a ∈ s) : terminates s := ⟨⟨a, h⟩⟩ theorem terminates_def (s : computation α) : terminates s ↔ ∃ n, (s.1 n).is_some := ⟨λ ⟨⟨a, n, h⟩⟩, ⟨n, by {dsimp [stream.nth] at h, rw ←h, exact rfl}⟩, λ ⟨n, h⟩, ⟨⟨option.get h, n, (option.eq_some_of_is_some h).symm⟩⟩⟩ theorem ret_mem (a : α) : a ∈ return a := exists.intro 0 rfl theorem eq_of_ret_mem {a a' : α} (h : a' ∈ return a) : a' = a := mem_unique h (ret_mem _) instance ret_terminates (a : α) : terminates (return a) := terminates_of_mem (ret_mem _) theorem think_mem {s : computation α} {a} : a ∈ s → a ∈ think s | ⟨n, h⟩ := ⟨n+1, h⟩ instance think_terminates (s : computation α) : ∀ [terminates s], terminates (think s) | ⟨⟨a, n, h⟩⟩ := ⟨⟨a, n+1, h⟩⟩ theorem of_think_mem {s : computation α} {a} : a ∈ think s → a ∈ s | ⟨n, h⟩ := by {cases n with n', contradiction, exact ⟨n', h⟩} theorem of_think_terminates {s : computation α} : terminates (think s) → terminates s | ⟨⟨a, h⟩⟩ := ⟨⟨a, of_think_mem h⟩⟩ theorem not_mem_empty (a : α) : a ∉ empty α := λ ⟨n, h⟩, by clear _fun_match; contradiction theorem not_terminates_empty : ¬ terminates (empty α) := λ ⟨⟨a, h⟩⟩, not_mem_empty a h theorem eq_empty_of_not_terminates {s} (H : ¬ terminates s) : s = empty α := begin apply subtype.eq, funext n, induction h : s.val n, {refl}, refine absurd _ H, exact ⟨⟨_, _, h.symm⟩⟩ end theorem thinkN_mem {s : computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s | 0 := iff.rfl | (n+1) := iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n) instance thinkN_terminates (s : computation α) : ∀ [terminates s] n, terminates (thinkN s n) | ⟨⟨a, h⟩⟩ n := ⟨⟨a, (thinkN_mem n).2 h⟩⟩ theorem of_thinkN_terminates (s : computation α) (n) : terminates (thinkN s n) → terminates s | ⟨⟨a, h⟩⟩ := ⟨⟨a, (thinkN_mem _).1 h⟩⟩ /-- `promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ def promises (s : computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a' infix ` ~> `:50 := promises theorem mem_promises {s : computation α} {a : α} : a ∈ s → s ~> a := λ h a', mem_unique h theorem empty_promises (a : α) : empty α ~> a := λ a' h, absurd h (not_mem_empty _) section get variables (s : computation α) [h : terminates s] include s h /-- `length s` gets the number of steps of a terminating computation -/ def length : ℕ := nat.find ((terminates_def _).1 h) /-- `get s` returns the result of a terminating computation -/ def get : α := option.get (nat.find_spec $ (terminates_def _).1 h) theorem get_mem : get s ∈ s := exists.intro (length s) (option.eq_some_of_is_some _).symm theorem get_eq_of_mem {a} : a ∈ s → get s = a := mem_unique (get_mem _) theorem mem_of_get_eq {a} : get s = a → a ∈ s := by intro h; rw ←h; apply get_mem @[simp] theorem get_think : get (think s) = get s := get_eq_of_mem _ $ let ⟨n, h⟩ := get_mem s in ⟨n+1, h⟩ @[simp] theorem get_thinkN (n) : get (thinkN s n) = get s := get_eq_of_mem _ $ (thinkN_mem _).2 (get_mem _) theorem get_promises : s ~> get s := λ a, get_eq_of_mem _ theorem mem_of_promises {a} (p : s ~> a) : a ∈ s := by { casesI h, cases h with a' h, rw p h, exact h } theorem get_eq_of_promises {a} : s ~> a → get s = a := get_eq_of_mem _ ∘ mem_of_promises _ end get /-- `results s a n` completely characterizes a terminating computation: it asserts that `s` terminates after exactly `n` steps, with result `a`. -/ def results (s : computation α) (a : α) (n : ℕ) := ∃ (h : a ∈ s), @length _ s (terminates_of_mem h) = n theorem results_of_terminates (s : computation α) [T : terminates s] : results s (get s) (length s) := ⟨get_mem _, rfl⟩ theorem results_of_terminates' (s : computation α) [T : terminates s] {a} (h : a ∈ s) : results s a (length s) := by rw ←get_eq_of_mem _ h; apply results_of_terminates theorem results.mem {s : computation α} {a n} : results s a n → a ∈ s | ⟨m, _⟩ := m theorem results.terminates {s : computation α} {a n} (h : results s a n) : terminates s := terminates_of_mem h.mem theorem results.length {s : computation α} {a n} [T : terminates s] : results s a n → length s = n | ⟨_, h⟩ := h theorem results.val_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : a = b := mem_unique h1.mem h2.mem theorem results.len_unique {s : computation α} {a b m n} (h1 : results s a m) (h2 : results s b n) : m = n := by haveI := h1.terminates; haveI := h2.terminates; rw [←h1.length, h2.length] theorem exists_results_of_mem {s : computation α} {a} (h : a ∈ s) : ∃ n, results s a n := by haveI := terminates_of_mem h; exact ⟨_, results_of_terminates' s h⟩ @[simp] theorem get_ret (a : α) : get (return a) = a := get_eq_of_mem _ ⟨0, rfl⟩ @[simp] theorem length_ret (a : α) : length (return a) = 0 := let h := computation.ret_terminates a in nat.eq_zero_of_le_zero $ nat.find_min' ((terminates_def (return a)).1 h) rfl theorem results_ret (a : α) : results (return a) a 0 := ⟨_, length_ret _⟩ @[simp] theorem length_think (s : computation α) [h : terminates s] : length (think s) = length s + 1 := begin apply le_antisymm, { exact nat.find_min' _ (nat.find_spec ((terminates_def _).1 h)) }, { have : (option.is_some ((think s).val (length (think s))) : Prop) := nat.find_spec ((terminates_def _).1 s.think_terminates), cases length (think s) with n, { contradiction }, { apply nat.succ_le_succ, apply nat.find_min', apply this } } end theorem results_think {s : computation α} {a n} (h : results s a n) : results (think s) a (n + 1) := by haveI := h.terminates; exact ⟨think_mem h.mem, by rw [length_think, h.length]⟩ theorem of_results_think {s : computation α} {a n} (h : results (think s) a n) : ∃ m, results s a m ∧ n = m + 1 := begin haveI := of_think_terminates h.terminates, have := results_of_terminates' _ (of_think_mem h.mem), exact ⟨_, this, results.len_unique h (results_think this)⟩, end @[simp] theorem results_think_iff {s : computation α} {a n} : results (think s) a (n + 1) ↔ results s a n := ⟨λ h, let ⟨n', r, e⟩ := of_results_think h in by injection e with h'; rwa h', results_think⟩ theorem results_thinkN {s : computation α} {a m} : ∀ n, results s a m → results (thinkN s n) a (m + n) | 0 h := h | (n+1) h := results_think (results_thinkN n h) theorem results_thinkN_ret (a : α) (n) : results (thinkN (return a) n) a n := by have := results_thinkN n (results_ret a); rwa nat.zero_add at this @[simp] theorem length_thinkN (s : computation α) [h : terminates s] (n) : length (thinkN s n) = length s + n := (results_thinkN n (results_of_terminates _)).length theorem eq_thinkN {s : computation α} {a n} (h : results s a n) : s = thinkN (return a) n := begin revert s, induction n with n IH; intro s; apply cases_on s (λ a', _) (λ s, _); intro h, { rw ←eq_of_ret_mem h.mem, refl }, { cases of_results_think h with n h, cases h, contradiction }, { have := h.len_unique (results_ret _), contradiction }, { rw IH (results_think_iff.1 h), refl } end theorem eq_thinkN' (s : computation α) [h : terminates s] : s = thinkN (return (get s)) (length s) := eq_thinkN (results_of_terminates _) def mem_rec_on {C : computation α → Sort v} {a s} (M : a ∈ s) (h1 : C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := begin haveI T := terminates_of_mem M, rw [eq_thinkN' s, get_eq_of_mem s M], generalize : length s = n, induction n with n IH, exacts [h1, h2 _ IH] end def terminates_rec_on {C : computation α → Sort v} (s) [terminates s] (h1 : ∀ a, C (return a)) (h2 : ∀ s, C s → C (think s)) : C s := mem_rec_on (get_mem s) (h1 _) h2 /-- Map a function on the result of a computation. -/ def map (f : α → β) : computation α → computation β | ⟨s, al⟩ := ⟨s.map (λo, option.cases_on o none (some ∘ f)), λn b, begin dsimp [stream.map, stream.nth], induction e : s n with a; intro h, { contradiction }, { rw [al e, ←h] } end⟩ def bind.G : β ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl b) := sum.inl b | (sum.inr cb') := sum.inr $ sum.inr cb' def bind.F (f : α → computation β) : computation α ⊕ computation β → β ⊕ computation α ⊕ computation β | (sum.inl ca) := match destruct ca with | sum.inl a := bind.G $ destruct (f a) | sum.inr ca' := sum.inr $ sum.inl ca' end | (sum.inr cb) := bind.G $ destruct cb /-- Compose two computations into a monadic `bind` operation. -/ def bind (c : computation α) (f : α → computation β) : computation β := corec (bind.F f) (sum.inl c) instance : has_bind computation := ⟨@bind⟩ theorem has_bind_eq_bind {β} (c : computation α) (f : α → computation β) : c >>= f = bind c f := rfl /-- Flatten a computation of computations into a single computation. -/ def join (c : computation (computation α)) : computation α := c >>= id @[simp] theorem map_ret (f : α → β) (a) : map f (return a) = return (f a) := rfl @[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [think, map]; rw stream.map_cons @[simp] theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) := by apply s.cases_on; intro; simp @[simp] theorem map_id : ∀ (s : computation α), map id s = s | ⟨f, al⟩ := begin apply subtype.eq; simp [map, function.comp], have e : (@option.rec α (λ_, option α) none some) = id, { ext ⟨⟩; refl }, simp [e, stream.map_id] end theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : computation α), map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw stream.map_map, apply congr_arg (λ f : _ → option γ, stream.map f s), ext ⟨⟩; refl end @[simp] theorem ret_bind (a) (f : α → computation β) : bind (return a) f = f a := begin apply eq_of_bisim (λc₁ c₂, c₁ = bind (return a) f ∧ c₂ = f a ∨ c₁ = corec (bind.F f) (sum.inr c₂)), { intros c₁ c₂ h, exact match c₁, c₂, h with | ._, ._, or.inl ⟨rfl, rfl⟩ := begin simp [bind, bind.F], cases destruct (f a) with b cb; simp [bind.G] end | ._, c, or.inr rfl := begin simp [bind.F], cases destruct c with b cb; simp [bind.G] end end }, { simp } end @[simp] theorem think_bind (c) (f : α → computation β) : bind (think c) f = think (bind c f) := destruct_eq_think $ by simp [bind, bind.F] @[simp] theorem bind_ret (f : α → β) (s) : bind s (return ∘ f) = map f s := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind s (return ∘ f) ∧ c₂ = map f s), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := begin cases destruct c with b cb; simp end | _, _, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, exact or.inr ⟨s, rfl, rfl⟩ end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end @[simp] theorem bind_ret' (s : computation α) : bind s return = s := by rw bind_ret; change (λ x : α, x) with @id α; rw map_id @[simp] theorem bind_assoc (s : computation α) (f : α → computation β) (g : β → computation γ) : bind (bind s f) g = bind s (λ (x : α), bind (f x) g) := begin apply eq_of_bisim (λc₁ c₂, c₁ = c₂ ∨ ∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s (λ (x : α), bind (f x) g)), { intros c₁ c₂ h, exact match c₁, c₂, h with | _, _, or.inl (eq.refl c) := by cases destruct c with b cb; simp | ._, ._, or.inr ⟨s, rfl, rfl⟩ := begin apply cases_on s; intros s; simp, { generalize : f s = fs, apply cases_on fs; intros t; simp, { cases destruct (g t) with b cb; simp } }, { exact or.inr ⟨s, rfl, rfl⟩ } end end }, { exact or.inr ⟨s, rfl, rfl⟩ } end theorem results_bind {s : computation α} {f : α → computation β} {a b m n} (h1 : results s a m) (h2 : results (f a) b n) : results (bind s f) b (n + m) := begin have := h1.mem, revert m, apply mem_rec_on this _ (λ s IH, _); intros m h1, { rw [ret_bind], rw h1.len_unique (results_ret _), exact h2 }, { rw [think_bind], cases of_results_think h1 with m' h, cases h with h1 e, rw e, exact results_think (IH h1) } end theorem mem_bind {s : computation α} {f : α → computation β} {a b} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f := let ⟨m, h1⟩ := exists_results_of_mem h1, ⟨n, h2⟩ := exists_results_of_mem h2 in (results_bind h1 h2).mem instance terminates_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : terminates (bind s f) := terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem get_bind (s : computation α) (f : α → computation β) [terminates s] [terminates (f (get s))] : get (bind s f) = get (f (get s)) := get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem length_bind (s : computation α) (f : α → computation β) [T1 : terminates s] [T2 : terminates (f (get s))] : length (bind s f) = length (f (get s)) + length s := (results_of_terminates _).len_unique $ results_bind (results_of_terminates _) (results_of_terminates _) theorem of_results_bind {s : computation α} {f : α → computation β} {b k} : results (bind s f) b k → ∃ a m n, results s a m ∧ results (f a) b n ∧ k = n + m := begin induction k with n IH generalizing s; apply cases_on s (λ a, _) (λ s', _); intro e, { simp [thinkN] at e, refine ⟨a, _, _, results_ret _, e, rfl⟩ }, { have := congr_arg head (eq_thinkN e), contradiction }, { simp at e, refine ⟨a, _, n+1, results_ret _, e, rfl⟩ }, { simp at e, exact let ⟨a, m, n', h1, h2, e'⟩ := IH e in by rw e'; exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ } end theorem exists_of_mem_bind {s : computation α} {f : α → computation β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨k, h⟩ := exists_results_of_mem h, ⟨a, m, n, h1, h2, e⟩ := of_results_bind h in ⟨a, h1.mem, h2.mem⟩ theorem bind_promises {s : computation α} {f : α → computation β} {a b} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b := λ b' bB, begin rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩, rw ←h1 a's at ba', exact h2 ba' end instance : monad computation := { map := @map, pure := @return, bind := @bind } instance : is_lawful_monad computation := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } theorem has_map_eq_map {β} (f : α → β) (c : computation α) : f <$> c = map f c := rfl @[simp] theorem return_def (a) : (_root_.return a : computation α) = return a := rfl @[simp] theorem map_ret' {α β} : ∀ (f : α → β) (a), f <$> return a = return (f a) := map_ret @[simp] theorem map_think' {α β} : ∀ (f : α → β) s, f <$> think s = think (f <$> s) := map_think theorem mem_map (f : α → β) {a} {s : computation α} (m : a ∈ s) : f a ∈ map f s := by rw ←bind_ret; apply mem_bind m; apply ret_mem theorem exists_of_mem_map {f : α → β} {b : β} {s : computation α} (h : b ∈ map f s) : ∃ a, a ∈ s ∧ f a = b := by rw ←bind_ret at h; exact let ⟨a, as, fb⟩ := exists_of_mem_bind h in ⟨a, as, mem_unique (ret_mem _) fb⟩ instance terminates_map (f : α → β) (s : computation α) [terminates s] : terminates (map f s) := by rw ←bind_ret; apply_instance theorem terminates_map_iff (f : α → β) (s : computation α) : terminates (map f s) ↔ terminates s := ⟨λ ⟨⟨a, h⟩⟩, let ⟨b, h1, _⟩ := exists_of_mem_map h in ⟨⟨_, h1⟩⟩, @computation.terminates_map _ _ _ _⟩ -- Parallel computation /-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning the first one that gives a result. -/ def orelse (c₁ c₂ : computation α) : computation α := @computation.corec α (computation α × computation α) (λ⟨c₁, c₂⟩, match destruct c₁ with | sum.inl a := sum.inl a | sum.inr c₁' := match destruct c₂ with | sum.inl a := sum.inl a | sum.inr c₂' := sum.inr (c₁', c₂') end end) (c₁, c₂) instance : alternative computation := { orelse := @orelse, failure := @empty, ..computation.monad } @[simp] theorem ret_orelse (a : α) (c₂ : computation α) : (return a <|> c₂) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_ret (c₁ : computation α) (a : α) : (think c₁ <|> return a) = return a := destruct_eq_ret $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem orelse_think (c₁ c₂ : computation α) : (think c₁ <|> think c₂) = think (c₁ <|> c₂) := destruct_eq_think $ by unfold has_orelse.orelse; simp [orelse] @[simp] theorem empty_orelse (c) : (empty α <|> c) = c := begin apply eq_of_bisim (λc₁ c₂, (empty α <|> c₂) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw ←think_empty, end @[simp] theorem orelse_empty (c : computation α) : (c <|> empty α) = c := begin apply eq_of_bisim (λc₁ c₂, (c₂ <|> empty α) = c₁) _ rfl, intros s' s h, rw ←h, apply cases_on s; intros s; rw think_empty; simp, rw←think_empty, end /-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result, or both loop forever. -/ def equiv (c₁ c₂ : computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂ infix ` ~ `:50 := equiv @[refl] theorem equiv.refl (s : computation α) : s ~ s := λ_, iff.rfl @[symm] theorem equiv.symm {s t : computation α} : s ~ t → t ~ s := λh a, (h a).symm @[trans] theorem equiv.trans {s t u : computation α} : s ~ t → t ~ u → s ~ u := λh1 h2 a, (h1 a).trans (h2 a) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ theorem equiv_of_mem {s t : computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t := λa', ⟨λma, by rw mem_unique ma h1; exact h2, λma, by rw mem_unique ma h2; exact h1⟩ theorem terminates_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) : terminates c₁ ↔ terminates c₂ := by simp only [terminates_iff, exists_congr h] theorem promises_congr {c₁ c₂ : computation α} (h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a := forall_congr (λa', imp_congr (h a') iff.rfl) theorem get_equiv {c₁ c₂ : computation α} (h : c₁ ~ c₂) [terminates c₁] [terminates c₂] : get c₁ = get c₂ := get_eq_of_mem _ $ (h _).2 $ get_mem _ theorem think_equiv (s : computation α) : think s ~ s := λ a, ⟨of_think_mem, think_mem⟩ theorem thinkN_equiv (s : computation α) (n) : thinkN s n ~ s := λ a, thinkN_mem n theorem bind_congr {s1 s2 : computation α} {f1 f2 : α → computation β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := λ b, ⟨λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).1 ha) ((h2 a b).1 hb), λh, let ⟨a, ha, hb⟩ := exists_of_mem_bind h in mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩ theorem equiv_ret_of_mem {s : computation α} {a} (h : a ∈ s) : s ~ return a := equiv_of_mem h (ret_mem _) /-- `lift_rel R ca cb` is a generalization of `equiv` to relations other than equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates with some `a` such that `R a b`. -/ def lift_rel (R : α → β → Prop) (ca : computation α) (cb : computation β) : Prop := (∀ {a}, a ∈ ca → ∃ {b}, b ∈ cb ∧ R a b) ∧ ∀ {b}, b ∈ cb → ∃ {a}, a ∈ ca ∧ R a b theorem lift_rel.swap (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel (swap R) cb ca ↔ lift_rel R ca cb := and_comm _ _ theorem lift_eq_iff_equiv (c₁ c₂ : computation α) : lift_rel (=) c₁ c₂ ↔ c₁ ~ c₂ := ⟨λ⟨h1, h2⟩ a, ⟨λ a1, let ⟨b, b2, ab⟩ := h1 a1 in by rwa ab, λ a2, let ⟨b, b1, ab⟩ := h2 a2 in by rwa ←ab⟩, λe, ⟨λ a a1, ⟨a, (e _).1 a1, rfl⟩, λ a a2, ⟨a, (e _).2 a2, rfl⟩⟩⟩ theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, ⟨λ a as, ⟨a, as, H a⟩, λ b bs, ⟨b, bs, H b⟩⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 ⟨l, r⟩, ⟨λ a a2, let ⟨b, b1, ab⟩ := r a2 in ⟨b, b1, H ab⟩, λ a a1, let ⟨b, b2, ab⟩ := l a1 in ⟨b, b2, H ab⟩⟩ theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s1 s2 s3 ⟨l1, r1⟩ ⟨l2, r2⟩, ⟨λ a a1, let ⟨b, b2, ab⟩ := l1 a1, ⟨c, c3, bc⟩ := l2 b2 in ⟨c, c3, H ab bc⟩, λ c c3, let ⟨b, b2, bc⟩ := r2 c3, ⟨a, a1, ab⟩ := r1 b2 in ⟨a, a1, H ab bc⟩⟩ theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ theorem lift_rel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) : lift_rel R s t → lift_rel S s t | ⟨l, r⟩ := ⟨λ a as, let ⟨b, bt, ab⟩ := l as in ⟨b, bt, H ab⟩, λ b bt, let ⟨a, as, ab⟩ := r bt in ⟨a, as, H ab⟩⟩ theorem terminates_of_lift_rel {R : α → β → Prop} {s t} : lift_rel R s t → (terminates s ↔ terminates t) | ⟨l, r⟩ := ⟨λ ⟨⟨a, as⟩⟩, let ⟨b, bt, ab⟩ := l as in ⟨⟨b, bt⟩⟩, λ ⟨⟨b, bt⟩⟩, let ⟨a, as, ab⟩ := r bt in ⟨⟨a, as⟩⟩⟩ theorem rel_of_lift_rel {R : α → β → Prop} {ca cb} : lift_rel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b | ⟨l, r⟩ a b ma mb := let ⟨b', mb', ab'⟩ := l ma in by rw mem_unique mb mb'; exact ab' theorem lift_rel_of_mem {R : α → β → Prop} {a b ca cb} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : lift_rel R ca cb := ⟨λ a' ma', by rw mem_unique ma' ma; exact ⟨b, mb, ab⟩, λ b' mb', by rw mem_unique mb' mb; exact ⟨a, ma, ab⟩⟩ theorem exists_of_lift_rel_left {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {a} (h : a ∈ ca) : ∃ {b}, b ∈ cb ∧ R a b := H.left h theorem exists_of_lift_rel_right {R : α → β → Prop} {ca cb} (H : lift_rel R ca cb) {b} (h : b ∈ cb) : ∃ {a}, a ∈ ca ∧ R a b := H.right h theorem lift_rel_def {R : α → β → Prop} {ca cb} : lift_rel R ca cb ↔ (terminates ca ↔ terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b := ⟨λh, ⟨terminates_of_lift_rel h, λ a b ma mb, let ⟨b', mb', ab⟩ := h.left ma in by rwa mem_unique mb mb'⟩, λ⟨l, r⟩, ⟨λ a ma, let ⟨⟨b, mb⟩⟩ := l.1 ⟨⟨_, ma⟩⟩ in ⟨b, mb, r ma mb⟩, λ b mb, let ⟨⟨a, ma⟩⟩ := l.2 ⟨⟨_, mb⟩⟩ in ⟨a, ma, r ma mb⟩⟩⟩ theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → computation γ} {f2 : β → computation δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := let ⟨l1, r1⟩ := h1 in ⟨λ c cB, let ⟨a, a1, c₁⟩ := exists_of_mem_bind cB, ⟨b, b2, ab⟩ := l1 a1, ⟨l2, r2⟩ := h2 ab, ⟨d, d2, cd⟩ := l2 c₁ in ⟨_, mem_bind b2 d2, cd⟩, λ d dB, let ⟨b, b1, d1⟩ := exists_of_mem_bind dB, ⟨a, a2, ab⟩ := r1 b1, ⟨l2, r2⟩ := h2 ab, ⟨c, c₂, cd⟩ := r2 d1 in ⟨_, mem_bind a2 c₂, cd⟩⟩ @[simp] theorem lift_rel_return_left (R : α → β → Prop) (a : α) (cb : computation β) : lift_rel R (return a) cb ↔ ∃ {b}, b ∈ cb ∧ R a b := ⟨λ⟨l, r⟩, l (ret_mem _), λ⟨b, mb, ab⟩, ⟨λ a' ma', by rw eq_of_ret_mem ma'; exact ⟨b, mb, ab⟩, λ b' mb', ⟨_, ret_mem _, by rw mem_unique mb' mb; exact ab⟩⟩⟩ @[simp] theorem lift_rel_return_right (R : α → β → Prop) (ca : computation α) (b : β) : lift_rel R ca (return b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [lift_rel.swap, lift_rel_return_left] @[simp] theorem lift_rel_return (R : α → β → Prop) (a : α) (b : β) : lift_rel R (return a) (return b) ↔ R a b := by rw [lift_rel_return_left]; exact ⟨λ⟨b', mb', ab'⟩, by rwa eq_of_ret_mem mb' at ab', λab, ⟨_, ret_mem _, ab⟩⟩ @[simp] theorem lift_rel_think_left (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R (think ca) cb ↔ lift_rel R ca cb := and_congr (forall_congr $ λb, imp_congr ⟨of_think_mem, think_mem⟩ iff.rfl) (forall_congr $ λb, imp_congr iff.rfl $ exists_congr $ λ b, and_congr ⟨of_think_mem, think_mem⟩ iff.rfl) @[simp] theorem lift_rel_think_right (R : α → β → Prop) (ca : computation α) (cb : computation β) : lift_rel R ca (think cb) ↔ lift_rel R ca cb := by rw [←lift_rel.swap R, ←lift_rel.swap R]; apply lift_rel_think_left theorem lift_rel_mem_cases {R : α → β → Prop} {ca cb} (Ha : ∀ a ∈ ca, lift_rel R ca cb) (Hb : ∀ b ∈ cb, lift_rel R ca cb) : lift_rel R ca cb := ⟨λ a ma, (Ha _ ma).left ma, λ b mb, (Hb _ mb).right mb⟩ theorem lift_rel_congr {R : α → β → Prop} {ca ca' : computation α} {cb cb' : computation β} (ha : ca ~ ca') (hb : cb ~ cb') : lift_rel R ca cb ↔ lift_rel R ca' cb' := and_congr (forall_congr $ λ a, imp_congr (ha _) $ exists_congr $ λ b, and_congr (hb _) iff.rfl) (forall_congr $ λ b, imp_congr (hb _) $ exists_congr $ λ a, and_congr (ha _) iff.rfl) theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : computation α} {s2 : computation β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := by rw [←bind_ret, ←bind_ret]; apply lift_rel_bind _ _ h1; simp; exact @h2 theorem map_congr (R : α → α → Prop) (S : β → β → Prop) {s1 s2 : computation α} {f : α → β} (h1 : s1 ~ s2) : map f s1 ~ map f s2 := by rw [←lift_eq_iff_equiv]; exact lift_rel_map eq _ ((lift_eq_iff_equiv _ _).2 h1) (λ a b, congr_arg _) def lift_rel_aux (R : α → β → Prop) (C : computation α → computation β → Prop) : α ⊕ computation α → β ⊕ computation β → Prop | (sum.inl a) (sum.inl b) := R a b | (sum.inl a) (sum.inr cb) := ∃ {b}, b ∈ cb ∧ R a b | (sum.inr ca) (sum.inl b) := ∃ {a}, a ∈ ca ∧ R a b | (sum.inr ca) (sum.inr cb) := C ca cb attribute [simp] lift_rel_aux @[simp] lemma lift_rel_aux.ret_left (R : α → β → Prop) (C : computation α → computation β → Prop) (a cb) : lift_rel_aux R C (sum.inl a) (destruct cb) ↔ ∃ {b}, b ∈ cb ∧ R a b := begin apply cb.cases_on (λ b, _) (λ cb, _), { exact ⟨λ h, ⟨_, ret_mem _, h⟩, λ ⟨b', mb, h⟩, by rw [mem_unique (ret_mem _) mb]; exact h⟩ }, { rw [destruct_think], exact ⟨λ ⟨b, h, r⟩, ⟨b, think_mem h, r⟩, λ ⟨b, h, r⟩, ⟨b, of_think_mem h, r⟩⟩ } end theorem lift_rel_aux.swap (R : α → β → Prop) (C) (a b) : lift_rel_aux (swap R) (swap C) b a = lift_rel_aux R C a b := by cases a with a ca; cases b with b cb; simp only [lift_rel_aux] @[simp] lemma lift_rel_aux.ret_right (R : α → β → Prop) (C : computation α → computation β → Prop) (b ca) : lift_rel_aux R C (destruct ca) (sum.inl b) ↔ ∃ {a}, a ∈ ca ∧ R a b := by rw [←lift_rel_aux.swap, lift_rel_aux.ret_left] theorem lift_rel_rec.lem {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : lift_rel R ca cb := begin revert cb, refine mem_rec_on ha _ (λ ca' IH, _); intros cb Hc; have h := H Hc, { simp at h, simp [h] }, { have h := H Hc, simp, revert h, apply cb.cases_on (λ b, _) (λ cb', _); intro h; simp at h; simp [h], exact IH _ h } end theorem lift_rel_rec {R : α → β → Prop} (C : computation α → computation β → Prop) (H : ∀ {ca cb}, C ca cb → lift_rel_aux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) : lift_rel R ca cb := lift_rel_mem_cases (lift_rel_rec.lem C @H ca cb Hc) (λ b hb, (lift_rel.swap _ _ _).2 $ lift_rel_rec.lem (swap C) (λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h) cb ca Hc b hb) end computation
86952f6b9c0a784adea4181959a8663c0c0fa50a
6de8ea38e7f58ace8fbf74ba3ad0bf3b3d1d7ab5
/homework2/Problem1/solutions.lean
2de21a5efd8e4dc733bb80db1846d0ee1c537de5
[]
no_license
KinanBab/CS591K1-Labs
72f4e2c7d230d4e4f548a343a47bf815272b1f58
d4569bf99d20c22cd56721024688cda247d1447f
refs/heads/master
1,587,016,758,873
1,558,148,366,000
1,558,148,366,000
165,329,114
5
2
null
1,550,689,848,000
1,547,252,664,000
TeX
UTF-8
Lean
false
false
1,745
lean
-- Problem 1: filtering elements of a list (30 points) -- Part A: Implement a filter (5 points) -- only keeps elements that satisfy the condition F @[simp] def filter{T} : (T -> bool) -> list T -> list T -- Implementation goes here | F l := l -- Part B: filter and boolean and (5 points) theorem filter_and (T: Type) (F1 F2: T -> bool) (l: list T) : filter (λ x, F1 x ∧ F2 x) l = filter F1 (filter F2 l) := begin -- Proof goes here -- HINT: [cases] are your friend end -- Part C: filter produces an equal or smaller array (5 points) theorem filter_len (T: Type) (F1: T -> bool) (l: list T) : list.length (filter F1 l) ≤ list.length l := begin -- Proof goes here -- HINT: check nat.add_comm, nat.add_one, and nat.le_trans and nat.succ_le_succ -- use the first three with [rewrite] and [apply] the last one when applicable end -- Part D: filter is safe (10 points) -- it does not add any elments that do not satisify the condition @[simp] def is_safe{T} : (T -> bool) -> list T -> bool | F list.nil := tt | F (list.cons h l') := (F h) && (is_safe F l') theorem filter_safe (T: Type) (F1: T -> bool) (l: list T) : is_safe F1 (filter F1 l) = tt := begin -- Proof goes here -- HINT: you will need to use cases H: (<expression>) -- instead of cases (<expression>), so that the case is added as a hypothesis with name H -- HINT: #check eq_ff_of_not_eq_tt at https://github.com/leanprover/lean/blob/master/library/init/data/bool/lemmas.lean end -- part E: correctness (5 points) -- are these properties enough to guarantee correctness? can you -- think of an example that satisfy these properties but is incorrect? -- You do not have to prove it or write it down, just give an informal arguments in comments
43484578d8bd59dd2514b353031230950df07739
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/order/monoid_lemmas.lean
629325700a6f4697104e1a6374fc6a904bedb0e8
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
43,983
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl, Damiano Testa, Yuyang Zhao -/ import algebra.covariant_and_contravariant import order.monotone /-! # Ordered monoids This file develops the basics of ordered monoids. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. ## Remark Almost no monoid is actually present in this file: most assumptions have been generalized to `has_mul` or `mul_one_class`. -/ -- TODO: If possible, uniformize lemma names, taking special care of `'`, -- after the `ordered`-refactor is done. open function variables {α β : Type*} section has_mul variables [has_mul α] section has_le variables [has_le α] /- The prime on this lemma is present only on the multiplicative version. The unprimed version is taken by the analogous lemma for semiring, with an extra non-negativity assumption. -/ @[to_additive add_le_add_left] lemma mul_le_mul_left' [covariant_class α α (*) (≤)] {b c : α} (bc : b ≤ c) (a : α) : a * b ≤ a * c := covariant_class.elim _ bc @[to_additive le_of_add_le_add_left] lemma le_of_mul_le_mul_left' [contravariant_class α α (*) (≤)] {a b c : α} (bc : a * b ≤ a * c) : b ≤ c := contravariant_class.elim _ bc /- The prime on this lemma is present only on the multiplicative version. The unprimed version is taken by the analogous lemma for semiring, with an extra non-negativity assumption. -/ @[to_additive add_le_add_right] lemma mul_le_mul_right' [covariant_class α α (swap (*)) (≤)] {b c : α} (bc : b ≤ c) (a : α) : b * a ≤ c * a := covariant_class.elim a bc @[to_additive le_of_add_le_add_right] lemma le_of_mul_le_mul_right' [contravariant_class α α (swap (*)) (≤)] {a b c : α} (bc : b * a ≤ c * a) : b ≤ c := contravariant_class.elim a bc @[simp, to_additive] lemma mul_le_mul_iff_left [covariant_class α α (*) (≤)] [contravariant_class α α (*) (≤)] (a : α) {b c : α} : a * b ≤ a * c ↔ b ≤ c := rel_iff_cov α α (*) (≤) a @[simp, to_additive] lemma mul_le_mul_iff_right [covariant_class α α (swap (*)) (≤)] [contravariant_class α α (swap (*)) (≤)] (a : α) {b c : α} : b * a ≤ c * a ↔ b ≤ c := rel_iff_cov α α (swap (*)) (≤) a end has_le section has_lt variables [has_lt α] @[simp, to_additive] lemma mul_lt_mul_iff_left [covariant_class α α (*) (<)] [contravariant_class α α (*) (<)] (a : α) {b c : α} : a * b < a * c ↔ b < c := rel_iff_cov α α (*) (<) a @[simp, to_additive] lemma mul_lt_mul_iff_right [covariant_class α α (swap (*)) (<)] [contravariant_class α α (swap (*)) (<)] (a : α) {b c : α} : b * a < c * a ↔ b < c := rel_iff_cov α α (swap (*)) (<) a @[to_additive add_lt_add_left] lemma mul_lt_mul_left' [covariant_class α α (*) (<)] {b c : α} (bc : b < c) (a : α) : a * b < a * c := covariant_class.elim _ bc @[to_additive lt_of_add_lt_add_left] lemma lt_of_mul_lt_mul_left' [contravariant_class α α (*) (<)] {a b c : α} (bc : a * b < a * c) : b < c := contravariant_class.elim _ bc @[to_additive add_lt_add_right] lemma mul_lt_mul_right' [covariant_class α α (swap (*)) (<)] {b c : α} (bc : b < c) (a : α) : b * a < c * a := covariant_class.elim a bc @[to_additive lt_of_add_lt_add_right] lemma lt_of_mul_lt_mul_right' [contravariant_class α α (swap (*)) (<)] {a b c : α} (bc : b * a < c * a) : b < c := contravariant_class.elim a bc end has_lt section preorder variables [preorder α] @[to_additive] lemma mul_lt_mul_of_lt_of_lt [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a * c < b * d := calc a * c < a * d : mul_lt_mul_left' h₂ a ... < b * d : mul_lt_mul_right' h₁ d alias add_lt_add_of_lt_of_lt ← add_lt_add @[to_additive] lemma mul_lt_mul_of_le_of_lt [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h₁ : a ≤ b) (h₂ : c < d) : a * c < b * d := (mul_le_mul_right' h₁ _).trans_lt (mul_lt_mul_left' h₂ b) @[to_additive] lemma mul_lt_mul_of_lt_of_le [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (<)] {a b c d : α} (h₁ : a < b) (h₂ : c ≤ d) : a * c < b * d := (mul_le_mul_left' h₂ _).trans_lt (mul_lt_mul_right' h₁ d) /-- Only assumes left strict covariance. -/ @[to_additive "Only assumes left strict covariance"] lemma left.mul_lt_mul [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a * c < b * d := mul_lt_mul_of_le_of_lt h₁.le h₂ /-- Only assumes right strict covariance. -/ @[to_additive "Only assumes right strict covariance"] lemma right.mul_lt_mul [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (<)] {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a * c < b * d := mul_lt_mul_of_lt_of_le h₁ h₂.le @[to_additive add_le_add] lemma mul_le_mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := (mul_le_mul_left' h₂ _).trans (mul_le_mul_right' h₁ d) @[to_additive] lemma mul_le_mul_three [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a * b * c ≤ d * e * f := mul_le_mul' (mul_le_mul' h₁ h₂) h₃ @[to_additive] lemma mul_lt_of_mul_lt_left [covariant_class α α (*) (≤)] {a b c d : α} (h : a * b < c) (hle : d ≤ b) : a * d < c := (mul_le_mul_left' hle a).trans_lt h @[to_additive] lemma mul_le_of_mul_le_left [covariant_class α α (*) (≤)] {a b c d : α} (h : a * b ≤ c) (hle : d ≤ b) : a * d ≤ c := @act_rel_of_rel_of_act_rel _ _ _ (≤) _ ⟨λ _ _ _, le_trans⟩ a _ _ _ hle h @[to_additive] lemma mul_lt_of_mul_lt_right [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h : a * b < c) (hle : d ≤ a) : d * b < c := (mul_le_mul_right' hle b).trans_lt h @[to_additive] lemma mul_le_of_mul_le_right [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h : a * b ≤ c) (hle : d ≤ a) : d * b ≤ c := (mul_le_mul_right' hle b).trans h @[to_additive] lemma lt_mul_of_lt_mul_left [covariant_class α α (*) (≤)] {a b c d : α} (h : a < b * c) (hle : c ≤ d) : a < b * d := h.trans_le (mul_le_mul_left' hle b) @[to_additive] lemma le_mul_of_le_mul_left [covariant_class α α (*) (≤)] {a b c d : α} (h : a ≤ b * c) (hle : c ≤ d) : a ≤ b * d := @rel_act_of_rel_of_rel_act _ _ _ (≤) _ ⟨λ _ _ _, le_trans⟩ b _ _ _ hle h @[to_additive] lemma lt_mul_of_lt_mul_right [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h : a < b * c) (hle : b ≤ d) : a < d * c := h.trans_le (mul_le_mul_right' hle c) @[to_additive] lemma le_mul_of_le_mul_right [covariant_class α α (swap (*)) (≤)] {a b c d : α} (h : a ≤ b * c) (hle : b ≤ d) : a ≤ d * c := h.trans (mul_le_mul_right' hle c) end preorder section partial_order variables [partial_order α] @[to_additive] lemma mul_left_cancel'' [contravariant_class α α (*) (≤)] {a b c : α} (h : a * b = a * c) : b = c := (le_of_mul_le_mul_left' h.le).antisymm (le_of_mul_le_mul_left' h.ge) @[to_additive] lemma mul_right_cancel'' [contravariant_class α α (swap (*)) (≤)] {a b c : α} (h : a * b = c * b) : a = c := le_antisymm (le_of_mul_le_mul_right' h.le) (le_of_mul_le_mul_right' h.ge) end partial_order end has_mul -- using one section mul_one_class variables [mul_one_class α] section has_le variables [has_le α] @[to_additive le_add_of_nonneg_right] lemma le_mul_of_one_le_right' [covariant_class α α (*) (≤)] {a b : α} (h : 1 ≤ b) : a ≤ a * b := calc a = a * 1 : (mul_one a).symm ... ≤ a * b : mul_le_mul_left' h a @[to_additive add_le_of_nonpos_right] lemma mul_le_of_le_one_right' [covariant_class α α (*) (≤)] {a b : α} (h : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : mul_le_mul_left' h a ... = a : mul_one a @[to_additive le_add_of_nonneg_left] lemma le_mul_of_one_le_left' [covariant_class α α (swap (*)) (≤)] {a b : α} (h : 1 ≤ b) : a ≤ b * a := calc a = 1 * a : (one_mul a).symm ... ≤ b * a : mul_le_mul_right' h a @[to_additive add_le_of_nonpos_left] lemma mul_le_of_le_one_left' [covariant_class α α (swap (*)) (≤)] {a b : α} (h : b ≤ 1) : b * a ≤ a := calc b * a ≤ 1 * a : mul_le_mul_right' h a ... = a : one_mul a @[simp, to_additive le_add_iff_nonneg_right] lemma le_mul_iff_one_le_right' [covariant_class α α (*) (≤)] [contravariant_class α α (*) (≤)] (a : α) {b : α} : a ≤ a * b ↔ 1 ≤ b := iff.trans (by rw [mul_one]) (mul_le_mul_iff_left a) @[simp, to_additive le_add_iff_nonneg_left] lemma le_mul_iff_one_le_left' [covariant_class α α (swap (*)) (≤)] [contravariant_class α α (swap (*)) (≤)] (a : α) {b : α} : a ≤ b * a ↔ 1 ≤ b := iff.trans (by rw one_mul) (mul_le_mul_iff_right a) @[simp, to_additive add_le_iff_nonpos_right] lemma mul_le_iff_le_one_right' [covariant_class α α (*) (≤)] [contravariant_class α α (*) (≤)] (a : α) {b : α} : a * b ≤ a ↔ b ≤ 1 := iff.trans (by rw [mul_one]) (mul_le_mul_iff_left a) @[simp, to_additive add_le_iff_nonpos_left] lemma mul_le_iff_le_one_left' [covariant_class α α (swap (*)) (≤)] [contravariant_class α α (swap (*)) (≤)] {a b : α} : a * b ≤ b ↔ a ≤ 1 := iff.trans (by rw one_mul) (mul_le_mul_iff_right b) end has_le section has_lt variable [has_lt α] @[to_additive lt_add_of_pos_right] lemma lt_mul_of_one_lt_right' [covariant_class α α (*) (<)] (a : α) {b : α} (h : 1 < b) : a < a * b := calc a = a * 1 : (mul_one a).symm ... < a * b : mul_lt_mul_left' h a @[to_additive add_lt_of_neg_right] lemma mul_lt_of_lt_one_right' [covariant_class α α (*) (<)] (a : α) {b : α} (h : b < 1) : a * b < a := calc a * b < a * 1 : mul_lt_mul_left' h a ... = a : mul_one a @[to_additive lt_add_of_pos_left] lemma lt_mul_of_one_lt_left' [covariant_class α α (swap (*)) (<)] (a : α) {b : α} (h : 1 < b) : a < b * a := calc a = 1 * a : (one_mul a).symm ... < b * a : mul_lt_mul_right' h a @[to_additive add_lt_of_neg_left] lemma mul_lt_of_lt_one_left' [covariant_class α α (swap (*)) (<)] (a : α) {b : α} (h : b < 1) : b * a < a := calc b * a < 1 * a : mul_lt_mul_right' h a ... = a : one_mul a @[simp, to_additive lt_add_iff_pos_right] lemma lt_mul_iff_one_lt_right' [covariant_class α α (*) (<)] [contravariant_class α α (*) (<)] (a : α) {b : α} : a < a * b ↔ 1 < b := iff.trans (by rw mul_one) (mul_lt_mul_iff_left a) @[simp, to_additive lt_add_iff_pos_left] lemma lt_mul_iff_one_lt_left' [covariant_class α α (swap (*)) (<)] [contravariant_class α α (swap (*)) (<)] (a : α) {b : α} : a < b * a ↔ 1 < b := iff.trans (by rw one_mul) (mul_lt_mul_iff_right a) @[simp, to_additive add_lt_iff_neg_left] lemma mul_lt_iff_lt_one_left' [covariant_class α α (*) (<)] [contravariant_class α α (*) (<)] {a b : α} : a * b < a ↔ b < 1 := iff.trans (by rw mul_one) (mul_lt_mul_iff_left a) @[simp, to_additive add_lt_iff_neg_right] lemma mul_lt_iff_lt_one_right' [covariant_class α α (swap (*)) (<)] [contravariant_class α α (swap (*)) (<)] {a : α} (b : α) : a * b < b ↔ a < 1 := iff.trans (by rw one_mul) (mul_lt_mul_iff_right b) end has_lt section preorder variable [preorder α] /-! Lemmas of the form `b ≤ c → a ≤ 1 → b * a ≤ c`, which assume left covariance. -/ @[to_additive] lemma mul_le_of_le_of_le_one [covariant_class α α (*) (≤)] {a b c : α} (hbc : b ≤ c) (ha : a ≤ 1) : b * a ≤ c := calc b * a ≤ b * 1 : mul_le_mul_left' ha b ... = b : mul_one b ... ≤ c : hbc @[to_additive] lemma mul_lt_of_le_of_lt_one [covariant_class α α (*) (<)] {a b c : α} (hbc : b ≤ c) (ha : a < 1) : b * a < c := calc b * a < b * 1 : mul_lt_mul_left' ha b ... = b : mul_one b ... ≤ c : hbc @[to_additive] lemma mul_lt_of_lt_of_le_one [covariant_class α α (*) (≤)] {a b c : α} (hbc : b < c) (ha : a ≤ 1) : b * a < c := calc b * a ≤ b * 1 : mul_le_mul_left' ha b ... = b : mul_one b ... < c : hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one [covariant_class α α (*) (<)] {a b c : α} (hbc : b < c) (ha : a < 1) : b * a < c := calc b * a < b * 1 : mul_lt_mul_left' ha b ... = b : mul_one b ... < c : hbc @[to_additive] lemma mul_lt_of_lt_of_lt_one' [covariant_class α α (*) (≤)] {a b c : α} (hbc : b < c) (ha : a < 1) : b * a < c := mul_lt_of_lt_of_le_one hbc ha.le /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_le_one`. -/ @[to_additive "Assumes left covariance. The lemma assuming right covariance is `right.add_nonpos`."] lemma left.mul_le_one [covariant_class α α (*) (≤)] {a b : α} (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := mul_le_of_le_of_le_one ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_lt_one_of_le_of_lt`. -/ @[to_additive left.add_neg_of_nonpos_of_neg "Assumes left covariance. The lemma assuming right covariance is `right.add_neg_of_nonpos_of_neg`."] lemma left.mul_lt_one_of_le_of_lt [covariant_class α α (*) (<)] {a b : α} (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := mul_lt_of_le_of_lt_one ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_lt_one_of_lt_of_le`. -/ @[to_additive left.add_neg_of_neg_of_nonpos "Assumes left covariance. The lemma assuming right covariance is `right.add_neg_of_neg_of_nonpos`."] lemma left.mul_lt_one_of_lt_of_le [covariant_class α α (*) (≤)] {a b : α} (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := mul_lt_of_lt_of_le_one ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_lt_one`. -/ @[to_additive "Assumes left covariance. The lemma assuming right covariance is `right.add_neg`."] lemma left.mul_lt_one [covariant_class α α (*) (<)] {a b : α} (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_of_lt_of_lt_one ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.mul_lt_one'`. -/ @[to_additive "Assumes left covariance. The lemma assuming right covariance is `right.add_neg'`."] lemma left.mul_lt_one' [covariant_class α α (*) (≤)] {a b : α} (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_of_lt_of_lt_one' ha hb /-! Lemmas of the form `b ≤ c → 1 ≤ a → b ≤ c * a`, which assume left covariance. -/ @[to_additive] lemma le_mul_of_le_of_one_le [covariant_class α α (*) (≤)] {a b c : α} (hbc : b ≤ c) (ha : 1 ≤ a) : b ≤ c * a := calc b ≤ c : hbc ... = c * 1 : (mul_one c).symm ... ≤ c * a : mul_le_mul_left' ha c @[to_additive] lemma lt_mul_of_le_of_one_lt [covariant_class α α (*) (<)] {a b c : α} (hbc : b ≤ c) (ha : 1 < a) : b < c * a := calc b ≤ c : hbc ... = c * 1 : (mul_one c).symm ... < c * a : mul_lt_mul_left' ha c @[to_additive] lemma lt_mul_of_lt_of_one_le [covariant_class α α (*) (≤)] {a b c : α} (hbc : b < c) (ha : 1 ≤ a) : b < c * a := calc b < c : hbc ... = c * 1 : (mul_one c).symm ... ≤ c * a : mul_le_mul_left' ha c @[to_additive] lemma lt_mul_of_lt_of_one_lt [covariant_class α α (*) (<)] {a b c : α} (hbc : b < c) (ha : 1 < a) : b < c * a := calc b < c : hbc ... = c * 1 : (mul_one c).symm ... < c * a : mul_lt_mul_left' ha c @[to_additive] lemma lt_mul_of_lt_of_one_lt' [covariant_class α α (*) (≤)] {a b c : α} (hbc : b < c) (ha : 1 < a) : b < c * a := lt_mul_of_lt_of_one_le hbc ha.le /-- Assumes left covariance. The lemma assuming right covariance is `right.one_le_mul`. -/ @[to_additive left.add_nonneg "Assumes left covariance. The lemma assuming right covariance is `right.add_nonneg`."] lemma left.one_le_mul [covariant_class α α (*) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_le_of_one_le ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.one_lt_mul_of_le_of_lt`. -/ @[to_additive left.add_pos_of_nonneg_of_pos "Assumes left covariance. The lemma assuming right covariance is `right.add_pos_of_nonneg_of_pos`."] lemma left.one_lt_mul_of_le_of_lt [covariant_class α α (*) (<)] {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_mul_of_le_of_one_lt ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.one_lt_mul_of_lt_of_le`. -/ @[to_additive left.add_pos_of_pos_of_nonneg "Assumes left covariance. The lemma assuming right covariance is `right.add_pos_of_pos_of_nonneg`."] lemma left.one_lt_mul_of_lt_of_le [covariant_class α α (*) (≤)] {a b : α} (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_mul_of_lt_of_one_le ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.one_lt_mul`. -/ @[to_additive left.add_pos "Assumes left covariance. The lemma assuming right covariance is `right.add_pos`."] lemma left.one_lt_mul [covariant_class α α (*) (<)] {a b : α} (ha : 1 < a) (hb : 1 < b) : 1 < a * b := lt_mul_of_lt_of_one_lt ha hb /-- Assumes left covariance. The lemma assuming right covariance is `right.one_lt_mul'`. -/ @[to_additive left.add_pos' "Assumes left covariance. The lemma assuming right covariance is `right.add_pos'`."] lemma left.one_lt_mul' [covariant_class α α (*) (≤)] {a b : α} (ha : 1 < a) (hb : 1 < b) : 1 < a * b := lt_mul_of_lt_of_one_lt' ha hb /-! Lemmas of the form `a ≤ 1 → b ≤ c → a * b ≤ c`, which assume right covariance. -/ @[to_additive] lemma mul_le_of_le_one_of_le [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : a ≤ 1) (hbc : b ≤ c) : a * b ≤ c := calc a * b ≤ 1 * b : mul_le_mul_right' ha b ... = b : one_mul b ... ≤ c : hbc @[to_additive] lemma mul_lt_of_lt_one_of_le [covariant_class α α (swap (*)) (<)] {a b c : α} (ha : a < 1) (hbc : b ≤ c) : a * b < c := calc a * b < 1 * b : mul_lt_mul_right' ha b ... = b : one_mul b ... ≤ c : hbc @[to_additive] lemma mul_lt_of_le_one_of_lt [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : a ≤ 1) (hb : b < c) : a * b < c := calc a * b ≤ 1 * b : mul_le_mul_right' ha b ... = b : one_mul b ... < c : hb @[to_additive] lemma mul_lt_of_lt_one_of_lt [covariant_class α α (swap (*)) (<)] {a b c : α} (ha : a < 1) (hb : b < c) : a * b < c := calc a * b < 1 * b : mul_lt_mul_right' ha b ... = b : one_mul b ... < c : hb @[to_additive] lemma mul_lt_of_lt_one_of_lt' [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : a < 1) (hbc : b < c) : a * b < c := mul_lt_of_le_one_of_lt ha.le hbc /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_le_one`. -/ @[to_additive "Assumes right covariance. The lemma assuming left covariance is `left.add_nonpos`."] lemma right.mul_le_one [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : a ≤ 1) (hb : b ≤ 1) : a * b ≤ 1 := mul_le_of_le_one_of_le ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_lt_one_of_lt_of_le`. -/ @[to_additive right.add_neg_of_neg_of_nonpos "Assumes right covariance. The lemma assuming left covariance is `left.add_neg_of_neg_of_nonpos`."] lemma right.mul_lt_one_of_lt_of_le [covariant_class α α (swap (*)) (<)] {a b : α} (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := mul_lt_of_lt_one_of_le ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_lt_one_of_le_of_lt`. -/ @[to_additive right.add_neg_of_nonpos_of_neg "Assumes right covariance. The lemma assuming left covariance is `left.add_neg_of_nonpos_of_neg`."] lemma right.mul_lt_one_of_le_of_lt [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : a ≤ 1) (hb : b < 1) : a * b < 1 := mul_lt_of_le_one_of_lt ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_lt_one`. -/ @[to_additive "Assumes right covariance. The lemma assuming left covariance is `left.add_neg`."] lemma right.mul_lt_one [covariant_class α α (swap (*)) (<)] {a b : α} (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_of_lt_one_of_lt ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.mul_lt_one'`. -/ @[to_additive "Assumes right covariance. The lemma assuming left covariance is `left.add_neg'`."] lemma right.mul_lt_one' [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : a < 1) (hb : b < 1) : a * b < 1 := mul_lt_of_lt_one_of_lt' ha hb /-! Lemmas of the form `1 ≤ a → b ≤ c → b ≤ a * c`, which assume right covariance. -/ @[to_additive] lemma le_mul_of_one_le_of_le [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : 1 ≤ a) (hbc : b ≤ c) : b ≤ a * c := calc b ≤ c : hbc ... = 1 * c : (one_mul c).symm ... ≤ a * c : mul_le_mul_right' ha c @[to_additive] lemma lt_mul_of_one_lt_of_le [covariant_class α α (swap (*)) (<)] {a b c : α} (ha : 1 < a) (hbc : b ≤ c) : b < a * c := calc b ≤ c : hbc ... = 1 * c : (one_mul c).symm ... < a * c : mul_lt_mul_right' ha c @[to_additive] lemma lt_mul_of_one_le_of_lt [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : 1 ≤ a) (hbc : b < c) : b < a * c := calc b < c : hbc ... = 1 * c : (one_mul c).symm ... ≤ a * c : mul_le_mul_right' ha c @[to_additive] lemma lt_mul_of_one_lt_of_lt [covariant_class α α (swap (*)) (<)] {a b c : α} (ha : 1 < a) (hbc : b < c) : b < a * c := calc b < c : hbc ... = 1 * c : (one_mul c).symm ... < a * c : mul_lt_mul_right' ha c @[to_additive] lemma lt_mul_of_one_lt_of_lt' [covariant_class α α (swap (*)) (≤)] {a b c : α} (ha : 1 < a) (hbc : b < c) : b < a * c := lt_mul_of_one_le_of_lt ha.le hbc /-- Assumes right covariance. The lemma assuming left covariance is `left.one_le_mul`. -/ @[to_additive right.add_nonneg "Assumes right covariance. The lemma assuming left covariance is `left.add_nonneg`."] lemma right.one_le_mul [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : 1 ≤ a * b := le_mul_of_one_le_of_le ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.one_lt_mul_of_lt_of_le`. -/ @[to_additive right.add_pos_of_pos_of_nonneg "Assumes right covariance. The lemma assuming left covariance is `left.add_pos_of_pos_of_nonneg`."] lemma right.one_lt_mul_of_lt_of_le [covariant_class α α (swap (*)) (<)] {a b : α} (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := lt_mul_of_one_lt_of_le ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.one_lt_mul_of_le_of_lt`. -/ @[to_additive right.add_pos_of_nonneg_of_pos "Assumes right covariance. The lemma assuming left covariance is `left.add_pos_of_nonneg_of_pos`."] lemma right.one_lt_mul_of_le_of_lt [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := lt_mul_of_one_le_of_lt ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.one_lt_mul`. -/ @[to_additive right.add_pos "Assumes right covariance. The lemma assuming left covariance is `left.add_pos`."] lemma right.one_lt_mul [covariant_class α α (swap (*)) (<)] {a b : α} (ha : 1 < a) (hb : 1 < b) : 1 < a * b := lt_mul_of_one_lt_of_lt ha hb /-- Assumes right covariance. The lemma assuming left covariance is `left.one_lt_mul'`. -/ @[to_additive right.add_pos' "Assumes right covariance. The lemma assuming left covariance is `left.add_pos'`."] lemma right.one_lt_mul' [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : 1 < a) (hb : 1 < b) : 1 < a * b := lt_mul_of_one_lt_of_lt' ha hb alias left.mul_le_one ← mul_le_one' alias left.mul_lt_one_of_le_of_lt ← mul_lt_one_of_le_of_lt alias left.mul_lt_one_of_lt_of_le ← mul_lt_one_of_lt_of_le alias left.mul_lt_one ← mul_lt_one alias left.mul_lt_one' ← mul_lt_one' attribute [to_additive add_nonpos "**Alias** of `left.add_nonpos`."] mul_le_one' attribute [to_additive add_neg_of_nonpos_of_neg "**Alias** of `left.add_neg_of_nonpos_of_neg`."] mul_lt_one_of_le_of_lt attribute [to_additive add_neg_of_neg_of_nonpos "**Alias** of `left.add_neg_of_neg_of_nonpos`."] mul_lt_one_of_lt_of_le attribute [to_additive "**Alias** of `left.add_neg`."] mul_lt_one attribute [to_additive "**Alias** of `left.add_neg'`."] mul_lt_one' alias left.one_le_mul ← one_le_mul alias left.one_lt_mul_of_le_of_lt ← one_lt_mul_of_le_of_lt' alias left.one_lt_mul_of_lt_of_le ← one_lt_mul_of_lt_of_le' alias left.one_lt_mul ← one_lt_mul' alias left.one_lt_mul' ← one_lt_mul'' attribute [to_additive add_nonneg "**Alias** of `left.add_nonneg`."] one_le_mul attribute [to_additive add_pos_of_nonneg_of_pos "**Alias** of `left.add_pos_of_nonneg_of_pos`."] one_lt_mul_of_le_of_lt' attribute [to_additive add_pos_of_pos_of_nonneg "**Alias** of `left.add_pos_of_pos_of_nonneg`."] one_lt_mul_of_lt_of_le' attribute [to_additive add_pos "**Alias** of `left.add_pos`."] one_lt_mul' attribute [to_additive add_pos' "**Alias** of `left.add_pos'`."] one_lt_mul'' @[to_additive] lemma lt_of_mul_lt_of_one_le_left [covariant_class α α (*) (≤)] {a b c : α} (h : a * b < c) (hle : 1 ≤ b) : a < c := (le_mul_of_one_le_right' hle).trans_lt h @[to_additive] lemma le_of_mul_le_of_one_le_left [covariant_class α α (*) (≤)] {a b c : α} (h : a * b ≤ c) (hle : 1 ≤ b) : a ≤ c := (le_mul_of_one_le_right' hle).trans h @[to_additive] lemma lt_of_lt_mul_of_le_one_left [covariant_class α α (*) (≤)] {a b c : α} (h : a < b * c) (hle : c ≤ 1) : a < b := h.trans_le (mul_le_of_le_one_right' hle) @[to_additive] lemma le_of_le_mul_of_le_one_left [covariant_class α α (*) (≤)] {a b c : α} (h : a ≤ b * c) (hle : c ≤ 1) : a ≤ b := h.trans (mul_le_of_le_one_right' hle) @[to_additive] lemma lt_of_mul_lt_of_one_le_right [covariant_class α α (swap (*)) (≤)] {a b c : α} (h : a * b < c) (hle : 1 ≤ a) : b < c := (le_mul_of_one_le_left' hle).trans_lt h @[to_additive] lemma le_of_mul_le_of_one_le_right [covariant_class α α (swap (*)) (≤)] {a b c : α} (h : a * b ≤ c) (hle : 1 ≤ a) : b ≤ c := (le_mul_of_one_le_left' hle).trans h @[to_additive] lemma lt_of_lt_mul_of_le_one_right [covariant_class α α (swap (*)) (≤)] {a b c : α} (h : a < b * c) (hle : b ≤ 1) : a < c := h.trans_le (mul_le_of_le_one_left' hle) @[to_additive] lemma le_of_le_mul_of_le_one_right [covariant_class α α (swap (*)) (≤)] {a b c : α} (h : a ≤ b * c) (hle : b ≤ 1) : a ≤ c := h.trans (mul_le_of_le_one_left' hle) end preorder section partial_order variables [partial_order α] @[to_additive] lemma mul_eq_one_iff' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : a * b = 1 ↔ a = 1 ∧ b = 1 := iff.intro (assume hab : a * b = 1, have a ≤ 1, from hab ▸ le_mul_of_le_of_one_le le_rfl hb, have a = 1, from le_antisymm this ha, have b ≤ 1, from hab ▸ le_mul_of_one_le_of_le ha le_rfl, have b = 1, from le_antisymm this hb, and.intro ‹a = 1› ‹b = 1›) (assume ⟨ha', hb'⟩, by rw [ha', hb', mul_one]) end partial_order section linear_order variables [linear_order α] lemma exists_square_le [covariant_class α α (*) (<)] (a : α) : ∃ (b : α), b * b ≤ a := begin by_cases h : a < 1, { use a, have : a*a < a*1, exact mul_lt_mul_left' h a, rw mul_one at this, exact le_of_lt this }, { use 1, push_neg at h, rwa mul_one } end end linear_order end mul_one_class section semigroup variables [semigroup α] section partial_order variables [partial_order α] /- This is not instance, since we want to have an instance from `left_cancel_semigroup`s to the appropriate `covariant_class`. -/ /-- A semigroup with a partial order and satisfying `left_cancel_semigroup` (i.e. `a * c < b * c → a < b`) is a `left_cancel semigroup`. -/ @[to_additive "An additive semigroup with a partial order and satisfying `left_cancel_add_semigroup` (i.e. `c + a < c + b → a < b`) is a `left_cancel add_semigroup`."] def contravariant.to_left_cancel_semigroup [contravariant_class α α (*) (≤)] : left_cancel_semigroup α := { mul_left_cancel := λ a b c, mul_left_cancel'' ..‹semigroup α› } /- This is not instance, since we want to have an instance from `right_cancel_semigroup`s to the appropriate `covariant_class`. -/ /-- A semigroup with a partial order and satisfying `right_cancel_semigroup` (i.e. `a * c < b * c → a < b`) is a `right_cancel semigroup`. -/ @[to_additive "An additive semigroup with a partial order and satisfying `right_cancel_add_semigroup` (`a + c < b + c → a < b`) is a `right_cancel add_semigroup`."] def contravariant.to_right_cancel_semigroup [contravariant_class α α (swap (*)) (≤)] : right_cancel_semigroup α := { mul_right_cancel := λ a b c, mul_right_cancel'' ..‹semigroup α› } @[to_additive] lemma left.mul_eq_mul_iff_eq_and_eq [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] [contravariant_class α α (*) (≤)] [contravariant_class α α (swap (*)) (≤)] {a b c d : α} (hac : a ≤ c) (hbd : b ≤ d) : a * b = c * d ↔ a = c ∧ b = d := begin refine ⟨λ h, _, λ h, congr_arg2 (*) h.1 h.2⟩, rcases hac.eq_or_lt with rfl | hac, { exact ⟨rfl, mul_left_cancel'' h⟩ }, rcases eq_or_lt_of_le hbd with rfl | hbd, { exact ⟨mul_right_cancel'' h, rfl⟩ }, exact ((left.mul_lt_mul hac hbd).ne h).elim, end @[to_additive] lemma right.mul_eq_mul_iff_eq_and_eq [covariant_class α α (*) (≤)] [contravariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (<)] [contravariant_class α α (swap (*)) (≤)] {a b c d : α} (hac : a ≤ c) (hbd : b ≤ d) : a * b = c * d ↔ a = c ∧ b = d := begin refine ⟨λ h, _, λ h, congr_arg2 (*) h.1 h.2⟩, rcases hac.eq_or_lt with rfl | hac, { exact ⟨rfl, mul_left_cancel'' h⟩ }, rcases eq_or_lt_of_le hbd with rfl | hbd, { exact ⟨mul_right_cancel'' h, rfl⟩ }, exact ((right.mul_lt_mul hac hbd).ne h).elim, end alias left.mul_eq_mul_iff_eq_and_eq ← mul_eq_mul_iff_eq_and_eq attribute [to_additive] mul_eq_mul_iff_eq_and_eq end partial_order end semigroup section mono variables [has_mul α] [preorder α] [preorder β] {f g : β → α} {s : set β} @[to_additive const_add] lemma monotone.const_mul' [covariant_class α α (*) (≤)] (hf : monotone f) (a : α) : monotone (λ x, a * f x) := λ x y h, mul_le_mul_left' (hf h) a @[to_additive const_add] lemma monotone_on.const_mul' [covariant_class α α (*) (≤)] (hf : monotone_on f s) (a : α) : monotone_on (λ x, a * f x) s := λ x hx y hy h, mul_le_mul_left' (hf hx hy h) a @[to_additive const_add] lemma antitone.const_mul' [covariant_class α α (*) (≤)] (hf : antitone f) (a : α) : antitone (λ x, a * f x) := λ x y h, mul_le_mul_left' (hf h) a @[to_additive const_add] lemma antitone_on.const_mul' [covariant_class α α (*) (≤)] (hf : antitone_on f s) (a : α) : antitone_on (λ x, a * f x) s := λ x hx y hy h, mul_le_mul_left' (hf hx hy h) a @[to_additive add_const] lemma monotone.mul_const' [covariant_class α α (swap (*)) (≤)] (hf : monotone f) (a : α) : monotone (λ x, f x * a) := λ x y h, mul_le_mul_right' (hf h) a @[to_additive add_const] lemma monotone_on.mul_const' [covariant_class α α (swap (*)) (≤)] (hf : monotone_on f s) (a : α) : monotone_on (λ x, f x * a) s := λ x hx y hy h, mul_le_mul_right' (hf hx hy h) a @[to_additive add_const] lemma antitone.mul_const' [covariant_class α α (swap (*)) (≤)] (hf : antitone f) (a : α) : antitone (λ x, f x * a) := λ x y h, mul_le_mul_right' (hf h) a @[to_additive add_const] lemma antitone_on.mul_const' [covariant_class α α (swap (*)) (≤)] (hf : antitone_on f s) (a : α) : antitone_on (λ x, f x * a) s := λ x hx y hy h, mul_le_mul_right' (hf hx hy h) a /-- The product of two monotone functions is monotone. -/ @[to_additive add "The sum of two monotone functions is monotone."] lemma monotone.mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (hf : monotone f) (hg : monotone g) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) /-- The product of two monotone functions is monotone. -/ @[to_additive add "The sum of two monotone functions is monotone."] lemma monotone_on.mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x * g x) s := λ x hx y hy h, mul_le_mul' (hf hx hy h) (hg hx hy h) /-- The product of two antitone functions is antitone. -/ @[to_additive add "The sum of two antitone functions is antitone."] lemma antitone.mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (hf : antitone f) (hg : antitone g) : antitone (λ x, f x * g x) := λ x y h, mul_le_mul' (hf h) (hg h) /-- The product of two antitone functions is antitone. -/ @[to_additive add "The sum of two antitone functions is antitone."] lemma antitone_on.mul' [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x * g x) s := λ x hx y hy h, mul_le_mul' (hf hx hy h) (hg hx hy h) section left variables [covariant_class α α (*) (<)] @[to_additive const_add] lemma strict_mono.const_mul' (hf : strict_mono f) (c : α) : strict_mono (λ x, c * f x) := λ a b ab, mul_lt_mul_left' (hf ab) c @[to_additive const_add] lemma strict_mono_on.const_mul' (hf : strict_mono_on f s) (c : α) : strict_mono_on (λ x, c * f x) s := λ a ha b hb ab, mul_lt_mul_left' (hf ha hb ab) c @[to_additive const_add] lemma strict_anti.const_mul' (hf : strict_anti f) (c : α) : strict_anti (λ x, c * f x) := λ a b ab, mul_lt_mul_left' (hf ab) c @[to_additive const_add] lemma strict_anti_on.const_mul' (hf : strict_anti_on f s) (c : α) : strict_anti_on (λ x, c * f x) s := λ a ha b hb ab, mul_lt_mul_left' (hf ha hb ab) c end left section right variables [covariant_class α α (swap (*)) (<)] @[to_additive add_const] lemma strict_mono.mul_const' (hf : strict_mono f) (c : α) : strict_mono (λ x, f x * c) := λ a b ab, mul_lt_mul_right' (hf ab) c @[to_additive add_const] lemma strict_mono_on.mul_const' (hf : strict_mono_on f s) (c : α) : strict_mono_on (λ x, f x * c) s := λ a ha b hb ab, mul_lt_mul_right' (hf ha hb ab) c @[to_additive add_const] lemma strict_anti.mul_const' (hf : strict_anti f) (c : α) : strict_anti (λ x, f x * c) := λ a b ab, mul_lt_mul_right' (hf ab) c @[to_additive add_const] lemma strict_anti_on.mul_const' (hf : strict_anti_on f s) (c : α) : strict_anti_on (λ x, f x * c) s := λ a ha b hb ab, mul_lt_mul_right' (hf ha hb ab) c end right /-- The product of two strictly monotone functions is strictly monotone. -/ @[to_additive add "The sum of two strictly monotone functions is strictly monotone."] lemma strict_mono.mul' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] (hf : strict_mono f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ a b ab, mul_lt_mul_of_lt_of_lt (hf ab) (hg ab) /-- The product of two strictly monotone functions is strictly monotone. -/ @[to_additive add "The sum of two strictly monotone functions is strictly monotone."] lemma strict_mono_on.mul' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] (hf : strict_mono_on f s) (hg : strict_mono_on g s) : strict_mono_on (λ x, f x * g x) s := λ a ha b hb ab, mul_lt_mul_of_lt_of_lt (hf ha hb ab) (hg ha hb ab) /-- The product of two strictly antitone functions is strictly antitone. -/ @[to_additive add "The sum of two strictly antitone functions is strictly antitone."] lemma strict_anti.mul' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] (hf : strict_anti f) (hg : strict_anti g) : strict_anti (λ x, f x * g x) := λ a b ab, mul_lt_mul_of_lt_of_lt (hf ab) (hg ab) /-- The product of two strictly antitone functions is strictly antitone. -/ @[to_additive add "The sum of two strictly antitone functions is strictly antitone."] lemma strict_anti_on.mul' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] (hf : strict_anti_on f s) (hg : strict_anti_on g s) : strict_anti_on (λ x, f x * g x) s := λ a ha b hb ab, mul_lt_mul_of_lt_of_lt (hf ha hb ab) (hg ha hb ab) /-- The product of a monotone function and a strictly monotone function is strictly monotone. -/ @[to_additive add_strict_mono "The sum of a monotone function and a strictly monotone function is strictly monotone."] lemma monotone.mul_strict_mono' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {f g : β → α} (hf : monotone f) (hg : strict_mono g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf h.le) (hg h) /-- The product of a monotone function and a strictly monotone function is strictly monotone. -/ @[to_additive add_strict_mono "The sum of a monotone function and a strictly monotone function is strictly monotone."] lemma monotone_on.mul_strict_mono' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {f g : β → α} (hf : monotone_on f s) (hg : strict_mono_on g s) : strict_mono_on (λ x, f x * g x) s := λ x hx y hy h, mul_lt_mul_of_le_of_lt (hf hx hy h.le) (hg hx hy h) /-- The product of a antitone function and a strictly antitone function is strictly antitone. -/ @[to_additive add_strict_anti "The sum of a antitone function and a strictly antitone function is strictly antitone."] lemma antitone.mul_strict_anti' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {f g : β → α} (hf : antitone f) (hg : strict_anti g) : strict_anti (λ x, f x * g x) := λ x y h, mul_lt_mul_of_le_of_lt (hf h.le) (hg h) /-- The product of a antitone function and a strictly antitone function is strictly antitone. -/ @[to_additive add_strict_anti "The sum of a antitone function and a strictly antitone function is strictly antitone."] lemma antitone_on.mul_strict_anti' [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (≤)] {f g : β → α} (hf : antitone_on f s) (hg : strict_anti_on g s) : strict_anti_on (λ x, f x * g x) s := λ x hx y hy h, mul_lt_mul_of_le_of_lt (hf hx hy h.le) (hg hx hy h) variables [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (<)] /-- The product of a strictly monotone function and a monotone function is strictly monotone. -/ @[to_additive add_monotone "The sum of a strictly monotone function and a monotone function is strictly monotone."] lemma strict_mono.mul_monotone' (hf : strict_mono f) (hg : monotone g) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg h.le) /-- The product of a strictly monotone function and a monotone function is strictly monotone. -/ @[to_additive add_monotone "The sum of a strictly monotone function and a monotone function is strictly monotone."] lemma strict_mono_on.mul_monotone' (hf : strict_mono_on f s) (hg : monotone_on g s) : strict_mono_on (λ x, f x * g x) s := λ x hx y hy h, mul_lt_mul_of_lt_of_le (hf hx hy h) (hg hx hy h.le) /-- The product of a strictly antitone function and a antitone function is strictly antitone. -/ @[to_additive add_antitone "The sum of a strictly antitone function and a antitone function is strictly antitone."] lemma strict_anti.mul_antitone' (hf : strict_anti f) (hg : antitone g) : strict_anti (λ x, f x * g x) := λ x y h, mul_lt_mul_of_lt_of_le (hf h) (hg h.le) /-- The product of a strictly antitone function and a antitone function is strictly antitone. -/ @[to_additive add_antitone "The sum of a strictly antitone function and a antitone function is strictly antitone."] lemma strict_anti_on.mul_antitone' (hf : strict_anti_on f s) (hg : antitone_on g s) : strict_anti_on (λ x, f x * g x) s := λ x hx y hy h, mul_lt_mul_of_lt_of_le (hf hx hy h) (hg hx hy h.le) end mono /-- An element `a : α` is `mul_le_cancellable` if `x ↦ a * x` is order-reflecting. We will make a separate version of many lemmas that require `[contravariant_class α α (*) (≤)]` with `mul_le_cancellable` assumptions instead. These lemmas can then be instantiated to specific types, like `ennreal`, where we can replace the assumption `add_le_cancellable x` by `x ≠ ∞`. -/ @[to_additive /-" An element `a : α` is `add_le_cancellable` if `x ↦ a + x` is order-reflecting. We will make a separate version of many lemmas that require `[contravariant_class α α (+) (≤)]` with `mul_le_cancellable` assumptions instead. These lemmas can then be instantiated to specific types, like `ennreal`, where we can replace the assumption `add_le_cancellable x` by `x ≠ ∞`. "-/ ] def mul_le_cancellable [has_mul α] [has_le α] (a : α) : Prop := ∀ ⦃b c⦄, a * b ≤ a * c → b ≤ c @[to_additive] lemma contravariant.mul_le_cancellable [has_mul α] [has_le α] [contravariant_class α α (*) (≤)] {a : α} : mul_le_cancellable a := λ b c, le_of_mul_le_mul_left' @[to_additive] lemma mul_le_cancellable_one [monoid α] [has_le α] : mul_le_cancellable (1 : α) := λ a b, by simpa only [one_mul] using id namespace mul_le_cancellable @[to_additive] protected lemma injective [has_mul α] [partial_order α] {a : α} (ha : mul_le_cancellable a) : injective ((*) a) := λ b c h, le_antisymm (ha h.le) (ha h.ge) @[to_additive] protected lemma inj [has_mul α] [partial_order α] {a b c : α} (ha : mul_le_cancellable a) : a * b = a * c ↔ b = c := ha.injective.eq_iff @[to_additive] protected lemma injective_left [comm_semigroup α] [partial_order α] {a : α} (ha : mul_le_cancellable a) : injective (* a) := λ b c h, ha.injective $ by rwa [mul_comm a, mul_comm a] @[to_additive] protected lemma inj_left [comm_semigroup α] [partial_order α] {a b c : α} (hc : mul_le_cancellable c) : a * c = b * c ↔ a = b := hc.injective_left.eq_iff variable [has_le α] @[to_additive] protected lemma mul_le_mul_iff_left [has_mul α] [covariant_class α α (*) (≤)] {a b c : α} (ha : mul_le_cancellable a) : a * b ≤ a * c ↔ b ≤ c := ⟨λ h, ha h, λ h, mul_le_mul_left' h a⟩ @[to_additive] protected lemma mul_le_mul_iff_right [comm_semigroup α] [covariant_class α α (*) (≤)] {a b c : α} (ha : mul_le_cancellable a) : b * a ≤ c * a ↔ b ≤ c := by rw [mul_comm b, mul_comm c, ha.mul_le_mul_iff_left] @[to_additive] protected lemma le_mul_iff_one_le_right [mul_one_class α] [covariant_class α α (*) (≤)] {a b : α} (ha : mul_le_cancellable a) : a ≤ a * b ↔ 1 ≤ b := iff.trans (by rw [mul_one]) ha.mul_le_mul_iff_left @[to_additive] protected lemma mul_le_iff_le_one_right [mul_one_class α] [covariant_class α α (*) (≤)] {a b : α} (ha : mul_le_cancellable a) : a * b ≤ a ↔ b ≤ 1 := iff.trans (by rw [mul_one]) ha.mul_le_mul_iff_left @[to_additive] protected lemma le_mul_iff_one_le_left [comm_monoid α] [covariant_class α α (*) (≤)] {a b : α} (ha : mul_le_cancellable a) : a ≤ b * a ↔ 1 ≤ b := by rw [mul_comm, ha.le_mul_iff_one_le_right] @[to_additive] protected lemma mul_le_iff_le_one_left [comm_monoid α] [covariant_class α α (*) (≤)] {a b : α} (ha : mul_le_cancellable a) : b * a ≤ a ↔ b ≤ 1 := by rw [mul_comm, ha.mul_le_iff_le_one_right] end mul_le_cancellable
b2de1981bad961875063d2c8cc4f628635a394b0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/apply.lean
56f20c3d5a5f0daef3692647a53d3fda4de3f679
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,907
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.core /-! This file provides an alternative implementation for `apply` to fix the so-called "apply bug". The issue arises when the goals is a Π-type -- whether it is visible or hidden behind a definition. For instance, consider the following proof: ``` example {α β} (x y z : α → β) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := begin apply le_trans, end ``` Because `x ≤ z` is definitionally equal to `∀ i, x i ≤ z i`, `apply` will fail. The alternative definition, `apply'` fixes this. When `apply` would work, `apply` is used and otherwise, a different strategy is deployed -/ namespace tactic /-- With `gs` a list of proof goals, `reorder_goals gs new_g` will use the `new_goals` policy `new_g` to rearrange the dependent goals to either drop them, push them to the end of the list or leave them in place. The `bool` values in `gs` indicates whether the goal is dependent or not. -/ def reorder_goals {α} (gs : list (bool × α)) : new_goals → list α | new_goals.non_dep_first := let ⟨dep,non_dep⟩ := gs.partition (coe ∘ prod.fst) in non_dep.map prod.snd ++ dep.map prod.snd | new_goals.non_dep_only := (gs.filter (coe ∘ bnot ∘ prod.fst)).map prod.snd | new_goals.all := gs.map prod.snd private meta def has_opt_auto_param_inst_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, b ← is_class type, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2 || b) ff private meta def try_apply_opt_auto_param_instance_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_inst_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> try apply_instance >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs private meta def retry_apply_aux : Π (e : expr) (cfg : apply_cfg), list (bool × name × expr) → tactic (list (name × expr)) | e cfg gs := focus1 (do { tgt : expr ← target, t ← infer_type e, unify t tgt, exact e, gs' ← get_goals, let r := reorder_goals gs.reverse cfg.new_goals, set_goals (gs' ++ r.map prod.snd), return r }) <|> do (expr.pi n bi d b) ← infer_type e >>= whnf | apply_core e cfg, v ← mk_meta_var d, let b := b.has_var, e ← head_beta $ e v, retry_apply_aux e cfg ((b, n, v) :: gs) private meta def retry_apply (e : expr) (cfg : apply_cfg) : tactic (list (name × expr)) := apply_core e cfg <|> retry_apply_aux e cfg [] /-- `apply'` mimics the behavior of `apply_core`. When `apply_core` fails, it is retried by providing the term with meta variables as additional arguments. The meta variables can then become new goals depending on the `cfg.new_goals` policy. `apply'` also finds instances and applies opt_params and auto_params. -/ meta def apply' (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← retry_apply e cfg, try_apply_opt_auto_param_instance_for_apply cfg r, return r /-- Same as `apply'` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply' (e : expr) : tactic (list (name × expr)) := apply' e {new_goals := new_goals.all} /-- Same as `apply'` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply' (e : expr) : tactic (list (name × expr)) := apply' e {new_goals := new_goals.non_dep_only} /-- `relation_tactic` finds a proof rule for the relation found in the goal and uses `apply'` to make one proof step. -/ private meta def relation_tactic (md : transparency) (op_for : environment → name → option name) (tac_name : string) : tactic unit := do tgt ← target >>= instantiate_mvars, env ← get_env, let r := expr.get_app_fn tgt, match op_for env (expr.const_name r) with | (some refl) := do r ← mk_const refl, retry_apply r {md := md, new_goals := new_goals.non_dep_only }, return () | none := fail $ tac_name ++ " tactic failed, target is not a relation application with the expected property." end /-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply` -/ meta def reflexivity' (md := semireducible) : tactic unit := relation_tactic md environment.refl_for "reflexivity" /-- Similar to `symmetry` with the difference that `apply'` is used instead of `apply` -/ meta def symmetry' (md := semireducible) : tactic unit := relation_tactic md environment.symm_for "symmetry" /-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply` -/ meta def transitivity' (md := semireducible) : tactic unit := relation_tactic md environment.trans_for "transitivity" namespace interactive setup_tactic_parser /-- Similarly to `apply`, the `apply'` tactic tries to match the current goal against the conclusion of the type of term. It differs from `apply` in that it does not unfold definition in order to find out what the assumptions of the provided term is. It is especially useful when defining relations on function spaces (e.g. `≤`) so that rules like transitivity on `le : (α → β) → (α → β) → (α → β)` will be considered to have three parameters and two assumptions (i.e. `f g h : α → β`, `H₀ : f ≤ g`, `H₁ : g ≤ h`) instead of three parameters, two assumptions and then one more parameter (i.e. `f g h : α → β`, `H₀ : f ≤ g`, `H₁ : g ≤ h`, `x : α`). Whereas `apply` would expect the goal `f x ≤ h x`, `apply'` will work with the goal `f ≤ h`. -/ meta def apply' (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply' h) /-- Similar to the `apply'` tactic, but does not reorder goals. -/ meta def fapply' (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.fapply') /-- Similar to the `apply'` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply' (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.eapply') /-- Similar to the `apply'` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with' (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e cfg) /-- Similar to the `apply'` tactic, but uses matching instead of unification. `mapply' t` is equivalent to `apply_with' t {unify := ff}` -/ meta def mapply' (q : parse texpr) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e {unify := ff}) /-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply`. -/ meta def reflexivity' : tactic unit := tactic.reflexivity' /-- Shorter name for the tactic `reflexivity'`. -/ meta def refl' : tactic unit := tactic.reflexivity' /-- `symmetry'` behaves like `symmetry` but also offers the option `symmetry' at h` to apply symmetry to assumption `h` -/ meta def symmetry' : parse location → tactic unit | l@loc.wildcard := l.try_apply symmetry_hyp tactic.symmetry' | (loc.ns hs) := (loc.ns hs.reverse).apply symmetry_hyp tactic.symmetry' /-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply`. -/ meta def transitivity' (q : parse texpr?) : tactic unit := tactic.transitivity' >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, t ← infer_type lhs, i_to_expr ``(%%q : %%t) >>= unify rhs end end interactive end tactic
381267bb6ad895692cb05c10567bc6e7ad1db0a2
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/ctxopt.lean
04e4c6d7b657c3dfe753fd2662b8cbc249757d09
[ "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
78
lean
-- section set_option pp.implicit true check id true end check id true
04fc5c31adcffbdd59ed43eccc19503e31eebcec
1437b3495ef9020d5413178aa33c0a625f15f15f
/algebra/pi_instances.lean
d3dcd600b31e3907b19fec4d91b619edc7f61e53
[ "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
16,728
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot Pi instances for algebraic structures. -/ import order.basic import algebra.module algebra.group import data.finset import tactic.pi_instances namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equiped with instances variables (x y : Π i, f i) (i : I) instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩ @[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩ @[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl attribute [to_additive pi.has_zero] pi.has_one attribute [to_additive pi.zero_apply] pi.one_apply instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩ @[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩ @[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl attribute [to_additive pi.has_add] pi.has_mul attribute [to_additive pi.add_apply] pi.mul_apply instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩ @[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩ @[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl attribute [to_additive pi.has_neg] pi.has_inv attribute [to_additive pi.neg_apply] pi.inv_apply instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) := by pi_instance instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule α} instance vector_space (α) {r : discrete_field α} [∀ i, add_comm_group $ f i] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) := {..pi.module α} instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) := by pi_instance instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) := by pi_instance instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) := by pi_instance attribute [to_additive pi.add_semigroup] pi.semigroup attribute [to_additive pi.add_comm_semigroup] pi.comm_semigroup attribute [to_additive pi.add_monoid] pi.monoid attribute [to_additive pi.add_comm_monoid] pi.comm_monoid attribute [to_additive pi.add_group] pi.group attribute [to_additive pi.add_comm_group] pi.comm_group attribute [to_additive pi.add_left_cancel_semigroup] pi.left_cancel_semigroup attribute [to_additive pi.add_right_cancel_semigroup] pi.right_cancel_semigroup @[to_additive pi.list_sum_apply] lemma list_prod_apply {α : Type*} {β} [monoid β] (a : α) : ∀ (l : list (α → β)), l.prod a = (l.map (λf:α → β, f a)).prod | [] := rfl | (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l] @[to_additive pi.multiset_sum_apply] lemma multiset_prod_apply {α : Type*} {β} [comm_monoid β] (a : α) (s : multiset (α → β)) : s.prod a = (s.map (λf:α → β, f a)).prod := quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end @[to_additive pi.finset_sum_apply] lemma finset_prod_apply {α : Type*} {β γ} [comm_monoid β] (a : α) (s : finset γ) (g : γ → α → β) : s.prod g a = s.prod (λc, g c a) := show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod, by rw [multiset_prod_apply, multiset.map_map] def is_ring_hom_pi {α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)] {γ : Type w} [ring γ] (f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] : is_ring_hom (λ x b, f b x) := begin dsimp at *, split, -- It's a pity that these can't be done using `simp` lemmas. { ext, rw [is_ring_hom.map_one (f x)], refl, }, { intros x y, ext1 z, rw [is_ring_hom.map_mul (f z)], refl, }, { intros x y, ext1 z, rw [is_ring_hom.map_add (f z)], refl, } end end pi namespace prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β} instance [has_add α] [has_add β] : has_add (α × β) := ⟨λp q, (p.1 + q.1, p.2 + q.2)⟩ @[to_additive prod.has_add] instance [has_mul α] [has_mul β] : has_mul (α × β) := ⟨λp q, (p.1 * q.1, p.2 * q.2)⟩ @[simp, to_additive prod.fst_add] lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive prod.snd_add] lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive prod.mk_add_mk] lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩ @[to_additive prod.has_zero] instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩ @[simp, to_additive prod.fst_zero] lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl @[simp, to_additive prod.snd_zero] lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl @[to_additive prod.zero_eq_mk] lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩ @[to_additive prod.has_neg] instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive prod.fst_neg] lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive prod.snd_neg] lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl @[to_additive prod.neg_mk] lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) := { add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩, .. prod.has_add } @[to_additive prod.add_semigroup] instance [semigroup α] [semigroup β] : semigroup (α × β) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } instance [add_monoid α] [add_monoid β] : add_monoid (α × β) := { zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩, add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩, .. prod.add_semigroup, .. prod.has_zero } @[to_additive prod.add_monoid] instance [monoid α] [monoid β] : monoid (α × β) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.semigroup, .. prod.has_one } instance [add_group α] [add_group β] : add_group (α × β) := { add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩, .. prod.add_monoid, .. prod.has_neg } @[to_additive prod.add_group] instance [group α] [group β] : group (α × β) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, .. prod.monoid, .. prod.has_inv } instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) := { add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩, .. prod.add_semigroup } @[to_additive prod.add_comm_semigroup] instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) := { .. prod.add_comm_semigroup, .. prod.add_monoid } @[to_additive prod.add_comm_monoid] instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) := { .. prod.comm_semigroup, .. prod.monoid } instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) := { .. prod.add_comm_semigroup, .. prod.add_group } @[to_additive prod.add_comm_group] instance [comm_group α] [comm_group β] : comm_group (α × β) := { .. prod.comm_semigroup, .. prod.group } @[to_additive fst.is_add_monoid_hom] lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) := by refine_struct {..}; simp @[to_additive snd.is_add_monoid_hom] lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) := by refine_struct {..}; simp @[to_additive fst.is_add_group_hom] lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) := by refine_struct {..}; simp @[to_additive snd.is_add_group_hom] lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) := by refine_struct {..}; simp attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom @[to_additive prod.fst_sum] lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).1 = t.prod (λc, (f c).1) := (finset.prod_hom prod.fst).symm @[to_additive prod.snd_sum] lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).2 = t.prod (λc, (f c).2) := (finset.prod_hom prod.snd).symm instance [semiring α] [semiring β] : semiring (α × β) := { zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩, right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩, ..prod.add_comm_monoid, ..prod.monoid } instance [ring α] [ring β] : ring (α × β) := { ..prod.add_comm_group, ..prod.semiring } instance [comm_ring α] [comm_ring β] : comm_ring (α × β) := { ..prod.ring, ..prod.comm_monoid } instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) := { zero_ne_one := mt (congr_arg prod.fst) zero_ne_one, ..prod.comm_ring } instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) := by refine_struct {..}; simp instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) := by refine_struct {..}; simp instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) := by refine_struct {..}; simp instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) := by refine_struct {..}; simp /-- Left injection function for the inner product From a vector space (and also group and module) perspective the product is the same as the sum of two vector spaces. `inl` and `inr` provide the corresponding injection functions. -/ def inl [has_zero β] (a : α) : α × β := (a, 0) /-- Right injection function for the inner product -/ def inr [has_zero α] (b : β) : α × β := (0, b) lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) := assume x y h, (prod.mk.inj_iff.mp h).1 lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) := assume x y h, (prod.mk.inj_iff.mp h).2 @[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ := iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl) @[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ := iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl) @[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} : inl a = inr b ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} : inr b = inl a ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl @[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl @[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl @[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl @[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl @[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ] (a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ] [semimodule α β] [semimodule α γ] : semimodule α (β × γ) := { smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _, one_smul _⟩, zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _, zero_smul _⟩, smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩, .. prod.has_scalar } instance {r : ring α} [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] : module α (β × γ) := {} instance {r : discrete_field α} [add_comm_group β] [add_comm_group γ] [vector_space α β] [vector_space α γ] : vector_space α (β × γ) := {} end prod namespace finset @[to_additive finset.prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) end finset
23592fd8c14297588013d42064b31fd3d219b276
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/774.lean
92518303c2a1a2df1577f2577a29d6d5deb2bee2
[ "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
162
lean
open nat example : ℕ → ℕ → Prop | 0 0 := true | (succ n) 0 := false | 0 (succ m) := false | (succ n) (succ m) := _example n m
8be6ddf168f4957759b0115fb41ebbf039687dd1
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/algebra/lie/skew_adjoint.lean
c70743c3e33975739f191ec03b63cbedaca7e46d
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,509
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.basic import linear_algebra.bilinear_form /-! # Lie algebras of skew-adjoint endomorphisms of a bilinear form ## Tags lie algebra, skew-adjoint, bilinear form -/ universes u v w w₁ section skew_adjoint_endomorphisms open bilin_form variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables (B : bilin_form R M) lemma bilin_form.is_skew_adjoint_bracket (f g : module.End R M) (hf : f ∈ B.skew_adjoint_submodule) (hg : g ∈ B.skew_adjoint_submodule) : ⁅f, g⁆ ∈ B.skew_adjoint_submodule := begin rw mem_skew_adjoint_submodule at *, have hfg : is_adjoint_pair B B (f * g) (g * f), { rw ←neg_mul_neg g f, exact hf.mul hg, }, have hgf : is_adjoint_pair B B (g * f) (f * g), { rw ←neg_mul_neg f g, exact hg.mul hf, }, change bilin_form.is_adjoint_pair B B (f * g - g * f) (-(f * g - g * f)), rw neg_sub, exact hfg.sub hgf, end /-- Given an `R`-module `M`, equipped with a bilinear form, the skew-adjoint endomorphisms form a Lie subalgebra of the Lie algebra of endomorphisms. -/ def skew_adjoint_lie_subalgebra : lie_subalgebra R (module.End R M) := { lie_mem' := B.is_skew_adjoint_bracket, ..B.skew_adjoint_submodule } variables {N : Type w} [add_comm_group N] [module R N] (e : N ≃ₗ[R] M) /-- An equivalence of modules with bilinear forms gives equivalence of Lie algebras of skew-adjoint endomorphisms. -/ def skew_adjoint_lie_subalgebra_equiv : skew_adjoint_lie_subalgebra (B.comp (↑e : N →ₗ[R] M) ↑e) ≃ₗ⁅R⁆ skew_adjoint_lie_subalgebra B := begin apply lie_algebra.equiv.of_subalgebras _ _ e.lie_conj, ext f, simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact (bilin_form.is_pair_self_adjoint_equiv (-B) B e f).symm, end @[simp] lemma skew_adjoint_lie_subalgebra_equiv_apply (f : skew_adjoint_lie_subalgebra (B.comp ↑e ↑e)) : ↑(skew_adjoint_lie_subalgebra_equiv B e f) = e.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] @[simp] lemma skew_adjoint_lie_subalgebra_equiv_symm_apply (f : skew_adjoint_lie_subalgebra B) : ↑((skew_adjoint_lie_subalgebra_equiv B e).symm f) = e.symm.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] end skew_adjoint_endomorphisms section skew_adjoint_matrices open_locale matrix variables {R : Type u} {n : Type w} [comm_ring R] [decidable_eq n] [fintype n] variables (J : matrix n n R) lemma matrix.lie_transpose (A B : matrix n n R) : ⁅A, B⁆ᵀ = ⁅Bᵀ, Aᵀ⁆ := show (A * B - B * A)ᵀ = (Bᵀ * Aᵀ - Aᵀ * Bᵀ), by simp lemma matrix.is_skew_adjoint_bracket (A B : matrix n n R) (hA : A ∈ skew_adjoint_matrices_submodule J) (hB : B ∈ skew_adjoint_matrices_submodule J) : ⁅A, B⁆ ∈ skew_adjoint_matrices_submodule J := begin simp only [mem_skew_adjoint_matrices_submodule] at *, change ⁅A, B⁆ᵀ ⬝ J = J ⬝ -⁅A, B⁆, change Aᵀ ⬝ J = J ⬝ -A at hA, change Bᵀ ⬝ J = J ⬝ -B at hB, simp only [←matrix.mul_eq_mul] at *, rw [matrix.lie_transpose, lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, sub_mul, mul_assoc, mul_assoc, hA, hB, ←mul_assoc, ←mul_assoc, hA, hB], noncomm_ring, end /-- The Lie subalgebra of skew-adjoint square matrices corresponding to a square matrix `J`. -/ def skew_adjoint_matrices_lie_subalgebra : lie_subalgebra R (matrix n n R) := { lie_mem' := J.is_skew_adjoint_bracket, ..(skew_adjoint_matrices_submodule J) } @[simp] lemma mem_skew_adjoint_matrices_lie_subalgebra (A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra J ↔ A ∈ skew_adjoint_matrices_submodule J := iff.rfl /-- An invertible matrix `P` gives a Lie algebra equivalence between those endomorphisms that are skew-adjoint with respect to a square matrix `J` and those with respect to `PᵀJP`. -/ noncomputable def skew_adjoint_matrices_lie_subalgebra_equiv (P : matrix n n R) (h : is_unit P) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (Pᵀ ⬝ J ⬝ P) := lie_algebra.equiv.of_subalgebras _ _ (P.lie_conj h).symm begin ext A, suffices : P.lie_conj h A ∈ skew_adjoint_matrices_submodule J ↔ A ∈ skew_adjoint_matrices_submodule (Pᵀ ⬝ J ⬝ P), { simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact this, }, simp [matrix.is_skew_adjoint, J.is_adjoint_pair_equiv _ _ P h], end lemma skew_adjoint_matrices_lie_subalgebra_equiv_apply (P : matrix n n R) (h : is_unit P) (A : skew_adjoint_matrices_lie_subalgebra J) : ↑(skew_adjoint_matrices_lie_subalgebra_equiv J P h A) = P⁻¹ ⬝ ↑A ⬝ P := by simp [skew_adjoint_matrices_lie_subalgebra_equiv] /-- An equivalence of matrix algebras commuting with the transpose endomorphisms restricts to an equivalence of Lie algebras of skew-adjoint matrices. -/ def skew_adjoint_matrices_lie_subalgebra_equiv_transpose {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (e J) := lie_algebra.equiv.of_subalgebras _ _ e.to_lie_equiv begin ext A, suffices : J.is_skew_adjoint (e.symm A) ↔ (e J).is_skew_adjoint A, by simpa [this], simp [matrix.is_skew_adjoint, matrix.is_adjoint_pair, ← matrix.mul_eq_mul, ← h, ← function.injective.eq_iff e.injective], end @[simp] lemma skew_adjoint_matrices_lie_subalgebra_equiv_transpose_apply {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) (A : skew_adjoint_matrices_lie_subalgebra J) : (skew_adjoint_matrices_lie_subalgebra_equiv_transpose J e h A : matrix m m R) = e A := rfl lemma mem_skew_adjoint_matrices_lie_subalgebra_unit_smul (u : units R) (J A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra ((u : R) • J) ↔ A ∈ skew_adjoint_matrices_lie_subalgebra J := begin change A ∈ skew_adjoint_matrices_submodule ((u : R) • J) ↔ A ∈ skew_adjoint_matrices_submodule J, simp only [mem_skew_adjoint_matrices_submodule, matrix.is_skew_adjoint, matrix.is_adjoint_pair], split; intros h, { simpa using congr_arg (λ B, (↑u⁻¹ : R) • B) h, }, { simp [h], }, end end skew_adjoint_matrices
85959eea19716dada4a391cbd75be058375e7a0d
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/principal_ideal_domain.lean
ccf8a7be9eacbf67f08dbaa6d677717e01e6e223
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
16,497
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Morenikeji Neri -/ import algebra.euclidean_domain.instances import ring_theory.unique_factorization_domain /-! # Principal ideal rings and principal ideal domains A principal ideal ring (PIR) is a ring in which all left ideals are principal. A principal ideal domain (PID) is an integral domain which is a principal ideal ring. # Main definitions Note that for principal ideal domains, one should use `[is_domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID. Theorems about PID's are in the `principal_ideal_ring` namespace. - `is_principal_ideal_ring`: a predicate on rings, saying that every left ideal is principal. - `generator`: a generator of a principal ideal (or more generally submodule) - `to_unique_factorization_monoid`: a PID is a unique factorization domain # Main results - `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal. - `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID. -/ universes u v variables {R : Type u} {M : Type v} open set function open submodule open_locale classical section variables [ring R] [add_comm_group M] [module R M] /-- An `R`-submodule of `M` is principal if it is generated by one element. -/ @[mk_iff] class submodule.is_principal (S : submodule R M) : Prop := (principal [] : ∃ a, S = span R {a}) instance bot_is_principal : (⊥ : submodule R M).is_principal := ⟨⟨0, by simp⟩⟩ instance top_is_principal : (⊤ : submodule R R).is_principal := ⟨⟨1, ideal.span_singleton_one.symm⟩⟩ variables (R) /-- A ring is a principal ideal ring if all (left) ideals are principal. -/ class is_principal_ideal_ring (R : Type u) [ring R] : Prop := (principal : ∀ (S : ideal R), S.is_principal) attribute [instance] is_principal_ideal_ring.principal @[priority 100] instance division_ring.is_principal_ideal_ring (K : Type u) [division_ring K] : is_principal_ideal_ring K := { principal := λ S, by rcases ideal.eq_bot_or_top S with (rfl|rfl); apply_instance } end namespace submodule.is_principal variables [add_comm_group M] section ring variables [ring R] [module R M] /-- `generator I`, if `I` is a principal submodule, is an `x ∈ M` such that `span R {x} = I` -/ noncomputable def generator (S : submodule R M) [S.is_principal] : M := classical.some (principal S) lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S := eq.symm (classical.some_spec (principal S)) lemma _root_.ideal.span_singleton_generator (I : ideal R) [I.is_principal] : ideal.span ({generator I} : set R) = I := eq.symm (classical.some_spec (principal I)) @[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S := by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) } lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} : x ∈ S ↔ ∃ s : R, x = s • generator S := by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator] lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← @span_singleton_eq_bot R M, span_singleton_generator] end ring section comm_ring variables [comm_ring R] [module R M] lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x := (mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul])) lemma prime_generator_of_is_prime (S : ideal R) [submodule.is_principal S] [is_prime : S.is_prime] (ne_bot : S ≠ ⊥) : prime (generator S) := ⟨λ h, ne_bot ((eq_bot_iff_generator_eq_zero S).2 h), λ h, is_prime.ne_top (S.eq_top_of_is_unit_mem (generator_mem S) h), λ _ _, by simpa only [← mem_iff_generator_dvd S] using is_prime.2⟩ -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_map_dvd_of_mem {N : submodule R M} (ϕ : M →ₗ[R] R) [(N.map ϕ).is_principal] {x : M} (hx : x ∈ N) : generator (N.map ϕ) ∣ ϕ x := by { rw [← mem_iff_generator_dvd, submodule.mem_map], exact ⟨x, hx, rfl⟩ } -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_submodule_image_dvd_of_mem {N O : submodule R M} (hNO : N ≤ O) (ϕ : O →ₗ[R] R) [(ϕ.submodule_image N).is_principal] {x : M} (hx : x ∈ N) : generator (ϕ.submodule_image N) ∣ ϕ ⟨x, hNO hx⟩ := by { rw [← mem_iff_generator_dvd, linear_map.mem_submodule_image_of_le hNO], exact ⟨x, hx, rfl⟩ } end comm_ring end submodule.is_principal namespace is_prime open submodule.is_principal ideal -- TODO -- for a non-ID one could perhaps prove that if p < q are prime then q maximal; -- 0 isn't prime in a non-ID PIR but the Krull dimension is still <= 1. -- The below result follows from this, but we could also use the below result to -- prove this (quotient out by p). lemma to_maximal_ideal [comm_ring R] [is_domain R] [is_principal_ideal_ring R] {S : ideal R} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.mem_or_mem (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← T.span_singleton_generator, ideal.span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, mul_right_inj' this] at hz, exact hz.symm ▸ T.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain R] lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ S.add_mem (S.mul_mem_right _ hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ S.sub_mem hx (S.mul_mem_right _ hy)⟩ @[priority 100] -- see Note [lower instance priority] instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R := { principal := λ S, by exactI ⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty then have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded, have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸ (ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0, by { simp only [not_and_distrib, set.mem_set_of_eq, not_ne_iff] at this, cases this, cases this ((mod_mem_iff hmin.1).2 hx), exact this }, by simp *), λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ S.mul_mem_right _ hmin.1⟩⟩ else ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ } end lemma is_field.is_principal_ideal_ring {R : Type*} [comm_ring R] (h : is_field R) : is_principal_ideal_ring R := @euclidean_domain.to_principal_ideal_domain R (@field.to_euclidean_domain R h.to_field) namespace principal_ideal_ring open is_principal_ideal_ring @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring [ring R] [is_principal_ideal_ring R] : is_noetherian_ring R := is_noetherian_ring_iff.2 ⟨assume s : ideal R, begin rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, set_like.coe_injective rfl⟩ end⟩ lemma is_maximal_of_irreducible [comm_ring R] [is_principal_ideal_ring R] {p : R} (hp : irreducible p) : ideal.is_maximal (span R ({p} : set R)) := ⟨⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, erw ideal.span_singleton_eq_top, unfreezingI { rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩ }, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), erw [ideal.span_singleton_le_span_singleton, is_unit.mul_right_dvd hb] end⟩⟩ variables [comm_ring R] [is_domain R] [is_principal_ideal_ring R] lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p := ⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, prime.irreducible⟩ lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ prime p := associates.irreducible_iff_prime_iff.1 (λ _, irreducible_iff_prime) section open_locale classical /-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/ noncomputable def factors (a : R) : multiset R := if h : a = 0 then ∅ else classical.some (wf_dvd_monoid.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated (factors a).prod a := begin unfold factors, rw [dif_neg h], exact classical.some_spec (wf_dvd_monoid.exists_factors a h) end lemma ne_zero_of_mem_factors {R : Type v} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] {a b : R} (ha : a ≠ 0) (hb : b ∈ factors a) : b ≠ 0 := irreducible.ne_zero ((factors_spec a ha).1 b hb) lemma mem_submonoid_of_factors_subset_of_units_subset (s : submonoid R) {a : R} (ha : a ≠ 0) (hfac : ∀ b ∈ factors a, b ∈ s) (hunit : ∀ c : Rˣ, (c : R) ∈ s) : a ∈ s := begin rcases ((factors_spec a ha).2) with ⟨c, hc⟩, rw [← hc], exact mul_mem (multiset_prod_mem _ hfac) (hunit _) end /-- If a `ring_hom` maps all units and all factors of an element `a` into a submonoid `s`, then it also maps `a` into that submonoid. -/ lemma ring_hom_mem_submonoid_of_factors_subset_of_units_subset {R S : Type*} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] [semiring S] (f : R →+* S) (s : submonoid S) (a : R) (ha : a ≠ 0) (h : ∀ b ∈ factors a, f b ∈ s) (hf: ∀ c : Rˣ, f c ∈ s) : f a ∈ s := mem_submonoid_of_factors_subset_of_units_subset (s.comap f.to_monoid_hom) ha h hf /-- A principal ideal domain has unique factorization -/ @[priority 100] -- see Note [lower instance priority] instance to_unique_factorization_monoid : unique_factorization_monoid R := { irreducible_iff_prime := λ _, principal_ideal_ring.irreducible_iff_prime .. (is_noetherian_ring.wf_dvd_monoid : wf_dvd_monoid R) } end end principal_ideal_ring section surjective open submodule variables {S N : Type*} [ring R] [add_comm_group M] [add_comm_group N] [ring S] variables [module R M] [module R N] lemma submodule.is_principal.of_comap (f : M →ₗ[R] N) (hf : function.surjective f) (S : submodule R N) [hI : is_principal (S.comap f)] : is_principal S := ⟨⟨f (is_principal.generator (S.comap f)), by rw [← set.image_singleton, ← submodule.map_span, is_principal.span_singleton_generator, submodule.map_comap_eq_of_surjective hf]⟩⟩ lemma ideal.is_principal.of_comap (f : R →+* S) (hf : function.surjective f) (I : ideal S) [hI : is_principal (I.comap f)] : is_principal I := ⟨⟨f (is_principal.generator (I.comap f)), by rw [ideal.submodule_span_eq, ← set.image_singleton, ← ideal.map_span, ideal.span_singleton_generator, ideal.map_comap_of_surjective f hf]⟩⟩ /-- The surjective image of a principal ideal ring is again a principal ideal ring. -/ lemma is_principal_ideal_ring.of_surjective [is_principal_ideal_ring R] (f : R →+* S) (hf : function.surjective f) : is_principal_ideal_ring S := ⟨λ I, ideal.is_principal.of_comap f hf I⟩ end surjective section open ideal variables [comm_ring R] [is_domain R] [is_principal_ideal_ring R] [gcd_monoid R] theorem span_gcd (x y : R) : span ({gcd x y} : set R) = span ({x, y} : set R) := begin obtain ⟨d, hd⟩ := is_principal_ideal_ring.principal (span ({x, y} : set R)), rw submodule_span_eq at hd, rw [hd], suffices : associated d (gcd x y), { obtain ⟨D, HD⟩ := this, rw ←HD, exact (span_singleton_mul_right_unit D.is_unit _) }, apply associated_of_dvd_dvd, { rw dvd_gcd_iff, split; rw [←ideal.mem_span_singleton, ←hd, ideal.mem_span_pair], { use [1, 0], rw [one_mul, zero_mul, add_zero] }, { use [0, 1], rw [one_mul, zero_mul, zero_add] } }, { obtain ⟨r, s, rfl⟩ : ∃ r s, r * x + s * y = d, { rw [←ideal.mem_span_pair, hd, ideal.mem_span_singleton] }, apply dvd_add; apply dvd_mul_of_dvd_right, exacts [gcd_dvd_left x y, gcd_dvd_right x y] }, end theorem gcd_dvd_iff_exists (a b : R) {z} : gcd a b ∣ z ↔ ∃ x y, z = a * x + b * y := by simp_rw [mul_comm a, mul_comm b, @eq_comm _ z, ←ideal.mem_span_pair, ←span_gcd, ideal.mem_span_singleton] /-- **Bézout's lemma** -/ theorem exists_gcd_eq_mul_add_mul (a b : R) : ∃ x y, gcd a b = a * x + b * y := by rw [←gcd_dvd_iff_exists] theorem gcd_is_unit_iff (x y : R) : is_unit (gcd x y) ↔ is_coprime x y := by rw [is_coprime, ←ideal.mem_span_pair, ←span_gcd, ←span_singleton_eq_top, eq_top_iff_one] -- this should be proved for UFDs surely? theorem is_coprime_of_dvd (x y : R) (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits R, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, gcd_eq_zero_iff] end -- this should be proved for UFDs surely? theorem dvd_or_coprime (x y : R) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), apply is_coprime_of_dvd, { unfreezingI { rintro ⟨rfl, rfl⟩ }, simpa using h }, { unfreezingI { rintro z nu nz ⟨w, rfl⟩ dy }, refine h' (dvd_trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end theorem is_coprime_of_irreducible_dvd {x y : R} (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z : R, irreducible z → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin apply is_coprime_of_dvd x y nonzero, intros z znu znz zx zy, obtain ⟨i, h1, h2⟩ := wf_dvd_monoid.exists_irreducible_factor znu znz, apply H i h1; { apply dvd_trans h2, assumption }, end theorem is_coprime_of_prime_dvd {x y : R} (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z : R, prime z → z ∣ x → ¬ z ∣ y) : is_coprime x y := is_coprime_of_irreducible_dvd nonzero $ λ z zi, H z $ gcd_monoid.prime_of_irreducible zi theorem irreducible.coprime_iff_not_dvd {p n : R} (pp : irreducible p) : is_coprime p n ↔ ¬ p ∣ n := begin split, { intros co H, apply pp.not_unit, rw is_unit_iff_dvd_one, apply is_coprime.dvd_of_dvd_mul_left co, rw mul_one n, exact H }, { intro nd, apply is_coprime_of_irreducible_dvd, { rintro ⟨hp, -⟩, exact pp.ne_zero hp }, rintro z zi zp zn, exact nd (((zi.associated_of_dvd pp zp).symm.dvd).trans zn) }, end theorem prime.coprime_iff_not_dvd {p n : R} (pp : prime p) : is_coprime p n ↔ ¬ p ∣ n := pp.irreducible.coprime_iff_not_dvd theorem irreducible.dvd_iff_not_coprime {p n : R} (hp : irreducible p) : p ∣ n ↔ ¬ is_coprime p n := iff_not_comm.2 hp.coprime_iff_not_dvd theorem irreducible.coprime_pow_of_not_dvd {p a : R} (m : ℕ) (hp : irreducible p) (h : ¬ p ∣ a) : is_coprime a (p ^ m) := (hp.coprime_iff_not_dvd.2 h).symm.pow_right theorem irreducible.coprime_or_dvd {p : R} (hp : irreducible p) (i : R) : is_coprime p i ∨ p ∣ i := (em _).imp_right hp.dvd_iff_not_coprime.2 theorem exists_associated_pow_of_mul_eq_pow' {a b c : R} (hab : is_coprime a b) {k : ℕ} (h : a * b = c ^ k) : ∃ d, associated (d ^ k) a := exists_associated_pow_of_mul_eq_pow ((gcd_is_unit_iff _ _).mpr hab) h end
d972fada8bdce27c7369770db013881931b91b92
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/plus.lean
b9673ffeb6709a91af3e1a975358b2ede1be1b61
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
11,674
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.sites.sheaf /-! # The plus construction for presheaves. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the construction of `P⁺`, for a presheaf `P : Cᵒᵖ ⥤ D` where `C` is endowed with a grothendieck topology `J`. See <https://stacks.math.columbia.edu/tag/00W1> for details. -/ namespace category_theory.grothendieck_topology open category_theory open category_theory.limits open opposite universes w v u variables {C : Type u} [category.{v} C] (J : grothendieck_topology C) variables {D : Type w} [category.{max v u} D] noncomputable theory variables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)] variables (P : Cᵒᵖ ⥤ D) /-- The diagram whose colimit defines the values of `plus`. -/ @[simps] def diagram (X : C) : (J.cover X)ᵒᵖ ⥤ D := { obj := λ S, multiequalizer (S.unop.index P), map := λ S T f, multiequalizer.lift _ _ (λ I, multiequalizer.ι (S.unop.index P) (I.map f.unop)) $ λ I, multiequalizer.condition (S.unop.index P) (I.map f.unop), map_id' := λ S, by { ext I, cases I, simpa }, map_comp' := λ S T W f g, by { ext I, simpa } } /-- A helper definition used to define the morphisms for `plus`. -/ @[simps] def diagram_pullback {X Y : C} (f : X ⟶ Y) : J.diagram P Y ⟶ (J.pullback f).op ⋙ J.diagram P X := { app := λ S, multiequalizer.lift _ _ (λ I, multiequalizer.ι (S.unop.index P) I.base) $ λ I, multiequalizer.condition (S.unop.index P) I.base, naturality' := λ S T f, by { ext, dsimp, simpa } } /-- A natural transformation `P ⟶ Q` induces a natural transformation between diagrams whose colimits define the values of `plus`. -/ @[simps] def diagram_nat_trans {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (X : C) : J.diagram P X ⟶ J.diagram Q X := { app := λ W, multiequalizer.lift _ _ (λ i, multiequalizer.ι _ i ≫ η.app _) begin intros i, erw [category.assoc, category.assoc, ← η.naturality, ← η.naturality, ← category.assoc, ← category.assoc, multiequalizer.condition], refl, end, naturality' := λ _ _ _, by { dsimp, ext, simpa } } @[simp] lemma diagram_nat_trans_id (X : C) (P : Cᵒᵖ ⥤ D) : J.diagram_nat_trans (𝟙 P) X = 𝟙 (J.diagram P X) := begin ext, dsimp, simp only [multiequalizer.lift_ι, category.id_comp], erw category.comp_id end @[simp] lemma diagram_nat_trans_zero [preadditive D] (X : C) (P Q : Cᵒᵖ ⥤ D) : J.diagram_nat_trans (0 : P ⟶ Q) X = 0 := by { ext j x, dsimp, rw [zero_comp, multiequalizer.lift_ι, comp_zero] } @[simp] lemma diagram_nat_trans_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) (X : C) : J.diagram_nat_trans (η ≫ γ) X = J.diagram_nat_trans η X ≫ J.diagram_nat_trans γ X := by { ext, dsimp, simp } variable (D) /-- `J.diagram P`, as a functor in `P`. -/ @[simps] def diagram_functor (X : C) : (Cᵒᵖ ⥤ D) ⥤ (J.cover X)ᵒᵖ ⥤ D := { obj := λ P, J.diagram P X, map := λ P Q η, J.diagram_nat_trans η X, map_id' := λ P, J.diagram_nat_trans_id _ _, map_comp' := λ P Q R η γ, J.diagram_nat_trans_comp _ _ _ } variable {D} variable [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D] /-- The plus construction, associating a presheaf to any presheaf. See `plus_functor` below for a functorial version. -/ def plus_obj : Cᵒᵖ ⥤ D := { obj := λ X, colimit (J.diagram P X.unop), map := λ X Y f, colim_map (J.diagram_pullback P f.unop) ≫ colimit.pre _ _, map_id' := begin intros X, ext S, dsimp, simp only [diagram_pullback_app, colimit.ι_pre, ι_colim_map_assoc, category.comp_id], let e := S.unop.pullback_id, dsimp only [functor.op, pullback_obj], erw [← colimit.w _ e.inv.op, ← category.assoc], convert category.id_comp _, ext I, dsimp, simp only [multiequalizer.lift_ι, category.id_comp, category.assoc], dsimp [cover.arrow.map, cover.arrow.base], cases I, congr, simp, end, map_comp' := begin intros X Y Z f g, ext S, dsimp, simp only [diagram_pullback_app, colimit.ι_pre_assoc, colimit.ι_pre, ι_colim_map_assoc, category.assoc], let e := S.unop.pullback_comp g.unop f.unop, dsimp only [functor.op, pullback_obj], erw [← colimit.w _ e.inv.op, ← category.assoc, ← category.assoc], congr' 1, ext I, dsimp, simp only [multiequalizer.lift_ι, category.assoc], cases I, dsimp only [cover.arrow.base, cover.arrow.map], congr' 2, simp, end } /-- An auxiliary definition used in `plus` below. -/ def plus_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : J.plus_obj P ⟶ J.plus_obj Q := { app := λ X, colim_map (J.diagram_nat_trans η X.unop), naturality' := begin intros X Y f, dsimp [plus_obj], ext, simp only [diagram_pullback_app, ι_colim_map, colimit.ι_pre_assoc, colimit.ι_pre, ι_colim_map_assoc, category.assoc], simp_rw ← category.assoc, congr' 1, ext, dsimp, simpa, end } @[simp] lemma plus_map_id (P : Cᵒᵖ ⥤ D) : J.plus_map (𝟙 P) = 𝟙 _ := begin ext x : 2, dsimp only [plus_map, plus_obj], rw [J.diagram_nat_trans_id, nat_trans.id_app], ext, dsimp, simp, end @[simp] lemma plus_map_zero [preadditive D] (P Q : Cᵒᵖ ⥤ D) : J.plus_map (0 : P ⟶ Q) = 0 := by { ext, erw [comp_zero, colimit.ι_map, J.diagram_nat_trans_zero, zero_comp] } @[simp] lemma plus_map_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) : J.plus_map (η ≫ γ) = J.plus_map η ≫ J.plus_map γ := begin ext : 2, dsimp only [plus_map], rw J.diagram_nat_trans_comp, ext, dsimp, simp, end variable (D) /-- The plus construction, a functor sending `P` to `J.plus_obj P`. -/ @[simps] def plus_functor : (Cᵒᵖ ⥤ D) ⥤ Cᵒᵖ ⥤ D := { obj := λ P, J.plus_obj P, map := λ P Q η, J.plus_map η, map_id' := λ _, plus_map_id _ _, map_comp' := λ _ _ _ _ _, plus_map_comp _ _ _ } variable {D} /-- The canonical map from `P` to `J.plus.obj P`. See `to_plus` for a functorial version. -/ def to_plus : P ⟶ J.plus_obj P := { app := λ X, cover.to_multiequalizer (⊤ : J.cover X.unop) P ≫ colimit.ι (J.diagram P X.unop) (op ⊤), naturality' := begin intros X Y f, dsimp [plus_obj], delta cover.to_multiequalizer, simp only [diagram_pullback_app, colimit.ι_pre, ι_colim_map_assoc, category.assoc], dsimp only [functor.op, unop_op], let e : (J.pullback f.unop).obj ⊤ ⟶ ⊤ := hom_of_le (order_top.le_top _), rw [← colimit.w _ e.op, ← category.assoc, ← category.assoc, ← category.assoc], congr' 1, ext, dsimp, simp only [multiequalizer.lift_ι, category.assoc], dsimp [cover.arrow.base], simp, end } @[simp, reassoc] lemma to_plus_naturality {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : η ≫ J.to_plus Q = J.to_plus _ ≫ J.plus_map η := begin ext, dsimp [to_plus, plus_map], delta cover.to_multiequalizer, simp only [ι_colim_map, category.assoc], simp_rw ← category.assoc, congr' 1, ext, dsimp, simp, end variable (D) /-- The natural transformation from the identity functor to `plus`. -/ @[simps] def to_plus_nat_trans : (𝟭 (Cᵒᵖ ⥤ D)) ⟶ J.plus_functor D := { app := λ P, J.to_plus P, naturality' := λ _ _ _, to_plus_naturality _ _ } variable {D} /-- `(P ⟶ P⁺)⁺ = P⁺ ⟶ P⁺⁺` -/ @[simp] lemma plus_map_to_plus : J.plus_map (J.to_plus P) = J.to_plus (J.plus_obj P) := begin ext X S, dsimp [to_plus, plus_obj, plus_map], delta cover.to_multiequalizer, simp only [ι_colim_map], let e : S.unop ⟶ ⊤ := hom_of_le (order_top.le_top _), simp_rw [← colimit.w _ e.op, ← category.assoc], congr' 1, ext I, dsimp, simp only [diagram_pullback_app, colimit.ι_pre, multiequalizer.lift_ι, ι_colim_map_assoc, category.assoc], dsimp only [functor.op], let ee : (J.pullback (I.map e).f).obj S.unop ⟶ ⊤ := hom_of_le (order_top.le_top _), simp_rw [← colimit.w _ ee.op, ← category.assoc], congr' 1, ext II, dsimp, simp only [limit.lift_π, multifork.of_ι_π_app, multiequalizer.lift_ι, category.assoc], dsimp [multifork.of_ι], convert multiequalizer.condition (S.unop.index P) ⟨_, _, _, II.f, 𝟙 _, I.f, II.f ≫ I.f, I.hf, sieve.downward_closed _ I.hf _, by simp⟩, { cases I, refl }, { dsimp [cover.index], erw [P.map_id, category.comp_id], refl } end lemma is_iso_to_plus_of_is_sheaf (hP : presheaf.is_sheaf J P) : is_iso (J.to_plus P) := begin rw presheaf.is_sheaf_iff_multiequalizer at hP, rsufficesI : ∀ X, is_iso ((J.to_plus P).app X), { apply nat_iso.is_iso_of_is_iso_app }, intros X, dsimp, rsufficesI : is_iso (colimit.ι (J.diagram P X.unop) (op ⊤)), { apply is_iso.comp_is_iso }, rsufficesI : ∀ (S T : (J.cover X.unop)ᵒᵖ) (f : S ⟶ T), is_iso ((J.diagram P X.unop).map f), { apply is_iso_ι_of_is_initial (initial_op_of_terminal is_terminal_top) }, intros S T e, have : S.unop.to_multiequalizer P ≫ (J.diagram P (X.unop)).map e = T.unop.to_multiequalizer P, by { ext, dsimp, simpa }, have : (J.diagram P (X.unop)).map e = inv (S.unop.to_multiequalizer P) ≫ T.unop.to_multiequalizer P, by simp [← this], rw this, apply_instance, end /-- The natural isomorphism between `P` and `P⁺` when `P` is a sheaf. -/ def iso_to_plus (hP : presheaf.is_sheaf J P) : P ≅ J.plus_obj P := by letI := is_iso_to_plus_of_is_sheaf J P hP; exact as_iso (J.to_plus P) @[simp] lemma iso_to_plus_hom (hP : presheaf.is_sheaf J P) : (J.iso_to_plus P hP).hom = J.to_plus P := rfl /-- Lift a morphism `P ⟶ Q` to `P⁺ ⟶ Q` when `Q` is a sheaf. -/ def plus_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) : J.plus_obj P ⟶ Q := J.plus_map η ≫ (J.iso_to_plus Q hQ).inv @[simp, reassoc] lemma to_plus_plus_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) : J.to_plus P ≫ J.plus_lift η hQ = η := begin dsimp [plus_lift], rw ← category.assoc, rw iso.comp_inv_eq, dsimp only [iso_to_plus, as_iso], rw to_plus_naturality, end lemma plus_lift_unique {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) (γ : J.plus_obj P ⟶ Q) (hγ : J.to_plus P ≫ γ = η) : γ = J.plus_lift η hQ := begin dsimp only [plus_lift], rw [iso.eq_comp_inv, ← hγ, plus_map_comp], dsimp, simp, end lemma plus_hom_ext {P Q : Cᵒᵖ ⥤ D} (η γ : J.plus_obj P ⟶ Q) (hQ : presheaf.is_sheaf J Q) (h : J.to_plus P ≫ η = J.to_plus P ≫ γ) : η = γ := begin have : γ = J.plus_lift (J.to_plus P ≫ γ) hQ, { apply plus_lift_unique, refl }, rw this, apply plus_lift_unique, exact h end @[simp] lemma iso_to_plus_inv (hP : presheaf.is_sheaf J P) : (J.iso_to_plus P hP).inv = J.plus_lift (𝟙 _) hP := begin apply J.plus_lift_unique, rw [iso.comp_inv_eq, category.id_comp], refl, end @[simp] lemma plus_map_plus_lift {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) (hR : presheaf.is_sheaf J R) : J.plus_map η ≫ J.plus_lift γ hR = J.plus_lift (η ≫ γ) hR := begin apply J.plus_lift_unique, rw [← category.assoc, ← J.to_plus_naturality, category.assoc, J.to_plus_plus_lift], end instance plus_functor_preserves_zero_morphisms [preadditive D] : (plus_functor J D).preserves_zero_morphisms := { map_zero' := λ F G, by { ext, dsimp, rw [J.plus_map_zero, nat_trans.app_zero] } } end category_theory.grothendieck_topology
3e13ae77b2fa1a92e396ca60ac40330725b3a38a
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/linear_algebra/finsupp.lean
ecce2b4a5bd340e57003933298e24f9a8b5172d2
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,867
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finite support `α →₀ M`. -/ import algebra.monoid_algebra noncomputable theory open set linear_map submodule open_locale classical big_operators namespace finsupp variables {α : Type*} {M : Type*} {N : Type*} {R : Type*} variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] /-- Interpret `finsupp.single a` as a linear map. -/ def lsingle (a : α) : M →ₗ[R] (α →₀ M) := ⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩ /-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/ def lapply (a : α) : (α →₀ M) →ₗ[R] M := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩ section lsubtype_domain variables (s : set α) /-- Interpret `finsupp.subtype_domain s` as a linear map. -/ def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := ⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩ lemma lsubtype_domain_apply (f : α →₀ M) : (lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain @[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b := rfl @[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ := ker_eq_bot_of_injective (single_injective a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ := begin simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ := begin refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _), rw [← sum_single f], refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem a $ set.mem_image_of_mem _ trivial) end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) := begin refine disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right s) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right t) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨his, hit⟩).elim }, exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set M) (a : α) : submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) := by rw ← span_image; refl variables (M R) /-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/ def supported (s : set α) : submodule R (α →₀ M) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end variables {M} lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s := iff.rfl lemma mem_supported' {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 := by haveI := classical.dec_pred (λ (x : α), x ∈ s); simp [mem_supported, set.subset_def, not_imp_comm] lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h) lemma supported_eq_span_single (s : set α) : supported R R s = span R ((λ i, single i 1) '' s) := begin refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm, { rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp }, { rw ← l.sum_single, refine sum_mem _ (λ i il, _), convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _, { simp }, apply subset_span, apply set.mem_image_of_mem _ (hl il) } end variables (M R) /-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/ def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s := linear_map.cod_restrict _ { to_fun := filter (∈ s), map_add' := λ l₁ l₂, filter_add, map_smul' := λ a l, filter_smul } (λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l) variables {M R} section @[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) : ((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl end theorem restrict_dom_comp_subtype (s : set α) : (restrict_dom M R s).comp (submodule.subtype _) = linear_map.id := begin ext l a, by_cases a ∈ s; simp [h], exact ((mem_supported' R l.1).1 l.2 a h).symm end theorem range_restrict_dom (s : set α) : (restrict_dom M R s).range = ⊤ := begin have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s), rw [restrict_dom_comp_subtype, linear_map.range_id] at this, exact eq_top_mono (submodule.map_mono le_top) this.symm end theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, apply finsupp.induction l, {exact zero_mem _}, refine λ x a l hl a0, add_mem _ _, by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := begin refine le_antisymm (le_infi $ λ i, supported_mono $ set.Inter_subset _ _) _, simp [le_def, infi_coe, set.subset_def], exact λ l, set.subset_Inter end /-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between `supported M R s` and `s →₀ M`. -/ def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := begin let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M, refine F.to_linear_equiv _, have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))) := rfl, rw this, exact linear_map.is_linear _ end /-- `finsupp.sum` as a linear map. -/ def lsum (f : α → M →ₗ[R] N) : (α →₀ M) →ₗ[R] N := ⟨λ d, d.sum (λ i, f i), assume d₁ d₂, by simp [sum_add_index], assume a d, by simp [sum_smul_index', smul_sum]⟩ @[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) : finsupp.lsum f l = l.sum (λ b, f b) := rfl theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) : finsupp.lsum f (finsupp.single i m) = f i m := finsupp.sum_single_index (f i).map_zero section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) /-- Interpret `finsupp.lmap_domain` as a linear map. -/ def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := ⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩ @[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) : (lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl @[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id := linear_map.ext $ λ l, map_domain_id theorem lmap_domain_comp (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) := linear_map.ext $ λ l, map_domain_comp theorem supported_comap_lmap_domain (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) := λ l (hl : ↑l.support ⊆ f ⁻¹' s), show ↑(map_domain f l).support ⊆ s, begin rw [← set.image_subset_iff, ← finset.coe_image] at hl, exact set.subset.trans map_domain_support hl end theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) : (supported M R s).map (lmap_domain M R f) = supported M R (f '' s) := begin inhabit α, refine le_antisymm (map_le_iff_le_comap.2 $ le_trans (supported_mono $ set.subset_preimage_image _ _) (supported_comap_lmap_domain _ _ _ _)) _, intros l hl, refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩, { rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩, exact function.inv_fun_on_mem (by simpa using hl hc) }, { rw [← linear_map.comp_apply, ← lmap_domain_comp], refine (map_domain_congr $ λ c hc, _).trans map_domain_id, exact function.inv_fun_on_eq (by simpa using hl hc) } end theorem lmap_domain_disjoint_ker (f : α → α') {s : set α} (H : ∀ a b ∈ s, f a = f b → a = b) : disjoint (supported M R s) (lmap_domain M R f).ker := begin rintro l ⟨h₁, h₂⟩, rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂, simp, ext x, haveI := classical.dec_pred (λ x, x ∈ s), by_cases xs : x ∈ s, { have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl}, rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this, { simpa [finsupp.single_apply] }, { intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] }, { simp {contextual := tt} } }, { by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) } end end lmap_domain section total variables (α) {α' : Type*} (M) {M' : Type*} (R) [add_comm_monoid M'] [semimodule R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total : (α →₀ R) →ₗ M := finsupp.lsum (λ i, linear_map.id.smul_right (v i)) variables {α M v} theorem total_apply (l : α →₀ R) : finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α} (hs : l ∈ supported R R (↑s : set α)) : finsupp.total α M R v l = s.sum (λ i, l i • v i) := finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul] @[simp] theorem total_single (c : R) (a : α) : finsupp.total α M R v (single a c) = c • (v a) := by simp [total_apply, sum_single_index] theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := begin apply range_eq_top.2, intros x, apply exists.elim (h x), exact λ i hi, ⟨single i 1, by simp [hi]⟩ end lemma range_total : (finsupp.total α M R v).range = span R (range v) := begin ext x, split, { intros hx, rw [linear_map.mem_range] at hx, rcases hx with ⟨l, hl⟩, rw ← hl, rw finsupp.total_apply, unfold finsupp.sum, apply sum_mem (span R (range v)), exact λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i)) }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [mem_coe, linear_map.mem_range], use finsupp.single i 1, simp [hi] } end theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) := by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) : (finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply] theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := begin have : map_domain f l = emb_domain ⟨f, hf⟩ l, { rw emb_domain_eq_map_domain ⟨f, hf⟩, refl }, rw this, apply total_emb_domain R ⟨f, hf⟩ l end theorem span_eq_map_total (s : set α): span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := begin apply span_eq_of_le, { intros x hx, rw set.mem_image at hx, apply exists.elim hx, intros i hi, exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ }, { refine map_le_iff_le_comap.2 (λ z hz, _), have : ∀i, z i • v i ∈ span R (v '' s), { intro c, haveI := classical.dec_pred (λ x, x ∈ s), by_cases c ∈ s, { exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) }, { simp [(finsupp.mem_supported' R _).1 hz _ h] } }, refine sum_mem _ _, simp [this] } end theorem mem_span_iff_total {s : set α} {x : M} : x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x := by rw span_eq_map_total; simp variables (α) (M) (v) /-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a subset of the vectors in `v`, mapping it to the span of those vectors. The subset is indicated by a set `s : set α` of indices. -/ protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) := linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $ λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _) theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := begin ext l, simp [total_apply], rw sum_map_domain_index; simp [add_smul], end lemma total_comap_domain (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) := by rw finsupp.total_apply; refl lemma total_on_finset {s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s): finsupp.total α M R g (finsupp.on_finset s f hf) = finset.sum s (λ (x : α), f x • g x) := begin simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset], rw finset.sum_filter_of_ne, intros x hx h, contrapose! h, simp [h], end end total /-- An equivalence of domains induces a linear equivalence of finitely supported functions. -/ protected def dom_lcongr {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (@finsupp.dom_congr M _ _ _ e).to_linear_equiv (lmap_domain M R e).map_smul @[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m := by simp [finsupp.dom_lcongr, finsupp.dom_congr, map_domain_single] /-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/ noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) : supported M R s ≃ₗ[R] supported M R t := begin haveI := classical.dec_pred (λ x, x ∈ s), haveI := classical.dec_pred (λ x, x ∈ t), refine linear_equiv.trans (finsupp.supported_equiv_finsupp s) (linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end /-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the corresponding finitely supported functions. -/ def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) := (finsupp.dom_lcongr e₁).trans { to_fun := map_range e₂ e₂.map_zero, inv_fun := map_range e₂.symm e₂.symm.map_zero, left_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih, by rw [map_range_add e₂.map_add, map_range_add e₂.symm.map_add, map_range_single, map_range_single, e₂.symm_apply_apply, ih], right_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih, by rw [map_range_add e₂.symm.map_add, map_range_add e₂.map_add, map_range_single, map_range_single, e₂.apply_symm_apply, ih], map_add' := map_range_add e₂.map_add, map_smul' := λ c f, finsupp.induction f (by rw [smul_zero, map_range_zero, smul_zero]) $ λ a b f ha hb ih, by rw [smul_add, smul_single, map_range_add e₂.map_add, map_range_single, e₂.map_smul, ih, map_range_add e₂.map_add, smul_add, map_range_single, smul_single] } @[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (i : ι) (m : M) : lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) := by simp [lcongr] end finsupp variables {R : Type*} {M : Type*} {N : Type*} variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] lemma linear_map.map_finsupp_total (f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) : f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l := by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul] lemma submodule.exists_finset_of_mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) : ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := begin obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m, { have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _, rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm }, let t : finset M := f.support, have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i, { intros x, rw finsupp.mem_supported at hf, specialize hf x.2, rwa set.mem_Union at hf }, choose g hg using ht, let s : finset ι := finset.univ.image g, use s, simp only [mem_supr, supr_le_iff], assume N hN, rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe], apply N.sum_mem, assume x hx, apply submodule.smul_mem, let i : ι := g ⟨x, hx⟩, have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ }, exact hN i hi (hg _), end lemma mem_span_finset {s : finset M} {x : M} : x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x := ⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_iff_total _).1 (show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in ⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩, λ ⟨f, hf⟩, hf ▸ sum_mem _ (λ i hi, smul_mem _ _ $ subset_span hi)⟩
9ce6b525777ae193eac5e2bf40350ef7700dc51b
e1da55f4222dac91b940ca052928eaace09762da
/src/prereqs.lean
91d95d70fabdb8caf170f8a996532399bb5ef7a9
[]
no_license
b-mehta/regularity-lemma
c5826e22c280d0b073a4e62dba731f4dd3d1b69f
cf26082b0c88fa54276e6fdc3338c15e607c52c6
refs/heads/master
1,658,209,524,267
1,644,406,456,000
1,644,406,456,000
457,327,371
1
0
null
null
null
null
UTF-8
Lean
false
false
5,772
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import .mathlib /-! # Prerequisites for SRL -/ open_locale big_operators open finset fintype function relation variables {α : Type*} section relation variables (r : α → α → Prop) [decidable_rel r] {A B A' B' : finset α} lemma lemma_B_ineq_zero {s t : finset α} (hst : s ⊆ t) (f : α → ℝ) {x : ℝ} (hs : x^2 ≤ ((∑ x in s, f x)/s.card)^2) (hs' : (s.card : ℝ) ≠ 0) : (s.card : ℝ) * x^2 ≤ ∑ x in t, f x^2 := (mul_le_mul_of_nonneg_left (hs.trans (chebyshev s f)) (nat.cast_nonneg _)).trans $ (mul_div_cancel' _ hs').le.trans $ sum_le_sum_of_subset_of_nonneg hst $ λ i _ _, sq_nonneg _ lemma lemma_B_ineq {s t : finset α} (hst : s ⊆ t) (f : α → ℝ) (d : ℝ) {x : ℝ} (hx : 0 ≤ x) (hs : x ≤ abs ((∑ i in s, f i)/s.card - (∑ i in t, f i)/t.card)) (ht : d ≤ ((∑ i in t, f i)/t.card)^2) : d + s.card/t.card * x^2 ≤ (∑ i in t, f i^2)/t.card := begin obtain hscard | hscard := (s.card.cast_nonneg : (0 : ℝ) ≤ s.card).eq_or_lt, { simpa [←hscard] using ht.trans (chebyshev t f) }, have htcard : (0:ℝ) < t.card := hscard.trans_le (nat.cast_le.2 (card_le_of_subset hst)), have h₁ : x^2 ≤ ((∑ i in s, f i)/s.card - (∑ i in t, f i)/t.card)^2 := sq_le_sq (by rwa [abs_of_nonneg hx]), have h₂ : x^2 ≤ ((∑ i in s, (f i - (∑ j in t, f j)/t.card))/s.card)^2, { apply h₁.trans, rw [sum_sub_distrib, sum_const, nsmul_eq_mul, sub_div, mul_div_cancel_left _ hscard.ne'] }, apply (add_le_add_right ht _).trans, rw [←mul_div_right_comm, le_div_iff htcard, add_mul, div_mul_cancel _ htcard.ne'], have h₃ := lemma_B_ineq_zero hst (λ i, f i - (∑ j in t, f j) / t.card) h₂ hscard.ne', apply (add_le_add_left h₃ _).trans, simp [←mul_div_right_comm _ (t.card : ℝ), sub_div' _ _ _ htcard.ne', ←sum_div, ←add_div, mul_pow, div_le_iff (sq_pos_of_ne_zero _ htcard.ne'), sub_sq, sum_add_distrib, ←sum_mul, ←mul_sum], ring_nf, end lemma aux₀ (hA : A' ⊆ A) (hB : B' ⊆ B) (hA' : A'.nonempty) (hB' : B'.nonempty) : (A'.card : ℝ)/A.card * (B'.card/B.card) * pairs_density r A' B' ≤ pairs_density r A B := begin have hAB' : (A'.card : ℝ) * (B'.card) ≠ 0 := by simp [hA'.ne_empty, hB'.ne_empty], rw [pairs_density, pairs_density, div_mul_div, mul_comm, div_mul_div_cancel _ hAB'], refine div_le_div_of_le (by exact_mod_cast (A.card * B.card).zero_le) _, exact_mod_cast card_le_of_subset (pairs_finset_mono r hA hB), end lemma aux₁ (hA : A' ⊆ A) (hB : B' ⊆ B) (hA' : A'.nonempty) (hB' : B'.nonempty) : pairs_density r A' B' - pairs_density r A B ≤ 1 - (A'.card : ℝ)/A.card * (B'.card/B.card) := begin refine (sub_le_sub_left (aux₀ r hA hB hA' hB') _).trans _, refine le_trans _ (mul_le_of_le_one_right _ (pairs_density_le_one r A' B')), { rw [sub_mul, one_mul] }, refine sub_nonneg_of_le (mul_le_one _ (div_nonneg (nat.cast_nonneg _) (nat.cast_nonneg _)) _); exact div_le_one_of_le (nat.cast_le.2 (card_le_of_subset ‹_›)) (nat.cast_nonneg _), end lemma aux₂ (hA : A' ⊆ A) (hB : B' ⊆ B) (hA' : A'.nonempty) (hB' : B'.nonempty) : abs (pairs_density r A' B' - pairs_density r A B) ≤ 1 - (A'.card : ℝ)/A.card * (B'.card/B.card) := begin have habs : abs (pairs_density r A' B' - pairs_density r A B) ≤ 1, { rw [abs_sub_le_iff, ←sub_zero (1 : ℝ)], split; exact sub_le_sub (pairs_density_le_one r _ _) (pairs_density_nonneg r _ _) }, refine abs_sub_le_iff.2 ⟨aux₁ r hA hB hA' hB', _⟩, rw [←add_sub_cancel (pairs_density r A B) (pairs_density (λ x y, ¬r x y) A B), ←add_sub_cancel (pairs_density r A' B') (pairs_density (λ x y, ¬r x y) A' B'), pairs_density_compl _ (hA'.mono hA) (hB'.mono hB), pairs_density_compl _ hA' hB', sub_sub_sub_cancel_left], exact aux₁ _ hA hB hA' hB', end lemma aux₃ (hA : A' ⊆ A) (hB : B' ⊆ B) {δ : ℝ} (hδ₀ : 0 ≤ δ) (hδ₁ : δ < 1) (hA' : (1 - δ) * A.card ≤ A'.card) (hB' : (1 - δ) * B.card ≤ B'.card) : abs (pairs_density r A' B' - pairs_density r A B) ≤ 2*δ - δ^2 := begin have hδ' : 0 ≤ 2 * δ - δ ^ 2, { rw [sub_nonneg, sq], exact mul_le_mul_of_nonneg_right (hδ₁.le.trans (by norm_num)) hδ₀ }, rw ←sub_pos at hδ₁, simp only [pairs_density], obtain rfl | hA'' := A'.eq_empty_or_nonempty, { simpa [(nonpos_of_mul_nonpos_left hA' hδ₁).antisymm (nat.cast_nonneg _)] using hδ' }, obtain rfl | hB'' := B'.eq_empty_or_nonempty, { simpa [(nonpos_of_mul_nonpos_left hB' hδ₁).antisymm (nat.cast_nonneg _)] using hδ' }, apply (aux₂ r hA hB hA'' hB'').trans (le_trans _ (show 1 - (1-δ)*(1-δ) = 2*δ - δ^2, by ring).le), apply sub_le_sub_left (mul_le_mul ((le_div_iff _).2 hA') ((le_div_iff _).2 hB') hδ₁.le _) _, { exact_mod_cast (hA''.mono hA).card_pos }, { exact_mod_cast (hB''.mono hB).card_pos }, { exact div_nonneg (nat.cast_nonneg _) (nat.cast_nonneg _) } end /-- Lemma A: if A' ⊆ A, B' ⊆ B each take up all but a δ-proportion, then the difference in edge densities is `≤ 2 δ`. -/ lemma lemma_A (hA : A' ⊆ A) (hB : B' ⊆ B) {δ : ℝ} (hδ : 0 ≤ δ) (hAcard : (1 - δ) * A.card ≤ A'.card) (hBcard : (1 - δ) * B.card ≤ B'.card) : abs (pairs_density r A' B' - pairs_density r A B) ≤ 2 * δ := begin cases lt_or_le δ 1, { exact (aux₃ r hA hB hδ h hAcard hBcard).trans ((sub_le_self_iff _).2 (sq_nonneg δ)) }, refine (abs_sub _ _).trans _, simp only [abs_of_nonneg (pairs_density_nonneg r _ _), two_mul], exact add_le_add ((pairs_density_le_one r _ _).trans h) ((pairs_density_le_one r A B).trans h), end end relation
fd4edd3b2930ef666d843c83329f049016c64d25
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/game.lean
e11f6ccd920e0c3be1884afef5f0bb480de518cb
[]
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,321
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.set_theory.pgame import Mathlib.PostPort universes u_1 u namespace Mathlib /-! # Combinatorial games. In this file we define the quotient of pre-games by the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`, and construct an instance `add_comm_group game`, as well as an instance `partial_order game` (although note carefully the warning that the `<` field in this instance is not the usual relation on combinatorial games). -/ protected instance pgame.setoid : setoid pgame := setoid.mk (fun (x y : pgame) => pgame.equiv x y) sorry /-- The type of combinatorial games. In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a combinatorial pre-game is built inductively from two families of combinatorial games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. A combinatorial game is then constructed by quotienting by the equivalence `x ≈ y ↔ x ≤ y ∧ y ≤ x`. -/ def game := quotient pgame.setoid namespace game /-- The relation `x ≤ y` on games. -/ def le : game → game → Prop := quotient.lift₂ (fun (x y : pgame) => x ≤ y) sorry protected instance has_le : HasLessEq game := { LessEq := le } theorem le_refl (x : game) : x ≤ x := quot.induction_on x fun (x : pgame) => pgame.le_refl x theorem le_trans (x : game) (y : game) (z : game) : x ≤ y → y ≤ z → x ≤ z := quot.induction_on x fun (x : pgame) => quot.induction_on y fun (y : pgame) => quot.induction_on z fun (z : pgame) => pgame.le_trans theorem le_antisymm (x : game) (y : game) : x ≤ y → y ≤ x → x = y := sorry /-- The relation `x < y` on games. -/ -- We don't yet make this into an instance, because it will conflict with the (incorrect) notion -- of `<` provided by `partial_order` later. def lt : game → game → Prop := quotient.lift₂ (fun (x y : pgame) => x < y) sorry theorem not_le {x : game} {y : game} : ¬x ≤ y ↔ lt y x := quot.induction_on x fun (x : pgame) => quot.induction_on y fun (y : pgame) => pgame.not_le protected instance has_zero : HasZero game := { zero := quotient.mk 0 } protected instance inhabited : Inhabited game := { default := 0 } protected instance has_one : HasOne game := { one := quotient.mk 1 } /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : game → game := Quot.lift (fun (x : pgame) => quotient.mk (-x)) sorry protected instance has_neg : Neg game := { neg := neg } /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ def add : game → game → game := quotient.lift₂ (fun (x y : pgame) => quotient.mk (x + y)) sorry protected instance has_add : Add game := { add := add } theorem add_assoc (x : game) (y : game) (z : game) : x + y + z = x + (y + z) := quot.induction_on x fun (x : pgame) => quot.induction_on y fun (y : pgame) => quot.induction_on z fun (z : pgame) => quot.sound pgame.add_assoc_equiv protected instance add_semigroup : add_semigroup game := add_semigroup.mk Add.add add_assoc theorem add_zero (x : game) : x + 0 = x := quot.induction_on x fun (x : pgame) => quot.sound (pgame.add_zero_equiv x) theorem zero_add (x : game) : 0 + x = x := quot.induction_on x fun (x : pgame) => quot.sound (pgame.zero_add_equiv x) protected instance add_monoid : add_monoid game := add_monoid.mk add_semigroup.add add_semigroup.add_assoc 0 zero_add add_zero theorem add_left_neg (x : game) : -x + x = 0 := quot.induction_on x fun (x : pgame) => quot.sound pgame.add_left_neg_equiv protected instance add_group : add_group game := add_group.mk add_monoid.add add_monoid.add_assoc add_monoid.zero add_monoid.zero_add add_monoid.add_zero Neg.neg (sub_neg_monoid.sub._default add_monoid.add add_monoid.add_assoc add_monoid.zero add_monoid.zero_add add_monoid.add_zero Neg.neg) add_left_neg theorem add_comm (x : game) (y : game) : x + y = y + x := quot.induction_on x fun (x : pgame) => quot.induction_on y fun (y : pgame) => quot.sound pgame.add_comm_equiv protected instance add_comm_semigroup : add_comm_semigroup game := add_comm_semigroup.mk add_semigroup.add add_semigroup.add_assoc add_comm protected instance add_comm_group : add_comm_group game := add_comm_group.mk add_comm_semigroup.add add_comm_semigroup.add_assoc add_group.zero add_group.zero_add add_group.add_zero add_group.neg add_group.sub add_group.add_left_neg add_comm_semigroup.add_comm theorem add_le_add_left (a : game) (b : game) : a ≤ b → ∀ (c : game), c + a ≤ c + b := sorry -- While it is very tempting to define a `partial_order` on games, and prove -- that games form an `ordered_add_comm_group`, it is a bit dangerous. -- The relations `≤` and `<` on games do not satisfy -- `lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)` -- (Consider `a = 0`, `b = star`.) -- (`lt_iff_le_not_le` is satisfied by surreal numbers, however.) -- Thus we can not use `<` when defining a `partial_order`. -- Because of this issue, we define the `partial_order` and `ordered_add_comm_group` instances, -- but do not actually mark them as instances, for safety. /-- The `<` operation provided by this partial order is not the usual `<` on games! -/ def game_partial_order : partial_order game := partial_order.mk LessEq (preorder.lt._default LessEq) le_refl le_trans le_antisymm /-- The `<` operation provided by this `ordered_add_comm_group` is not the usual `<` on games! -/ def ordered_add_comm_group_game : ordered_add_comm_group game := ordered_add_comm_group.mk add_comm_group.add add_comm_group.add_assoc add_comm_group.zero add_comm_group.zero_add add_comm_group.add_zero add_comm_group.neg add_comm_group.sub add_comm_group.add_left_neg add_comm_group.add_comm partial_order.le partial_order.lt partial_order.le_refl partial_order.le_trans partial_order.le_antisymm add_le_add_left
74c83e14496be11055e014567f6e0f365510b5e2
ba4ad8a778c69640c9cca8e5dcaeb40d4a10fa10
/lean4/Bin/Lean4DataNumBasic.lean
d203b8d7dee36fb14456242e58be8c6eb3622db1
[]
no_license
tangentstorm/tangentlabs
390ac60618bd913b567d20933dab70b84aac7151
137adbba6e7c35f8bb54b0786ada6c8c2ff6bc72
refs/heads/master
1,693,514,213,127
1,692,322,210,000
1,692,322,210,000
7,815,356
33
22
null
1,433,592,935,000
1,359,097,381,000
Visual Basic
UTF-8
Lean
false
false
16,482
lean
import Mathlib.Algebra.Group.Defs /- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ /-! # Binary representation of integers using inductive types Note: Unlike in Coq, where this representation is preferred because of the reliance on kernel reduction, in Lean this representation is discouraged in favor of the "Peano" natural numbers `nat`, and the purpose of this collection of theorems is to show the equivalence of the different approaches. -/ /-- The type of positive binary numbers. 13 = 1101(base 2) = bit1 (bit0 (bit1 one)) -/ inductive PosNum : Type | one : PosNum | bit1 : PosNum → PosNum | bit0 : PosNum → PosNum deriving DecidableEq instance : One PosNum := ⟨PosNum.one⟩ instance : Inhabited PosNum := ⟨1⟩ /-- The type of nonnegative binary numbers, using `pos_num`. 13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -/ inductive Num : Type | zero : Num | pos : PosNum → Num deriving DecidableEq instance : Zero Num := ⟨Num.zero⟩ instance : One Num := ⟨Num.pos 1⟩ instance : Inhabited Num := ⟨0⟩ /-- Representation of integers using trichotomy around zero. 13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -13 = -1101(base 2) = neg (bit1 (bit0 (bit1 one))) -/ inductive Znum : Type | zero : Znum | pos : PosNum → Znum | neg : PosNum → Znum deriving DecidableEq instance : Zero Znum := ⟨Znum.zero⟩ instance : One Znum := ⟨Znum.pos 1⟩ instance : Inhabited Znum := ⟨0⟩ namespace PosNum /-- `bit b n` appends the bit `b` to the end of `n`, where `bit tt x = x1` and `bit ff x = x0`. -/ def bit (b : Bool) : PosNum → PosNum := cond b bit1 bit0 /-- The successor of a `pos_num`. -/ def succ : PosNum → PosNum | 1 => bit0 one | bit1 n => bit0 (succ n) | bit0 n => bit1 n /-- Returns a boolean for whether the `pos_num` is `one`. -/ def isOne : PosNum → Bool | 1 => true | _ => false /-- Addition of two `pos_num`s. -/ protected def add : PosNum → PosNum → PosNum | 1, b => succ b | a, 1 => succ a | bit0 a, bit0 b => bit0 (PosNum.add a b) | bit1 a, bit1 b => bit0 (succ (PosNum.add a b)) | bit0 a, bit1 b => bit1 (PosNum.add a b) | bit1 a, bit0 b => bit1 (PosNum.add a b) instance : Add PosNum := ⟨PosNum.add⟩ /-- The predecessor of a `pos_num` as a `num`. -/ def pred' : PosNum → Num | 1 => 0 | bit0 n => Num.pos (Num.casesOn (motive := fun _ => PosNum) (pred' n) 1 bit1) | bit1 n => Num.pos (bit0 n) /-- The predecessor of a `pos_num` as a `pos_num`. This means that `pred 1 = 1`. -/ def pred (a : PosNum) : PosNum := Num.casesOn (motive := fun _ => PosNum) (pred' a) 1 id /-- The number of bits of a `pos_num`, as a `pos_num`. -/ def size : PosNum → PosNum | 1 => 1 | bit0 n => succ (size n) | bit1 n => succ (size n) /-- The number of bits of a `pos_num`, as a `nat`. -/ def natSize : PosNum → Nat | 1 => 1 | bit0 n => Nat.succ (natSize n) | bit1 n => Nat.succ (natSize n) /-- Multiplication of two `pos_num`s. -/ protected def mul (a : PosNum) : PosNum → PosNum | 1 => a | bit0 b => bit0 (PosNum.mul a b) | bit1 b => bit0 (PosNum.mul a b) + a instance : Mul PosNum := ⟨PosNum.mul⟩ /-- `of_nat_succ n` is the `pos_num` corresponding to `n + 1`. -/ def ofNatSucc : ℕ → PosNum | 0 => 1 | Nat.succ n => succ (ofNatSucc n) /-- `of_nat n` is the `pos_num` corresponding to `n`, except for `of_nat 0 = 1`. -/ def ofNat (n : ℕ) : PosNum := ofNatSucc (Nat.pred n) open Ordering /-- Ordering of `pos_num`s. -/ def cmp : PosNum → PosNum → Ordering | 1, 1 => eq | _, 1 => gt | 1, _ => lt | bit0 a, bit0 b => cmp a b | bit0 a, bit1 b => Ordering.casesOn (motive := fun _ => Ordering) (cmp a b) lt lt gt | bit1 a, bit0 b => Ordering.casesOn (motive := fun _ => Ordering) (cmp a b) lt gt gt | bit1 a, bit1 b => cmp a b instance : LT PosNum := ⟨fun a b => cmp a b = Ordering.lt⟩ instance : LE PosNum := ⟨fun a b => ¬b < a⟩ instance decidableLt : @DecidableRel PosNum (· < ·) | a, b => by dsimp' [(· < ·)] <;> infer_instance instance decidableLe : @DecidableRel PosNum (· ≤ ·) | a, b => by dsimp' [(· ≤ ·)] <;> infer_instance end PosNum section variable {α : Type _} [One α] [Add α] /-- `cast_pos_num` casts a `pos_num` into any type which has `1` and `+`. -/ def castPosNum : PosNum → α | 1 => 1 | PosNum.bit0 a => bit0 (castPosNum a) | PosNum.bit1 a => bit1 (castPosNum a) /-- `cast_num` casts a `num` into any type which has `0`, `1` and `+`. -/ def castNum [z : Zero α] : Num → α | 0 => 0 | Num.pos p => castPosNum p -- see Note [coercion into rings] instance (priority := 900) posNumCoe : CoeTₓ PosNum α := ⟨castPosNum⟩ -- see Note [coercion into rings] instance (priority := 900) numNatCoe [z : Zero α] : CoeTₓ Num α := ⟨castNum⟩ instance : HasRepr PosNum := ⟨fun n => reprₓ (n : ℕ)⟩ instance : HasRepr Num := ⟨fun n => reprₓ (n : ℕ)⟩ end namespace Num open PosNum /-- The successor of a `num` as a `pos_num`. -/ def succ' : Num → PosNum | 0 => 1 | pos p => succ p /-- The successor of a `num` as a `num`. -/ def succ (n : Num) : Num := pos (succ' n) /-- Addition of two `num`s. -/ protected def add : Num → Num → Num | 0, a => a | b, 0 => b | pos a, pos b => pos (a + b) instance : Add Num := ⟨Num.add⟩ /-- `bit0 n` appends a `0` to the end of `n`, where `bit0 n = n0`. -/ protected def bit0 : Num → Num | 0 => 0 | pos n => pos (PosNum.bit0 n) /-- `bit1 n` appends a `1` to the end of `n`, where `bit1 n = n1`. -/ protected def bit1 : Num → Num | 0 => 1 | pos n => pos (PosNum.bit1 n) /-- `bit b n` appends the bit `b` to the end of `n`, where `bit tt x = x1` and `bit ff x = x0`. -/ def bit (b : Bool) : Num → Num := cond b Num.bit1 Num.bit0 /-- The number of bits required to represent a `num`, as a `num`. `size 0` is defined to be `0`. -/ def size : Num → Num | 0 => 0 | pos n => pos (PosNum.size n) /-- The number of bits required to represent a `num`, as a `nat`. `size 0` is defined to be `0`. -/ def natSize : Num → Nat | 0 => 0 | pos n => PosNum.natSize n /-- Multiplication of two `num`s. -/ protected def mul : Num → Num → Num | 0, _ => 0 | _, 0 => 0 | pos a, pos b => pos (a * b) instance : Mul Num := ⟨Num.mul⟩ open Ordering /-- Ordering of `num`s. -/ def cmp : Num → Num → Ordering | 0, 0 => eq | _, 0 => gt | 0, _ => lt | pos a, pos b => PosNum.cmp a b instance : LT Num := ⟨fun a b => cmp a b = Ordering.lt⟩ instance : LE Num := ⟨fun a b => ¬b < a⟩ instance decidableLt : @DecidableRel Num (· < ·) | a, b => by dsimp' [(· < ·)] <;> infer_instance instance decidableLe : @DecidableRel Num (· ≤ ·) | a, b => by dsimp' [(· ≤ ·)] <;> infer_instance /-- Converts a `num` to a `znum`. -/ def toZnum : Num → Znum | 0 => 0 | pos a => Znum.pos a /-- Converts `x : num` to `-x : znum`. -/ def toZnumNeg : Num → Znum | 0 => 0 | pos a => Znum.neg a /-- Converts a `nat` to a `num`. -/ def ofNat' : ℕ → Num := Nat.binaryRec 0 fun b n => cond b Num.bit1 Num.bit0 end Num namespace Znum open PosNum /-- The negation of a `znum`. -/ def zneg : Znum → Znum | 0 => 0 | pos a => neg a | neg a => pos a instance : Neg Znum := ⟨zneg⟩ /-- The absolute value of a `znum` as a `num`. -/ def abs : Znum → Num | 0 => 0 | pos a => Num.pos a | neg a => Num.pos a /-- The successor of a `znum`. -/ def succ : Znum → Znum | 0 => 1 | pos a => pos (PosNum.succ a) | neg a => (PosNum.pred' a).toZnumNeg /-- The predecessor of a `znum`. -/ def pred : Znum → Znum | 0 => neg 1 | pos a => (PosNum.pred' a).toZnum | neg a => neg (PosNum.succ a) /-- `bit0 n` appends a `0` to the end of `n`, where `bit0 n = n0`. -/ protected def bit0 : Znum → Znum | 0 => 0 | pos n => pos (PosNum.bit0 n) | neg n => neg (PosNum.bit0 n) /-- `bit1 x` appends a `1` to the end of `x`, mapping `x` to `2 * x + 1`. -/ protected def bit1 : Znum → Znum | 0 => 1 | pos n => pos (PosNum.bit1 n) | neg n => neg (Num.casesOn (motive := fun _ => PosNum) (pred' n) 1 PosNum.bit1) /-- `bitm1 x` appends a `1` to the end of `x`, mapping `x` to `2 * x - 1`. -/ protected def bitm1 : Znum → Znum | 0 => neg 1 | pos n => pos (Num.casesOn (motive := fun _ => PosNum) (pred' n) 1 PosNum.bit1) | neg n => neg (PosNum.bit1 n) /-- Converts an `int` to a `znum`. -/ def ofInt' : ℤ → Znum | (n : ℕ) => Num.toZnum (Num.ofNat' n) | -[1+ n] => Num.toZnumNeg (Num.ofNat' (n + 1)) end Znum namespace PosNum open Znum /-- Subtraction of two `pos_num`s, producing a `znum`. -/ def sub' : PosNum → PosNum → Znum | a, 1 => (pred' a).toZnum | 1, b => (pred' b).toZnumNeg | bit0 a, bit0 b => (sub' a b).bit0 | bit0 a, bit1 b => (sub' a b).bitm1 | bit1 a, bit0 b => (sub' a b).bit1 | bit1 a, bit1 b => (sub' a b).bit0 /-- Converts a `znum` to `option pos_num`, where it is `some` if the `znum` was positive and `none` otherwise. -/ def ofZnum' : Znum → Option PosNum | Znum.pos p => some p | _ => none /-- Converts a `znum` to a `pos_num`, mapping all out of range values to `1`. -/ def ofZnum : Znum → PosNum | Znum.pos p => p | _ => 1 /-- Subtraction of `pos_num`s, where if `a < b`, then `a - b = 1`. -/ protected def sub (a b : PosNum) : PosNum := match sub' a b with | Znum.pos p => p | _ => 1 instance : Sub PosNum := ⟨PosNum.sub⟩ end PosNum namespace Num /-- The predecessor of a `num` as an `option num`, where `ppred 0 = none` -/ def ppred : Num → Option Num | 0 => none | pos p => some p.pred' /-- The predecessor of a `num` as a `num`, where `pred 0 = 0`. -/ def pred : Num → Num | 0 => 0 | pos p => p.pred' /-- Divides a `num` by `2` -/ def div2 : Num → Num | 0 => 0 | 1 => 0 | pos (PosNum.bit0 p) => pos p | pos (PosNum.bit1 p) => pos p /-- Converts a `znum` to an `option num`, where `of_znum' p = none` if `p < 0`. -/ def ofZnum' : Znum → Option Num | 0 => some 0 | Znum.pos p => some (pos p) | Znum.neg p => none /-- Converts a `znum` to an `option num`, where `of_znum p = 0` if `p < 0`. -/ def ofZnum : Znum → Num | Znum.pos p => pos p | _ => 0 /-- Subtraction of two `num`s, producing a `znum`. -/ def sub' : Num → Num → Znum | 0, 0 => 0 | pos a, 0 => Znum.pos a | 0, pos b => Znum.neg b | pos a, pos b => a.sub' b /-- Subtraction of two `num`s, producing an `option num`. -/ def psub (a b : Num) : Option Num := ofZnum' (sub' a b) /-- Subtraction of two `num`s, where if `a < b`, `a - b = 0`. -/ protected def sub (a b : Num) : Num := ofZnum (sub' a b) instance : Sub Num := ⟨Num.sub⟩ end Num namespace Znum open PosNum /-- Addition of `znum`s. -/ protected def add : Znum → Znum → Znum | 0, a => a | b, 0 => b | pos a, pos b => pos (a + b) | pos a, neg b => sub' a b | neg a, pos b => sub' b a | neg a, neg b => neg (a + b) instance : Add Znum := ⟨Znum.add⟩ /-- Multiplication of `znum`s. -/ protected def mul : Znum → Znum → Znum | 0, _ => 0 | _, 0 => 0 | pos a, pos b => pos (a * b) | pos a, neg b => neg (a * b) | neg a, pos b => neg (a * b) | neg a, neg b => pos (a * b) instance : Mul Znum := ⟨Znum.mul⟩ open Ordering /-- Ordering on `znum`s. -/ def cmp : Znum → Znum → Ordering | 0, 0 => eq | pos a, pos b => PosNum.cmp a b | neg a, neg b => PosNum.cmp b a | pos _, _ => gt | neg _, _ => lt | _, pos _ => lt | _, neg _ => gt instance : LT Znum := ⟨fun a b => cmp a b = Ordering.lt⟩ instance : LE Znum := ⟨fun a b => ¬b < a⟩ instance decidableLt : @DecidableRel Znum (· < ·) | a, b => by dsimp' [(· < ·)] <;> infer_instance instance decidableLe : @DecidableRel Znum (· ≤ ·) | a, b => by dsimp' [(· ≤ ·)] <;> infer_instance end Znum namespace PosNum /-- Auxiliary definition for `pos_num.divmod`. -/ def divmodAux (d : PosNum) (q r : Num) : Num × Num := match Num.ofZnum' (Num.sub' r (Num.pos d)) with | some r' => (Num.bit1 q, r') | none => (Num.bit0 q, r) /-- `divmod x y = (y / x, y % x)`. -/ def divmod (d : PosNum) : PosNum → Num × Num | bit0 n => let (q, r₁) := divmod d n divmodAux d q (Num.bit0 r₁) | bit1 n => let (q, r₁) := divmod d n divmodAux d q (Num.bit1 r₁) | 1 => divmodAux d 0 1 /-- Division of `pos_num`, -/ def div' (n d : PosNum) : Num := (divmod d n).1 /-- Modulus of `pos_num`s. -/ def mod' (n d : PosNum) : Num := (divmod d n).2 /- private def sqrt_aux1 (b : pos_num) (r n : num) : num × num := match num.of_znum' (n.sub' (r + num.pos b)) with | some n' := (r.div2 + num.pos b, n') | none := (r.div2, n) end private def sqrt_aux : pos_num → num → num → num | b@(bit0 b') r n := let (r', n') := sqrt_aux1 b r n in sqrt_aux b' r' n' | b@(bit1 b') r n := let (r', n') := sqrt_aux1 b r n in sqrt_aux b' r' n' | 1 r n := (sqrt_aux1 1 r n).1 -/ /- def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end -/ end PosNum namespace Num /-- Division of `num`s, where `x / 0 = 0`. -/ def div : Num → Num → Num | 0, _ => 0 | _, 0 => 0 | pos n, pos d => PosNum.div' n d /-- Modulus of `num`s. -/ def mod : Num → Num → Num | 0, _ => 0 | n, 0 => n | pos n, pos d => PosNum.mod' n d instance : Div Num := ⟨Num.div⟩ instance : Mod Num := ⟨Num.mod⟩ /-- Auxiliary definition for `num.gcd`. -/ def gcdAux : Nat → Num → Num → Num | 0, _, b => b | Nat.succ _, 0, b => b | Nat.succ n, a, b => gcdAux n (b % a) a /-- Greatest Common Divisor (GCD) of two `num`s. -/ def gcd (a b : Num) : Num := if a ≤ b then gcdAux (a.natSize + b.natSize) a b else gcdAux (b.natSize + a.natSize) b a end Num namespace Znum /-- Division of `znum`, where `x / 0 = 0`. -/ def div : Znum → Znum → Znum | 0, _ => 0 | _, 0 => 0 | pos n, pos d => Num.toZnum (PosNum.div' n d) | pos n, neg d => Num.toZnumNeg (PosNum.div' n d) | neg n, pos d => neg (PosNum.pred' n / Num.pos d).succ' | neg n, neg d => pos (PosNum.pred' n / Num.pos d).succ' /-- Modulus of `znum`s. -/ def mod : Znum → Znum → Znum | 0, d => 0 | pos n, d => Num.toZnum (Num.pos n % d.abs) | neg n, d => d.abs.sub' (PosNum.pred' n % d.abs).succ instance : Div Znum := ⟨Znum.div⟩ instance : Mod Znum := ⟨Znum.mod⟩ /-- Greatest Common Divisor (GCD) of two `znum`s. -/ def gcd (a b : Znum) : Num := a.abs.gcd b.abs end Znum section variable {α : Type _} [Zero α] [One α] [Add α] [Neg α] /-- `cast_znum` casts a `znum` into any type which has `0`, `1`, `+` and `neg` -/ def castZnum : Znum → α | 0 => 0 | Znum.pos p => p | Znum.neg p => -p -- see Note [coercion into rings] instance (priority := 900) znumCoe : CoeTₓ Znum α := ⟨castZnum⟩ instance : HasRepr Znum := ⟨fun n => reprₓ (n : ℤ)⟩ end -- TODO: implement has_reflect for all these types. -- (this cannot yet be derived in lean 4) instance : has_reflect PosNum := sorry
ef319dd0d054af64b33d27f9491849091e86d37b
137c667471a40116a7afd7261f030b30180468c2
/src/topology/continuous_function/weierstrass.lean
b2b9565ed1826f447cad31188dd40b4662fc40b1
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,418
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 algebra.algebra.subalgebra import analysis.special_functions.bernstein /-! # The Weierstrass approximation theorem for continuous functions on `[a,b]` We've already proved the Weierstrass approximation theorem in the sense that we've shown that the Bernstein approximations to a continuous function on `[0,1]` converge uniformly. Here we rephrase this more abstractly as `polynomial_functions_closure_eq_top' : (polynomial_functions I).topological_closure = ⊤` and then, by precomposing with suitable affine functions, `polynomial_functions_closure_eq_top : (polynomial_functions (set.Icc a b)).topological_closure = ⊤` -/ open continuous_map filter open_locale unit_interval /-- The special case of the Weierstrass approximation theorem for the interval `[0,1]`. This is just a matter of unravelling definitions and using the Bernstein approximations. -/ theorem polynomial_functions_closure_eq_top' : (polynomial_functions I).topological_closure = ⊤ := begin apply eq_top_iff.mpr, rintros f -, refine filter.frequently.mem_closure _, refine filter.tendsto.frequently (bernstein_approximation_uniform f) _, apply frequently_of_forall, intro n, simp only [set_like.mem_coe], apply subalgebra.sum_mem, rintro n -, apply subalgebra.smul_mem, dsimp [bernstein, polynomial_functions], simp, end /-- The **Weierstrass Approximation Theorem**: polynomials functions on `[a, b] ⊆ ℝ` are dense in `C([a,b],ℝ)` (While we could deduce this as an application of the Stone-Weierstrass theorem, our proof of that relies on the fact that `abs` is in the closure of polynomials on `[-M, M]`, so we may as well get this done first.) -/ theorem polynomial_functions_closure_eq_top (a b : ℝ) : (polynomial_functions (set.Icc a b)).topological_closure = ⊤ := begin by_cases h : a < b, -- (Otherwise it's easy; we'll deal with that later.) { -- We can pullback continuous functions on `[a,b]` to continuous functions on `[0,1]`, -- by precomposing with an affine map. let W : C(set.Icc a b, ℝ) →ₐ[ℝ] C(I, ℝ) := comp_right_alg_hom ℝ (Icc_homeo_I a b h).symm.to_continuous_map, -- This operation is itself a homeomorphism -- (with respect to the norm topologies on continuous functions). let W' : C(set.Icc a b, ℝ) ≃ₜ C(I, ℝ) := comp_right_homeomorph ℝ (Icc_homeo_I a b h).symm, have w : (W : C(set.Icc a b, ℝ) → C(I, ℝ)) = W' := rfl, -- Thus we take the statement of the Weierstrass approximation theorem for `[0,1]`, have p := polynomial_functions_closure_eq_top', -- and pullback both sides, obtaining an equation between subalgebras of `C([a,b], ℝ)`. apply_fun (λ s, s.comap' W) at p, simp only [algebra.comap_top] at p, -- Since the pullback operation is continuous, it commutes with taking `topological_closure`, rw subalgebra.topological_closure_comap'_homeomorph _ W W' w at p, -- and precomposing with an affine map takes polynomial functions to polynomial functions. rw polynomial_functions.comap'_comp_right_alg_hom_Icc_homeo_I at p, -- 🎉 exact p }, { -- Otherwise, `b ≤ a`, and the interval is a subsingleton, -- so all subalgebras are the same anyway. haveI : subsingleton (set.Icc a b) := ⟨λ x y, le_antisymm ((x.2.2.trans (not_lt.mp h)).trans y.2.1) ((y.2.2.trans (not_lt.mp h)).trans x.2.1)⟩, haveI := (continuous_map.subsingleton_subalgebra (set.Icc a b) ℝ), apply subsingleton.elim, } end /-- An alternative statement of Weierstrass' theorem. Every real-valued continuous function on `[a,b]` is a uniform limit of polynomials. -/ theorem continuous_map_mem_polynomial_functions_closure (a b : ℝ) (f : C(set.Icc a b, ℝ)) : f ∈ (polynomial_functions (set.Icc a b)).topological_closure := begin rw polynomial_functions_closure_eq_top _ _, simp, end /-- An alternative statement of Weierstrass' theorem, for those who like their epsilons. Every real-valued continuous function on `[a,b]` is within any `ε > 0` of some polynomial. -/ theorem exists_polynomial_near_continuous_map (a b : ℝ) (f : C(set.Icc a b, ℝ)) (ε : ℝ) (pos : 0 < ε) : ∃ (p : polynomial ℝ), ∥p.to_continuous_map_on _ - f∥ < ε := begin have w := mem_closure_iff_frequently.mp (continuous_map_mem_polynomial_functions_closure _ _ f), rw metric.nhds_basis_ball.frequently_iff at w, obtain ⟨-, H, ⟨m, ⟨-, rfl⟩⟩⟩ := w ε pos, rw [metric.mem_ball, dist_eq_norm] at H, exact ⟨m, H⟩, end /-- Another alternative statement of Weierstrass's theorem, for those who like epsilons, but not bundled continuous functions. Every real-valued function `ℝ → ℝ` which is continuous on `[a,b]` can be approximated to within any `ε > 0` on `[a,b]` by some polynomial. -/ theorem exists_polynomial_near_of_continuous_on (a b : ℝ) (f : ℝ → ℝ) (c : continuous_on f (set.Icc a b)) (ε : ℝ) (pos : 0 < ε) : ∃ (p : polynomial ℝ), ∀ x ∈ set.Icc a b, abs (p.eval x - f x) < ε := begin let f' : C(set.Icc a b, ℝ) := ⟨λ x, f x, continuous_on_iff_continuous_restrict.mp c⟩, obtain ⟨p, b⟩ := exists_polynomial_near_continuous_map a b f' ε pos, use p, rw norm_lt_iff _ pos at b, intros x m, exact b ⟨x, m⟩, end
a1a15a630b0178abdf99f25e3e0fdcec7ff49745
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/buffer/parser/numeral.lean
1397ecd91bc20649a15aad7dc603d736ab509863
[]
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
3,624
lean
/- Copyright (c) 2020 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.card import Mathlib.PostPort namespace Mathlib /-! # Numeral parsers This file expands on the existing `nat : parser ℕ` to provide parsers into any type `α` that can be represented by a numeral, which relies on `α` having a 0, 1, and addition operation. There are also convenience parsers that ensure that the numeral parsed in is not larger than the cardinality of the type `α` , if it is known that `fintype α`. Additionally, there are convenience parsers that parse in starting from "1", which can be useful for positive ordinals; or parser from a given character or character range. ## Main definitions * 'numeral` : The parser which uses `nat.cast` to map the result of `parser.nat` to the desired `α` * `numeral.of_fintype` : The parser which `guard`s to make sure the parsed numeral is within the cardinality of the target `fintype` type `α`. ## Implementation details When the `numeral` or related parsers are invoked, the desired type is provided explicitly. In many cases, it can be inferred, so one can write, for example ```lean def get_fin : string → fin 5 := sum.elim (λ _, 0) id ∘ parser.run_string (parser.numeral.of_fintype _) ``` In the definitions of the parsers (except for `numeral`), there is an explicit `nat.bin_cast` instead an explicit or implicit `nat.cast` -/ namespace parser /-- Parse a string of digits as a numeral while casting it to target type `α`. -/ def numeral (α : Type) [HasZero α] [HasOne α] [Add α] : parser α := nat.bin_cast <$> nat /-- Parse a string of digits as a numeral while casting it to target type `α`, which has a `[fintype α]` constraint. The parser ensures that the numeral parsed in is within the cardinality of the type `α`. -/ def numeral.of_fintype (α : Type) [HasZero α] [HasOne α] [Add α] [fintype α] : parser α := sorry /-- Parse a string of digits as a numeral while casting it to target type `α`. The parsing starts at "1", so `"1"` is parsed in as `nat.cast 0`. Providing `"0"` to the parser causes a failure. -/ def numeral.from_one (α : Type) [HasZero α] [HasOne α] [Add α] : parser α := sorry /-- Parse a string of digits as a numeral while casting it to target type `α`, which has a `[fintype α]` constraint. The parser ensures that the numeral parsed in is within the cardinality of the type `α`. The parsing starts at "1", so `"1"` is parsed in as `nat.cast 0`. Providing `"0"` to the parser causes a failure. -/ def numeral.from_one.of_fintype (α : Type) [HasZero α] [HasOne α] [Add α] [fintype α] : parser α := sorry /-- Parse a character as a numeral while casting it to target type `α`, The parser ensures that the character parsed in is within the bounds set by `fromc` and `toc`, and subtracts the value of `fromc` from the parsed in character. -/ def numeral.char (α : Type) [HasZero α] [HasOne α] [Add α] (fromc : char) (toc : char) : parser α := sorry /-- Parse a character as a numeral while casting it to target type `α`, which has a `[fintype α]` constraint. The parser ensures that the character parsed in is greater or equal to `fromc` and and subtracts the value of `fromc` from the parsed in character. There is also a check that the resulting value is within the cardinality of the type `α`. -/ def numeral.char.of_fintype (α : Type) [HasZero α] [HasOne α] [Add α] [fintype α] (fromc : char) : parser α := sorry
88181eb5fd07523bf281b52f4aa358efc40a49ba
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/Submissions/hw4.lean
2ad0e188601609c3ffce3484653e9a87942ca10a
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
6,749
lean
-- 1 example : 0 ≠ 1 := begin -- ¬ (0 = 1) -- (0 = 1) → false assume h, cases h, end -- 2 example : 0 ≠ 0 → 2 = 3 := begin assume h, have f : false := h (eq.refl 0), exact false.elim (f), end -- 3 example : ∀ (P : Prop), P → ¬¬P := begin assume P, assume (p : P), -- ¬¬P -- ¬P → false -- (P → false) → false assume h, have f := h p, exact f, end -- We might need classical (vs constructive) reasoning #check classical.em open classical #check em /- axiom em : ∀ (p : Prop), p ∨ ¬p This is the famous and historically controversial "law" (now axiom) of the excluded middle. It's is a key to proving many intuitive theorems in logic and mathematics. But it also leads to giving up on having evidence *why* something is either true or not true, in that you no longer need a proof of either P or of ¬P to have a proof of P ∨ ¬P. -/ -- 4 theorem neg_elim : ∀ (P : Prop), ¬¬P → P := begin assume P, assume h, have pornp := classical.em P, cases pornp with p pn, assumption, contradiction, end #check not.intro -- 5 theorem demorgan_1 : ∀ (P Q : Prop), ¬ (P ∧ Q) ↔ ¬ P ∨ ¬ Q := begin assume P Q, apply iff.intro _ _, --forward intro h, by_cases p : P, right, intro q, have pnq : P ∧ Q := and.intro p q, apply h pnq, left, exact p, --backward assume npornq, by_cases p : P, by_cases q : Q, apply not.intro, assume pnq, apply or.elim npornq, assume np, apply np p, assume nq, apply nq q, apply not.intro, assume pnq, have q1 : Q := and.elim_right pnq, apply q q1, apply not.intro, assume pnq, have p1 : P := and.elim_left pnq, apply p p1, end -- 6 theorem demorgan_2 : ∀ (P Q : Prop), ¬ (P ∨ Q) → ¬P ∧ ¬Q := begin assume P Q, intro h, have pornp := classical.em P, have qornq := classical.em Q, cases pornp with p np, -- p have falso := h (or.intro_left _ p), exact false.elim falso, -- np cases qornq with q nq, -- q have falso := h (or.intro_right _ q), exact false.elim falso, -- nq exact and.intro np nq, end -- 7 theorem disappearing_opposite : ∀ (P Q : Prop), P ∨ ¬P ∧ Q ↔ P ∨ Q := begin --forward assume P Q, apply iff.intro _ _, assume p_or_npandq, apply or.elim p_or_npandq, assume p, apply or.intro_left, exact p, assume npandq, have q := and.elim_right npandq, apply or.intro_right, exact q, --backward assume porq, apply or.elim porq, assume p, apply or.intro_left, exact p, /-assume q, apply or.intro_right, apply and.intro,-/ assume q, have pornp := classical.em P, apply or.elim pornp, assume p, apply or.intro_left, exact p, assume np, apply or.intro_right, apply and.intro np q, end -- 8 theorem distrib_and_or : ∀ (P Q R: Prop), (P ∨ Q) ∧ (P ∨ R) ↔ P ∨ (Q ∧ R) := begin intros P Q R, apply iff.intro _ _, assume h, have porq := h.left, have porr := h.right, cases porq with p q, exact or.intro_left _ p, cases porr with p r, exact or.intro_left _ p, exact or.intro_right _ (and.intro q r), assume h, cases h with p qnr, -- p exact and.intro (or.intro_left _ p) (or.intro_left _ p), -- qnr have r := and.elim_right qnr, have q := and.elim_left qnr, exact and.intro (or.intro_right _ q) (or.intro_right _ r), end -- remember or is right associative -- you need this to know what the lefts and rights are -- 9 theorem distrib_and_or_foil : ∀ (P Q R S : Prop), (P ∨ Q) ∧ (R ∨ S) ↔ (P ∧ R) ∨ (P ∧ S) ∨ (Q ∧ R) ∨ (Q ∧ S) := begin intros P Q R S, apply iff.intro _ _, --forward assume h, have rors := h.right, have porq := h.left, cases porq with p q, -- p cases rors with r s, -- r within p have j := and.intro p r, exact or.intro_left _ j, -- s within p have pands := and.intro p s, exact or.intro_right _ (or.intro_left _ pands), -- q cases rors with r s, -- r within q have qandr := and.intro q r, exact or.intro_right _ (or.intro_right _ (or.intro_left _ qandr)), -- s within q have qands := and.intro q s, have qandr_or_qands := or.intro_right _ qands, exact or.intro_right _ (or.intro_right _ qandr_or_qands), --backward assume h, cases h with i j, -- case i (P ∧ R) have p := and.elim_left i, have r := and.elim_right i, have porq := or.intro_left _ p, have rors := or.intro_left _ r, exact and.intro porq rors, -- case j ( P ∧ S ∨ Q ∧ R ∨ Q ∧ S) cases j with m n, -- case m (P ∧ S) have p:= and.elim_left m, have s := and.elim_right m, have rors := or.intro_right _ s, have porq := or.intro_left _ p, exact and.intro porq rors, -- case n (Q ∧ R ∨ Q ∧ S) cases n with a b, -- case a (Q ∧ R) have q := and.elim_left a, have r := and.elim_right a, have porq := or.intro_right _ q, have rors := or.intro_left _ r, exact and.intro porq rors, -- case b ( Q ∧ S) have q := and.elim_left b, have s := and.elim_right b, have porq := or.intro_right _ q, have rors := or.intro_right _ s, exact and.intro porq rors, end /- 10 Formally state and prove the proposition that not every natural number is equal to zero. -/ lemma not_all_nats_are_zero : ∀(n : ℕ), (n=0) ∨ (n≠0):= begin assume n, apply classical.em, end -- 11. equivalence of P→Q and (¬P∨Q) example : ∀ (P Q : Prop), (P → Q) ↔ (¬P ∨ Q) := begin intros P Q, apply iff.intro, --forward assume h, have pornp := classical.em P, cases pornp with p np, --case p have q := h p, exact or.intro_right _ q, -- case np exact or.intro_left _ np, --backward assume h, assume p, cases h with np q, -- case np exact false.elim(np p), --case q exact q, end -- 12 example : ∀ (P Q : Prop), (P → Q) → (¬ Q → ¬ P) := begin intros P Q, assume pimpq, assume nq, apply not.intro, assume p, have q := pimpq p, exact (nq q), end -- 13 example : ∀ (P Q : Prop), ( ¬P → ¬Q) → (Q → P) := begin intros P Q, assume npimpnq, assume q, have pornp := classical.em P, cases pornp with p np, -- p exact p, -- np have nq := npimpnq np, have falso := nq q, exact false.elim falso, end
fd5a814055062bbe73304512036ea85efc2f92ea
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/encodable/lattice_auto.lean
b6119acc8444870fb1b6a2a21dccb35d621a343e
[]
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
1,920
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.encodable.basic import Mathlib.data.finset.basic import Mathlib.data.set.disjointed import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Lattice operations on encodable types Lemmas about lattice and set operations on encodable types ## Implementation Notes This is a separate file, to avoid unnecessary imports in basic files. Previously some of these results were in the `measure_theory` folder. -/ namespace encodable theorem supr_decode2 {α : Type u_1} {β : Type u_2} [encodable β] [complete_lattice α] (f : β → α) : (supr fun (i : ℕ) => supr fun (b : β) => supr fun (H : b ∈ decode2 β i) => f b) = supr fun (b : β) => f b := sorry theorem Union_decode2 {α : Type u_1} {β : Type u_2} [encodable β] (f : β → set α) : (set.Union fun (i : ℕ) => set.Union fun (b : β) => set.Union fun (H : b ∈ decode2 β i) => f b) = set.Union fun (b : β) => f b := supr_decode2 f theorem Union_decode2_cases {α : Type u_1} {β : Type u_2} [encodable β] {f : β → set α} {C : set α → Prop} (H0 : C ∅) (H1 : ∀ (b : β), C (f b)) {n : ℕ} : C (set.Union fun (b : β) => set.Union fun (H : b ∈ decode2 β n) => f b) := sorry theorem Union_decode2_disjoint_on {α : Type u_1} {β : Type u_2} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) : pairwise (disjoint on fun (i : ℕ) => set.Union fun (b : β) => set.Union fun (H : b ∈ decode2 β i) => f b) := sorry end encodable namespace finset theorem nonempty_encodable {α : Type u_1} (t : finset α) : Nonempty (encodable (Subtype fun (i : α) => i ∈ t)) := sorry end Mathlib
14ee538162fb5689ff0ae80df1d84afc32847672
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/specialize1.lean
85de542b503ab12b85c6e7a87dd67f918f1f586d
[ "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
666
lean
example (x y z : Prop) (f : x → y → z) (xp : x) (yp : y) : z := by specialize f xp yp assumption example (B C : Prop) (f : forall (A : Prop), A → C) (x : B) : C := by specialize f _ x exact f example (B C : Prop) (f : forall {A : Prop}, A → C) (x : B) : C := by specialize f x exact f example (B C : Prop) (f : forall {A : Prop}, A → C) (x : B) : C := by specialize @f _ x exact f example (X : Type) [Add X] (f : forall {A : Type} [Add A], A → A → A) (x : X) : X := by specialize f x x assumption def ex (f : Nat → Nat → Nat) : Nat := by specialize f _ _ exact f exact 10 exact 2 example : ex (. - .) = 8 := rfl
f63452293e38d09d3aaaa6a8369a6806f2af6575
f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83
/algebra/ordered_ring.lean
20e61ae71c042d3254f2ca4d53533d80e1c8d940
[ "Apache-2.0" ]
permissive
mjendrusch/mathlib
df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214
5c209edb7eb616a26f64efe3500f2b1ba95b8d55
refs/heads/master
1,585,663,284,800
1,539,062,055,000
1,539,062,055,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,161
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import order.basic algebra.order algebra.ordered_group algebra.ring universe u variable {α : Type u} -- TODO: this is necessary additionally to mul_nonneg otherwise the simplifier can not match lemma zero_le_mul [ordered_semiring α] {a b : α} : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := mul_nonneg section linear_ordered_semiring variable [linear_ordered_semiring α] @[simp] lemma mul_le_mul_left {a b c : α} (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h)⟩ @[simp] lemma mul_le_mul_right {a b c : α} (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h)⟩ @[simp] lemma mul_lt_mul_left {a b c : α} (h : 0 < c) : c * a < c * b ↔ a < b := ⟨λ h', lt_of_mul_lt_mul_left h' (le_of_lt h), λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right {a b c : α} (h : 0 < c) : a * c < b * c ↔ a < b := ⟨λ h', lt_of_mul_lt_mul_right h' (le_of_lt h), λ h', mul_lt_mul_of_pos_right h' h⟩ lemma mul_lt_mul'' {a b c d : α} (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := (lt_or_eq_of_le h4).elim (λ b0, mul_lt_mul h1 (le_of_lt h2) b0 (le_trans h3 (le_of_lt h1))) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (lt_of_le_of_lt h3 h1) (lt_of_le_of_lt h4 h2)) lemma le_mul_iff_one_le_left {a b : α} (hb : b > 0) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left {a b : α} (hb : b > 0) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right {a b : α} (hb : b > 0) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right {a b : α} (hb : b > 0) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb lemma lt_mul_of_gt_one_right' {a b : α} (hb : b > 0) : a > 1 → b < b * a := (lt_mul_iff_one_lt_right hb).2 lemma le_mul_of_ge_one_right' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_ge_one_left' {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, mul_le_mul_of_nonneg_right h hb theorem mul_nonneg_iff_right_nonneg_of_pos {a b : α} (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := ⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩ lemma bit1_pos {a : α} (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma bit1_pos' {a : α} (h : 0 < a) : 0 < bit1 a := bit1_pos (le_of_lt h) lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos (le_refl _) zero_lt_one lemma one_lt_two : 1 < (2 : α) := lt_add_one _ lemma one_lt_mul {a b : α} (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := (one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha) lemma mul_le_one {a b : α} (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end lemma mul_le_iff_le_one_left {a b : α} (hb : b > 0) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 (not_lt_of_ge h)), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 (not_lt_of_ge h)) ⟩ lemma mul_lt_iff_lt_one_left {a b : α} (hb : b > 0) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 (not_le_of_gt h)), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 (not_le_of_gt h)) ⟩ lemma mul_le_iff_le_one_right {a b : α} (hb : b > 0) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 (not_lt_of_ge h)), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 (not_lt_of_ge h)) ⟩ lemma mul_lt_iff_lt_one_right {a b : α} (hb : b > 0) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 (not_le_of_gt h)), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 (not_le_of_gt h)) ⟩ end linear_ordered_semiring instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ instance linear_ordered_semiring.to_no_bot_order {α : Type*} [linear_ordered_ring α] : no_bot_order α := ⟨assume a, ⟨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩ instance to_domain [s : linear_ordered_ring α] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α s, ..s } section linear_ordered_ring variable [linear_ordered_ring α] @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := ⟨le_imp_le_iff_lt_imp_lt.2 $ λ h', mul_lt_mul_of_neg_left h' h, λ h', mul_le_mul_of_nonpos_left h' (le_of_lt h)⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := ⟨le_imp_le_iff_lt_imp_lt.2 $ λ h', mul_lt_mul_of_neg_right h' h, λ h', mul_le_mul_of_nonpos_right h' (le_of_lt h)⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := le_iff_le_iff_lt_iff_lt.1 (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := le_iff_le_iff_lt_iff_lt.1 (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] end linear_ordered_ring set_option old_structure_cmd true /-- Extend `nonneg_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, zero_ne_one_class α, nonneg_comm_group α := (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) /-- Extend `nonneg_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_comm_group α := (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) namespace nonneg_ring open nonneg_comm_group variable [s : nonneg_ring α] instance to_ordered_ring : ordered_ring α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, add_lt_add_left := @add_lt_add_left _ _, add_le_add_left := @add_le_add_left _ _, mul_nonneg := λ a b, by simp [nonneg_def.symm]; exact mul_nonneg, mul_pos := λ a b, by simp [pos_def.symm]; exact mul_pos, ..s } def nonneg_ring.to_linear_nonneg_ring (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, classical.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, classical.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _ _).2 ⟨na, pa⟩) ((pos_iff _ _).2 ⟨nb, pb⟩))), ..s } end nonneg_ring namespace linear_nonneg_ring open nonneg_comm_group variable [s : linear_nonneg_ring α] instance to_nonneg_ring : nonneg_ring α := { mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff α a).1 pa, ⟨b1, b2⟩ := (pos_iff α b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff α _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..s } instance to_linear_order : linear_order α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, ..s } instance to_linear_ordered_ring : linear_ordered_ring α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := @le_total _ _, add_lt_add_left := @add_lt_add_left _ _, add_le_add_left := @add_le_add_left _ _, mul_nonneg := by simp [nonneg_def.symm]; exact @mul_nonneg _ _, mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_lt_one := lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one _ (nonneg_antisymm this h).symm end, ..s } instance to_decidable_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : decidable_linear_ordered_comm_ring α := { decidable_le := by apply_instance, decidable_eq := by apply_instance, decidable_lt := by apply_instance, mul_comm := is_commutative.comm (*), ..@linear_nonneg_ring.to_linear_ordered_ring _ s } end linear_nonneg_ring class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_monoid α, comm_semiring α, zero_ne_one_class α := (mul_eq_zero_iff (a b : α) : a * b = 0 ↔ a = 0 ∨ b = 0) namespace canonically_ordered_semiring open canonically_ordered_monoid lemma mul_le_mul [canonically_ordered_comm_semiring α] {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a * c ≤ b * d := begin rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩, rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩, suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul], exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩ end end canonically_ordered_semiring instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, zero_ne_one := ne_of_lt zero_lt_one, mul_eq_zero_iff := assume a b, iff.intro nat.eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}), .. (infer_instance : ordered_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } namespace with_top variables [canonically_ordered_comm_semiring α] [decidable_eq α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } instance : has_one (with_top α) := ⟨↑(1:α)⟩ lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] theorem top_ne_zero [partial_order α] : ⊤ ≠ (0 : with_top α) . @[simp] theorem zero_ne_top [partial_order α] : (0 : with_top α) ≠ ⊤ . @[simp] theorem coe_eq_zero [partial_order α] {a : α} : (a : with_top α) = 0 ↔ a = 0 := iff.intro (assume h, match a, h with _, rfl := rfl end) (assume h, h.symm ▸ rfl) @[simp] theorem zero_eq_coe [partial_order α] {a : α} : 0 = (a : with_top α) ↔ a = 0 := by rw [eq_comm, coe_eq_zero] @[simp] theorem coe_zero [partial_order α] : ↑(0 : α) = (0 : with_top α) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by simp [*, mul_def]; refl lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm private lemma comm (a b : with_top α) : a * b = b * a := begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end private lemma mul_eq_zero (a b : with_top α) : a * b = 0 ↔ a = 0 ∨ b = 0 := by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, canonically_ordered_comm_semiring.mul_eq_zero_iff] at * private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) := begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top, mul_eq_zero b c] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a c] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a ↑b] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end private lemma one_mul' : ∀a : with_top α, 1 * a = a | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm] instance [canonically_ordered_comm_semiring α] [decidable_eq α] : canonically_ordered_comm_semiring (with_top α) := { one := (1 : α), right_distrib := distrib', left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl, mul_assoc := assoc, mul_comm := comm, mul_eq_zero_iff := mul_eq_zero, one_mul := one_mul', mul_one := assume a, by rw [comm, one_mul'], zero_ne_one := assume h, @zero_ne_one α _ $ option.some.inj h, .. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_monoid } end with_top
ad7867c7ec495e39669849c5be138afcda763689
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/abel.lean
e108a84616ab8b44f835c36a78e3404ebd42bfe6
[ "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
13,509
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num /-! # The `abel` tactic Evaluate expressions in the language of additive, commutative monoids and groups. -/ namespace tactic namespace abel meta structure cache := (α : expr) (univ : level) (α0 : expr) (is_group : bool) (inst : expr) meta def mk_cache (e : expr) : tactic cache := do α ← infer_type e, c ← mk_app ``add_comm_monoid [α] >>= mk_instance, cg ← try_core (mk_app ``add_comm_group [α] >>= mk_instance), u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, α0 ← expr.of_nat α 0, match cg with | (some cg) := return ⟨α, u, α0, tt, cg⟩ | _ := return ⟨α, u, α0, ff, c⟩ end meta def cache.app (c : cache) (n : name) (inst : expr) : list expr → expr := (@expr.const tt n [c.univ] c.α inst).mk_app meta def cache.mk_app (c : cache) (n inst : name) (l : list expr) : tactic expr := do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ c.app n m l meta def add_g : name → name | (name.mk_string s p) := name.mk_string (s ++ "g") p | n := n meta def cache.iapp (c : cache) (n : name) : list expr → expr := c.app (if c.is_group then add_g n else n) c.inst def term {α} [add_comm_monoid α] (n : ℕ) (x a : α) : α := n • x + a def termg {α} [add_comm_group α] (n : ℤ) (x a : α) : α := n • x + a meta def cache.mk_term (c : cache) (n x a : expr) : expr := c.iapp ``term [n, x, a] meta def cache.int_to_expr (c : cache) (n : ℤ) : tactic expr := expr.of_int (if c.is_group then `(ℤ) else `(ℕ)) n meta inductive normal_expr : Type | zero (e : expr) : normal_expr | nterm (e : expr) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr meta def normal_expr.e : normal_expr → expr | (normal_expr.zero e) := e | (normal_expr.nterm e _ _ _) := e meta instance : has_coe normal_expr expr := ⟨normal_expr.e⟩ meta instance : has_coe_to_fun normal_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ meta def normal_expr.term' (c : cache) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr := normal_expr.nterm (c.mk_term n.1 x a) n x a meta def normal_expr.zero' (c : cache) : normal_expr := normal_expr.zero c.α0 meta def normal_expr.to_list : normal_expr → list (ℤ × expr) | (normal_expr.zero _) := [] | (normal_expr.nterm _ (_, n) x a) := (n, x) :: a.to_list open normal_expr meta def normal_expr.to_string (e : normal_expr) : string := " + ".intercalate $ (to_list e).map $ λ ⟨n, e⟩, to_string n ++ " • (" ++ to_string e ++ ")" meta def normal_expr.pp (e : normal_expr) : tactic format := do l ← (to_list e).mmap (λ ⟨n, e⟩, do pe ← pp e, return (to_fmt n ++ " • (" ++ pe ++ ")")), return $ format.join $ l.intersperse ↑" + " meta instance : has_to_tactic_format normal_expr := ⟨normal_expr.pp⟩ meta def normal_expr.refl_conv (e : normal_expr) : tactic (normal_expr × expr) := do p ← mk_eq_refl e, return (e, p) theorem const_add_term {α} [add_comm_monoid α] (k n x a a') (h : k + a = a') : k + @term α _ n x a = term n x a' := by simp [h.symm, term]; ac_refl theorem const_add_termg {α} [add_comm_group α] (k n x a a') (h : k + a = a') : k + @termg α _ n x a = termg n x a' := by simp [h.symm, termg]; ac_refl theorem term_add_const {α} [add_comm_monoid α] (n x a k a') (h : a + k = a') : @term α _ n x a + k = term n x a' := by simp [h.symm, term, add_assoc] theorem term_add_constg {α} [add_comm_group α] (n x a k a') (h : a + k = a') : @termg α _ n x a + k = termg n x a' := by simp [h.symm, termg, add_assoc] theorem term_add_term {α} [add_comm_monoid α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @term α _ n₁ x a₁ + @term α _ n₂ x a₂ = term n' x a' := by simp [h₁.symm, h₂.symm, term, add_nsmul]; ac_refl theorem term_add_termg {α} [add_comm_group α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @termg α _ n₁ x a₁ + @termg α _ n₂ x a₂ = termg n' x a' := by simp [h₁.symm, h₂.symm, termg, add_gsmul]; ac_refl theorem zero_term {α} [add_comm_monoid α] (x a) : @term α _ 0 x a = a := by simp [term, zero_nsmul, one_nsmul] theorem zero_termg {α} [add_comm_group α] (x a) : @termg α _ 0 x a = a := by simp [termg] meta def eval_add (c : cache) : normal_expr → normal_expr → tactic (normal_expr × expr) | (zero _) e₂ := do p ← mk_app ``zero_add [e₂], return (e₂, p) | e₁ (zero _) := do p ← mk_app ``add_zero [e₁], return (e₁, p) | he₁@(nterm e₁ n₁ x₁ a₁) he₂@(nterm e₂ n₂ x₂ a₂) := if expr.lex_lt x₁ x₂ then do (a', h) ← eval_add a₁ he₂, return (term' c n₁ x₁ a', c.iapp ``term_add_const [n₁.1, x₁, a₁, e₂, a', h]) else if x₁ ≠ x₂ then do (a', h) ← eval_add he₁ a₂, return (term' c n₂ x₂ a', c.iapp ``const_add_term [e₁, n₂.1, x₂, a₂, a', h]) else do (n', h₁) ← mk_app ``has_add.add [n₁.1, n₂.1] >>= norm_num.eval_field, (a', h₂) ← eval_add a₁ a₂, let k := n₁.2 + n₂.2, let p₁ := c.iapp ``term_add_term [n₁.1, x₁, a₁, n₂.1, a₂, n', a', h₁, h₂], if k = 0 then do p ← mk_eq_trans p₁ (c.iapp ``zero_term [x₁, a']), return (a', p) else return (term' c (n', k) x₁ a', p₁) theorem term_neg {α} [add_comm_group α] (n x a n' a') (h₁ : -n = n') (h₂ : -a = a') : -@termg α _ n x a = termg n' x a' := by simp [h₂.symm, h₁.symm, termg]; ac_refl meta def eval_neg (c : cache) : normal_expr → tactic (normal_expr × expr) | (zero e) := do p ← c.mk_app ``neg_zero ``add_group [], return (zero' c, p) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_neg.neg [n.1] >>= norm_num.eval_field, (a', h₂) ← eval_neg a, return (term' c (n', -n.2) x a', c.app ``term_neg c.inst [n.1, x, a, n', a', h₁, h₂]) def smul {α} [add_comm_monoid α] (n : ℕ) (x : α) : α := n • x def smulg {α} [add_comm_group α] (n : ℤ) (x : α) : α := n • x theorem zero_smul {α} [add_comm_monoid α] (c) : smul c (0 : α) = 0 := by simp [smul, nsmul_zero] theorem zero_smulg {α} [add_comm_group α] (c) : smulg c (0 : α) = 0 := by simp [smulg] theorem term_smul {α} [add_comm_monoid α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smul c a = a') : smul c (@term α _ n x a) = term n' x a' := by simp [h₂.symm, h₁.symm, term, smul, nsmul_add, mul_nsmul] theorem term_smulg {α} [add_comm_group α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smulg c a = a') : smulg c (@termg α _ n x a) = termg n' x a' := by simp [h₂.symm, h₁.symm, termg, smulg, gsmul_add, mul_gsmul] meta def eval_smul (c : cache) (k : expr × ℤ) : normal_expr → tactic (normal_expr × expr) | (zero _) := return (zero' c, c.iapp ``zero_smul [k.1]) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_mul.mul [k.1, n.1] >>= norm_num.eval_field, (a', h₂) ← eval_smul a, return (term' c (n', k.2 * n.2) x a', c.iapp ``term_smul [k.1, n.1, x, a, n', a', h₁, h₂]) theorem term_atom {α} [add_comm_monoid α] (x : α) : x = term 1 x 0 := by simp [term] theorem term_atomg {α} [add_comm_group α] (x : α) : x = termg 1 x 0 := by simp [termg] meta def eval_atom (c : cache) (e : expr) : tactic (normal_expr × expr) := do n1 ← c.int_to_expr 1, return (term' c (n1, 1) e (zero' c), c.iapp ``term_atom [e]) lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] theorem unfold_smul {α} [add_comm_monoid α] (n) (x y : α) (h : smul n x = y) : n • x = y := h theorem unfold_smulg {α} [add_comm_group α] (n : ℕ) (x y : α) (h : smulg (int.of_nat n) x = y) : (n : ℤ) • x = y := h theorem unfold_gsmul {α} [add_comm_group α] (n : ℤ) (x y : α) (h : smulg n x = y) : gsmul n x = y := h lemma subst_into_smul {α} [add_comm_monoid α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smul α _ tl tr = t) : smul l r = t := by simp [prl, prr, prt] lemma subst_into_smulg {α} [add_comm_group α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smulg α _ tl tr = t) : smulg l r = t := by simp [prl, prr, prt] /-- Deal with a `smul` term of the form `e₁ • e₂`, handling both natural and integer `e₁`. -/ meta def eval_smul' (c : cache) (eval : expr → tactic (normal_expr × expr)) (e₁ e₂ : expr) : tactic (normal_expr × expr) := do (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁, n ← if c.is_group then e₁'.to_int else coe <$> e₁'.to_nat, (e₂', p₂) ← eval e₂, (e', p) ← eval_smul c (e₁', n) e₂', return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p]) meta def eval (c : cache) : expr → tactic (normal_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add c e₁' e₂', p ← c.mk_app ``norm_num.subst_into_add ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | `(%%e₁ - %%e₂) := do e₂' ← mk_app ``has_neg.neg [e₂], e ← mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← c.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p], return (e', p') | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg c e₁, p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(nsmul %%e₁ %%e₂) := do n ← if c.is_group then mk_app ``int.of_nat [e₁] else return e₁, (e', p) ← eval $ c.iapp ``smul [n, e₂], return (e', c.iapp ``unfold_smul [e₁, e₂, e', p]) | `(gsmul %%e₁ %%e₂) := do guardb c.is_group, (e', p) ← eval $ c.iapp ``smul [e₁, e₂], return (e', c.app ``unfold_gsmul c.inst [e₁, e₂, e', p]) | `(@has_scalar.smul nat _ add_monoid.has_scalar_nat %%e₁ %%e₂) := eval_smul' c eval e₁ e₂ | `(@has_scalar.smul int _ sub_neg_monoid.has_scalar_int %%e₁ %%e₂) := eval_smul' c eval e₁ e₂ | `(smul %%e₁ %%e₂) := eval_smul' c eval e₁ e₂ | `(smulg %%e₁ %%e₂) := eval_smul' c eval e₁ e₂ | e := eval_atom c e meta def eval' (c : cache) (e : expr) : tactic (expr × expr) := do (e', p) ← eval c e, return (e', p) @[derive has_reflect] inductive normalize_mode | raw | term instance : inhabited normalize_mode := ⟨normalize_mode.term⟩ meta def normalize (mode := normalize_mode.term) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.term := [``term.equations._eqn_1, ``termg.equations._eqn_1, ``add_zero, ``one_nsmul, ``one_gsmul, ``gsmul_zero] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do c ← mk_cache e, (new_e, pr) ← match mode with | normalize_mode.raw := eval' c | normalize_mode.term := trans_conv (eval' c) (λ e, do (e', prf, _) ← simplify lemmas [] e, return (e', prf)) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end abel namespace interactive open interactive interactive.types lean.parser open tactic.abel local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *additive*, commutative monoids and groups. This version of `abel` fails if the target is not an equality that is provable by the axioms of commutative monoids/groups. -/ meta def abel1 : tactic unit := do `(%%e₁ = %%e₂) ← target, c ← mk_cache e₁, (e₁', p₁) ← eval c e₁, (e₂', p₂) ← eval c e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def abel.mode : lean.parser abel.normalize_mode := with_desc "(raw|term)?" $ do mode ← ident?, match mode with | none := return abel.normalize_mode.term | some `term := return abel.normalize_mode.term | some `raw := return abel.normalize_mode.raw | _ := failed end /-- Evaluate expressions in the language of *additive*, commutative monoids and groups. It attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails, it falls back to rewriting all monoid expressions into a normal form. If there is an `at` specifier, it rewrites the given target into a normal form. ```lean example {α : Type*} {a b : α} [add_comm_monoid α] : a + (b + a) = a + a + b := by abel example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - ((b + a) + a) = -a := by abel example {α : Type*} {a b : α} [add_comm_group α] (hyp : a + a - a = b - b) : a = 0 := by { abel at hyp, exact hyp } ``` -/ meta def abel (SOP : parse abel.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := abel1 | _ := failed end <|> do ns ← loc.get_locals, tt ← tactic.replace_at (normalize SOP) ns loc.include_goal | fail "abel failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "abel", category := doc_category.tactic, decl_names := [`tactic.interactive.abel], tags := ["arithmetic", "decision procedure"] } end interactive end tactic
3f51adf80b3dfb4487162e30d3c8178d8f2be8ee
e58fe8dce8abdb027029831196eef44ecb90a19a
/Imperial/def_ex.lean
5d1eb51c651ef03993dfb4fbb4ec69a0fc5327a7
[]
no_license
hieule3004/Imperial
89fc066eded43cf6015e19f6f83677411013b47c
829d0d96603ff3e68ede818873db4931b8d854da
refs/heads/master
1,584,834,346,353
1,531,250,018,000
1,531,250,018,000
139,205,362
0
0
null
null
null
null
UTF-8
Lean
false
false
2,165
lean
namespace hidden def divides (m n : ℕ) : Prop := ∃ k, m * k = n instance : has_dvd nat := ⟨divides⟩ def even (n : ℕ) : Prop := 2 ∣ n section user_def def pow : ℕ → ℕ → ℕ-- [¬ (m = 0 ∧ n = 0)] | 0 0 := sorry | _ 0 := 1 | m (nat.succ n) := m * pow m n end user_def -- BEGIN def prime (n : ℕ) : Prop := n > 1 ∧ (∀ m : ℕ, 1 < m ∧ m < n → ¬ divides n m) def infinitely_many_primes : Prop := ∀ n : ℕ, prime n → ∃ m : ℕ, m > n ∧ prime m def Fermat_prime (n : ℕ) : Prop := ∃ m : ℕ, n = pow 2 (pow 2 m) + 1 def infinitely_many_Fermat_primes : Prop := ∀ n : ℕ, Fermat_prime n → ∃ m : ℕ, m > n ∧ Fermat_prime m def goldbach_conjecture : Prop := ∀ n : ℕ, even n ∧ n > 2 → ∃ p1 p2 : ℕ, prime p1 ∧ prime p2 ∧ n = p1 + p2 def Goldbach's_weak_conjecture : Prop := ∀ n : ℕ, ¬ even n ∧ n > 5 → ∃ p1 p2 p3 : ℕ, prime p1 ∧ prime p2 ∧ prime p3 ∧ n = p1 + p2 + p3 def Fermat's_last_theorem : Prop := ∀ n : ℕ, n > 2 → ¬ ∃ a b c : ℕ, pow a n + pow b n = pow c n -- END end hidden section variables (real : Type) [ordered_ring real] variables (log exp : real → real) variable log_exp_eq : ∀ x, log (exp x) = x variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x variable exp_pos : ∀ x, exp x > 0 variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- this ensures the assumptions are available in tactic proofs include log_exp_eq exp_log_eq exp_pos exp_add example (x y z : real) : exp (x + y + z) = exp x * exp y * exp z := by rw [exp_add, exp_add] example (y : real) (h : y > 0) : exp (log y) = y := exp_log_eq h theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := calc log (x * y) = log (exp (log x) * y) : by rw [exp_log_eq hx] ... = log (exp (log x) * exp (log y)) : by rw [exp_log_eq hy] ... = log (exp (log x + log y)) : by rw [exp_add] ... = log x + log y : by rw [log_exp_eq] end section example (x : ℤ) : x * 0 = 0 := calc x * 0 = x * (x - x) : by rw [sub_self] ... = x * x - x * x : by rw [mul_sub] ... = 0 : by rw [sub_self] end
c793da9f3cc386e272cbbac9e726bf34572bb15b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/lattice.lean
c6cc3ce3ae7de15fa83205c4d38ed65bbaed8451
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,111
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.monotone import order.rel_classes import tactic.simps import tactic.pi_instances /-! # (Semi-)lattices Semilattices are partially ordered sets with join (greatest lower bound, or `sup`) or meet (least upper bound, or `inf`) operations. Lattices are posets that are both join-semilattices and meet-semilattices. Distributive lattices are lattices which satisfy any of four equivalent distributivity properties, of `sup` over `inf`, on the left or on the right. ## Main declarations * `has_sup`: type class for the `⊔` notation * `has_inf`: type class for the `⊓` notation * `semilattice_sup`: a type class for join semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_sup` via proofs that `⊔` is commutative, associative and idempotent. * `semilattice_inf`: a type class for meet semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_inf` via proofs that `⊓` is commutative, associative and idempotent. * `lattice`: a type class for lattices * `lattice.mk'`: an alternative constructor for `lattice` via profs that `⊔` and `⊓` are commutative, associative and satisfy a pair of "absorption laws". * `distrib_lattice`: a type class for distributive lattices. ## Notations * `a ⊔ b`: the supremum or join of `a` and `b` * `a ⊓ b`: the infimum or meet of `a` and `b` ## TODO * (Semi-)lattice homomorphisms * Alternative constructors for distributive lattices from the other distributive properties ## Tags semilattice, lattice -/ set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := @le_antisymm _ _ end /- TODO: automatic construction of dual definitions / theorems -/ /-- Typeclass for the `⊔` (`\lub`) notation -/ @[notation_class] class has_sup (α : Type u) := (sup : α → α → α) /-- Typeclass for the `⊓` (`\glb`) notation -/ @[notation_class] class has_inf (α : Type u) := (inf : α → α → α) infix ⊔ := has_sup.sup infix ⊓ := has_inf.inf /-! ### Join-semilattices -/ /-- A `semilattice_sup` is a join-semilattice, that is, a partial order with a join (a.k.a. lub / least upper bound, sup / supremum) operation `⊔` which is the least element larger than both factors. -/ class semilattice_sup (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) /-- A type with a commutative, associative and idempotent binary `sup` operation has the structure of a join-semilattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def semilattice_sup.mk' {α : Type*} [has_sup α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) : semilattice_sup α := { sup := (⊔), le := λ a b, a ⊔ b = b, le_refl := sup_idem, le_trans := λ a b c hab hbc, begin dsimp only [(≤)] at *, rwa [←hbc, ←sup_assoc, hab], end, le_antisymm := λ a b hab hba, begin dsimp only [(≤)] at *, rwa [←hba, sup_comm], end, le_sup_left := λ a b, show a ⊔ (a ⊔ b) = (a ⊔ b), by rw [←sup_assoc, sup_idem], le_sup_right := λ a b, show b ⊔ (a ⊔ b) = (a ⊔ b), by rw [sup_comm, sup_assoc, sup_idem], sup_le := λ a b c hac hbc, begin dsimp only [(≤), preorder.le] at *, rwa [sup_assoc, hbc], end } instance (α : Type*) [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩ instance (α : Type*) [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩ section semilattice_sup variables [semilattice_sup α] {a b c d : α} @[simp] theorem le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) := le_sup_left @[simp] theorem le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) := le_sup_right theorem le_sup_of_le_left (h : c ≤ a) : c ≤ a ⊔ b := le_trans h le_sup_left theorem le_sup_of_le_right (h : c ≤ b) : c ≤ a ⊔ b := le_trans h le_sup_right theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ @[simp] theorem sup_eq_left : a ⊔ b = a ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a := sup_eq_left.2 h @[simp] theorem left_eq_sup : a = a ⊔ b ↔ b ≤ a := eq_comm.trans sup_eq_left @[simp] theorem sup_eq_right : a ⊔ b = b ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b := sup_eq_right.2 h @[simp] theorem right_eq_sup : b = a ⊔ b ↔ a ≤ b := eq_comm.trans sup_eq_right theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := sup_le (le_sup_of_le_left h₁) (le_sup_of_le_right h₂) theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b := sup_le_sup (le_refl _) h₁ theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c := sup_le_sup h₁ (le_refl _) theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by { rw ← h, simp } lemma sup_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊔ b) := (is_total.total a b).elim (λ h : a ≤ b, by rwa sup_eq_right.2 h) (λ h, by rwa sup_eq_left.2 h) @[simp] lemma sup_lt_iff [is_total α (≤)] {a b c : α} : b ⊔ c < a ↔ b < a ∧ c < a := ⟨λ h, ⟨le_sup_left.trans_lt h, le_sup_right.trans_lt h⟩, λ h, sup_ind b c h.1 h.2⟩ @[simp] lemma le_sup_iff [is_total α (≤)] {a b c : α} : a ≤ b ⊔ c ↔ a ≤ b ∨ a ≤ c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim le_sup_of_le_left le_sup_of_le_right⟩ @[simp] lemma lt_sup_iff [is_total α (≤)] {a b c : α} : a < b ⊔ c ↔ a < b ∨ a < c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim (λ h, h.trans_le le_sup_left) (λ h, h.trans_le le_sup_right)⟩ @[simp] theorem sup_idem : a ⊔ a = a := by apply le_antisymm; simp instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩ theorem sup_comm : a ⊔ b = b ⊔ a := by apply le_antisymm; simp instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := le_antisymm (sup_le (sup_le le_sup_left (le_sup_of_le_right le_sup_left)) (le_sup_of_le_right le_sup_right)) (sup_le (le_sup_of_le_left le_sup_left) (sup_le (le_sup_of_le_left le_sup_right) le_sup_right)) instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ lemma sup_left_right_swap (a b c : α) : a ⊔ b ⊔ c = c ⊔ b ⊔ a := by rw [sup_comm, @sup_comm _ _ a, sup_assoc] @[simp] lemma sup_left_idem : a ⊔ (a ⊔ b) = a ⊔ b := by rw [← sup_assoc, sup_idem] @[simp] lemma sup_right_idem : (a ⊔ b) ⊔ b = a ⊔ b := by rw [sup_assoc, sup_idem] lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) := by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a] lemma sup_right_comm (a b c : α) : a ⊔ b ⊔ c = a ⊔ c ⊔ b := by rw [sup_assoc, sup_assoc, @sup_comm _ _ b] lemma sup_sup_sup_comm (a b c d : α) : a ⊔ b ⊔ (c ⊔ d) = a ⊔ c ⊔ (b ⊔ d) := by rw [sup_assoc, sup_left_comm b, ←sup_assoc] lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) := suffices (∃b, ¬b ≤ a) → (∃b, a < b), by rwa [or_iff_not_imp_left, not_forall], assume ⟨b, hb⟩, ⟨a ⊔ b, lt_of_le_of_ne le_sup_left $ mt left_eq_sup.1 hb⟩ /-- If `f` is monotone, `g` is antitone, and `f ≤ g`, then for all `a`, `b` we have `f a ≤ g b`. -/ theorem monotone.forall_le_of_antitone {β : Type*} [preorder β] {f g : α → β} (hf : monotone f) (hg : antitone g) (h : f ≤ g) (m n : α) : f m ≤ g n := calc f m ≤ f (m ⊔ n) : hf le_sup_left ... ≤ g (m ⊔ n) : h _ ... ≤ g n : hg le_sup_right theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y := eq_of_forall_ge_iff $ λ c, by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H] theorem semilattice_sup.ext {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x), casesI A, casesI B, injection this; congr' end theorem exists_lt_of_sup (α : Type*) [semilattice_sup α] [nontrivial α] : ∃ a b : α, a < b := begin rcases exists_pair_ne α with ⟨a, b, hne⟩, rcases forall_le_or_exists_lt_sup b with (hb|H), exacts [⟨a, b, (hb a).lt_of_ne hne⟩, ⟨b, H⟩] end end semilattice_sup /-! ### Meet-semilattices -/ /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) instance (α) [semilattice_inf α] : semilattice_sup (order_dual α) := { le_sup_left := semilattice_inf.inf_le_left, le_sup_right := semilattice_inf.inf_le_right, sup_le := assume a b c hca hcb, @semilattice_inf.le_inf α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_sup α } instance (α) [semilattice_sup α] : semilattice_inf (order_dual α) := { inf_le_left := @le_sup_left α _, inf_le_right := @le_sup_right α _, le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_inf α } theorem semilattice_sup.dual_dual (α : Type*) [H : semilattice_sup α] : order_dual.semilattice_sup (order_dual α) = H := semilattice_sup.ext $ λ _ _, iff.rfl section semilattice_inf variables [semilattice_inf α] {a b c d : α} @[simp] theorem inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b @[simp] theorem inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c theorem inf_le_of_left_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h theorem inf_le_of_right_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h @[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := @sup_le_iff (order_dual α) _ _ _ _ @[simp] theorem inf_eq_left : a ⊓ b = a ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a := inf_eq_left.2 h @[simp] theorem left_eq_inf : a = a ⊓ b ↔ a ≤ b := eq_comm.trans inf_eq_left @[simp] theorem inf_eq_right : a ⊓ b = b ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b := inf_eq_right.2 h @[simp] theorem right_eq_inf : b = a ⊓ b ↔ b ≤ a := eq_comm.trans inf_eq_right theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := le_inf (inf_le_of_left_le h₁) (inf_le_of_right_le h₂) lemma inf_le_inf_right (a : α) {b c : α} (h : b ≤ c) : b ⊓ a ≤ c ⊓ a := inf_le_inf h (le_refl _) lemma inf_le_inf_left (a : α) {b c : α} (h : b ≤ c) : a ⊓ b ≤ a ⊓ c := inf_le_inf (le_refl _) h theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := by { rw ← h, simp } lemma inf_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊓ b) := @sup_ind (order_dual α) _ _ _ _ _ ha hb @[simp] lemma lt_inf_iff [is_total α (≤)] {a b c : α} : a < b ⊓ c ↔ a < b ∧ a < c := @sup_lt_iff (order_dual α) _ _ _ _ _ @[simp] lemma inf_le_iff [is_total α (≤)] {a b c : α} : b ⊓ c ≤ a ↔ b ≤ a ∨ c ≤ a := @le_sup_iff (order_dual α) _ _ _ _ _ @[simp] theorem inf_idem : a ⊓ a = a := @sup_idem (order_dual α) _ _ instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩ theorem inf_comm : a ⊓ b = b ⊓ a := @sup_comm (order_dual α) _ _ _ instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := @sup_assoc (order_dual α) _ a b c instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ lemma inf_left_right_swap (a b c : α) : a ⊓ b ⊓ c = c ⊓ b ⊓ a := by rw [inf_comm, @inf_comm _ _ a, inf_assoc] @[simp] lemma inf_left_idem : a ⊓ (a ⊓ b) = a ⊓ b := @sup_left_idem (order_dual α) _ a b @[simp] lemma inf_right_idem : (a ⊓ b) ⊓ b = a ⊓ b := @sup_right_idem (order_dual α) _ a b lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := @sup_left_comm (order_dual α) _ a b c lemma inf_right_comm (a b c : α) : a ⊓ b ⊓ c = a ⊓ c ⊓ b := @sup_right_comm (order_dual α) _ a b c lemma inf_inf_inf_comm (a b c d : α) : a ⊓ b ⊓ (c ⊓ d) = a ⊓ c ⊓ (b ⊓ d) := @sup_sup_sup_comm (order_dual α) _ _ _ _ _ lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) := @forall_le_or_exists_lt_sup (order_dual α) _ a theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H] theorem semilattice_inf.ext {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x), casesI A, casesI B, injection this; congr' end theorem semilattice_inf.dual_dual (α : Type*) [H : semilattice_inf α] : order_dual.semilattice_inf (order_dual α) = H := semilattice_inf.ext $ λ _ _, iff.rfl theorem exists_lt_of_inf (α : Type*) [semilattice_inf α] [nontrivial α] : ∃ a b : α, a < b := let ⟨a, b, h⟩ := exists_lt_of_sup (order_dual α) in ⟨b, a, h⟩ end semilattice_inf /-- A type with a commutative, associative and idempotent binary `inf` operation has the structure of a meet-semilattice. The partial order is defined so that `a ≤ b` unfolds to `b ⊓ a = a`; cf. `inf_eq_right`. -/ def semilattice_inf.mk' {α : Type*} [has_inf α] (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) : semilattice_inf α := begin haveI : semilattice_sup (order_dual α) := semilattice_sup.mk' inf_comm inf_assoc inf_idem, haveI i := order_dual.semilattice_inf (order_dual α), exact i, end /-! ### Lattices -/ /-- A lattice is a join-semilattice which is also a meet-semilattice. -/ class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α instance (α) [lattice α] : lattice (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α } /-- The partial orders from `semilattice_sup_mk'` and `semilattice_inf_mk'` agree if `sup` and `inf` satisfy the lattice absorption laws `sup_inf_self` (`a ⊔ a ⊓ b = a`) and `inf_sup_self` (`a ⊓ (a ⊔ b) = a`). -/ lemma semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : @semilattice_sup.to_partial_order _ (semilattice_sup.mk' sup_comm sup_assoc sup_idem) = @semilattice_inf.to_partial_order _ (semilattice_inf.mk' inf_comm inf_assoc inf_idem) := partial_order.ext $ λ a b, show a ⊔ b = b ↔ b ⊓ a = a, from ⟨λ h, by rw [←h, inf_comm, inf_sup_self], λ h, by rw [←h, sup_comm, sup_inf_self]⟩ /-- A type with a pair of commutative and associative binary operations which satisfy two absorption laws relating the two operations has the structure of a lattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def lattice.mk' {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : lattice α := have sup_idem : ∀ (b : α), b ⊔ b = b := λ b, calc b ⊔ b = b ⊔ b ⊓ (b ⊔ b) : by rw inf_sup_self ... = b : by rw sup_inf_self, have inf_idem : ∀ (b : α), b ⊓ b = b := λ b, calc b ⊓ b = b ⊓ (b ⊔ b ⊓ b) : by rw sup_inf_self ... = b : by rw inf_sup_self, let semilatt_inf_inst := semilattice_inf.mk' inf_comm inf_assoc inf_idem, semilatt_sup_inst := semilattice_sup.mk' sup_comm sup_assoc sup_idem, -- here we help Lean to see that the two partial orders are equal partial_order_inst := @semilattice_sup.to_partial_order _ semilatt_sup_inst in have partial_order_eq : partial_order_inst = @semilattice_inf.to_partial_order _ semilatt_inf_inst := semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order _ _ _ _ _ _ sup_inf_self inf_sup_self, { inf_le_left := λ a b, by { rw partial_order_eq, apply inf_le_left }, inf_le_right := λ a b, by { rw partial_order_eq, apply inf_le_right }, le_inf := λ a b c, by { rw partial_order_eq, apply le_inf }, ..partial_order_inst, ..semilatt_sup_inst, ..semilatt_inf_inst, } section lattice variables [lattice α] {a b c d : α} lemma inf_le_sup : a ⊓ b ≤ a ⊔ b := inf_le_left.trans le_sup_left @[simp] lemma inf_lt_sup : a ⊓ b < a ⊔ b ↔ a ≠ b := begin split, { rintro H rfl, simpa using H }, { refine λ Hne, lt_iff_le_and_ne.2 ⟨inf_le_sup, λ Heq, Hne _⟩, refine le_antisymm _ _, exacts [le_sup_left.trans (Heq.symm.trans_le inf_le_right), le_sup_right.trans (Heq.symm.trans_le inf_le_left)] } end /-! #### Distributivity laws -/ /- TODO: better names? -/ theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := le_inf (sup_le_sup_left inf_le_left _) (sup_le_sup_left inf_le_right _) theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := sup_le (inf_le_inf_left _ le_sup_left) (inf_le_inf_left _ le_sup_right) theorem inf_sup_self : a ⊓ (a ⊔ b) = a := by simp theorem sup_inf_self : a ⊔ (a ⊓ b) = a := by simp theorem sup_eq_iff_inf_eq : a ⊔ b = b ↔ a ⊓ b = a := by rw [sup_eq_right, ←inf_eq_left] theorem lattice.ext {α} {A B : lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have SS : @lattice.to_semilattice_sup α A = @lattice.to_semilattice_sup α B := semilattice_sup.ext H, have II := semilattice_inf.ext H, casesI A, casesI B, injection SS; injection II; congr' end end lattice /-! ### Distributive lattices -/ /-- A distributive lattice is a lattice that satisfies any of four equivalent distributive properties (of `sup` over `inf` or `inf` over `sup`, on the left or right). The definition here chooses `le_sup_inf`: `(x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)`. A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) /- TODO: alternative constructors from the other distributive properties, and perhaps a `tfae` statement -/ section distrib_lattice variables [distrib_lattice α] {x y z : α} theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true] theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] instance (α : Type*) [distrib_lattice α] : distrib_lattice (order_dual α) := { le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm, .. order_dual.lattice α } theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true] lemma le_of_inf_le_sup_le (h₁ : x ⊓ z ≤ y ⊓ z) (h₂ : x ⊔ z ≤ y ⊔ z) : x ≤ y := calc x ≤ (y ⊓ z) ⊔ x : le_sup_right ... = (y ⊔ x) ⊓ (x ⊔ z) : by rw [sup_inf_right, @sup_comm _ _ x] ... ≤ (y ⊔ x) ⊓ (y ⊔ z) : inf_le_inf_left _ h₂ ... = y ⊔ (x ⊓ z) : sup_inf_left.symm ... ≤ y ⊔ (y ⊓ z) : sup_le_sup_left h₁ _ ... ≤ _ : sup_le (le_refl y) inf_le_left lemma eq_of_inf_eq_sup_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (le_of_inf_le_sup_le (le_of_eq h₁) (le_of_eq h₂)) (le_of_inf_le_sup_le (le_of_eq h₁.symm) (le_of_eq h₂.symm)) end distrib_lattice /-! ### Lattices derived from linear orders -/ @[priority 100] -- see Note [lower instance priority] instance lattice_of_linear_order {α : Type u} [o : linear_order α] : lattice α := { sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min, ..o } theorem sup_eq_max [linear_order α] {x y : α} : x ⊔ y = max x y := rfl theorem inf_eq_min [linear_order α] {x y : α} : x ⊓ y = min x y := rfl /-- A lattice with total order is a linear order. See note [reducible non-instances]. -/ @[reducible] def lattice.to_linear_order (α : Type u) [lattice α] [decidable_eq α] [decidable_rel ((≤) : α → α → Prop)] [decidable_rel ((<) : α → α → Prop)] (h : ∀ x y : α, x ≤ y ∨ y ≤ x) : linear_order α := { decidable_le := ‹_›, decidable_eq := ‹_›, decidable_lt := ‹_›, le_total := h, max := (⊔), max_def := by { funext x y, dunfold max_default, split_ifs with h', exacts [sup_of_le_left h', sup_of_le_right $ (h x y).resolve_right h'] }, min := (⊓), min_def := by { funext x y, dunfold min_default, split_ifs with h', exacts [inf_of_le_left h', inf_of_le_right $ (h x y).resolve_left h'] }, .. ‹lattice α› } @[priority 100] -- see Note [lower instance priority] instance distrib_lattice_of_linear_order {α : Type u} [o : linear_order α] : distrib_lattice α := { le_sup_inf := assume a b c, match le_total b c with | or.inl h := inf_le_of_left_le $ sup_le_sup_left (le_inf (le_refl b) h) _ | or.inr h := inf_le_of_right_le $ sup_le_sup_left (le_inf h (le_refl c)) _ end, ..lattice_of_linear_order } instance nat.distrib_lattice : distrib_lattice ℕ := by apply_instance /-! ### Function lattices -/ namespace pi variables {ι : Type*} {α' : ι → Type*} instance [Π i, has_sup (α' i)] : has_sup (Π i, α' i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply [Π i, has_sup (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl lemma sup_def [Π i, has_sup (α' i)] (f g : Π i, α' i) : f ⊔ g = λ i, f i ⊔ g i := rfl instance [Π i, has_inf (α' i)] : has_inf (Π i, α' i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply [Π i, has_inf (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl lemma inf_def [Π i, has_inf (α' i)] (f g : Π i, α' i) : f ⊓ g = λ i, f i ⊓ g i := rfl instance [Π i, semilattice_sup (α' i)] : semilattice_sup (Π i, α' i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance [Π i, semilattice_inf (α' i)] : semilattice_inf (Π i, α' i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance [Π i, lattice (α' i)] : lattice (Π i, α' i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance [Π i, distrib_lattice (α' i)] : distrib_lattice (Π i, α' i) := by refine_struct { .. pi.lattice }; tactic.pi_instance_derive_field end pi /-! ### Monotone functions and lattices -/ namespace monotone /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (f ⊔ g) := λ x y h, sup_le_sup (hf h) (hg h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (f ⊓ g) := λ x y h, inf_le_inf (hf h) (hg h) /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (λ x, max (f x) (g x)) := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (λ x, min (f x) (g x)) := hf.inf hg lemma le_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : monotone f) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := sup_le (h le_sup_left) (h le_sup_right) lemma map_sup [semilattice_sup α] [is_total α (≤)] [semilattice_sup β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (is_total.total x y).elim (λ h : x ≤ y, by simp only [h, hf h, sup_of_le_right]) (λ h, by simp only [h, hf h, sup_of_le_left]) lemma map_inf_le [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : monotone f) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := le_inf (h inf_le_left) (h inf_le_right) lemma map_inf [semilattice_inf α] [is_total α (≤)] [semilattice_inf β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := @monotone.map_sup (order_dual α) _ _ _ _ _ hf.dual x y end monotone /-! ### Products of (semi-)lattices -/ namespace prod variables (α β) instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩ instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩ instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) := { sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩, le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩, le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩, .. prod.partial_order α β, .. prod.has_sup α β } instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) := { le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩, inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩, inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩, .. prod.partial_order α β, .. prod.has_inf α β } instance [lattice α] [lattice β] : lattice (α × β) := { .. prod.semilattice_inf α β, .. prod.semilattice_sup α β } instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) := { le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩, .. prod.lattice α β } end prod /-! ### Subtypes of (semi-)lattices -/ namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype
17440384f5a7605c7f64d97b4dbfbfb88dea3e82
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/group_power.lean
35fe8ff491d983771b4165cf3eab0ec0e17e1c84
[ "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
8,364
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The power operation on monoids and groups. We separate this from group, because it depends on nat, which in turn depends on other parts of algebra. We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation a^n is used for the first, but users can locally redefine it to gpow when needed. Note: power adopts the convention that 0^0=1. -/ import data.nat.basic data.int.basic variables {A : Type} structure has_pow_nat [class] (A : Type) := (pow_nat : A → nat → A) definition pow_nat {A : Type} [s : has_pow_nat A] : A → nat → A := has_pow_nat.pow_nat infix ` ^ ` := pow_nat structure has_pow_int [class] (A : Type) := (pow_int : A → int → A) definition pow_int {A : Type} [s : has_pow_int A] : A → int → A := has_pow_int.pow_int /- monoid -/ section monoid open nat variable [s : monoid A] include s definition monoid.pow (a : A) : ℕ → A | 0 := 1 | (n+1) := a * monoid.pow n definition monoid_has_pow_nat [instance] : has_pow_nat A := has_pow_nat.mk monoid.pow theorem pow_zero (a : A) : a^0 = 1 := rfl theorem pow_succ (a : A) (n : ℕ) : a^(succ n) = a * a^n := rfl theorem pow_one (a : A) : a^1 = a := !mul_one theorem pow_two (a : A) : a^2 = a * a := calc a^2 = a * (a * 1) : rfl ... = a * a : mul_one theorem pow_three (a : A) : a^3 = a * (a * a) := calc a^3 = a * (a * (a * 1)) : rfl ... = a * (a * a) : mul_one theorem pow_four (a : A) : a^4 = a * (a * (a * a)) := calc a^4 = a * a^3 : rfl ... = a * (a * (a * a)) : pow_three theorem pow_succ' (a : A) : ∀n, a^(succ n) = a^n * a | 0 := by rewrite [pow_succ, *pow_zero, one_mul, mul_one] | (succ n) := by rewrite [pow_succ, pow_succ' at {1}, pow_succ, mul.assoc] theorem one_pow : ∀ n : ℕ, 1^n = (1:A) | 0 := rfl | (succ n) := by rewrite [pow_succ, one_mul, one_pow] theorem pow_add (a : A) (m n : ℕ) : a^(m + n) = a^m * a^n := begin induction n with n ih, {krewrite [nat.add_zero, pow_zero, mul_one]}, rewrite [add_succ, *pow_succ', ih, mul.assoc] end theorem pow_mul (a : A) (m : ℕ) : ∀ n, a^(m * n) = (a^m)^n | 0 := by rewrite [nat.mul_zero, pow_zero] | (succ n) := by rewrite [nat.mul_succ, pow_add, pow_succ', pow_mul] theorem pow_comm (a : A) (m n : ℕ) : a^m * a^n = a^n * a^m := by rewrite [-*pow_add, add.comm] end monoid /- commutative monoid -/ section comm_monoid open nat variable [s : comm_monoid A] include s theorem mul_pow (a b : A) : ∀ n, (a * b)^n = a^n * b^n | 0 := by rewrite [*pow_zero, mul_one] | (succ n) := by rewrite [*pow_succ', mul_pow, *mul.assoc, mul.left_comm a] end comm_monoid section group variable [s : group A] include s section nat open nat theorem inv_pow (a : A) : ∀n, (a⁻¹)^n = (a^n)⁻¹ | 0 := by rewrite [*pow_zero, one_inv] | (succ n) := by rewrite [pow_succ, pow_succ', inv_pow, mul_inv] theorem pow_sub (a : A) {m n : ℕ} (H : m ≥ n) : a^(m - n) = a^m * (a^n)⁻¹ := have H1 : m - n + n = m, from nat.sub_add_cancel H, have H2 : a^(m - n) * a^n = a^m, by rewrite [-pow_add, H1], eq_mul_inv_of_mul_eq H2 theorem pow_inv_comm (a : A) : ∀m n, (a⁻¹)^m * a^n = a^n * (a⁻¹)^m | 0 n := by rewrite [*pow_zero, one_mul, mul_one] | m 0 := by rewrite [*pow_zero, one_mul, mul_one] | (succ m) (succ n) := by rewrite [pow_succ' at {1}, pow_succ at {1}, pow_succ', pow_succ, *mul.assoc, inv_mul_cancel_left, mul_inv_cancel_left, pow_inv_comm] end nat open int definition gpow (a : A) : ℤ → A | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ open nat private lemma gpow_add_aux (a : A) (m n : nat) : gpow a ((of_nat m) + -[1+n]) = gpow a (of_nat m) * gpow a (-[1+n]) := or.elim (nat.lt_or_ge m (nat.succ n)) (assume H : (m < nat.succ n), have H1 : (#nat nat.succ n - m > nat.zero), from nat.sub_pos_of_lt H, calc gpow a ((of_nat m) + -[1+n]) = gpow a (sub_nat_nat m (nat.succ n)) : rfl ... = gpow a (-[1+ nat.pred (nat.sub (nat.succ n) m)]) : {sub_nat_nat_of_lt H} ... = (a ^ (nat.succ (nat.pred (nat.sub (nat.succ n) m))))⁻¹ : rfl ... = (a ^ (nat.succ n) * (a ^ m)⁻¹)⁻¹ : by krewrite [succ_pred_of_pos H1, pow_sub a (nat.le_of_lt H)] ... = a ^ m * (a ^ (nat.succ n))⁻¹ : by rewrite [mul_inv, inv_inv] ... = gpow a (of_nat m) * gpow a (-[1+n]) : rfl) (assume H : (m ≥ nat.succ n), calc gpow a ((of_nat m) + -[1+n]) = gpow a (sub_nat_nat m (nat.succ n)) : rfl ... = gpow a (#nat m - nat.succ n) : {sub_nat_nat_of_ge H} ... = a ^ m * (a ^ (nat.succ n))⁻¹ : pow_sub a H ... = gpow a (of_nat m) * gpow a (-[1+n]) : rfl) theorem gpow_add (a : A) : ∀i j : int, gpow a (i + j) = gpow a i * gpow a j | (of_nat m) (of_nat n) := !pow_add | (of_nat m) -[1+n] := !gpow_add_aux | -[1+m] (of_nat n) := by rewrite [add.comm, gpow_add_aux, ↑gpow, -*inv_pow, pow_inv_comm] | -[1+m] -[1+n] := calc gpow a (-[1+m] + -[1+n]) = (a^(#nat nat.succ m + nat.succ n))⁻¹ : rfl ... = (a^(nat.succ m))⁻¹ * (a^(nat.succ n))⁻¹ : by rewrite [pow_add, pow_comm, mul_inv] ... = gpow a (-[1+m]) * gpow a (-[1+n]) : rfl theorem gpow_comm (a : A) (i j : ℤ) : gpow a i * gpow a j = gpow a j * gpow a i := by rewrite [-*gpow_add, add.comm] end group section ordered_ring open nat variable [s : linear_ordered_ring A] include s theorem pow_pos {a : A} (H : a > 0) (n : ℕ) : a ^ n > 0 := begin induction n, krewrite pow_zero, apply zero_lt_one, rewrite pow_succ', apply mul_pos, apply v_0, apply H end theorem pow_ge_one_of_ge_one {a : A} (H : a ≥ 1) (n : ℕ) : a ^ n ≥ 1 := begin induction n, krewrite pow_zero, apply le.refl, rewrite [pow_succ', -mul_one 1], apply mul_le_mul v_0 H zero_le_one, apply le_of_lt, apply pow_pos, apply gt_of_ge_of_gt H zero_lt_one end theorem pow_two_add (n : ℕ) : (2:A)^n + 2^n = 2^(succ n) := by rewrite [pow_succ', -one_add_one_eq_two, left_distrib, *mul_one] end ordered_ring /- additive monoid -/ section add_monoid variable [s : add_monoid A] include s local attribute add_monoid.to_monoid [trans_instance] open nat definition nmul : ℕ → A → A := λ n a, a^n infix [priority algebra.prio] `⬝` := nmul theorem zero_nmul (a : A) : (0:ℕ) ⬝ a = 0 := pow_zero a theorem succ_nmul (n : ℕ) (a : A) : nmul (succ n) a = a + (nmul n a) := pow_succ a n theorem succ_nmul' (n : ℕ) (a : A) : succ n ⬝ a = nmul n a + a := pow_succ' a n theorem nmul_zero (n : ℕ) : n ⬝ 0 = (0:A) := one_pow n theorem one_nmul (a : A) : 1 ⬝ a = a := pow_one a theorem add_nmul (m n : ℕ) (a : A) : (m + n) ⬝ a = (m ⬝ a) + (n ⬝ a) := pow_add a m n theorem mul_nmul (m n : ℕ) (a : A) : (m * n) ⬝ a = m ⬝ (n ⬝ a) := eq.subst (mul.comm n m) (pow_mul a n m) theorem nmul_comm (m n : ℕ) (a : A) : (m ⬝ a) + (n ⬝ a) = (n ⬝ a) + (m ⬝ a) := pow_comm a m n end add_monoid /- additive commutative monoid -/ section add_comm_monoid open nat variable [s : add_comm_monoid A] include s local attribute add_comm_monoid.to_comm_monoid [trans_instance] theorem nmul_add (n : ℕ) (a b : A) : n ⬝ (a + b) = (n ⬝ a) + (n ⬝ b) := mul_pow a b n end add_comm_monoid section add_group variable [s : add_group A] include s local attribute add_group.to_group [trans_instance] section nat open nat theorem nmul_neg (n : ℕ) (a : A) : n ⬝ (-a) = -(n ⬝ a) := inv_pow a n theorem sub_nmul {m n : ℕ} (a : A) (H : m ≥ n) : (m - n) ⬝ a = (m ⬝ a) + -(n ⬝ a) := pow_sub a H theorem nmul_neg_comm (m n : ℕ) (a : A) : (m ⬝ (-a)) + (n ⬝ a) = (n ⬝ a) + (m ⬝ (-a)) := pow_inv_comm a m n end nat open int definition imul : ℤ → A → A := λ i a, gpow a i theorem add_imul (i j : ℤ) (a : A) : imul (i + j) a = imul i a + imul j a := gpow_add a i j theorem imul_comm (i j : ℤ) (a : A) : imul i a + imul j a = imul j a + imul i a := gpow_comm a i j end add_group
4cec198c4c74987508596724218a835bc087019c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/sigma/order.lean
3e026d226f1c2834a4d90991269802b0283228de
[ "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
9,643
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.sigma.lex import order.bounded_order /-! # Orders on a sigma type This file defines two orders on a sigma type: * The disjoint sum of orders. `a` is less `b` iff `a` and `b` are in the same summand and `a` is less than `b` there. * The lexicographical order. `a` is less than `b` if its summand is strictly less than the summand of `b` or they are in the same summand and `a` is less than `b` there. We make the disjoint sum of orders the default set of instances. The lexicographic order goes on a type synonym. ## Notation * `Σₗ i, α i`: Sigma type equipped with the lexicographic order. Type synonym of `Σ i, α i`. ## See also Related files are: * `data.finset.colex`: Colexicographic order on finite sets. * `data.list.lex`: Lexicographic order on lists. * `data.pi.lex`: Lexicographic order on `Πₗ i, α i`. * `data.psigma.order`: Lexicographic order on `Σₗ' i, α i`. Basically a twin of this file. * `data.prod.lex`: Lexicographic order on `α × β`. ## TODO Upgrade `equiv.sigma_congr_left`, `equiv.sigma_congr`, `equiv.sigma_assoc`, `equiv.sigma_prod_of_equiv`, `equiv.sigma_equiv_prod`, ... to order isomorphisms. -/ namespace sigma variables {ι : Type*} {α : ι → Type*} /-! ### Disjoint sum of orders on `sigma` -/ /-- Disjoint sum of orders. `⟨i, a⟩ ≤ ⟨j, b⟩` iff `i = j` and `a ≤ b`. -/ inductive le [Π i, has_le (α i)] : Π a b : Σ i, α i, Prop | fiber (i : ι) (a b : α i) : a ≤ b → le ⟨i, a⟩ ⟨i, b⟩ /-- Disjoint sum of orders. `⟨i, a⟩ < ⟨j, b⟩` iff `i = j` and `a < b`. -/ inductive lt [Π i, has_lt (α i)] : Π a b : Σ i, α i, Prop | fiber (i : ι) (a b : α i) : a < b → lt ⟨i, a⟩ ⟨i, b⟩ instance [Π i, has_le (α i)] : has_le (Σ i, α i) := ⟨le⟩ instance [Π i, has_lt (α i)] : has_lt (Σ i, α i) := ⟨lt⟩ @[simp] lemma mk_le_mk_iff [Π i, has_le (α i)] {i : ι} {a b : α i} : (⟨i, a⟩ : sigma α) ≤ ⟨i, b⟩ ↔ a ≤ b := ⟨λ ⟨_, _, _, h⟩, h, le.fiber _ _ _⟩ @[simp] lemma mk_lt_mk_iff [Π i, has_lt (α i)] {i : ι} {a b : α i} : (⟨i, a⟩ : sigma α) < ⟨i, b⟩ ↔ a < b := ⟨λ ⟨_, _, _, h⟩, h, lt.fiber _ _ _⟩ lemma le_def [Π i, has_le (α i)] {a b : Σ i, α i} : a ≤ b ↔ ∃ h : a.1 = b.1, h.rec a.2 ≤ b.2 := begin split, { rintro ⟨i, a, b, h⟩, exact ⟨rfl, h⟩ }, { obtain ⟨i, a⟩ := a, obtain ⟨j, b⟩ := b, rintro ⟨(rfl : i = j), h⟩, exact le.fiber _ _ _ h } end lemma lt_def [Π i, has_lt (α i)] {a b : Σ i, α i} : a < b ↔ ∃ h : a.1 = b.1, h.rec a.2 < b.2 := begin split, { rintro ⟨i, a, b, h⟩, exact ⟨rfl, h⟩ }, { obtain ⟨i, a⟩ := a, obtain ⟨j, b⟩ := b, rintro ⟨(rfl : i = j), h⟩, exact lt.fiber _ _ _ h } end instance [Π i, preorder (α i)] : preorder (Σ i, α i) := { le_refl := λ ⟨i, a⟩, le.fiber i a a le_rfl, le_trans := begin rintro _ _ _ ⟨i, a, b, hab⟩ ⟨_, _, c, hbc⟩, exact le.fiber i a c (hab.trans hbc), end, lt_iff_le_not_le := λ _ _, begin split, { rintro ⟨i, a, b, hab⟩, rwa [mk_le_mk_iff, mk_le_mk_iff, ←lt_iff_le_not_le] }, { rintro ⟨⟨i, a, b, hab⟩, h⟩, rw mk_le_mk_iff at h, exact mk_lt_mk_iff.2 (hab.lt_of_not_le h) } end, .. sigma.has_le, .. sigma.has_lt } instance [Π i, partial_order (α i)] : partial_order (Σ i, α i) := { le_antisymm := begin rintro _ _ ⟨i, a, b, hab⟩ ⟨_, _, _, hba⟩, exact ext rfl (heq_of_eq $ hab.antisymm hba), end, .. sigma.preorder } instance [Π i, preorder (α i)] [Π i, densely_ordered (α i)] : densely_ordered (Σ i, α i) := ⟨begin rintro ⟨i, a⟩ ⟨_, _⟩ ⟨_, _, b, h⟩, obtain ⟨c, ha, hb⟩ := exists_between h, exact ⟨⟨i, c⟩, lt.fiber i a c ha, lt.fiber i c b hb⟩, end⟩ /-! ### Lexicographical order on `sigma` -/ namespace lex notation `Σₗ` binders `, ` r:(scoped p, _root_.lex (sigma p)) := r /-- The lexicographical `≤` on a sigma type. -/ instance has_le [has_lt ι] [Π i, has_le (α i)] : has_le (Σₗ i, α i) := ⟨lex (<) (λ i, (≤))⟩ /-- The lexicographical `<` on a sigma type. -/ instance has_lt [has_lt ι] [Π i, has_lt (α i)] : has_lt (Σₗ i, α i) := ⟨lex (<) (λ i, (<))⟩ lemma le_def [has_lt ι] [Π i, has_le (α i)] {a b : Σₗ i, α i} : a ≤ b ↔ a.1 < b.1 ∨ ∃ (h : a.1 = b.1), h.rec a.2 ≤ b.2 := sigma.lex_iff lemma lt_def [has_lt ι] [Π i, has_lt (α i)] {a b : Σₗ i, α i} : a < b ↔ a.1 < b.1 ∨ ∃ (h : a.1 = b.1), h.rec a.2 < b.2 := sigma.lex_iff /-- The lexicographical preorder on a sigma type. -/ instance preorder [preorder ι] [Π i, preorder (α i)] : preorder (Σₗ i, α i) := { le_refl := λ ⟨i, a⟩, lex.right a a le_rfl, le_trans := λ _ _ _, trans_of (lex (<) $ λ _, (≤)), lt_iff_le_not_le := begin refine λ a b, ⟨λ hab, ⟨hab.mono_right (λ i a b, le_of_lt), _⟩, _⟩, { rintro (⟨b, a, hji⟩ | ⟨b, a, hba⟩); obtain (⟨_, _, hij⟩ | ⟨_, _, hab⟩) := hab, { exact hij.not_lt hji }, { exact lt_irrefl _ hji }, { exact lt_irrefl _ hij }, { exact hab.not_le hba } }, { rintro ⟨⟨a, b, hij⟩ | ⟨a, b, hab⟩, hba⟩, { exact lex.left _ _ hij }, { exact lex.right _ _ (hab.lt_of_not_le $ λ h, hba $ lex.right _ _ h) } } end, .. lex.has_le, .. lex.has_lt } /-- The lexicographical partial order on a sigma type. -/ instance partial_order [preorder ι] [Π i, partial_order (α i)] : partial_order (Σₗ i, α i) := { le_antisymm := λ _ _, antisymm_of (lex (<) $ λ _, (≤)), .. lex.preorder } /-- The lexicographical linear order on a sigma type. -/ instance linear_order [linear_order ι] [Π i, linear_order (α i)] : linear_order (Σₗ i, α i) := { le_total := total_of (lex (<) $ λ _, (≤)), decidable_eq := sigma.decidable_eq, decidable_le := lex.decidable _ _, .. lex.partial_order } /-- The lexicographical linear order on a sigma type. -/ instance order_bot [partial_order ι] [order_bot ι] [Π i, preorder (α i)] [order_bot (α ⊥)] : order_bot (Σₗ i, α i) := { bot := ⟨⊥, ⊥⟩, bot_le := λ ⟨a, b⟩, begin obtain rfl | ha := eq_bot_or_bot_lt a, { exact lex.right _ _ bot_le }, { exact lex.left _ _ ha } end } /-- The lexicographical linear order on a sigma type. -/ instance order_top [partial_order ι] [order_top ι] [Π i, preorder (α i)] [order_top (α ⊤)] : order_top (Σₗ i, α i) := { top := ⟨⊤, ⊤⟩, le_top := λ ⟨a, b⟩, begin obtain rfl | ha := eq_top_or_lt_top a, { exact lex.right _ _ le_top }, { exact lex.left _ _ ha } end } /-- The lexicographical linear order on a sigma type. -/ instance bounded_order [partial_order ι] [bounded_order ι] [Π i, preorder (α i)] [order_bot (α ⊥)] [order_top (α ⊤)] : bounded_order (Σₗ i, α i) := { .. lex.order_bot, .. lex.order_top } instance densely_ordered [preorder ι] [densely_ordered ι] [Π i, nonempty (α i)] [Π i, preorder (α i)] [Π i, densely_ordered (α i)] : densely_ordered (Σₗ i, α i) := ⟨begin rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩), { obtain ⟨k, hi, hj⟩ := exists_between h, obtain ⟨c⟩ : nonempty (α k) := infer_instance, exact ⟨⟨k, c⟩, left _ _ hi, left _ _ hj⟩ }, { obtain ⟨c, ha, hb⟩ := exists_between h, exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ } end⟩ instance densely_ordered_of_no_max_order [preorder ι] [Π i, preorder (α i)] [Π i, densely_ordered (α i)] [Π i, no_max_order (α i)] : densely_ordered (Σₗ i, α i) := ⟨begin rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩), { obtain ⟨c, ha⟩ := exists_gt a, exact ⟨⟨i, c⟩, right _ _ ha, left _ _ h⟩ }, { obtain ⟨c, ha, hb⟩ := exists_between h, exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ } end⟩ instance densely_ordered_of_no_min_order [preorder ι] [Π i, preorder (α i)] [Π i, densely_ordered (α i)] [Π i, no_min_order (α i)] : densely_ordered (Σₗ i, α i) := ⟨begin rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩), { obtain ⟨c, hb⟩ := exists_lt b, exact ⟨⟨j, c⟩, left _ _ h, right _ _ hb⟩ }, { obtain ⟨c, ha, hb⟩ := exists_between h, exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ } end⟩ instance no_max_order_of_nonempty [preorder ι] [Π i, preorder (α i)] [no_max_order ι] [Π i, nonempty (α i)] : no_max_order (Σₗ i, α i) := ⟨begin rintro ⟨i, a⟩, obtain ⟨j, h⟩ := exists_gt i, obtain ⟨b⟩ : nonempty (α j) := infer_instance, exact ⟨⟨j, b⟩, left _ _ h⟩ end⟩ instance no_min_order_of_nonempty [preorder ι] [Π i, preorder (α i)] [no_max_order ι] [Π i, nonempty (α i)] : no_max_order (Σₗ i, α i) := ⟨begin rintro ⟨i, a⟩, obtain ⟨j, h⟩ := exists_gt i, obtain ⟨b⟩ : nonempty (α j) := infer_instance, exact ⟨⟨j, b⟩, left _ _ h⟩ end⟩ instance no_max_order [preorder ι] [Π i, preorder (α i)] [Π i, no_max_order (α i)] : no_max_order (Σₗ i, α i) := ⟨by { rintro ⟨i, a⟩, obtain ⟨b, h⟩ := exists_gt a, exact ⟨⟨i, b⟩, right _ _ h⟩ }⟩ instance no_min_order [preorder ι] [Π i, preorder (α i)] [Π i, no_min_order (α i)] : no_min_order (Σₗ i, α i) := ⟨by { rintro ⟨i, a⟩, obtain ⟨b, h⟩ := exists_lt a, exact ⟨⟨i, b⟩, right _ _ h⟩ }⟩ end lex end sigma
ab910d89d1962c7c2d1f892542948bf806e35719
bdb33f8b7ea65f7705fc342a178508e2722eb851
/analysis/topology/infinite_sum.lean
c73e382304e1489e434e79da3ae581e97899ee51
[ "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
20,438
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 Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. -/ import logic.function algebra.big_operators data.set data.finset analysis.metric_space analysis.topology.topological_structures noncomputable theory open set lattice finset filter function classical local attribute [instance] prop_decidable variables {α : Type*} {β : Type*} {γ : Type*} section is_sum variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute sum operator. This is based on Mario Carneiro's infinite sum in Metamath. -/ def is_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (nhds a) /-- `has_sum f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def has_sum (f : β → α) : Prop := ∃a, is_sum f a /-- `tsum f` is the sum of `f` it exists, or 0 otherwise -/ def tsum (f : β → α) := if h : has_sum f then classical.some h else 0 notation `∑` binders `, ` r:(scoped f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma is_sum_tsum (ha : has_sum f) : is_sum f (∑b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum_spec (ha : is_sum f a) : has_sum f := ⟨a, ha⟩ lemma is_sum_zero : is_sum (λb, 0 : β → α) 0 := by simp [is_sum, tendsto_const_nhds] lemma has_sum_zero : has_sum (λb, 0 : β → α) := has_sum_spec is_sum_zero lemma is_sum_add (hf : is_sum f a) (hg : is_sum g b) : is_sum (λb, f b + g b) (a + b) := by simp [is_sum, sum_add_distrib]; exact tendsto_add hf hg lemma has_sum_add (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b + g b) := has_sum_spec $ is_sum_add (is_sum_tsum hf)(is_sum_tsum hg) lemma is_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, is_sum (f i) (a i)) → is_sum (λb, s.sum $ λi, f i b) (s.sum a) := finset.induction_on s (by simp [is_sum_zero]) (by simp [is_sum_add] {contextual := tt}) lemma has_sum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) : has_sum (λb, s.sum $ λi, f i b) := has_sum_spec $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi lemma is_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : is_sum f (s.sum f) := tendsto_infi' s $ tendsto_cong tendsto_const_nhds $ assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f := has_sum_spec $ is_sum_sum_of_ne_finset_zero hf lemma is_sum_of_iso {j : γ → β} {i : β → γ} (hf : is_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : is_sum (f ∘ j) a := have ∀x y, j x = j y → x = y, from assume x y h, have i (j x) = i (j y), by rw [h], by rwa [h₁, h₁] at this, have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j), from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm, show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (nhds a), by rw [this]; apply (tendsto_finset_image_at_top_at_top h₂).comp hf lemma is_sum_iff_is_sum_of_iso {j : γ → β} (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : is_sum (f ∘ j) a ↔ is_sum f a := iff.intro (assume hfj, have is_sum ((f ∘ j) ∘ i) a, from is_sum_of_iso hfj h₂ h₁, by simp [(∘), h₂] at this; assumption) (assume hf, is_sum_of_iso hf h₁ h₂) lemma is_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ] [topological_add_monoid γ] (h₁ : g 0 = 0) (h₂ : ∀x y, g (x + y) = g x + g y) (h₃ : continuous g) (hf : is_sum f a) : is_sum (g ∘ f) (g a) := have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f), from funext $ assume s, sum_hom g h₁ h₂, show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (nhds (g a)), by rw [this]; exact hf.comp (continuous_iff_tendsto.mp h₃ a) lemma tendsto_sum_nat_of_is_sum {f : ℕ → α} (h : is_sum f a) : tendsto (λn:ℕ, (range n).sum f) at_top (nhds a) := suffices map (λ (n : ℕ), sum (range n) f) at_top ≤ map (λ (s : finset ℕ), sum s f) at_top, from le_trans this h, assume s (hs : {t : finset ℕ | t.sum f ∈ s} ∈ at_top.sets), let ⟨t, ht⟩ := mem_at_top_sets.mp hs, ⟨n, hn⟩ := @exists_nat_subset_range t in mem_at_top_sets.mpr ⟨n, assume n' hn', ht _ $ finset.subset.trans hn $ range_subset.mpr hn'⟩ lemma is_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (hf : ∀b, is_sum (λc, f ⟨b, c⟩) (g b)) (ha : is_sum f a) : is_sum g a := assume s' hs', let ⟨s, hs, hss', hsc⟩ := nhds_is_closed hs', ⟨u, hu⟩ := mem_at_top_sets.mp $ ha $ hs, fsts := u.image sigma.fst, snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b))) in have u_subset : u ⊆ fsts.sigma snds, from subset_iff.mpr $ assume ⟨b, c⟩ hu, have hb : b ∈ fsts, from finset.mem_image.mpr ⟨_, hu, rfl⟩, have hc : c ∈ snds b, from mem_bind.mpr ⟨_, hu, by simp; refl⟩, by simp [mem_sigma, hb, hc] , mem_at_top_sets.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs), have h : ∀cs:(Πb, b ∈ bs → finset (γ b)), (⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩ (λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s ≠ ∅, from assume cs, let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f, from sum_sigma.symm, have (bs.sigma cs').sum f ∈ s, from hu _ $ finset.subset.trans u_subset $ sigma_mono hbs $ assume b, @finset.subset_union_right (γ b) _ _ _, ne_empty_iff_exists_mem.mpr $ exists.intro cs' $ by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_right] }, have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) (⨅b (h : b ∈ bs), at_top.vmap (λp, p b)) (nhds (bs.sum g)), from tendsto_sum $ assume c hc, tendsto_infi' c $ tendsto_infi' hc $ tendsto_vmap.comp (hf c), have bs.sum g ∈ s, from mem_closure_of_tendsto this hsc $ forall_sets_neq_empty_iff_neq_bot.mp $ by simp [mem_inf_sets, exists_imp_distrib, and_imp, forall_and_distrib, filter.mem_infi_sets_finset, mem_vmap_sets, skolem, mem_at_top_sets, and_comm]; from assume s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp', have (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b), from infi_le_infi $ assume b, infi_le_infi $ assume hb, le_trans (preimage_mono $ hp' b hb) (hp b hb), neq_bot_of_le_neq_bot (h _) (le_trans (inter_subset_inter (le_trans this hs₂) hs₃) hs₁), hss' this lemma has_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (hf : ∀b, has_sum (λc, f ⟨b, c⟩)) (ha : has_sum f) : has_sum (λb, ∑c, f ⟨b, c⟩):= has_sum_spec $ is_sum_sigma (assume b, is_sum_tsum $ hf b) (is_sum_tsum ha) end is_sum section is_sum_iff_is_sum_of_iso_ne_zero variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] variables {f : β → α} {g : γ → α} {a : α} lemma is_sum_of_is_sum (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (hf : is_sum g a) : is_sum f a := suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g), from le_trans this hf, by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [image_subset_iff]; exact hv) lemma is_sum_iff_is_sum (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) : is_sum f a ↔ is_sum g a := ⟨is_sum_of_is_sum h₂, is_sum_of_is_sum h₁⟩ variables (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) include hi hj hji hij hgj lemma is_sum_of_is_sum_ne_zero : is_sum g a → is_sum f a := have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y), from assume x y hx hy, ⟨assume h, have i (hj hx) = i (hj hy), by simp [h], by rwa [hij, hij] at this; assumption, by simp {contextual := tt}⟩, let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in is_sum_of_is_sum $ assume u, exists.intro (ii u) $ assume v hv, exists.intro (u ∪ jj v) $ and.intro subset_union_left $ have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0, from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0, have c ∈ u, from (finset.mem_union.1 hc).resolve_right hnc, have i h ∈ v, from hv $ by simp [mem_bind]; existsi c; simp [h, this], have j (hi h) ∈ jj v, by simp [mem_bind]; existsi i h; simp [h, hi, this], by rw [hji h] at this; exact hnc this, calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset subset_union_right this).symm ... = v.sum _ : sum_bind $ by intros x hx y hy hxy; by_cases f x = 0; by_cases f y = 0; simp [*] ... = v.sum f : sum_congr rfl $ by intros x hx; by_cases f x = 0; simp [*] lemma is_sum_iff_is_sum_of_ne_zero : is_sum f a ↔ is_sum g a := iff.intro (is_sum_of_is_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji]) (is_sum_of_is_sum_ne_zero i hi j hj hji hij hgj) lemma has_sum_iff_has_sum_ne_zero : has_sum g ↔ has_sum f := exists_congr $ assume a, is_sum_iff_is_sum_of_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji] end is_sum_iff_is_sum_of_iso_ne_zero section tsum variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma is_sum_unique : is_sum f a₁ → is_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique at_top_ne_bot lemma tsum_eq_is_sum (ha : is_sum f a) : (∑b, f b) = a := is_sum_unique (is_sum_tsum ⟨a, ha⟩) ha @[simp] lemma tsum_zero : (∑b:β, 0:α) = 0 := tsum_eq_is_sum is_sum_zero lemma tsum_add (hf : has_sum f) (hg : has_sum g) : (∑b, f b + g b) = (∑b, f b) + (∑b, g b) := tsum_eq_is_sum $ is_sum_add (is_sum_tsum hf) (is_sum_tsum hg) lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) : (∑b, s.sum (λi, f i b)) = s.sum (λi, ∑b, f i b) := tsum_eq_is_sum $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : (∑b, f b) = s.sum f := tsum_eq_is_sum $ is_sum_sum_of_ne_finset_zero hf lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : (∑b, f b) = f b := calc (∑b, f b) = (finset.singleton b).sum f : tsum_eq_sum $ by simp [hf] {contextual := tt} ... = f b : by simp lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, has_sum (λc, f ⟨b, c⟩)) (h₂ : has_sum f) : (∑p, f p) = (∑b c, f ⟨b, c⟩):= (tsum_eq_is_sum $ is_sum_sigma (assume b, is_sum_tsum $ h₁ b) $ is_sum_tsum h₂).symm lemma tsum_eq_tsum_of_is_sum_iff_is_sum {f : β → α} {g : γ → α} (h : ∀{a}, is_sum f a ↔ is_sum g a) : (∑b, f b) = (∑c, g c) := by_cases (assume : ∃a, is_sum f a, let ⟨a, hfa⟩ := this in have hga : is_sum g a, from h.mp hfa, by rw [tsum_eq_is_sum hfa, tsum_eq_is_sum hga]) (assume hf : ¬ has_sum f, have hg : ¬ has_sum g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩, by simp [tsum, hf, hg]) lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) : (∑i, f i) = (∑j, g j) := tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_ne_zero i hi j hj hji hij hgj lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂) (h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b) (h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) : (∑i, f i) = (∑j, g j) := have hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0, from assume c h, by simp [h₃, h], let j : Π⦃b⦄, f b ≠ 0 → γ := λb h, some $ h₂ h in have hj : ∀⦃b⦄ (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b, from assume b h, some_spec $ h₂ h, have hj₁ : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0, from assume b h, let ⟨h₁, _⟩ := hj h in h₁, have hj₂ : ∀⦃b⦄ (h : f b ≠ 0), i (hj₁ h) = b, from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂, tsum_eq_tsum_of_ne_zero i hi j hj₁ (assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂]) lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_iso i h₁ h₂ end tsum section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} lemma is_sum_neg : is_sum f a → is_sum (λb, - f b) (- a) := is_sum_hom has_neg.neg (by simp) (by simp) continuous_neg' lemma has_sum_neg (hf : has_sum f) : has_sum (λb, - f b) := has_sum_spec $ is_sum_neg $ is_sum_tsum $ hf lemma is_sum_sub (hf : is_sum f a₁) (hg : is_sum g a₂) : is_sum (λb, f b - g b) (a₁ - a₂) := by simp; exact is_sum_add hf (is_sum_neg hg) lemma has_sum_sub (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b - g b) := has_sum_spec $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg) section tsum variables [t2_space α] lemma tsum_neg (hf : has_sum f) : (∑b, - f b) = - (∑b, f b) := tsum_eq_is_sum $ is_sum_neg $ is_sum_tsum $ hf lemma tsum_sub (hf : has_sum f) (hg : has_sum g) : (∑b, f b - g b) = (∑b, f b) - (∑b, g b) := tsum_eq_is_sum $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg) end tsum end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma is_sum_mul_left : is_sum f a₁ → is_sum (λb, a₂ * f b) (a₂ * a₁) := is_sum_hom _ (by simp) (by simp [mul_add]) (continuous_mul continuous_const continuous_id) lemma is_sum_mul_right (hf : is_sum f a₁) : is_sum (λb, f b * a₂) (a₁ * a₂) := @is_sum_hom _ _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _ (by simp) (by simp [add_mul]) (continuous_mul continuous_id continuous_const) hf lemma has_sum_mul_left (hf : has_sum f) : has_sum (λb, a * f b) := has_sum_spec $ is_sum_mul_left $ is_sum_tsum hf lemma has_sum_mul_right (hf : has_sum f) : has_sum (λb, f b * a) := has_sum_spec $ is_sum_mul_right $ is_sum_tsum hf section tsum variables [t2_space α] lemma tsum_mul_left (hf : has_sum f) : (∑b, a * f b) = a * (∑b, f b) := tsum_eq_is_sum $ is_sum_mul_left $ is_sum_tsum hf lemma tsum_mul_right (hf : has_sum f) : (∑b, f b * a) = (∑b, f b) * a := tsum_eq_is_sum $ is_sum_mul_right $ is_sum_tsum hf end tsum end topological_semiring section order_topology variables [ordered_comm_monoid α] [topological_space α] [ordered_topology α] [topological_add_monoid α] variables {f g : β → α} {a a₁ a₂ : α} lemma is_sum_le (h : ∀b, f b ≤ g b) (hf : is_sum f a₁) (hg : is_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto at_top_ne_bot hf hg $ univ_mem_sets' $ assume s, sum_le_sum' $ assume b _, h b lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : has_sum f) (hg : has_sum g) : (∑b, f b) ≤ (∑b, g b) := is_sum_le h (is_sum_tsum hf) (is_sum_tsum hg) end order_topology section uniform_group variables [add_comm_group α] [uniform_space α] [complete_space α] [uniform_add_group α] variables {f g : β → α} {a a₁ a₂ : α} /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma has_sum_of_has_sum_of_sub {f' : β → α} (hf : has_sum f) (h : ∀b, f' b = 0 ∨ f' b = f b) : has_sum f' := let ⟨a, hf⟩ := hf in suffices cauchy (at_top.map (λs:finset β, s.sum f')), from complete_space.complete this, ⟨map_ne_bot at_top_ne_bot, assume s' hs', have ∃t∈(@uniformity α _).sets, ∀{a₁ a₂ a₃ a₄}, (a₁, a₂) ∈ t → (a₃, a₄) ∈ t → (a₁ - a₃, a₂ - a₄) ∈ s', begin have h : {p:(α×α)×(α×α)| (p.1.1 - p.1.2, p.2.1 - p.2.2) ∈ s'} ∈ (@uniformity (α × α) _).sets, from uniform_continuous_sub' hs', rw [uniformity_prod_eq_prod, mem_map, mem_prod_same_iff] at h, cases h with t ht, cases ht with ht h, exact ⟨t, ht, assume a₁ a₂ a₃ a₄ h₁ h₂, @h ((a₁, a₂), (a₃, a₄)) ⟨h₁, h₂⟩⟩ end, let ⟨s, hs, hss'⟩ := this in have cauchy (at_top.map (λs:finset β, s.sum f)), from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hf, have ∃t, ∀u₁ u₂:finset β, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f, u₂.sum f) ∈ s, by simp [cauchy_iff, mem_at_top_sets, and.assoc, and.left_comm, and.comm] at this; from let ⟨t, ht, u, hu⟩ := this s hs in ⟨u, assume u₁ u₂ h₁ h₂, ht $ prod_mk_mem_set_prod_eq.mpr ⟨hu _ h₁, hu _ h₂⟩⟩, let ⟨t, ht⟩ := this in let d := (t.filter (λb, f' b = 0)).sum f in have eq : ∀{u}, t ⊆ u → (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d = u.sum f', from assume u hu, have t ∪ u.filter (λb, f' b ≠ 0) = t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0), from finset.ext.2 $ assume b, by by_cases f' b = 0; simp [h, subset_iff.mp hu, iff_def, or_imp_distrib] {contextual := tt}, calc (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d = (t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0)).sum f - d : by rw [this] ... = (d + (u.filter (λb, f' b ≠ 0)).sum f) - d : by rw [sum_union]; exact (finset.ext.2 $ by simp {contextual := tt}) ... = (u.filter (λb, f' b ≠ 0)).sum f : by simp ... = (u.filter (λb, f' b ≠ 0)).sum f' : sum_congr rfl $ assume b, by have h := h b; cases h with h h; simp [*] ... = u.sum f' : by apply sum_subset; by simp [subset_iff, not_not] {contextual := tt}, have ∀{u₁ u₂}, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f', u₂.sum f') ∈ s', from assume u₁ u₂ h₁ h₂, have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f) ∈ s, from ht _ _ subset_union_left subset_union_left, have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f - d, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f - d) ∈ s', from hss' this $ refl_mem_uniformity hs, by rwa [eq h₁, eq h₂] at this, mem_prod_same_iff.mpr ⟨(λu:finset β, u.sum f') '' {u | t ⊆ u}, image_mem_map $ mem_at_top t, assume ⟨a₁, a₂⟩ ⟨⟨t₁, h₁, eq₁⟩, ⟨t₂, h₂, eq₂⟩⟩, by simp at eq₁ eq₂; rw [←eq₁, ←eq₂]; exact this h₁ h₂⟩⟩ end uniform_group
de40e56e2c32c4a29f7bf7df7937452ce93b5414
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/instances/nnreal.lean
ceb03496d65d4244fc5b756967187fbfc511f34f
[ "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,941
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.algebra.infinite_sum.order import topology.algebra.infinite_sum.ring import topology.instances.real /-! # Topology on `ℝ≥0` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The natural topology on `ℝ≥0` (the one induced from `ℝ`), and a basic API. ## Main definitions Instances for the following typeclasses are defined: * `topological_space ℝ≥0` * `topological_semiring ℝ≥0` * `second_countable_topology ℝ≥0` * `order_topology ℝ≥0` * `has_continuous_sub ℝ≥0` * `has_continuous_inv₀ ℝ≥0` (continuity of `x⁻¹` away from `0`) * `has_continuous_smul ℝ≥0 α` (whenever `α` has a continuous `mul_action ℝ α`) Everything is inherited from the corresponding structures on the reals. ## Main statements Various mathematically trivial lemmas are proved about the compatibility of limits and sums in `ℝ≥0` and `ℝ`. For example * `tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} : tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x)` says that the limit of a filter along a map to `ℝ≥0` is the same in `ℝ` and `ℝ≥0`, and * `coe_tsum {f : α → ℝ≥0} : ((∑'a, f a) : ℝ) = (∑'a, (f a : ℝ))` says that says that a sum of elements in `ℝ≥0` is the same in `ℝ` and `ℝ≥0`. Similarly, some mathematically trivial lemmas about infinite sums are proved, a few of which rely on the fact that subtraction is continuous. -/ noncomputable theory open set topological_space metric filter open_locale topology namespace nnreal open_locale nnreal big_operators filter instance : topological_space ℝ≥0 := infer_instance -- short-circuit type class inference instance : topological_semiring ℝ≥0 := { continuous_mul := (continuous_subtype_val.fst'.mul continuous_subtype_val.snd').subtype_mk _, continuous_add := (continuous_subtype_val.fst'.add continuous_subtype_val.snd').subtype_mk _ } instance : second_countable_topology ℝ≥0 := topological_space.subtype.second_countable_topology _ _ instance : order_topology ℝ≥0 := @order_topology_of_ord_connected _ _ _ _ (Ici 0) _ section coe variable {α : Type*} open filter finset lemma _root_.continuous_real_to_nnreal : continuous real.to_nnreal := (continuous_id.max continuous_const).subtype_mk _ lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ) := continuous_subtype_val /-- Embedding of `ℝ≥0` to `ℝ` as a bundled continuous map. -/ @[simps { fully_applied := ff }] def _root_.continuous_map.coe_nnreal_real : C(ℝ≥0, ℝ) := ⟨coe, continuous_coe⟩ instance continuous_map.can_lift {X : Type*} [topological_space X] : can_lift C(X, ℝ) C(X, ℝ≥0) continuous_map.coe_nnreal_real.comp (λ f, ∀ x, 0 ≤ f x) := { prf := λ f hf, ⟨⟨λ x, ⟨f x, hf x⟩, f.2.subtype_mk _⟩, fun_like.ext' rfl⟩ } @[simp, norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} : tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x) := tendsto_subtype_rng.symm lemma tendsto_coe' {f : filter α} [ne_bot f] {m : α → ℝ≥0} {x : ℝ} : tendsto (λ a, m a : α → ℝ) f (𝓝 x) ↔ ∃ hx : 0 ≤ x, tendsto m f (𝓝 ⟨x, hx⟩) := ⟨λ h, ⟨ge_of_tendsto' h (λ c, (m c).2), tendsto_coe.1 h⟩, λ ⟨hx, hm⟩, tendsto_coe.2 hm⟩ @[simp] lemma map_coe_at_top : map (coe : ℝ≥0 → ℝ) at_top = at_top := map_coe_Ici_at_top 0 lemma comap_coe_at_top : comap (coe : ℝ≥0 → ℝ) at_top = at_top := (at_top_Ici_eq 0).symm @[simp, norm_cast] lemma tendsto_coe_at_top {f : filter α} {m : α → ℝ≥0} : tendsto (λ a, (m a : ℝ)) f at_top ↔ tendsto m f at_top := tendsto_Ici_at_top.symm lemma _root_.tendsto_real_to_nnreal {f : filter α} {m : α → ℝ} {x : ℝ} (h : tendsto m f (𝓝 x)) : tendsto (λa, real.to_nnreal (m a)) f (𝓝 (real.to_nnreal x)) := (continuous_real_to_nnreal.tendsto _).comp h lemma _root_.tendsto_real_to_nnreal_at_top : tendsto real.to_nnreal at_top at_top := begin rw ← tendsto_coe_at_top, apply tendsto_id.congr' _, filter_upwards [Ici_mem_at_top (0 : ℝ)] with x hx, simp only [max_eq_left (set.mem_Ici.1 hx), id.def, real.coe_to_nnreal'], end lemma nhds_zero : 𝓝 (0 : ℝ≥0) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0)).has_basis (λ a : ℝ≥0, 0 < a) (λ a, Iio a) := nhds_bot_basis instance : has_continuous_sub ℝ≥0 := ⟨((continuous_coe.fst'.sub continuous_coe.snd').max continuous_const).subtype_mk _⟩ instance : has_continuous_inv₀ ℝ≥0 := ⟨λ x hx, tendsto_coe.1 $ (real.tendsto_inv $ nnreal.coe_ne_zero.2 hx).comp continuous_coe.continuous_at⟩ instance [topological_space α] [mul_action ℝ α] [has_continuous_smul ℝ α] : has_continuous_smul ℝ≥0 α := { continuous_smul := (continuous_induced_dom.comp continuous_fst).smul continuous_snd } @[norm_cast] lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ)) (r : ℝ) ↔ has_sum f r := by simp only [has_sum, coe_sum.symm, tendsto_coe] lemma has_sum_real_to_nnreal_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : has_sum (λ n, real.to_nnreal (f n)) (real.to_nnreal (∑' n, f n)) := begin have h_sum : (λ s, ∑ b in s, real.to_nnreal (f b)) = λ s, real.to_nnreal (∑ b in s, f b), from funext (λ _, (real.to_nnreal_sum_of_nonneg (λ n _, hf_nonneg n)).symm), simp_rw [has_sum, h_sum], exact tendsto_real_to_nnreal hf.has_sum, end @[norm_cast] lemma summable_coe {f : α → ℝ≥0} : summable (λa, (f a : ℝ)) ↔ summable f := begin split, exact assume ⟨a, ha⟩, ⟨⟨a, has_sum_le (λa, (f a).2) has_sum_zero ha⟩, has_sum_coe.1 ha⟩, exact assume ⟨a, ha⟩, ⟨a.1, has_sum_coe.2 ha⟩ end lemma summable_coe_of_nonneg {f : α → ℝ} (hf₁ : ∀ n, 0 ≤ f n) : @summable (ℝ≥0) _ _ _ (λ n, ⟨f n, hf₁ n⟩) ↔ summable f := begin lift f to α → ℝ≥0 using hf₁ with f rfl hf₁, simp only [summable_coe, subtype.coe_eta] end open_locale classical @[norm_cast] lemma coe_tsum {f : α → ℝ≥0} : ↑∑'a, f a = ∑'a, (f a : ℝ) := if hf : summable f then (eq.symm $ (has_sum_coe.2 $ hf.has_sum).tsum_eq) else by simp [tsum, hf, mt summable_coe.1 hf] lemma coe_tsum_of_nonneg {f : α → ℝ} (hf₁ : ∀ n, 0 ≤ f n) : (⟨∑' n, f n, tsum_nonneg hf₁⟩ : ℝ≥0) = (∑' n, ⟨f n, hf₁ n⟩ : ℝ≥0) := begin lift f to α → ℝ≥0 using hf₁ with f rfl hf₁, simp_rw [← nnreal.coe_tsum, subtype.coe_eta] end lemma tsum_mul_left (a : ℝ≥0) (f : α → ℝ≥0) : ∑' x, a * f x = a * ∑' x, f x := nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_left] lemma tsum_mul_right (f : α → ℝ≥0) (a : ℝ≥0) : (∑' x, f x * a) = (∑' x, f x) * a := nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_right] lemma summable_comp_injective {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : summable (f ∘ i) := nnreal.summable_coe.1 $ show summable ((coe ∘ f) ∘ i), from (nnreal.summable_coe.2 hf).comp_injective hi lemma summable_nat_add (f : ℕ → ℝ≥0) (hf : summable f) (k : ℕ) : summable (λ i, f (i + k)) := summable_comp_injective hf $ add_left_injective k lemma summable_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) : summable (λ i, f (i + k)) ↔ summable f := begin rw [← summable_coe, ← summable_coe], exact @summable_nat_add_iff ℝ _ _ _ (λ i, (f i : ℝ)) k, end lemma has_sum_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) {a : ℝ≥0} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := by simp [← has_sum_coe, coe_sum, nnreal.coe_add, ← has_sum_nat_add_iff k] lemma sum_add_tsum_nat_add {f : ℕ → ℝ≥0} (k : ℕ) (hf : summable f) : ∑' i, f i = (∑ i in range k, f i) + ∑' i, f (i + k) := by rw [←nnreal.coe_eq, coe_tsum, nnreal.coe_add, coe_sum, coe_tsum, sum_add_tsum_nat_add k (nnreal.summable_coe.2 hf)] lemma infi_real_pos_eq_infi_nnreal_pos [complete_lattice α] {f : ℝ → α} : (⨅ (n : ℝ) (h : 0 < n), f n) = (⨅ (n : ℝ≥0) (h : 0 < n), f n) := le_antisymm (infi_mono' $ λ r, ⟨r, le_rfl⟩) (infi₂_mono' $ λ r hr, ⟨⟨r, hr.le⟩, hr, le_rfl⟩) end coe lemma tendsto_cofinite_zero_of_summable {α} {f : α → ℝ≥0} (hf : summable f) : tendsto f cofinite (𝓝 0) := begin have h_f_coe : f = λ n, real.to_nnreal (f n : ℝ), from funext (λ n, real.to_nnreal_coe.symm), rw [h_f_coe, ← @real.to_nnreal_coe 0], exact tendsto_real_to_nnreal ((summable_coe.mpr hf).tendsto_cofinite_zero), end lemma tendsto_at_top_zero_of_summable {f : ℕ → ℝ≥0} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_summable hf } /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero {α : Type*} (f : α → ℝ≥0) : tendsto (λ (s : finset α), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin simp_rw [← tendsto_coe, coe_tsum, nnreal.coe_zero], exact tendsto_tsum_compl_at_top_zero (λ (a : α), (f a : ℝ)) end /-- `x ↦ x ^ n` as an order isomorphism of `ℝ≥0`. -/ def pow_order_iso (n : ℕ) (hn : n ≠ 0) : ℝ≥0 ≃o ℝ≥0 := strict_mono.order_iso_of_surjective (λ x, x ^ n) (λ x y h, strict_mono_on_pow hn.bot_lt (zero_le x) (zero_le y) h) $ (continuous_id.pow _).surjective (tendsto_pow_at_top hn) $ by simpa [order_bot.at_bot_eq, pos_iff_ne_zero] end nnreal
9d8d5b7f3ddab125a84fdf4078e4fa80463e8940
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/principal_ideal_domain.lean
8dd56130fa7b35fec31b9cf76a5d03c816137880
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
15,974
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Morenikeji Neri -/ import ring_theory.unique_factorization_domain /-! # Principal ideal rings and principal ideal domains A principal ideal ring (PIR) is a ring in which all left ideals are principal. A principal ideal domain (PID) is an integral domain which is a principal ideal ring. # Main definitions Note that for principal ideal domains, one should use `[is_domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID. Theorems about PID's are in the `principal_ideal_ring` namespace. - `is_principal_ideal_ring`: a predicate on rings, saying that every left ideal is principal. - `generator`: a generator of a principal ideal (or more generally submodule) - `to_unique_factorization_monoid`: a PID is a unique factorization domain # Main results - `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal. - `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID. -/ universes u v variables {R : Type u} {M : Type v} open set function open submodule open_locale classical section variables [ring R] [add_comm_group M] [module R M] /-- An `R`-submodule of `M` is principal if it is generated by one element. -/ class submodule.is_principal (S : submodule R M) : Prop := (principal [] : ∃ a, S = span R {a}) instance bot_is_principal : (⊥ : submodule R M).is_principal := ⟨⟨0, by simp⟩⟩ instance top_is_principal : (⊤ : submodule R R).is_principal := ⟨⟨1, ideal.span_singleton_one.symm⟩⟩ variables (R) /-- A ring is a principal ideal ring if all (left) ideals are principal. -/ class is_principal_ideal_ring (R : Type u) [ring R] : Prop := (principal : ∀ (S : ideal R), S.is_principal) attribute [instance] is_principal_ideal_ring.principal @[priority 100] instance division_ring.is_principal_ideal_ring (K : Type u) [division_ring K] : is_principal_ideal_ring K := { principal := λ S, by rcases ideal.eq_bot_or_top S with (rfl|rfl); apply_instance } end namespace submodule.is_principal variables [add_comm_group M] section ring variables [ring R] [module R M] /-- `generator I`, if `I` is a principal submodule, is an `x ∈ M` such that `span R {x} = I` -/ noncomputable def generator (S : submodule R M) [S.is_principal] : M := classical.some (principal S) lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S := eq.symm (classical.some_spec (principal S)) lemma _root_.ideal.span_singleton_generator (I : ideal R) [I.is_principal] : ideal.span ({generator I} : set R) = I := eq.symm (classical.some_spec (principal I)) @[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S := by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) } lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} : x ∈ S ↔ ∃ s : R, x = s • generator S := by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator] lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← @span_singleton_eq_bot R M, span_singleton_generator] end ring section comm_ring variables [comm_ring R] [module R M] lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x := (mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul])) lemma prime_generator_of_is_prime (S : ideal R) [submodule.is_principal S] [is_prime : S.is_prime] (ne_bot : S ≠ ⊥) : prime (generator S) := ⟨λ h, ne_bot ((eq_bot_iff_generator_eq_zero S).2 h), λ h, is_prime.ne_top (S.eq_top_of_is_unit_mem (generator_mem S) h), by simpa only [← mem_iff_generator_dvd S] using is_prime.2⟩ -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_map_dvd_of_mem {N : submodule R M} (ϕ : M →ₗ[R] R) [(N.map ϕ).is_principal] {x : M} (hx : x ∈ N) : generator (N.map ϕ) ∣ ϕ x := by { rw [← mem_iff_generator_dvd, submodule.mem_map], exact ⟨x, hx, rfl⟩ } -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_submodule_image_dvd_of_mem {N O : submodule R M} (hNO : N ≤ O) (ϕ : O →ₗ[R] R) [(ϕ.submodule_image N).is_principal] {x : M} (hx : x ∈ N) : generator (ϕ.submodule_image N) ∣ ϕ ⟨x, hNO hx⟩ := by { rw [← mem_iff_generator_dvd, linear_map.mem_submodule_image_of_le hNO], exact ⟨x, hx, rfl⟩ } end comm_ring end submodule.is_principal namespace is_prime open submodule.is_principal ideal -- TODO -- for a non-ID one could perhaps prove that if p < q are prime then q maximal; -- 0 isn't prime in a non-ID PIR but the Krull dimension is still <= 1. -- The below result follows from this, but we could also use the below result to -- prove this (quotient out by p). lemma to_maximal_ideal [comm_ring R] [is_domain R] [is_principal_ideal_ring R] {S : ideal R} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.mem_or_mem (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← T.span_singleton_generator, ideal.span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, mul_right_inj' this] at hz, exact hz.symm ▸ T.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain R] lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ S.add_mem (S.mul_mem_right _ hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ S.sub_mem hx (S.mul_mem_right _ hy)⟩ @[priority 100] -- see Note [lower instance priority] instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R := { principal := λ S, by exactI ⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty then have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded, have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸ (ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0, by { simp only [not_and_distrib, set.mem_set_of_eq, not_ne_iff] at this, cases this, cases this ((mod_mem_iff hmin.1).2 hx), exact this }, by simp *), λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ S.mul_mem_right _ hmin.1⟩⟩ else ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ } end lemma is_field.is_principal_ideal_ring {R : Type*} [comm_ring R] (h : is_field R) : is_principal_ideal_ring R := @euclidean_domain.to_principal_ideal_domain R (@field.to_euclidean_domain R (h.to_field R)) namespace principal_ideal_ring open is_principal_ideal_ring @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring [ring R] [is_principal_ideal_ring R] : is_noetherian_ring R := is_noetherian_ring_iff.2 ⟨assume s : ideal R, begin rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, set_like.coe_injective rfl⟩ end⟩ lemma is_maximal_of_irreducible [comm_ring R] [is_principal_ideal_ring R] {p : R} (hp : irreducible p) : ideal.is_maximal (span R ({p} : set R)) := ⟨⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, erw ideal.span_singleton_eq_top, unfreezingI { rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩ }, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), erw [ideal.span_singleton_le_span_singleton, is_unit.mul_right_dvd hb] end⟩⟩ variables [comm_ring R] [is_domain R] [is_principal_ideal_ring R] lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p := ⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, prime.irreducible⟩ lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ prime p := associates.irreducible_iff_prime_iff.1 (λ _, irreducible_iff_prime) section open_locale classical /-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/ noncomputable def factors (a : R) : multiset R := if h : a = 0 then ∅ else classical.some (wf_dvd_monoid.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated (factors a).prod a := begin unfold factors, rw [dif_neg h], exact classical.some_spec (wf_dvd_monoid.exists_factors a h) end lemma ne_zero_of_mem_factors {R : Type v} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] {a b : R} (ha : a ≠ 0) (hb : b ∈ factors a) : b ≠ 0 := irreducible.ne_zero ((factors_spec a ha).1 b hb) lemma mem_submonoid_of_factors_subset_of_units_subset (s : submonoid R) {a : R} (ha : a ≠ 0) (hfac : ∀ b ∈ factors a, b ∈ s) (hunit : ∀ c : Rˣ, (c : R) ∈ s) : a ∈ s := begin rcases ((factors_spec a ha).2) with ⟨c, hc⟩, rw [← hc], exact submonoid.mul_mem _ (submonoid.multiset_prod_mem _ _ hfac) (hunit _), end /-- If a `ring_hom` maps all units and all factors of an element `a` into a submonoid `s`, then it also maps `a` into that submonoid. -/ lemma ring_hom_mem_submonoid_of_factors_subset_of_units_subset {R S : Type*} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] [semiring S] (f : R →+* S) (s : submonoid S) (a : R) (ha : a ≠ 0) (h : ∀ b ∈ factors a, f b ∈ s) (hf: ∀ c : Rˣ, f c ∈ s) : f a ∈ s := mem_submonoid_of_factors_subset_of_units_subset (s.comap f.to_monoid_hom) ha h hf /-- A principal ideal domain has unique factorization -/ @[priority 100] -- see Note [lower instance priority] instance to_unique_factorization_monoid : unique_factorization_monoid R := { irreducible_iff_prime := λ _, principal_ideal_ring.irreducible_iff_prime .. (is_noetherian_ring.wf_dvd_monoid : wf_dvd_monoid R) } end end principal_ideal_ring section surjective open submodule variables {S N : Type*} [ring R] [add_comm_group M] [add_comm_group N] [ring S] variables [module R M] [module R N] lemma submodule.is_principal.of_comap (f : M →ₗ[R] N) (hf : function.surjective f) (S : submodule R N) [hI : is_principal (S.comap f)] : is_principal S := ⟨⟨f (is_principal.generator (S.comap f)), by rw [← set.image_singleton, ← submodule.map_span, is_principal.span_singleton_generator, submodule.map_comap_eq_of_surjective hf]⟩⟩ lemma ideal.is_principal.of_comap (f : R →+* S) (hf : function.surjective f) (I : ideal S) [hI : is_principal (I.comap f)] : is_principal I := ⟨⟨f (is_principal.generator (I.comap f)), by rw [ideal.submodule_span_eq, ← set.image_singleton, ← ideal.map_span, ideal.span_singleton_generator, ideal.map_comap_of_surjective f hf]⟩⟩ /-- The surjective image of a principal ideal ring is again a principal ideal ring. -/ lemma is_principal_ideal_ring.of_surjective [is_principal_ideal_ring R] (f : R →+* S) (hf : function.surjective f) : is_principal_ideal_ring S := ⟨λ I, ideal.is_principal.of_comap f hf I⟩ end surjective section open ideal variables [comm_ring R] [is_domain R] [is_principal_ideal_ring R] [gcd_monoid R] theorem span_gcd (x y : R) : span ({gcd x y} : set R) = span ({x, y} : set R) := begin obtain ⟨d, hd⟩ := is_principal_ideal_ring.principal (span ({x, y} : set R)), rw submodule_span_eq at hd, rw [hd], suffices : associated d (gcd x y), { obtain ⟨D, HD⟩ := this, rw ←HD, exact (span_singleton_mul_right_unit D.is_unit _) }, apply associated_of_dvd_dvd, { rw dvd_gcd_iff, split; rw [←ideal.mem_span_singleton, ←hd, mem_span_pair], { use [1, 0], rw [one_mul, zero_mul, add_zero] }, { use [0, 1], rw [one_mul, zero_mul, zero_add] } }, { obtain ⟨r, s, rfl⟩ : ∃ r s, r * x + s * y = d, { rw [←mem_span_pair, hd, ideal.mem_span_singleton] }, apply dvd_add; apply dvd_mul_of_dvd_right, exacts [gcd_dvd_left x y, gcd_dvd_right x y] }, end theorem gcd_dvd_iff_exists (a b : R) {z} : gcd a b ∣ z ↔ ∃ x y, z = a * x + b * y := by simp_rw [mul_comm a, mul_comm b, @eq_comm _ z, ←mem_span_pair, ←span_gcd, ideal.mem_span_singleton] /-- **Bézout's lemma** -/ theorem exists_gcd_eq_mul_add_mul (a b : R) : ∃ x y, gcd a b = a * x + b * y := by rw [←gcd_dvd_iff_exists] theorem gcd_is_unit_iff (x y : R) : is_unit (gcd x y) ↔ is_coprime x y := by rw [is_coprime, ←mem_span_pair, ←span_gcd, ←span_singleton_eq_top, eq_top_iff_one] -- this should be proved for UFDs surely? theorem is_coprime_of_dvd (x y : R) (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits R, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, gcd_eq_zero_iff] end -- this should be proved for UFDs surely? theorem dvd_or_coprime (x y : R) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), apply is_coprime_of_dvd, { unfreezingI { rintro ⟨rfl, rfl⟩ }, simpa using h }, { unfreezingI { rintro z nu nz ⟨w, rfl⟩ dy }, refine h' (dvd_trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end theorem is_coprime_of_irreducible_dvd {x y : R} (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z : R, irreducible z → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin apply is_coprime_of_dvd x y nonzero, intros z znu znz zx zy, obtain ⟨i, h1, h2⟩ := wf_dvd_monoid.exists_irreducible_factor znu znz, apply H i h1; { apply dvd_trans h2, assumption }, end theorem is_coprime_of_prime_dvd {x y : R} (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z : R, prime z → z ∣ x → ¬ z ∣ y) : is_coprime x y := is_coprime_of_irreducible_dvd nonzero $ λ z zi, H z $ gcd_monoid.prime_of_irreducible zi theorem irreducible.coprime_iff_not_dvd {p n : R} (pp : irreducible p) : is_coprime p n ↔ ¬ p ∣ n := begin split, { intros co H, apply pp.not_unit, rw is_unit_iff_dvd_one, apply is_coprime.dvd_of_dvd_mul_left co, rw mul_one n, exact H }, { intro nd, apply is_coprime_of_irreducible_dvd, { rintro ⟨hp, -⟩, exact pp.ne_zero hp }, rintro z zi zp zn, exact nd (((zi.associated_of_dvd pp zp).symm.dvd).trans zn) }, end theorem prime.coprime_iff_not_dvd {p n : R} (pp : prime p) : is_coprime p n ↔ ¬ p ∣ n := pp.irreducible.coprime_iff_not_dvd theorem exists_associated_pow_of_mul_eq_pow' {a b c : R} (hab : is_coprime a b) {k : ℕ} (h : a * b = c ^ k) : ∃ d, associated (d ^ k) a := exists_associated_pow_of_mul_eq_pow ((gcd_is_unit_iff _ _).mpr hab) h end
5a0df26e6dc3fe98afb025283c958a4d427f9961
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/quaternion.lean
31a0dabe9292eccfc82acbbb1a5fc1c51eeb108d
[]
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
3,562
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.quaternion import Mathlib.analysis.normed_space.inner_product import Mathlib.PostPort namespace Mathlib /-! # Quaternions as a normed algebra In this file we define the following structures on the space `ℍ := ℍ[ℝ]` of quaternions: * inner product space; * normed ring; * normed space over `ℝ`. ## Notation The following notation is available with `open_locale quaternion`: * `ℍ` : quaternions ## Tags quaternion, normed ring, normed space, normed algebra -/ namespace quaternion protected instance has_inner : has_inner ℝ (quaternion ℝ) := has_inner.mk fun (a b : quaternion ℝ) => re (a * coe_fn conj b) theorem inner_self (a : quaternion ℝ) : inner a a = coe_fn norm_sq a := rfl theorem inner_def (a : quaternion ℝ) (b : quaternion ℝ) : inner a b = re (a * coe_fn conj b) := rfl protected instance inner_product_space : inner_product_space ℝ (quaternion ℝ) := inner_product_space.of_core (inner_product_space.core.mk inner sorry sorry sorry sorry sorry sorry) theorem norm_sq_eq_norm_square (a : quaternion ℝ) : coe_fn norm_sq a = norm a * norm a := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn norm_sq a = norm a * norm a)) (Eq.symm (inner_self a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (inner a a = norm a * norm a)) (real_inner_self_eq_norm_square a))) (Eq.refl (norm a * norm a))) protected instance norm_one_class : norm_one_class (quaternion ℝ) := norm_one_class.mk (eq.mpr (id (Eq._oldrec (Eq.refl (norm 1 = 1)) (norm_eq_sqrt_real_inner 1))) (eq.mpr (id (Eq._oldrec (Eq.refl (real.sqrt (inner 1 1) = 1)) (inner_self 1))) (eq.mpr (id (Eq._oldrec (Eq.refl (real.sqrt (coe_fn norm_sq 1) = 1)) (monoid_with_zero_hom.map_one norm_sq))) (eq.mpr (id (Eq._oldrec (Eq.refl (real.sqrt 1 = 1)) real.sqrt_one)) (Eq.refl 1))))) @[simp] theorem norm_mul (a : quaternion ℝ) (b : quaternion ℝ) : norm (a * b) = norm a * norm b := sorry @[simp] theorem norm_coe (a : ℝ) : norm ↑a = norm a := sorry protected instance normed_ring : normed_ring (quaternion ℝ) := normed_ring.mk sorry sorry protected instance normed_algebra : normed_algebra ℝ (quaternion ℝ) := normed_algebra.mk norm_coe protected instance has_coe : has_coe ℂ (quaternion ℝ) := has_coe.mk fun (z : ℂ) => quaternion_algebra.mk (complex.re z) (complex.im z) 0 0 @[simp] theorem coe_complex_re (z : ℂ) : re ↑z = complex.re z := rfl @[simp] theorem coe_complex_im_i (z : ℂ) : im_i ↑z = complex.im z := rfl @[simp] theorem coe_complex_im_j (z : ℂ) : im_j ↑z = 0 := rfl @[simp] theorem coe_complex_im_k (z : ℂ) : im_k ↑z = 0 := rfl @[simp] theorem coe_complex_add (z : ℂ) (w : ℂ) : ↑(z + w) = ↑z + ↑w := sorry @[simp] theorem coe_complex_mul (z : ℂ) (w : ℂ) : ↑(z * w) = ↑z * ↑w := sorry @[simp] theorem coe_complex_zero : ↑0 = 0 := rfl @[simp] theorem coe_complex_one : ↑1 = 1 := rfl @[simp] theorem coe_complex_smul (r : ℝ) (z : ℂ) : ↑(r • z) = r • ↑z := sorry @[simp] theorem coe_complex_coe (r : ℝ) : ↑↑r = ↑r := rfl /-- Coercion `ℂ →ₐ[ℝ] ℍ` as an algebra homomorphism. -/ def of_complex : alg_hom ℝ ℂ (quaternion ℝ) := alg_hom.mk coe sorry coe_complex_mul sorry coe_complex_add sorry @[simp] theorem coe_of_complex : ⇑of_complex = coe := rfl
6d7cbff22dcaa3094e14861ebff9c8534b9d5fa6
1d335ec6ac4181a0a762b12797936770cc9fcef9
/imperative_DSL/environment.lean
d558c3b64b59c83e47150ad604a9fce2f7d1a08a
[]
no_license
rohanrajnair/lang
dbadcc3997e44245ca84d48dc1733cf09a2605a6
3beb4e29d8faa692983a55fa18acb6eb947134e8
refs/heads/master
1,672,640,379,424
1,597,948,771,000
1,597,948,771,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
975
lean
import ..expressions.classical_geometry import ..expressions.classical_time import ..expressions.classical_velocity import ..expressions.boolean import ..expressions.classical_acceleration namespace environment structure env : Type := mk :: (g: lang.classicalGeometry.env) (t: lang.classicalTime.env) (v: lang.classicalVelocity.env) (a: lang.classicalAcceleration.env) def init_env := env.mk lang.classicalGeometry.init lang.classicalTime.init lang.classicalVelocity.init lang.classicalAcceleration.init def classicalGeometryGet : env → lang.classicalGeometry.env | (env.mk g t v a) := g def classicalTimeGet : env → lang.classicalTime.env | (env.mk g t v a) := t def classicalVelocityGet : env → lang.classicalVelocity.env | (env.mk g t v a) := v def classicalAccelerationGet : env → lang.classicalAcceleration.env | (env.mk g t v a) := a end environment
55dc3f4caf1d2bbc6802badb6affb49eeff0ad4a
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/mk_dec_eq_instance.lean
377bba93d5a331b06c1469bee537fc9ce964c979
[ "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
5,336
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 Helper tactic for showing that a type has decidable equality. -/ prelude import init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics import init.meta.rec_util init.meta.interactive namespace tactic open expr environment list /- Retrieve the name of the type we are building a decidable equality proof for. -/ private meta def get_dec_eq_type_name : tactic name := do { (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf, (const n ls) ← return (get_app_fn b), when (n ≠ `decidable) failed, (const I ls) ← return (get_app_fn d1), return I } <|> fail "mk_dec_eq_instance tactic failed, target type is expected to be of the form (decidable_eq ...)" /- Extract (lhs, rhs) from a goal (decidable (lhs = rhs)) -/ private meta def get_lhs_rhs : tactic (expr × expr) := do (app dec lhs_eq_rhs) ← target | fail "mk_dec_eq_instance failed, unexpected case", match_eq lhs_eq_rhs private meta def find_next_target : list expr → list expr → tactic (expr × expr) | (t::ts) (r::rs) := if t = r then find_next_target ts rs else return (t, r) | l1 l2 := failed /- Create an inhabitant of (decidable (lhs = rhs)) -/ private meta def mk_dec_eq_for (lhs : expr) (rhs : expr) : tactic expr := do lhs_type ← infer_type lhs, dec_type ← mk_app `decidable_eq [lhs_type] >>= whnf, do { inst ← mk_instance dec_type, return $ inst lhs rhs } <|> do { f ← pp dec_type, fail $ to_fmt "mk_dec_eq_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f) } /- Target is of the form (decidable (C ... = C ...)) where C is a constructor -/ private meta def dec_eq_same_constructor : name → name → nat → tactic unit | I_name F_name num_rec := do (lhs, rhs) ← get_lhs_rhs, -- Try easy case first, where the proof is just reflexivity (unify lhs rhs >> right >> reflexivity) <|> do { let lhs_list := get_app_args lhs, let rhs_list := get_app_args rhs, when (length lhs_list ≠ length rhs_list) (fail "mk_dec_eq_instance failed, constructor applications have different number of arguments"), (lhs_arg, rhs_arg) ← find_next_target lhs_list rhs_list, rec ← is_type_app_of lhs_arg I_name, inst ← if rec then do { inst_fn ← mk_brec_on_rec_value F_name num_rec, return $ app inst_fn rhs_arg } else do { mk_dec_eq_for lhs_arg rhs_arg }, `[apply @decidable.by_cases _ _ %%inst], -- discharge first (positive) case by recursion intro1 >>= subst >> dec_eq_same_constructor I_name F_name (if rec then num_rec + 1 else num_rec), -- discharge second (negative) case by contradiction intro1, left, -- decidable.is_false intro1 >>= injection, intros, contradiction, return () } /- Easy case: target is of the form (decidable (C_1 ... = C_2 ...)) where C_1 and C_2 are distinct constructors -/ private meta def dec_eq_diff_constructor : tactic unit := left >> intron 1 >> contradiction /- This tactic is invoked for each case of decidable_eq. There n^2 cases, where n is the number of constructors. -/ private meta def dec_eq_case_2 (I_name : name) (F_name : name) : tactic unit := do (lhs, rhs) ← get_lhs_rhs, let lhs_fn := get_app_fn lhs, let rhs_fn := get_app_fn rhs, if lhs_fn = rhs_fn then dec_eq_same_constructor I_name F_name 0 else dec_eq_diff_constructor private meta def dec_eq_case_1 (I_name : name) (F_name : name) : tactic unit := intro `w >>= cases >> all_goals (dec_eq_case_2 I_name F_name) meta def mk_dec_eq_instance_core : tactic unit := do I_name ← get_dec_eq_type_name, env ← get_env, let v_name := `_v, let F_name := `_F, let num_indices := inductive_num_indices env I_name, let idx_names := list.map (λ (p : name × nat), mk_num_name p.fst p.snd) (list.zip (list.repeat `idx num_indices) (list.iota num_indices)), -- Use brec_on if type is recursive. -- We store the functional in the variable F. if is_recursive env I_name then intro1 >>= (λ x, induction x (idx_names ++ [v_name, F_name]) (some $ I_name <.> "brec_on") >> return ()) else intro v_name >> return (), -- Apply cases to first element of type (I ...) get_local v_name >>= cases, all_goals (dec_eq_case_1 I_name F_name) meta def mk_dec_eq_instance : tactic unit := do env ← get_env, (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf, (const I_name ls) ← return (get_app_fn d1), when (is_ginductive env I_name ∧ ¬ is_inductive env I_name) $ do { d1' ← whnf d1, (app I_basic_const I_idx) ← return d1', I_idx_type ← infer_type I_idx, new_goal ← to_expr ``(∀ (_idx : %%I_idx_type), decidable_eq (%%I_basic_const _idx)), assert `_basic_dec_eq new_goal, swap, `[exact _basic_dec_eq %%I_idx], intro1, return () }, mk_dec_eq_instance_core meta instance binder_info.has_decidable_eq : decidable_eq binder_info := by mk_dec_eq_instance end tactic /- instances of types in dependent files -/ instance : decidable_eq ordering := by tactic.mk_dec_eq_instance
d71a3904232392129aa535d9ddf2c05ed81d05a1
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/geometry/manifold/charted_space.lean
5bee52ffc3cc556e17ba0cb4050c9c59e960c666
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
43,598
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.local_homeomorph /-! # Charted spaces A smooth manifold is a topological space `M` locally modelled on a euclidean space (or a euclidean half-space for manifolds with boundaries, or an infinite dimensional vector space for more general notions of manifolds), i.e., the manifold is covered by open subsets on which there are local homeomorphisms (the charts) going to a model space `H`, and the changes of charts should be smooth maps. In this file, we introduce a general framework describing these notions, where the model space is an arbitrary topological space. We avoid the word *manifold*, which should be reserved for the situation where the model space is a (subset of a) vector space, and use the terminology *charted space* instead. If the changes of charts satisfy some additional property (for instance if they are smooth), then `M` inherits additional structure (it makes sense to talk about smooth manifolds). There are therefore two different ingredients in a charted space: * the set of charts, which is data * the fact that changes of charts belong to some group (in fact groupoid), which is additional Prop. We separate these two parts in the definition: the charted space structure is just the set of charts, and then the different smoothness requirements (smooth manifold, orientable manifold, contact manifold, and so on) are additional properties of these charts. These properties are formalized through the notion of structure groupoid, i.e., a set of local homeomorphisms stable under composition and inverse, to which the change of coordinates should belong. ## Main definitions * `structure_groupoid H` : a subset of local homeomorphisms of `H` stable under composition, inverse and restriction (ex: local diffeos). * `continuous_groupoid H` : the groupoid of all local homeomorphisms of `H` * `charted_space H M` : charted space structure on `M` modelled on `H`, given by an atlas of local homeomorphisms from `M` to `H` whose sources cover `M`. This is a type class. * `has_groupoid M G` : when `G` is a structure groupoid on `H` and `M` is a charted space modelled on `H`, require that all coordinate changes belong to `G`. This is a type class. * `atlas H M` : when `M` is a charted space modelled on `H`, the atlas of this charted space structure, i.e., the set of charts. * `G.maximal_atlas M` : when `M` is a charted space modelled on `H` and admitting `G` as a structure groupoid, one can consider all the local homeomorphisms from `M` to `H` such that changing coordinate from any chart to them belongs to `G`. This is a larger atlas, called the maximal atlas (for the groupoid `G`). * `structomorph G M M'` : the type of diffeomorphisms between the charted spaces `M` and `M'` for the groupoid `G`. We avoid the word diffeomorphism, keeping it for the smooth category. As a basic example, we give the instance `instance charted_space_model_space (H : Type*) [topological_space H] : charted_space H H` saying that a topological space is a charted space over itself, with the identity as unique chart. This charted space structure is compatible with any groupoid. Additional useful definitions: * `pregroupoid H` : a subset of local mas of `H` stable under composition and restriction, but not inverse (ex: smooth maps) * `groupoid_of_pregroupoid` : construct a groupoid from a pregroupoid, by requiring that a map and its inverse both belong to the pregroupoid (ex: construct diffeos from smooth maps) * `chart_at H x` is a preferred chart at `x : M` when `M` has a charted space structure modelled on `H`. * `G.compatible he he'` states that, for any two charts `e` and `e'` in the atlas, the composition of `e.symm` and `e'` belongs to the groupoid `G` when `M` admits `G` as a structure groupoid. * `G.compatible_of_mem_maximal_atlas he he'` states that, for any two charts `e` and `e'` in the maximal atlas associated to the groupoid `G`, the composition of `e.symm` and `e'` belongs to the `G` if `M` admits `G` as a structure groupoid. * `charted_space_core.to_charted_space`: consider a space without a topology, but endowed with a set of charts (which are local equivs) for which the change of coordinates are local homeos. Then one can construct a topology on the space for which the charts become local homeos, defining a genuine charted space structure. ## Implementation notes The atlas in a charted space is *not* a maximal atlas in general: the notion of maximality depends on the groupoid one considers, and changing groupoids changes the maximal atlas. With the current formalization, it makes sense first to choose the atlas, and then to ask whether this precise atlas defines a smooth manifold, an orientable manifold, and so on. A consequence is that structomorphisms between `M` and `M'` do *not* induce a bijection between the atlases of `M` and `M'`: the definition is only that, read in charts, the structomorphism locally belongs to the groupoid under consideration. (This is equivalent to inducing a bijection between elements of the maximal atlas). A consequence is that the invariance under structomorphisms of properties defined in terms of the atlas is not obvious in general, and could require some work in theory (amounting to the fact that these properties only depend on the maximal atlas, for instance). In practice, this does not create any real difficulty. We use the letter `H` for the model space thinking of the case of manifolds with boundary, where the model space is a half space. Manifolds are sometimes defined as topological spaces with an atlas of local diffeomorphisms, and sometimes as spaces with an atlas from which a topology is deduced. We use the former approach: otherwise, there would be an instance from manifolds to topological spaces, which means that any instance search for topological spaces would try to find manifold structures involving a yet unknown model space, leading to problems. However, we also introduce the latter approach, through a structure `charted_space_core` making it possible to construct a topology out of a set of local equivs with compatibility conditions (but we do not register it as an instance). In the definition of a charted space, the model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen sometimes as a real manifold modelled over `ℝ^(2n)`. ## Notations In the locale `manifold`, we denote the composition of local homeomorphisms with `≫ₕ`, and the composition of local equivs with `≫`. -/ noncomputable theory open_locale classical universes u variables {H : Type u} {H' : Type*} {M : Type*} {M' : Type*} {M'' : Type*} /- Notational shortcut for the composition of local homeomorphisms and local equivs, i.e., `local_homeomorph.trans` and `local_equiv.trans`. Note that, as is usual for equivs, the composition is from left to right, hence the direction of the arrow. -/ localized "infixr ` ≫ₕ `:100 := local_homeomorph.trans" in manifold localized "infixr ` ≫ `:100 := local_equiv.trans" in manifold /- `simp` looks for subsingleton instances at every call. This turns out to be very inefficient, especially in `simp`-heavy parts of the library such as the manifold code. Disable two such instances to speed up things. NB: this is just a hack. TODO: fix `simp` properly. -/ localized "attribute [-instance] unique.subsingleton pi.subsingleton" in manifold open set local_homeomorph /-! ### Structure groupoids-/ section groupoid /-! One could add to the definition of a structure groupoid the fact that the restriction of an element of the groupoid to any open set still belongs to the groupoid. (This is in Kobayashi-Nomizu.) I am not sure I want this, for instance on `H × E` where `E` is a vector space, and the groupoid is made of functions respecting the fibers and linear in the fibers (so that a charted space over this groupoid is naturally a vector bundle) I prefer that the members of the groupoid are always defined on sets of the form `s × E`. There is a typeclass `closed_under_restriction` for groupoids which have the restriction property. The only nontrivial requirement is locality: if a local homeomorphism belongs to the groupoid around each point in its domain of definition, then it belongs to the groupoid. Without this requirement, the composition of structomorphisms does not have to be a structomorphism. Note that this implies that a local homeomorphism with empty source belongs to any structure groupoid, as it trivially satisfies this condition. There is also a technical point, related to the fact that a local homeomorphism is by definition a global map which is a homeomorphism when restricted to its source subset (and its values outside of the source are not relevant). Therefore, we also require that being a member of the groupoid only depends on the values on the source. We use primes in the structure names as we will reformulate them below (without primes) using a `has_mem` instance, writing `e ∈ G` instead of `e ∈ G.members`. -/ /-- A structure groupoid is a set of local homeomorphisms of a topological space stable under composition and inverse. They appear in the definition of the smoothness class of a manifold. -/ structure structure_groupoid (H : Type u) [topological_space H] := (members : set (local_homeomorph H H)) (trans' : ∀e e' : local_homeomorph H H, e ∈ members → e' ∈ members → e ≫ₕ e' ∈ members) (symm' : ∀e : local_homeomorph H H, e ∈ members → e.symm ∈ members) (id_mem' : local_homeomorph.refl H ∈ members) (locality' : ∀e : local_homeomorph H H, (∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ members) → e ∈ members) (eq_on_source' : ∀ e e' : local_homeomorph H H, e ∈ members → e' ≈ e → e' ∈ members) variable [topological_space H] instance : has_mem (local_homeomorph H H) (structure_groupoid H) := ⟨λ(e : local_homeomorph H H) (G : structure_groupoid H), e ∈ G.members⟩ lemma structure_groupoid.trans (G : structure_groupoid H) {e e' : local_homeomorph H H} (he : e ∈ G) (he' : e' ∈ G) : e ≫ₕ e' ∈ G := G.trans' e e' he he' lemma structure_groupoid.symm (G : structure_groupoid H) {e : local_homeomorph H H} (he : e ∈ G) : e.symm ∈ G := G.symm' e he lemma structure_groupoid.id_mem (G : structure_groupoid H) : local_homeomorph.refl H ∈ G := G.id_mem' lemma structure_groupoid.locality (G : structure_groupoid H) {e : local_homeomorph H H} (h : ∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ G) : e ∈ G := G.locality' e h lemma structure_groupoid.eq_on_source (G : structure_groupoid H) {e e' : local_homeomorph H H} (he : e ∈ G) (h : e' ≈ e) : e' ∈ G := G.eq_on_source' e e' he h /-- Partial order on the set of groupoids, given by inclusion of the members of the groupoid -/ instance structure_groupoid.partial_order : partial_order (structure_groupoid H) := partial_order.lift structure_groupoid.members (λa b h, by { cases a, cases b, dsimp at h, induction h, refl }) lemma structure_groupoid.le_iff {G₁ G₂ : structure_groupoid H} : G₁ ≤ G₂ ↔ ∀ e, e ∈ G₁ → e ∈ G₂ := iff.rfl /-- The trivial groupoid, containing only the identity (and maps with empty source, as this is necessary from the definition) -/ def id_groupoid (H : Type u) [topological_space H] : structure_groupoid H := { members := {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅}, trans' := λe e' he he', begin cases he; simp at he he', { simpa only [he, refl_trans]}, { have : (e ≫ₕ e').source ⊆ e.source := sep_subset _ _, rw he at this, have : (e ≫ₕ e') ∈ {e : local_homeomorph H H | e.source = ∅} := disjoint_iff.1 this, exact (mem_union _ _ _).2 (or.inr this) }, end, symm' := λe he, begin cases (mem_union _ _ _).1 he with E E, { finish }, { right, simpa only [e.to_local_equiv.image_source_eq_target.symm] with mfld_simps using E}, end, id_mem' := mem_union_left _ rfl, locality' := λe he, begin cases e.source.eq_empty_or_nonempty with h h, { right, exact h }, { left, rcases h with ⟨x, hx⟩, rcases he x hx with ⟨s, open_s, xs, hs⟩, have x's : x ∈ (e.restr s).source, { rw [restr_source, open_s.interior_eq], exact ⟨hx, xs⟩ }, cases hs, { replace hs : local_homeomorph.restr e s = local_homeomorph.refl H, by simpa only using hs, have : (e.restr s).source = univ, by { rw hs, simp }, change (e.to_local_equiv).source ∩ interior s = univ at this, have : univ ⊆ interior s, by { rw ← this, exact inter_subset_right _ _ }, have : s = univ, by rwa [open_s.interior_eq, univ_subset_iff] at this, simpa only [this, restr_univ] using hs }, { exfalso, rw mem_set_of_eq at hs, rwa hs at x's } }, end, eq_on_source' := λe e' he he'e, begin cases he, { left, have : e = e', { refine eq_of_eq_on_source_univ (setoid.symm he'e) _ _; rw set.mem_singleton_iff.1 he ; refl }, rwa ← this }, { right, change (e.to_local_equiv).source = ∅ at he, rwa [set.mem_set_of_eq, he'e.source_eq] } end } /-- Every structure groupoid contains the identity groupoid -/ instance : order_bot (structure_groupoid H) := { bot := id_groupoid H, bot_le := begin assume u f hf, change f ∈ {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅} at hf, simp only [singleton_union, mem_set_of_eq, mem_insert_iff] at hf, cases hf, { rw hf, apply u.id_mem }, { apply u.locality, assume x hx, rw [hf, mem_empty_eq] at hx, exact hx.elim } end, ..structure_groupoid.partial_order } instance (H : Type u) [topological_space H] : inhabited (structure_groupoid H) := ⟨id_groupoid H⟩ /-- To construct a groupoid, one may consider classes of local homeos such that both the function and its inverse have some property. If this property is stable under composition, one gets a groupoid. `pregroupoid` bundles the properties needed for this construction, with the groupoid of smooth functions with smooth inverses as an application. -/ structure pregroupoid (H : Type*) [topological_space H] := (property : (H → H) → (set H) → Prop) (comp : ∀{f g u v}, property f u → property g v → is_open u → is_open v → is_open (u ∩ f ⁻¹' v) → property (g ∘ f) (u ∩ f ⁻¹' v)) (id_mem : property id univ) (locality : ∀{f u}, is_open u → (∀x∈u, ∃v, is_open v ∧ x ∈ v ∧ property f (u ∩ v)) → property f u) (congr : ∀{f g : H → H} {u}, is_open u → (∀x∈u, g x = f x) → property f u → property g u) /-- Construct a groupoid of local homeos for which the map and its inverse have some property, from a pregroupoid asserting that this property is stable under composition. -/ def pregroupoid.groupoid (PG : pregroupoid H) : structure_groupoid H := { members := {e : local_homeomorph H H | PG.property e e.source ∧ PG.property e.symm e.target}, trans' := λe e' he he', begin split, { apply PG.comp he.1 he'.1 e.open_source e'.open_source, apply e.continuous_to_fun.preimage_open_of_open e.open_source e'.open_source }, { apply PG.comp he'.2 he.2 e'.open_target e.open_target, apply e'.continuous_inv_fun.preimage_open_of_open e'.open_target e.open_target } end, symm' := λe he, ⟨he.2, he.1⟩, id_mem' := ⟨PG.id_mem, PG.id_mem⟩, locality' := λe he, begin split, { apply PG.locality e.open_source (λx xu, _), rcases he x xu with ⟨s, s_open, xs, hs⟩, refine ⟨s, s_open, xs, _⟩, convert hs.1, exact s_open.interior_eq.symm }, { apply PG.locality e.open_target (λx xu, _), rcases he (e.symm x) (e.map_target xu) with ⟨s, s_open, xs, hs⟩, refine ⟨e.target ∩ e.symm ⁻¹' s, _, ⟨xu, xs⟩, _⟩, { exact continuous_on.preimage_open_of_open e.continuous_inv_fun e.open_target s_open }, { rw [← inter_assoc, inter_self], convert hs.2, exact s_open.interior_eq.symm } }, end, eq_on_source' := λe e' he ee', begin split, { apply PG.congr e'.open_source ee'.2, simp only [ee'.1, he.1] }, { have A := ee'.symm', apply PG.congr e'.symm.open_source A.2, convert he.2, rw A.1, refl } end } lemma mem_groupoid_of_pregroupoid {PG : pregroupoid H} {e : local_homeomorph H H} : e ∈ PG.groupoid ↔ PG.property e e.source ∧ PG.property e.symm e.target := iff.rfl lemma groupoid_of_pregroupoid_le (PG₁ PG₂ : pregroupoid H) (h : ∀f s, PG₁.property f s → PG₂.property f s) : PG₁.groupoid ≤ PG₂.groupoid := begin refine structure_groupoid.le_iff.2 (λ e he, _), rw mem_groupoid_of_pregroupoid at he ⊢, exact ⟨h _ _ he.1, h _ _ he.2⟩ end lemma mem_pregroupoid_of_eq_on_source (PG : pregroupoid H) {e e' : local_homeomorph H H} (he' : e ≈ e') (he : PG.property e e.source) : PG.property e' e'.source := begin rw ← he'.1, exact PG.congr e.open_source he'.eq_on.symm he, end /-- The pregroupoid of all local maps on a topological space `H` -/ @[reducible] def continuous_pregroupoid (H : Type*) [topological_space H] : pregroupoid H := { property := λf s, true, comp := λf g u v hf hg hu hv huv, trivial, id_mem := trivial, locality := λf u u_open h, trivial, congr := λf g u u_open hcongr hf, trivial } instance (H : Type*) [topological_space H] : inhabited (pregroupoid H) := ⟨continuous_pregroupoid H⟩ /-- The groupoid of all local homeomorphisms on a topological space `H` -/ def continuous_groupoid (H : Type*) [topological_space H] : structure_groupoid H := pregroupoid.groupoid (continuous_pregroupoid H) /-- Every structure groupoid is contained in the groupoid of all local homeomorphisms -/ instance : order_top (structure_groupoid H) := { top := continuous_groupoid H, le_top := λ u f hf, by { split; exact dec_trivial }, ..structure_groupoid.partial_order } /-- A groupoid is closed under restriction if it contains all restrictions of its element local homeomorphisms to open subsets of the source. -/ class closed_under_restriction (G : structure_groupoid H) : Prop := (closed_under_restriction : ∀ {e : local_homeomorph H H}, e ∈ G → ∀ (s : set H), is_open s → e.restr s ∈ G) lemma closed_under_restriction' {G : structure_groupoid H} [closed_under_restriction G] {e : local_homeomorph H H} (he : e ∈ G) {s : set H} (hs : is_open s) : e.restr s ∈ G := closed_under_restriction.closed_under_restriction he s hs /-- The trivial restriction-closed groupoid, containing only local homeomorphisms equivalent to the restriction of the identity to the various open subsets. -/ def id_restr_groupoid : structure_groupoid H := { members := {e | ∃ {s : set H} (h : is_open s), e ≈ local_homeomorph.of_set s h}, trans' := begin rintros e e' ⟨s, hs, hse⟩ ⟨s', hs', hse'⟩, refine ⟨s ∩ s', is_open_inter hs hs', _⟩, have := local_homeomorph.eq_on_source.trans' hse hse', rwa local_homeomorph.of_set_trans_of_set at this, end, symm' := begin rintros e ⟨s, hs, hse⟩, refine ⟨s, hs, _⟩, rw [← of_set_symm], exact local_homeomorph.eq_on_source.symm' hse, end, id_mem' := ⟨univ, is_open_univ, by simp only with mfld_simps⟩, locality' := begin intros e h, refine ⟨e.source, e.open_source, by simp only with mfld_simps, _⟩, intros x hx, rcases h x hx with ⟨s, hs, hxs, s', hs', hes'⟩, have hes : x ∈ (e.restr s).source, { rw e.restr_source, refine ⟨hx, _⟩, rw hs.interior_eq, exact hxs }, simpa only with mfld_simps using local_homeomorph.eq_on_source.eq_on hes' hes, end, eq_on_source' := begin rintros e e' ⟨s, hs, hse⟩ hee', exact ⟨s, hs, setoid.trans hee' hse⟩, end } lemma id_restr_groupoid_mem {s : set H} (hs : is_open s) : of_set s hs ∈ @id_restr_groupoid H _ := ⟨s, hs, by refl⟩ /-- The trivial restriction-closed groupoid is indeed `closed_under_restriction`. -/ instance closed_under_restriction_id_restr_groupoid : closed_under_restriction (@id_restr_groupoid H _) := ⟨ begin rintros e ⟨s', hs', he⟩ s hs, use [s' ∩ s, is_open_inter hs' hs], refine setoid.trans (local_homeomorph.eq_on_source.restr he s) _, exact ⟨by simp only [hs.interior_eq] with mfld_simps, by simp only with mfld_simps⟩, end ⟩ /-- A groupoid is closed under restriction if and only if it contains the trivial restriction-closed groupoid. -/ lemma closed_under_restriction_iff_id_le (G : structure_groupoid H) : closed_under_restriction G ↔ id_restr_groupoid ≤ G := begin split, { introsI _i, apply structure_groupoid.le_iff.mpr, rintros e ⟨s, hs, hes⟩, refine G.eq_on_source _ hes, convert closed_under_restriction' G.id_mem hs, rw hs.interior_eq, simp only with mfld_simps }, { intros h, split, intros e he s hs, rw ← of_set_trans (e : local_homeomorph H H) hs, refine G.trans _ he, apply structure_groupoid.le_iff.mp h, exact id_restr_groupoid_mem hs }, end /-- The groupoid of all local homeomorphisms on a topological space `H` is closed under restriction. -/ instance : closed_under_restriction (continuous_groupoid H) := (closed_under_restriction_iff_id_le _).mpr (by convert le_top) end groupoid /-! ### Charted spaces -/ /-- A charted space is a topological space endowed with an atlas, i.e., a set of local homeomorphisms taking value in a model space `H`, called charts, such that the domains of the charts cover the whole space. We express the covering property by chosing for each `x` a member `chart_at H x` of the atlas containing `x` in its source: in the smooth case, this is convenient to construct the tangent bundle in an efficient way. The model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen sometimes as a real manifold over `ℝ^(2n)`. -/ class charted_space (H : Type*) [topological_space H] (M : Type*) [topological_space M] := (atlas [] : set (local_homeomorph M H)) (chart_at [] : M → local_homeomorph M H) (mem_chart_source [] : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas [] : ∀x, chart_at x ∈ atlas) export charted_space attribute [simp, mfld_simps] mem_chart_source chart_mem_atlas section charted_space /-- Any space is a charted_space modelled over itself, by just using the identity chart -/ instance charted_space_self (H : Type*) [topological_space H] : charted_space H H := { atlas := {local_homeomorph.refl H}, chart_at := λx, local_homeomorph.refl H, mem_chart_source := λx, mem_univ x, chart_mem_atlas := λx, mem_singleton _ } /-- In the trivial charted_space structure of a space modelled over itself through the identity, the atlas members are just the identity -/ @[simp, mfld_simps] lemma charted_space_self_atlas {H : Type*} [topological_space H] {e : local_homeomorph H H} : e ∈ atlas H H ↔ e = local_homeomorph.refl H := by simp [atlas, charted_space.atlas] /-- In the model space, chart_at is always the identity -/ @[simp, mfld_simps] lemma chart_at_self_eq {H : Type*} [topological_space H] {x : H} : chart_at H x = local_homeomorph.refl H := by simpa using chart_mem_atlas H x /-- Same thing as `H × H'`. We introduce it for technical reasons: a charted space `M` with model `H` is a set of local charts from `M` to `H` covering the space. Every space is registered as a charted space over itself, using the only chart `id`, in `manifold_model_space`. You can also define a product of charted space `M` and `M'` (with model space `H × H'`) by taking the products of the charts. Now, on `H × H'`, there are two charted space structures with model space `H × H'` itself, the one coming from `manifold_model_space`, and the one coming from the product of the two `manifold_model_space` on each component. They are equal, but not defeq (because the product of `id` and `id` is not defeq to `id`), which is bad as we know. This expedient of renaming `H × H'` solves this problem. -/ def model_prod (H : Type*) (H' : Type*) := H × H' section local attribute [reducible] model_prod instance model_prod_inhabited {α β : Type*} [inhabited α] [inhabited β] : inhabited (model_prod α β) := ⟨(default α, default β)⟩ instance (H : Type*) [topological_space H] (H' : Type*) [topological_space H'] : topological_space (model_prod H H') := by apply_instance /- Next lemma shows up often when dealing with derivatives, register it as simp. -/ @[simp, mfld_simps] lemma model_prod_range_prod_id {H : Type*} {H' : Type*} {α : Type*} (f : H → α) : range (λ (p : model_prod H H'), (f p.1, p.2)) = set.prod (range f) univ := by rw prod_range_univ_eq end /-- The product of two charted spaces is naturally a charted space, with the canonical construction of the atlas of product maps. -/ instance prod_charted_space (H : Type*) [topological_space H] (M : Type*) [topological_space M] [charted_space H M] (H' : Type*) [topological_space H'] (M' : Type*) [topological_space M'] [charted_space H' M'] : charted_space (model_prod H H') (M × M') := { atlas := {f : (local_homeomorph (M×M') (model_prod H H')) | ∃ g ∈ charted_space.atlas H M, ∃ h ∈ (charted_space.atlas H' M'), f = local_homeomorph.prod g h}, chart_at := λ x: (M × M'), (charted_space.chart_at H x.1).prod (charted_space.chart_at H' x.2), mem_chart_source := begin intro x, simp only with mfld_simps, end, chart_mem_atlas := begin intro x, use (charted_space.chart_at H x.1), split, { apply chart_mem_atlas _, }, { use (charted_space.chart_at H' x.2), simp only [chart_mem_atlas, eq_self_iff_true, and_self], } end } section prod_charted_space variables [topological_space H] [topological_space M] [charted_space H M] [topological_space H'] [topological_space M'] [charted_space H' M'] {x : M×M'} @[simp, mfld_simps] lemma prod_charted_space_chart_at : (chart_at (model_prod H H') x) = (chart_at H x.fst).prod (chart_at H' x.snd) := rfl end prod_charted_space end charted_space /-! ### Constructing a topology from an atlas -/ /-- Sometimes, one may want to construct a charted space structure on a space which does not yet have a topological structure, where the topology would come from the charts. For this, one needs charts that are only local equivs, and continuity properties for their composition. This is formalised in `charted_space_core`. -/ @[nolint has_inhabited_instance] structure charted_space_core (H : Type*) [topological_space H] (M : Type*) := (atlas : set (local_equiv M H)) (chart_at : M → local_equiv M H) (mem_chart_source : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas : ∀x, chart_at x ∈ atlas) (open_source : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → is_open (e.symm.trans e').source) (continuous_to_fun : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → continuous_on (e.symm.trans e') (e.symm.trans e').source) namespace charted_space_core variables [topological_space H] (c : charted_space_core H M) {e : local_equiv M H} /-- Topology generated by a set of charts on a Type. -/ protected def to_topological_space : topological_space M := topological_space.generate_from $ ⋃ (e : local_equiv M H) (he : e ∈ c.atlas) (s : set H) (s_open : is_open s), {e ⁻¹' s ∩ e.source} lemma open_source' (he : e ∈ c.atlas) : @is_open M c.to_topological_space e.source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨e, he, univ, is_open_univ, _⟩, simp only [set.univ_inter, set.preimage_univ] end lemma open_target (he : e ∈ c.atlas) : is_open e.target := begin have E : e.target ∩ e.symm ⁻¹' e.source = e.target := subset.antisymm (inter_subset_left _ _) (λx hx, ⟨hx, local_equiv.target_subset_preimage_source _ hx⟩), simpa [local_equiv.trans_source, E] using c.open_source e e he he end /-- An element of the atlas in a charted space without topology becomes a local homeomorphism for the topology constructed from this atlas. The `local_homeomorph` version is given in this definition. -/ def local_homeomorph (e : local_equiv M H) (he : e ∈ c.atlas) : @local_homeomorph M H c.to_topological_space _ := { open_source := by convert c.open_source' he, open_target := by convert c.open_target he, continuous_to_fun := begin letI : topological_space M := c.to_topological_space, rw continuous_on_open_iff (c.open_source' he), assume s s_open, rw inter_comm, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨e, he, ⟨s, s_open, rfl⟩⟩ end, continuous_inv_fun := begin letI : topological_space M := c.to_topological_space, apply continuous_on_open_of_generate_from (c.open_target he), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, rcases ht with ⟨e', e'_atlas, s, s_open, ts⟩, rw ts, let f := e.symm.trans e', have : is_open (f ⁻¹' s ∩ f.source), by simpa [inter_comm] using (continuous_on_open_iff (c.open_source e e' he e'_atlas)).1 (c.continuous_to_fun e e' he e'_atlas) s s_open, have A : e' ∘ e.symm ⁻¹' s ∩ (e.target ∩ e.symm ⁻¹' e'.source) = e.target ∩ (e' ∘ e.symm ⁻¹' s ∩ e.symm ⁻¹' e'.source), by { rw [← inter_assoc, ← inter_assoc], congr' 1, exact inter_comm _ _ }, simpa [local_equiv.trans_source, preimage_inter, preimage_comp.symm, A] using this end, ..e } /-- Given a charted space without topology, endow it with a genuine charted space structure with respect to the topology constructed from the atlas. -/ def to_charted_space : @charted_space H _ M c.to_topological_space := { atlas := ⋃ (e : local_equiv M H) (he : e ∈ c.atlas), {c.local_homeomorph e he}, chart_at := λx, c.local_homeomorph (c.chart_at x) (c.chart_mem_atlas x), mem_chart_source := λx, c.mem_chart_source x, chart_mem_atlas := λx, begin simp only [mem_Union, mem_singleton_iff], exact ⟨c.chart_at x, c.chart_mem_atlas x, rfl⟩, end } end charted_space_core /-! ### Charted space with a given structure groupoid -/ section has_groupoid variables [topological_space H] [topological_space M] [charted_space H M] section set_option old_structure_cmd true /-- A charted space has an atlas in a groupoid `G` if the change of coordinates belong to the groupoid -/ class has_groupoid {H : Type*} [topological_space H] (M : Type*) [topological_space M] [charted_space H M] (G : structure_groupoid H) : Prop := (compatible [] : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → e.symm ≫ₕ e' ∈ G) end /-- Reformulate in the `structure_groupoid` namespace the compatibility condition of charts in a charted space admitting a structure groupoid, to make it more easily accessible with dot notation. -/ lemma structure_groupoid.compatible {H : Type*} [topological_space H] (G : structure_groupoid H) {M : Type*} [topological_space M] [charted_space H M] [has_groupoid M G] {e e' : local_homeomorph M H} (he : e ∈ atlas H M) (he' : e' ∈ atlas H M) : e.symm ≫ₕ e' ∈ G := has_groupoid.compatible G he he' lemma has_groupoid_of_le {G₁ G₂ : structure_groupoid H} (h : has_groupoid M G₁) (hle : G₁ ≤ G₂) : has_groupoid M G₂ := ⟨ λ e e' he he', hle ((h.compatible : _) he he') ⟩ lemma has_groupoid_of_pregroupoid (PG : pregroupoid H) (h : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → PG.property (e.symm ≫ₕ e') (e.symm ≫ₕ e').source) : has_groupoid M (PG.groupoid) := ⟨assume e e' he he', mem_groupoid_of_pregroupoid.mpr ⟨h he he', h he' he⟩⟩ /-- The trivial charted space structure on the model space is compatible with any groupoid -/ instance has_groupoid_model_space (H : Type*) [topological_space H] (G : structure_groupoid H) : has_groupoid H G := { compatible := λe e' he he', begin replace he : e ∈ atlas H H := he, replace he' : e' ∈ atlas H H := he', rw charted_space_self_atlas at he he', simp [he, he', structure_groupoid.id_mem] end } /-- Any charted space structure is compatible with the groupoid of all local homeomorphisms -/ instance has_groupoid_continuous_groupoid : has_groupoid M (continuous_groupoid H) := ⟨begin assume e e' he he', rw [continuous_groupoid, mem_groupoid_of_pregroupoid], simp only [and_self] end⟩ section maximal_atlas variables (M) (G : structure_groupoid H) /-- Given a charted space admitting a structure groupoid, the maximal atlas associated to this structure groupoid is the set of all local charts that are compatible with the atlas, i.e., such that changing coordinates with an atlas member gives an element of the groupoid. -/ def structure_groupoid.maximal_atlas : set (local_homeomorph M H) := {e | ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G} variable {M} /-- The elements of the atlas belong to the maximal atlas for any structure groupoid -/ lemma structure_groupoid.mem_maximal_atlas_of_mem_atlas [has_groupoid M G] {e : local_homeomorph M H} (he : e ∈ atlas H M) : e ∈ G.maximal_atlas M := λ e' he', ⟨G.compatible he he', G.compatible he' he⟩ lemma structure_groupoid.chart_mem_maximal_atlas [has_groupoid M G] (x : M) : chart_at H x ∈ G.maximal_atlas M := G.mem_maximal_atlas_of_mem_atlas (chart_mem_atlas H x) variable {G} lemma mem_maximal_atlas_iff {e : local_homeomorph M H} : e ∈ G.maximal_atlas M ↔ ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G := iff.rfl /-- Changing coordinates between two elements of the maximal atlas gives rise to an element of the structure groupoid. -/ lemma structure_groupoid.compatible_of_mem_maximal_atlas {e e' : local_homeomorph M H} (he : e ∈ G.maximal_atlas M) (he' : e' ∈ G.maximal_atlas M) : e.symm ≫ₕ e' ∈ G := begin apply G.locality (λ x hx, _), set f := chart_at H (e.symm x) with hf, let s := e.target ∩ (e.symm ⁻¹' f.source), have hs : is_open s, { apply e.symm.continuous_to_fun.preimage_open_of_open; apply open_source }, have xs : x ∈ s, by { dsimp at hx, simp [s, hx] }, refine ⟨s, hs, xs, _⟩, have A : e.symm ≫ₕ f ∈ G := (mem_maximal_atlas_iff.1 he f (chart_mem_atlas _ _)).1, have B : f.symm ≫ₕ e' ∈ G := (mem_maximal_atlas_iff.1 he' f (chart_mem_atlas _ _)).2, have C : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ∈ G := G.trans A B, have D : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ≈ (e.symm ≫ₕ e').restr s := calc (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') = e.symm ≫ₕ (f ≫ₕ f.symm) ≫ₕ e' : by simp [trans_assoc] ... ≈ e.symm ≫ₕ (of_set f.source f.open_source) ≫ₕ e' : by simp [eq_on_source.trans', trans_self_symm] ... ≈ (e.symm ≫ₕ (of_set f.source f.open_source)) ≫ₕ e' : by simp [trans_assoc] ... ≈ (e.symm.restr s) ≫ₕ e' : by simp [s, trans_of_set'] ... ≈ (e.symm ≫ₕ e').restr s : by simp [restr_trans], exact G.eq_on_source C (setoid.symm D), end variable (G) /-- In the model space, the identity is in any maximal atlas. -/ lemma structure_groupoid.id_mem_maximal_atlas : local_homeomorph.refl H ∈ G.maximal_atlas H := G.mem_maximal_atlas_of_mem_atlas (by simp) end maximal_atlas section singleton variables {α : Type*} [topological_space α] variables (e : local_homeomorph α H) /-- If a single local homeomorphism `e` from a space `α` into `H` has source covering the whole space `α`, then that local homeomorphism induces an `H`-charted space structure on `α`. (This condition is equivalent to `e` being an open embedding of `α` into `H`; see `local_homeomorph.to_open_embedding` and `open_embedding.to_local_homeomorph`.) -/ def singleton_charted_space (h : e.source = set.univ) : charted_space H α := { atlas := {e}, chart_at := λ _, e, mem_chart_source := λ _, by simp only [h] with mfld_simps, chart_mem_atlas := λ _, by tauto } lemma singleton_charted_space_one_chart (h : e.source = set.univ) (e' : local_homeomorph α H) (h' : e' ∈ (singleton_charted_space e h).atlas) : e' = e := h' /-- Given a local homeomorphism `e` from a space `α` into `H`, if its source covers the whole space `α`, then the induced charted space structure on `α` is `has_groupoid G` for any structure groupoid `G` which is closed under restrictions. -/ lemma singleton_has_groupoid (h : e.source = set.univ) (G : structure_groupoid H) [closed_under_restriction G] : @has_groupoid _ _ _ _ (singleton_charted_space e h) G := { compatible := begin intros e' e'' he' he'', rw singleton_charted_space_one_chart e h e' he', rw singleton_charted_space_one_chart e h e'' he'', refine G.eq_on_source _ e.trans_symm_self, have hle : id_restr_groupoid ≤ G := (closed_under_restriction_iff_id_le G).mp (by assumption), exact structure_groupoid.le_iff.mp hle _ (id_restr_groupoid_mem _), end } end singleton namespace topological_space.opens open topological_space variables (G : structure_groupoid H) [has_groupoid M G] variables (s : opens M) /-- An open subset of a charted space is naturally a charted space. -/ instance : charted_space H s := { atlas := ⋃ (x : s), {@local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩}, chart_at := λ x, @local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩, mem_chart_source := λ x, by { simp only with mfld_simps, exact (mem_chart_source H x.1) }, chart_mem_atlas := λ x, by { simp only [mem_Union, mem_singleton_iff], use x } } /-- If a groupoid `G` is `closed_under_restriction`, then an open subset of a space which is `has_groupoid G` is naturally `has_groupoid G`. -/ instance [closed_under_restriction G] : has_groupoid s G := { compatible := begin rintros e e' ⟨_, ⟨x, hc⟩, he⟩ ⟨_, ⟨x', hc'⟩, he'⟩, haveI : nonempty s := ⟨x⟩, simp only [hc.symm, mem_singleton_iff, subtype.val_eq_coe] at he, simp only [hc'.symm, mem_singleton_iff, subtype.val_eq_coe] at he', rw [he, he'], convert G.eq_on_source _ (subtype_restr_symm_trans_subtype_restr s (chart_at H x) (chart_at H x')), apply closed_under_restriction', { exact G.compatible (chart_mem_atlas H x) (chart_mem_atlas H x') }, { exact preimage_open_of_open_symm (chart_at H x) s.2 }, end } end topological_space.opens /-! ### Structomorphisms -/ /-- A `G`-diffeomorphism between two charted spaces is a homeomorphism which, when read in the charts, belongs to `G`. We avoid the word diffeomorph as it is too related to the smooth category, and use structomorph instead. -/ @[nolint has_inhabited_instance] structure structomorph (G : structure_groupoid H) (M : Type*) (M' : Type*) [topological_space M] [topological_space M'] [charted_space H M] [charted_space H M'] extends homeomorph M M' := (mem_groupoid : ∀c : local_homeomorph M H, ∀c' : local_homeomorph M' H, c ∈ atlas H M → c' ∈ atlas H M' → c.symm ≫ₕ to_homeomorph.to_local_homeomorph ≫ₕ c' ∈ G) variables [topological_space M'] [topological_space M''] {G : structure_groupoid H} [charted_space H M'] [charted_space H M''] /-- The identity is a diffeomorphism of any charted space, for any groupoid. -/ def structomorph.refl (M : Type*) [topological_space M] [charted_space H M] [has_groupoid M G] : structomorph G M M := { mem_groupoid := λc c' hc hc', begin change (local_homeomorph.symm c) ≫ₕ (local_homeomorph.refl M) ≫ₕ c' ∈ G, rw local_homeomorph.refl_trans, exact has_groupoid.compatible G hc hc' end, ..homeomorph.refl M } /-- The inverse of a structomorphism is a structomorphism -/ def structomorph.symm (e : structomorph G M M') : structomorph G M' M := { mem_groupoid := begin assume c c' hc hc', have : (c'.symm ≫ₕ e.to_homeomorph.to_local_homeomorph ≫ₕ c).symm ∈ G := G.symm (e.mem_groupoid c' c hc' hc), rwa [trans_symm_eq_symm_trans_symm, trans_symm_eq_symm_trans_symm, symm_symm, trans_assoc] at this, end, ..e.to_homeomorph.symm} /-- The composition of structomorphisms is a structomorphism -/ def structomorph.trans (e : structomorph G M M') (e' : structomorph G M' M'') : structomorph G M M'' := { mem_groupoid := begin /- Let c and c' be two charts in M and M''. We want to show that e' ∘ e is smooth in these charts, around any point x. For this, let y = e (c⁻¹ x), and consider a chart g around y. Then g ∘ e ∘ c⁻¹ and c' ∘ e' ∘ g⁻¹ are both smooth as e and e' are structomorphisms, so their composition is smooth, and it coincides with c' ∘ e' ∘ e ∘ c⁻¹ around x. -/ assume c c' hc hc', refine G.locality (λx hx, _), let f₁ := e.to_homeomorph.to_local_homeomorph, let f₂ := e'.to_homeomorph.to_local_homeomorph, let f := (e.to_homeomorph.trans e'.to_homeomorph).to_local_homeomorph, have feq : f = f₁ ≫ₕ f₂ := homeomorph.trans_to_local_homeomorph _ _, -- define the atlas g around y let y := (c.symm ≫ₕ f₁) x, let g := chart_at H y, have hg₁ := chart_mem_atlas H y, have hg₂ := mem_chart_source H y, let s := (c.symm ≫ₕ f₁).source ∩ (c.symm ≫ₕ f₁) ⁻¹' g.source, have open_s : is_open s, by apply (c.symm ≫ₕ f₁).continuous_to_fun.preimage_open_of_open; apply open_source, have : x ∈ s, { split, { simp only [trans_source, preimage_univ, inter_univ, homeomorph.to_local_homeomorph_source], rw trans_source at hx, exact hx.1 }, { exact hg₂ } }, refine ⟨s, open_s, this, _⟩, let F₁ := (c.symm ≫ₕ f₁ ≫ₕ g) ≫ₕ (g.symm ≫ₕ f₂ ≫ₕ c'), have A : F₁ ∈ G := G.trans (e.mem_groupoid c g hc hg₁) (e'.mem_groupoid g c' hg₁ hc'), let F₂ := (c.symm ≫ₕ f ≫ₕ c').restr s, have : F₁ ≈ F₂ := calc F₁ ≈ c.symm ≫ₕ f₁ ≫ₕ (g ≫ₕ g.symm) ≫ₕ f₂ ≫ₕ c' : by simp [F₁, trans_assoc] ... ≈ c.symm ≫ₕ f₁ ≫ₕ (of_set g.source g.open_source) ≫ₕ f₂ ≫ₕ c' : by simp [eq_on_source.trans', trans_self_symm g] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (of_set g.source g.open_source)) ≫ₕ (f₂ ≫ₕ c') : by simp [trans_assoc] ... ≈ ((c.symm ≫ₕ f₁).restr s) ≫ₕ (f₂ ≫ₕ c') : by simp [s, trans_of_set'] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (f₂ ≫ₕ c')).restr s : by simp [restr_trans] ... ≈ (c.symm ≫ₕ (f₁ ≫ₕ f₂) ≫ₕ c').restr s : by simp [eq_on_source.restr, trans_assoc] ... ≈ F₂ : by simp [F₂, feq], have : F₂ ∈ G := G.eq_on_source A (setoid.symm this), exact this end, ..homeomorph.trans e.to_homeomorph e'.to_homeomorph } end has_groupoid
879d817097d87be5d7059d9604212d098d413540
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/meta2.lean
1cd708e9ed61a808983cde966ead586a0df7dd21
[ "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
213
lean
import system.IO meta_definition foo : nat → nat | a := nat.cases_on a 1 (λ n, foo n + 2) vm_eval (foo 10) meta_definition loop : nat → IO unit | a := do put_str ">> ", put_nat a, put_str "\n", loop (a+1)
a71001d7e85773753a8a61045b344a340cde45a6
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/data/set/basic.lean
fcdb5ebc40b4a27694cb10a6708c749f052ece87
[ "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
2,706
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ namespace set universes u variable {α : Type u} lemma ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (take x, propext (h x)) lemma subset.refl (a : set α) : a ⊆ a := take x, assume H, H lemma subset.trans {a b c : set α} (subab : a ⊆ b) (subbc : b ⊆ c) : a ⊆ c := take x, assume ax, subbc (subab ax) lemma subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) -- an alterantive name lemma eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ lemma mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ lemma not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h lemma mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl lemma eq_empty_of_forall_not_mem {s : set α} (h : ∀ x, x ∉ s) : s = ∅ := ext (take x, iff.intro (assume xs, absurd xs (h x)) (assume xe, absurd xe (not_mem_empty _))) lemma ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := begin intro hs, rewrite hs at h, apply not_mem_empty _ h end lemma empty_subset (s : set α) : ∅ ⊆ s := take x, assume h, false.elim h lemma eq_empty_of_subset_empty {s : set α} (h : s ⊆ ∅) : s = ∅ := subset.antisymm h (empty_subset s) lemma union_comm (a b : set α) : a ∪ b = b ∪ a := ext (take x, or.comm) lemma union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (take x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ lemma union_self (a : set α) : a ∪ a = a := ext (take x, or_self _) lemma union_empty (a : set α) : a ∪ ∅ = a := ext (take x, or_false _) lemma empty_union (a : set α) : ∅ ∪ a = a := ext (take x, false_or _) lemma inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (take x, and.comm) lemma inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (take x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ lemma inter_self (a : set α) : a ∩ a = a := ext (take x, and_self _) lemma inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (take x, and_false _) lemma empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (take x, false_and _) end set
9663015440542275aa249bc210ce670f169376df
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/class_coe.lean
c453df10dd7f846bdff8b8776727c5719326d455
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
1,286
lean
import data.num namespace play constants int nat real : Type.{1} constant nat_add : nat → nat → nat constant int_add : int → int → int constant real_add : real → real → real inductive add_struct [class] (A : Type) := mk : (A → A → A) → add_struct A definition add {A : Type} {S : add_struct A} (a b : A) : A := add_struct.rec (λ m, m) S a b infixl `+` := add definition add_nat_struct [instance] : add_struct nat := add_struct.mk nat_add definition add_int_struct [instance] : add_struct int := add_struct.mk int_add definition add_real_struct [instance] : add_struct real := add_struct.mk real_add constants n m : nat constants i j : int constants x y : real constant num_to_nat : num → nat constant nat_to_int : nat → int constant int_to_real : int → real attribute num_to_nat [coercion] attribute nat_to_int [coercion] attribute int_to_real [coercion] set_option pp.implicit true set_option pp.coercions true check n + m check i + j check x + y check i + n check i + x check n + i check x + i check n + x check x + n check x + i + n namespace foo constant eq {A : Type} : A → A → Prop infixl `=` := eq definition id (A : Type) (a : A) := a notation A `=` B `:` C := @eq C A B check nat_to_int n + nat_to_int m = (n + m) : int end foo end play
00ceac5e6bc3d9254d398c56b0f6541bb2055267
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/algebra/group_power.lean
a6f3337dd995856e034a80c6143dc46f002e3222
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
27,314
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis The power operation on monoids and groups. We separate this from group, because it depends on nat, which in turn depends on other parts of algebra. We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation a^n is used for the first, but users can locally redefine it to gpow when needed. Note: power adopts the convention that 0^0=1. -/ import algebra.char_zero algebra.group algebra.ordered_field import data.int.basic data.list.basic universes u v variable {α : Type u} @[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one] @[simp] theorem inv_inv' [discrete_field α] {a:α} : a⁻¹⁻¹ = a := by rw [inv_eq_one_div, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_one] /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [monoid α] (a : α) : ℕ → α | 0 := 1 | (n+1) := a * monoid.pow n def add_monoid.smul [add_monoid α] (n : ℕ) (a : α) : α := @monoid.pow (multiplicative α) _ a n precedence `•`:70 local infix ` • ` := add_monoid.smul @[priority 5] instance monoid.has_pow [monoid α] : has_pow α ℕ := ⟨monoid.pow⟩ /- monoid -/ section monoid variables [monoid α] {β : Type u} [add_monoid β] @[simp] theorem pow_zero (a : α) : a^0 = 1 := rfl @[simp] theorem add_monoid.zero_smul (a : β) : 0 • a = 0 := rfl attribute [to_additive add_monoid.zero_smul] pow_zero theorem pow_succ (a : α) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_smul (a : β) (n : ℕ) : (n+1)•a = a + n•a := rfl attribute [to_additive succ_smul] pow_succ @[simp] theorem pow_one (a : α) : a^1 = a := mul_one _ @[simp] theorem add_monoid.one_smul (a : β) : 1•a = a := add_zero _ attribute [to_additive add_monoid.one_smul] pow_one theorem pow_mul_comm' (a : α) (n : ℕ) : a^n * a = a * a^n := by induction n with n ih; [rw [pow_zero, one_mul, mul_one], rw [pow_succ, mul_assoc, ih]] theorem smul_add_comm' : ∀ (a : β) (n : ℕ), n•a + a = a + n•a := @pow_mul_comm' (multiplicative β) _ theorem pow_succ' (a : α) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_smul' (a : β) (n : ℕ) : (n+1)•a = n•a + a := by rw [succ_smul, smul_add_comm'] attribute [to_additive succ_smul'] pow_succ' theorem pow_two (a : α) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_smul (a : β) : 2•a = a + a := show a+(a+0)=a+a, by rw add_zero attribute [to_additive two_smul] pow_two theorem pow_add (a : α) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [add_zero, pow_zero, mul_one], rw [pow_succ, ← pow_mul_comm', ← mul_assoc, ← ih, ← pow_succ']]; refl theorem add_monoid.add_smul : ∀ (a : β) (m n : ℕ), (m + n)•a = m•a + n•a := @pow_add (multiplicative β) _ attribute [to_additive add_monoid.add_smul] pow_add @[simp] theorem one_pow (n : ℕ) : (1 : α)^n = (1:α) := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : β) = (0:β) := by induction n with n ih; [refl, rw [succ_smul, ih, zero_add]] attribute [to_additive add_monoid.smul_zero] one_pow theorem pow_mul (a : α) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem add_monoid.mul_smul' : ∀ (a : β) (m n : ℕ), m * n • a = n•(m•a) := @pow_mul (multiplicative β) _ attribute [to_additive add_monoid.mul_smul'] pow_mul theorem pow_mul' (a : α) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [mul_comm, pow_mul] theorem add_monoid.mul_smul (a : β) (m n : ℕ) : m * n • a = m•(n•a) := by rw [mul_comm, add_monoid.mul_smul'] attribute [to_additive add_monoid.mul_smul] pow_mul' @[simp] theorem add_monoid.smul_one [has_one β] : ∀ n : ℕ, n • (1 : β) = n := nat.eq_cast _ (add_monoid.zero_smul _) (add_monoid.one_smul _) (add_monoid.add_smul _) theorem pow_bit0 (a : α) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_smul (a : β) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _ attribute [to_additive bit0_smul] pow_bit0 theorem pow_bit1 (a : α) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_smul : ∀ (a : β) (n : ℕ), bit1 n • a = n•a + n•a + a := @pow_bit1 (multiplicative β) _ attribute [to_additive bit1_smul] pow_bit1 theorem pow_mul_comm (a : α) (m n : ℕ) : a^m * a^n = a^n * a^m := by rw [←pow_add, ←pow_add, add_comm] theorem smul_add_comm : ∀ (a : β) (m n : ℕ), m•a + n•a = n•a + m•a := @pow_mul_comm (multiplicative β) _ attribute [to_additive smul_add_comm] pow_mul_comm @[simp] theorem list.prod_repeat (a : α) (n : ℕ) : (list.repeat a n).prod = a ^ n := by induction n with n ih; [refl, rw [list.repeat_succ, list.prod_cons, ih]]; refl @[simp] theorem list.sum_repeat : ∀ (a : β) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative β) _ attribute [to_additive list.sum_repeat] list.prod_repeat @[simp] lemma units.coe_pow (u : units α) (n : ℕ) : ((u ^ n : units α) : α) = u ^ n := by induction n; simp [*, pow_succ] end monoid namespace is_monoid_hom variables {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] theorem map_pow (a : α) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := is_monoid_hom.map_one f | (nat.succ n) := by rw [pow_succ, is_monoid_hom.map_mul f, map_pow n]; refl end is_monoid_hom namespace is_add_monoid_hom variables {β : Type*} [add_monoid α] [add_monoid β] (f : α → β) [is_add_monoid_hom f] theorem map_smul (a : α) : ∀(n : ℕ), f (n • a) = n • (f a) | 0 := is_add_monoid_hom.map_zero f | (nat.succ n) := by rw [succ_smul, is_add_monoid_hom.map_add f, map_smul n]; refl end is_add_monoid_hom attribute [to_additive is_add_monoid_hom.map_smul] is_monoid_hom.map_pow @[simp] theorem nat.pow_eq_pow (p q : ℕ) : @has_pow.pow _ _ monoid.has_pow p q = p ^ q := by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ, mul_comm, ih]] @[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n := by induction m with m ih; [rw [add_monoid.zero_smul, zero_mul], rw [succ_smul', ih, nat.succ_mul]] /- commutative monoid -/ section comm_monoid variables [comm_monoid α] {β : Type*} [add_comm_monoid β] theorem mul_pow (a b : α) (n : ℕ) : (a * b)^n = a^n * b^n := by induction n with n ih; [exact (mul_one _).symm, simp only [pow_succ, ih, mul_assoc, mul_left_comm]] theorem add_monoid.smul_add : ∀ (a b : β) (n : ℕ), n•(a + b) = n•a + n•b := @mul_pow (multiplicative β) _ attribute [to_additive add_monoid.add_smul] mul_pow instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : α → α) := by refine_struct {..}; simp [mul_pow, one_pow] instance add_monoid.smul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (add_monoid.smul n : β → β) := by refine_struct {..}; simp [add_monoid.smul_zero, add_monoid.smul_add] attribute [to_additive add_monoid.smul.is_add_monoid_hom] pow.is_monoid_hom end comm_monoid section group variables [group α] {β : Type*} [add_group β] section nat @[simp] theorem inv_pow (a : α) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem add_monoid.neg_smul : ∀ (a : β) (n : ℕ), n•(-a) = -(n•a) := @inv_pow (multiplicative β) _ attribute [to_additive add_monoid.neg_smul] inv_pow theorem pow_sub (a : α) {m n : ℕ} (h : m ≥ n) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem add_monoid.smul_sub : ∀ (a : β) {m n : ℕ}, m ≥ n → (m - n)•a = m•a - n•a := @pow_sub (multiplicative β) _ attribute [to_additive add_monoid.smul_sub] inv_pow theorem pow_inv_comm (a : α) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _) theorem add_monoid.smul_neg_comm : ∀ (a : β) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) := @pow_inv_comm (multiplicative β) _ attribute [to_additive add_monoid.smul_neg_comm] pow_inv_comm end nat open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : α) : ℤ → α | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ def gsmul (n : ℤ) (a : β) : β := @gpow (multiplicative β) _ a n @[priority 10] instance group.has_pow : has_pow α ℤ := ⟨gpow⟩ local infix ` • `:70 := gsmul local infix ` •ℕ `:70 := add_monoid.smul @[simp] theorem gpow_coe_nat (a : α) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : β) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl attribute [to_additive gsmul_coe_nat] gpow_coe_nat @[simp] theorem gpow_of_nat (a : α) (n : ℕ) : a ^ of_nat n = a ^ n := rfl @[simp] theorem gsmul_of_nat (a : β) (n : ℕ) : of_nat n • a = n •ℕ a := rfl attribute [to_additive gsmul_of_nat] gpow_of_nat @[simp] theorem gpow_neg_succ (a : α) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ (a : β) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl attribute [to_additive gsmul_neg_succ] gpow_neg_succ local attribute [ematch] le_of_lt open nat @[simp] theorem gpow_zero (a : α) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : β) : (0:ℤ) • a = 0 := rfl attribute [to_additive zero_gsmul] gpow_zero @[simp] theorem gpow_one (a : α) : a ^ (1:ℤ) = a := mul_one _ @[simp] theorem one_gsmul (a : β) : (1:ℤ) • a = a := add_zero _ attribute [to_additive one_gsmul] gpow_one @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : α) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:α), by rw [_root_.one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n • (0 : β) = 0 := @one_gpow (multiplicative β) _ attribute [to_additive gsmul_zero] one_gpow @[simp] theorem gpow_neg (a : α) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm @[simp] theorem neg_gsmul : ∀ (a : β) (n : ℤ), -n • a = -(n • a) := @gpow_neg (multiplicative β) _ attribute [to_additive neg_gsmul] gpow_neg theorem gpow_neg_one (x : α) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : β) : (-1:ℤ) • x = -x := congr_arg has_neg.neg $ add_monoid.one_smul x attribute [to_additive neg_one_gsmul] gpow_neg_one theorem inv_gpow (a : α) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) private lemma gpow_add_aux (a : α) (m n : nat) : a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] := or.elim (nat.lt_or_ge m (nat.succ n)) (assume h1 : m < succ n, have h2 : m ≤ n, from le_of_lt_succ h1, suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n], by rwa [of_nat_add_neg_succ_of_nat_of_lt h1], show (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], by rw [← succ_sub h2, pow_sub _ (le_of_lt h1), mul_inv_rev, inv_inv]; refl) (assume : m ≥ succ n, suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]), by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption, suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this, by rw pow_sub; assumption) theorem gpow_add (a : α) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j | (of_nat m) (of_nat n) := pow_add _ _ _ | (of_nat m) -[1+n] := gpow_add_aux _ _ _ | -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux, gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm] | -[1+m] -[1+n] := suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this, by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev] theorem add_gsmul : ∀ (a : β) (i j : ℤ), (i + j) • a = i • a + j • a := @gpow_add (multiplicative β) _ theorem gpow_add_one (a : α) (i : ℤ) : a ^ (i + 1) = a ^ i * a := by rw [gpow_add, gpow_one] theorem add_one_gsmul : ∀ (a : β) (i : ℤ), (i + 1) • a = i • a + a := @gpow_add_one (multiplicative β) _ attribute [to_additive add_one_gsmul] gpow_add_one theorem gpow_one_add (a : α) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : β) (i : ℤ), (1 + i) • a = a + i • a := @gpow_one_add (multiplicative β) _ attribute [to_additive one_add_gsmul] gpow_one_add theorem gpow_mul_comm (a : α) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : β) (i j), i • a + j • a = j • a + i • a := @gpow_mul_comm (multiplicative β) _ attribute [to_additive gsmul_add_comm] gpow_mul_comm theorem gpow_mul (a : α) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n | (m : ℕ) (n : ℕ) := pow_mul _ _ _ | (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $ show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl | -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $ show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow]; refl | -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $ show _ = (_⁻¹^_)⁻¹, by rw [inv_pow, inv_inv] theorem gsmul_mul' : ∀ (a : β) (m n : ℤ), m * n • a = n • (m • a) := @gpow_mul (multiplicative β) _ attribute [to_additive gsmul_mul'] gpow_mul theorem gpow_mul' (a : α) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : β) (m n : ℤ) : m * n • a = m • (n • a) := by rw [mul_comm, gsmul_mul'] attribute [to_additive gsmul_mul] gpow_mul' theorem gpow_bit0 (a : α) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : β) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _ attribute [to_additive bit0_gsmul] gpow_bit0 theorem gpow_bit1 (a : α) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add]; simp [gpow_bit0] theorem bit1_gsmul : ∀ (a : β) (n : ℤ), bit1 n • a = n • a + n • a + a := @gpow_bit1 (multiplicative β) _ attribute [to_additive bit1_gsmul] gpow_bit1 theorem gsmul_neg (a : β) (n : ℤ) : gsmul n (- a) = - gsmul n a := begin induction n using int.induction_on with z ih z ih, { simp }, { rw [add_comm] {occs := occurrences.pos [1]}, simp [add_gsmul, ih, -add_comm] }, { rw [sub_eq_add_neg, add_comm] {occs := occurrences.pos [1]}, simp [ih, add_gsmul, neg_gsmul, -add_comm] } end attribute [to_additive gsmul_neg] gpow_neg end group namespace is_group_hom variables {β : Type v} [group α] [group β] (f : α → β) [is_group_hom f] theorem pow (a : α) (n : ℕ) : f (a ^ n) = f a ^ n := is_monoid_hom.map_pow f a n theorem gpow (a : α) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact is_group_hom.pow f _ _, exact (is_group_hom.inv f _).trans (congr_arg _ $ is_group_hom.pow f _ _)] end is_group_hom namespace is_add_group_hom variables {β : Type v} [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] theorem smul (a : α) (n : ℕ) : f (n • a) = n • f a := is_add_monoid_hom.map_smul f a n theorem gsmul (a : α) (n : ℤ) : f (gsmul n a) = gsmul n (f a) := begin induction n using int.induction_on with z ih z ih, { simp [is_add_group_hom.zero f] }, { simp [is_add_group_hom.add f, add_gsmul, ih] }, { simp [is_add_group_hom.add f, is_add_group_hom.neg f, add_gsmul, ih] } end end is_add_group_hom local infix ` •ℤ `:70 := gsmul section comm_monoid variables [comm_group α] {β : Type*} [add_comm_group β] theorem mul_gpow (a b : α) : ∀ n:ℤ, (a * b)^n = a^n * b^n | (n : ℕ) := mul_pow a b n | -[1+ n] := show _⁻¹=_⁻¹*_⁻¹, by rw [mul_pow, mul_inv_rev, mul_comm] theorem gsmul_add : ∀ (a b : β) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative β) _ attribute [to_additive gsmul_add] mul_gpow theorem gsmul_sub : ∀ (a b : β) (n : ℤ), gsmul n (a - b) = gsmul n a - gsmul n b := by simp [gsmul_add, gsmul_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : α → α) := ⟨λ _ _, mul_gpow _ _ n⟩ instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : β → β) := ⟨λ _ _, gsmul_add _ _ n⟩ attribute [to_additive gsmul.is_add_group_hom] gpow.is_group_hom end comm_monoid section group @[instance] theorem is_add_group_hom_gsmul {α β} [add_group α] [add_comm_group β] (f : α → β) [is_add_group_hom f] (z : ℤ) : is_add_group_hom (λa, gsmul z (f a)) := ⟨assume a b, by rw [is_add_group_hom.add f, gsmul_add]⟩ end group @[simp] lemma with_bot.coe_smul [add_monoid α] (a : α) (n : ℕ) : ((add_monoid.smul n a : α) : with_bot α) = add_monoid.smul n a := by induction n; simp [*, succ_smul]; refl theorem add_monoid.smul_eq_mul' [semiring α] (a : α) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [add_monoid.zero_smul, nat.cast_zero, mul_zero], rw [succ_smul', ih, nat.cast_succ, mul_add, mul_one]] theorem add_monoid.smul_eq_mul [semiring α] (n : ℕ) (a : α) : n • a = n * a := by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm] theorem add_monoid.mul_smul_left [semiring α] (a b : α) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc] theorem add_monoid.mul_smul_assoc [semiring α] (a b : α) (n : ℕ) : n • (a * b) = n • a * b := by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc] lemma zero_pow [semiring α] : ∀ {n : ℕ}, 0 < n → (0 : α) ^ n = 0 | (n+1) _ := zero_mul _ @[simp] theorem nat.cast_pow [semiring α] (n m : ℕ) : (↑(n ^ m) : α) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]] @[simp] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]] theorem is_semiring_hom.map_pow {β} [semiring α] [semiring β] (f : α → β) [is_semiring_hom f] (x : α) (n : ℕ) : f (x ^ n) = f x ^ n := by induction n with n ih; [exact is_semiring_hom.map_one f, rw [pow_succ, pow_succ, is_semiring_hom.map_mul f, ih]] theorem neg_one_pow_eq_or {R} [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [comm_semiring α] (a : α) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩ theorem gsmul_eq_mul [ring α] (a : α) : ∀ n, n •ℤ a = n * a | (n : ℕ) := add_monoid.smul_eq_mul _ _ | -[1+ n] := show -(_•_)=-_*_, by rw [neg_mul_eq_neg_mul_symm, add_monoid.smul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring α] (a : α) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, int.mul_cast_comm] theorem mul_gsmul_left [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] theorem int.cast_pow [ring α] (n : ℤ) (m : ℕ) : (↑(n ^ m) : α) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring α] {n : ℕ} : (-1 : α) ^ n = -1 ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] theorem pow_eq_zero [domain α] {x : α} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end theorem pow_ne_zero [domain α] {a : α} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h @[simp] theorem one_div_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : (1 / a) ^ n = 1 / a ^ n := by induction n with n ih; [exact (div_one _).symm, rw [pow_succ', ih, division_ring.one_div_mul_one_div (pow_ne_zero _ ha) ha]]; refl @[simp] theorem division_ring.inv_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ := by simpa only [inv_eq_one_div] using one_div_pow ha n @[simp] theorem div_pow [field α] (a : α) {b : α} (hb : b ≠ 0) (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := by rw [div_eq_mul_one_div, mul_pow, one_div_pow hb, ← div_eq_mul_one_div] theorem add_monoid.smul_nonneg [ordered_comm_monoid α] {a : α} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a | 0 := le_refl _ | (n+1) := add_nonneg' H (add_monoid.smul_nonneg n) lemma pow_abs [decidable_linear_ordered_comm_ring α] (a : α) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma inv_pow' [discrete_field α] (a : α) (n : ℕ) : (a ^ n)⁻¹ = a⁻¹ ^ n := by induction n; simp [*, pow_succ, mul_inv', mul_comm] lemma pow_inv [division_ring α] (a : α) : ∀ n : ℕ, a ≠ 0 → (a^n)⁻¹ = (a⁻¹)^n | 0 ha := inv_one | (n+1) ha := by rw [pow_succ, pow_succ', mul_inv_eq (pow_ne_zero _ ha) ha, pow_inv _ ha] namespace add_monoid variable [ordered_comm_monoid α] theorem smul_le_smul {a : α} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a := let ⟨k, hk⟩ := nat.le.dest h in calc n • a = n • a + 0 : (add_zero _).symm ... ≤ n • a + k • a : add_le_add_left' (smul_nonneg ha _) ... = m • a : by rw [← hk, add_smul] lemma smul_le_smul_of_le_right {a b : α} (hab : a ≤ b) : ∀ i : ℕ, i • a ≤ i • b | 0 := by simp | (k+1) := add_le_add' hab (smul_le_smul_of_le_right _) end add_monoid section linear_ordered_semiring variable [linear_ordered_semiring α] theorem pow_pos {a : α} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := zero_lt_one | (n+1) := mul_pos H (pow_pos _) theorem pow_nonneg {a : α} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_lt_pow_of_lt_left {x y : α} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem pow_right_inj {x y : α} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := begin rcases lt_trichotomy x y with hxy | rfl | hyx, { exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) }, { refl }, { exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) }, end theorem one_le_pow_of_one_le {a : α} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) theorem pow_ge_one_add_mul {a : α} (H : a ≥ 0) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := begin rw [pow_succ', succ_smul'], refine le_trans _ (mul_le_mul_of_nonneg_right (pow_ge_one_add_mul n) (add_nonneg zero_le_one H)), rw [mul_add, mul_one, ← add_assoc, add_le_add_iff_left], simpa only [one_mul] using mul_le_mul_of_nonneg_right ((le_add_iff_nonneg_right 1).2 (add_monoid.smul_nonneg H n)) H end theorem pow_le_pow {a : α} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_lt_pow {a : α} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := begin have h' : 1 ≤ a := le_of_lt h, have h'' : 0 < a := lt_trans zero_lt_one h, cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)], exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'') end lemma pow_le_pow_of_le_left {a b : α} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) lemma lt_of_pow_lt_pow {a b : α} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h private lemma pow_lt_pow_of_lt_one_aux {a : α} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp, rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : α} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : α} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : α} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : α} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : α) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring α] (a : α) : 0 ≤ a ^ 2 := by rw pow_two; exact mul_self_nonneg _ theorem pow_ge_one_add_sub_mul [linear_ordered_ring α] {a : α} (H : a ≥ 1) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n := by simpa only [add_sub_cancel'_right] using pow_ge_one_add_mul (sub_nonneg.2 H) n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] end int @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma div_sq_cancel {α} [field α] {a : α} (ha : a ≠ 0) (b : α) : a^2 * b / a = a * b := by rw [pow_two, mul_assoc, mul_div_cancel_left _ ha]
ec433215ce33bb58cf6d3e4a482aa4c2aaf30e80
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/algebra/monoid.lean
33a6e1f2d8f3ab90e7469f3657667ec71977eb79
[ "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
8,338
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.continuous_on import group_theory.submonoid.basic import algebra.group.prod import algebra.pointwise /-! # Theory of topological monoids In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many applications the underlying type is a monoid (multiplicative or additive), we do not require this in the definitions. -/ open classical set filter topological_space open_locale classical topological_space big_operators variables {α β M N : Type*} /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `α`, for example, is obtained by requiring both the instances `add_monoid α` and `has_continuous_add α`. -/ class has_continuous_add (M : Type*) [topological_space M] [has_add M] : Prop := (continuous_add : continuous (λ p : M × M, p.1 + p.2)) /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `α`, for example, is obtained by requiring both the instances `monoid α` and `has_continuous_mul α`. -/ @[to_additive] class has_continuous_mul (M : Type*) [topological_space M] [has_mul M] : Prop := (continuous_mul : continuous (λ p : M × M, p.1 * p.2)) section has_continuous_mul variables [topological_space M] [has_mul M] [has_continuous_mul M] @[to_additive] lemma continuous_mul : continuous (λp:M×M, p.1 * p.2) := has_continuous_mul.continuous_mul @[to_additive, continuity] lemma continuous.mul [topological_space α] {f : α → M} {g : α → M} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg) attribute [continuity] continuous.add @[to_additive] lemma continuous_mul_left (a : M) : continuous (λ b:M, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : M) : continuous (λ b:M, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul [topological_space α] {f : α → M} {g : α → M} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) @[to_additive] lemma tendsto_mul {a b : M} : tendsto (λp:M×M, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b) @[to_additive] lemma filter.tendsto.mul {f : α → M} {g : α → M} {x : filter α} {a b : M} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto_mul.comp (hf.prod_mk_nhds hg) @[to_additive] lemma tendsto.const_mul (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), b * f k) l (𝓝 (b * c)) := tendsto_const_nhds.mul h @[to_additive] lemma tendsto.mul_const (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), f k * b) l (𝓝 (c * b)) := h.mul tendsto_const_nhds @[to_additive] lemma continuous_at.mul [topological_space α] {f : α → M} {g : α → M} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x * g x) x := hf.mul hg @[to_additive] lemma continuous_within_at.mul [topological_space α] {f : α → M} {g : α → M} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, f x * g x) s x := hf.mul hg @[to_additive] instance [topological_space N] [has_mul N] [has_continuous_mul N] : has_continuous_mul (M × N) := ⟨((continuous_fst.comp continuous_fst).mul (continuous_fst.comp continuous_snd)).prod_mk ((continuous_snd.comp continuous_fst).mul (continuous_snd.comp continuous_snd))⟩ end has_continuous_mul section has_continuous_mul variables [topological_space M] [monoid M] [has_continuous_mul M] @[to_additive exists_open_nhds_zero_half] lemma exists_open_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ ∀ (v ∈ V) (w ∈ V), v * w ∈ s := have ((λa:M×M, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : M × M), from tendsto_mul (by simpa only [one_mul] using hs), by simpa only [prod_subset_iff] using exists_nhds_square this @[to_additive exists_nhds_zero_half] lemma exists_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ (v ∈ V) (w ∈ V), v * w ∈ s := let ⟨V, Vo, V1, hV⟩ := exists_open_nhds_one_split hs in ⟨V, mem_nhds_sets Vo V1, hV⟩ @[to_additive exists_nhds_zero_quarter] lemma exists_nhds_one_split4 {u : set M} (hu : u ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_one_split hu with ⟨W, W1, h⟩, rcases exists_nhds_one_split W1 with ⟨V, V1, h'⟩, use [V, V1], intros v w s t v_in w_in s_in t_in, simpa only [mul_assoc] using h _ (h' v v_in w w_in) _ (h' s s_in t t_in) end /-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma exists_open_nhds_one_mul_subset {U : set M} (hU : U ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ V * V ⊆ U := begin rcases exists_open_nhds_one_split hU with ⟨V, Vo, V1, hV⟩, use [V, Vo, V1], rintros _ ⟨x, y, hx, hy, rfl⟩, exact hV _ hx _ hy end @[to_additive] lemma tendsto_list_prod {f : β → α → M} {x : filter α} {a : β → M} : ∀l:list β, (∀c∈l, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp only [list.map_cons, list.prod_cons], exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod [topological_space α] {f : β → α → M} (l : list β) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x -- @[to_additive continuous_smul] @[continuity] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : M, a ^ n) | 0 := by simpa using continuous_const | (k+1) := show continuous (λ (a : M), a * a ^ k), from continuous_id.mul (continuous_pow _) @[continuity] lemma continuous.pow {f : α → M} [topological_space α] (h : continuous f) (n : ℕ) : continuous (λ b, (f b) ^ n) := continuous.comp (continuous_pow n) h end has_continuous_mul section variables [topological_space M] [comm_monoid M] @[to_additive] lemma submonoid.mem_nhds_one (S : submonoid M) (oS : is_open (S : set M)) : (S : set M) ∈ 𝓝 (1 : M) := mem_nhds_sets oS S.one_mem variable [has_continuous_mul M] @[to_additive] lemma tendsto_multiset_prod {f : β → α → M} {x : filter α} {a : β → M} (s : multiset β) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : β → α → M} {x : filter α} {a : β → M} (s : finset β) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := tendsto_multiset_prod _ @[to_additive, continuity] lemma continuous_multiset_prod [topological_space α] {f : β → α → M} (s : multiset β) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } attribute [continuity] continuous_multiset_sum @[to_additive, continuity] lemma continuous_finset_prod [topological_space α] {f : β → α → M} (s : finset β) : (∀c∈s, continuous (f c)) → continuous (λa, ∏ c in s, f c a) := continuous_multiset_prod _ attribute [continuity] continuous_finset_sum end
99d759cbb1ddff40ed5af255f6ff92627de99bd7
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/function/lp_order.lean
1d1980e01364656ee9b26810656efd19608983be
[ "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
1,910
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.function.lp_space import analysis.normed_space.lattice_ordered_group /-! # Order related properties of Lp spaces ### Results - `Lp E p μ` is an `ordered_add_comm_group` when `E` is a `normed_lattice_add_comm_group`. ### TODO - move definitions of `Lp.pos_part` and `Lp.neg_part` to this file, and define them as `has_pos_part.pos` and `has_pos_part.neg` given by the lattice structure. - show that if `E` is a `normed_lattice_add_comm_group` then so is `Lp E p μ` for `1 ≤ p`. In particular, this shows `order_closed_topology` for `Lp`. -/ open topological_space measure_theory lattice_ordered_comm_group open_locale ennreal variables {α E : Type*} {m : measurable_space α} {μ : measure α} {p : ℝ≥0∞} namespace measure_theory namespace Lp section order variables [normed_lattice_add_comm_group E] lemma coe_fn_le (f g : Lp E p μ) : f ≤ᵐ[μ] g ↔ f ≤ g := by rw [← subtype.coe_le_coe, ← ae_eq_fun.coe_fn_le, ← coe_fn_coe_base, ← coe_fn_coe_base] lemma coe_fn_nonneg (f : Lp E p μ) : 0 ≤ᵐ[μ] f ↔ 0 ≤ f := begin rw ← coe_fn_le, have h0 := Lp.coe_fn_zero E p μ, split; intro h; filter_upwards [h, h0] with _ _ h2, { rwa h2, }, { rwa ← h2, }, end instance : covariant_class (Lp E p μ) (Lp E p μ) (+) (≤) := begin refine ⟨λ f g₁ g₂ hg₁₂, _⟩, rw ← coe_fn_le at hg₁₂ ⊢, filter_upwards [coe_fn_add f g₁, coe_fn_add f g₂, hg₁₂] with _ h1 h2 h3, rw [h1, h2, pi.add_apply, pi.add_apply], exact add_le_add le_rfl h3, end instance : ordered_add_comm_group (Lp E p μ) := { add_le_add_left := λ f g hfg f', add_le_add_left hfg f', ..subtype.partial_order _, ..add_subgroup.to_add_comm_group _} end order end Lp end measure_theory
23f10991b529ced9fea5efc8df4da9b370d8ee3f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/310.lean
507ce3383d1a5d6ef2ec74aa3da39725c79dd85d
[ "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
168
lean
variable (xs : List Nat) theorem foo1 : xs = xs := by induction xs <;> rfl theorem foo2 : xs = xs := by cases xs with | nil => rfl | cons x xs => rfl
cc1f7aed6de614ade38308ee02868b75d03dcd52
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/sequent/ltl.lean
77510495808fcd638ae3045bf36c6fe13b8f95b6
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,997
lean
import .core galois.temporal.temporal order.complete_lattice universes u open temporal lattice namespace sequent instance subset_complete_lattice {A : Type u} : complete_lattice (subset A) := begin apply lattice.complete_lattice_fun, end instance subset_cha {A : Type u} : cha (subset A) := begin constructor, tactic.rotate 2, apply_instance, constructor, intros P Q, exact (λ x, P x → Q x), intros, intros x Γx Px, apply a, split; assumption, intros, intros x ΓPx, induction ΓPx with Γx Px, apply a; assumption end instance tProp_cha {T : Type u} : cha (tProp T) := sequent.subset_cha lemma tautology {T : Type u} {A : tProp T} (H : rlist.nil ⊢ A) : ⊩ A := begin intros tr, apply H, constructor, end lemma tautology_iff {T : Type u} {A : tProp T} : (rlist.nil ⊢ A) ↔ (⊩ A) := begin split; intros H, intros tr, apply H, constructor, intros x Hx, apply H, end inductive formula (T : Type) (vTy : Type) : Type | var {} : vTy → formula | top {} : formula | bot {} : formula | and {} : formula → formula → formula | or {} : formula → formula → formula | always {} : formula → formula | eventually {} : formula → formula namespace formula def interp {T : Type} {vTy : Type} (ctxt : vTy → tProp T) : formula T vTy → tProp T | (var x) := ctxt x | top := ⊤ | bot := ⊥ | (and P Q) := interp P ⊓ interp Q | (or P Q) := interp P ⊔ interp Q | (always P) := □ (interp P) | (eventually P) := ◇ (interp P) end formula instance formula_decidable_eq {T : Type} {vTy : Type} [decidable_eq vTy] : decidable_eq (formula T vTy) := by tactic.mk_dec_eq_instance def formula_entails {T : Type} {vTy : Type} (Γ : rlist (formula T vTy)) (A : formula T vTy) := ∀ ctxt, Γ.map (formula.interp ctxt) ⊢ A.interp ctxt def interp_impl {T : Type} {vTy : Type} (Γ : rlist (formula T vTy)) (A : formula T vTy) (ctxt : vTy → tProp T) : formula_entails Γ A → Γ.map (formula.interp ctxt) ⊢ A.interp ctxt := begin intros H, apply H, end def formula_entails_auto {T : Type} {vTy : Type} [decidable_eq vTy] (Γ : rlist (formula T vTy)) : ∀ A : formula T vTy, option (plift (formula_entails Γ A)) | formula.top := some (plift.up begin dsimp [formula_entails, formula.interp], intros ctxt, apply @entails_top _ sequent.tProp_cha, end) | formula.bot := none | (formula.and P Q) := do plift.up HP ← formula_entails_auto P, plift.up HQ ← formula_entails_auto Q, some (plift.up begin unfold formula_entails, intros, dsimp [formula.interp], apply @split _ sequent.tProp_cha, apply HP, apply HQ, end) | (formula.or P Q) := (do plift.up HP ← formula_entails_auto P, some (plift.up (begin intros x, dsimp [formula.interp], apply @left _ sequent.tProp_cha, apply HP end))) <|> (do plift.up HQ ← formula_entails_auto Q, some (plift.up (begin intros x, dsimp [formula.interp], apply @right _ sequent.tProp_cha, apply HQ end))) | x := if H : x ∈ Γ then some (plift.up begin intros ctxt, apply @assumption _ sequent.tProp_cha, apply rlist.map_mem, assumption end) else none meta def intern_var (xs : list expr) (e : expr) : list expr × ℕ := (if e ∈ xs then xs else xs ++ [e], xs.index_of e) meta def reify_helper : list expr → expr → tactic (expr ff × list expr) | xs `(@lattice.has_top.top %%TT %%Tc) := pure (``(formula.top), xs) | xs `(@lattice.has_bot.bot %%TT %%Tc) := pure (``(formula.bot), xs) | xs `(always %%P) := do (P', xs') ← reify_helper xs P, pure (``(formula.always %%P'), xs') | xs `(eventually %%P) := do (P', xs') ← reify_helper xs P, pure (``(formula.eventually %%P'), xs') | xs `(%%P ⊓ %%Q) := do (P', xs') ← reify_helper xs P, (Q', xs'') ← reify_helper xs' Q, pure (``(formula.and %%P' %%Q'), xs'') | xs `(%%P ⊔ %%Q) := do (P', xs') ← reify_helper xs P, (Q', xs'') ← reify_helper xs' Q, pure (``(formula.or %%P' %%Q'), xs'') | xs P := let (xs', n) := intern_var xs P in pure (``(formula.var %%(n.reflect)), xs') meta def reify_all_helper (e : expr) : list expr → list expr → tactic (list (expr ff) × expr ff × list expr) | ctxt [] := do (e', ctxt') ← reify_helper ctxt e, pure ([], e', ctxt') | ctxt (x :: xs) := do (x', ctxt') ← reify_helper ctxt x, (xs', e', ctxt'') ← reify_all_helper ctxt' xs, pure (x' :: xs', e', ctxt'') meta def reify (es : list expr) (e : expr) : tactic (list (expr ff) × expr ff × list expr) := reify_all_helper e [] es end sequent namespace tactic.interactive namespace sequent open tactic lean lean.parser open interactive interactive.types expr meta def get_rlist : expr → tactic (list expr) | `(rlist.snoc %%xs %%x) := do xs' ← get_rlist xs, pure (x :: xs') | `(rlist.nil) := pure [] | _ := tactic.fail "uh-oh" meta def make_list : list expr → expr ff | [] := ``(list.nil) | (x :: xs) := ``(list.cons %%x %%(make_list xs)) meta def make_rlist : list (expr ff) → expr ff | [] := ``(rlist.nil) | (x :: xs) := ``(rlist.snoc %%(make_rlist xs) %%x) def list.nth_def {α : Type u} (xs : list α) (default : α) (n : ℕ) : α := match xs.nth n with | (some x) := x | none := default end meta def on_sequent_goal {A} (f : expr → expr → tactic A) : tactic A := do tgt ← target, tgt' ← instantiate_mvars tgt, match tgt' with | `(%%Γ ⊢ %%P) := f Γ P | _ := tactic.fail "not a logical entailment" end meta def reify_goal : tactic unit := on_sequent_goal $ λ xs P, do ty ← infer_type P >>= whnf, xs' ← get_rlist xs, (xs', P', ctxt) ← sequent.reify xs' P, let ctxt' := make_list ctxt, let xs'' := make_rlist xs', xs''' ← i_to_expr xs'', P'' ← i_to_expr P', ctxtf ← i_to_expr ``(list.nth_def %%ctxt' ⊥), e ← i_to_expr ``(sequent.interp_impl %%xs''' %%P'' %%ctxtf), tactic.apply e meta def entails_tactic (e : parse texpr) : tactic unit := do tgt ← target, tgt' ← instantiate_mvars tgt, match tgt' with | `(sequent.formula_entails %%Γ %%A) := do e' ← i_to_expr ``(%%e %%Γ %%A) >>= whnf, match e' with | `(some (plift.up %%x)) := tactic.apply x | _ := tactic.fail "Didn't get some" end | _ := tactic.fail "not a formula entailment" end meta def intros := repeat (apply ``(sequent.intro _)) meta def revert := apply ``(sequent.revert _) meta def left := apply ``(sequent.left _) meta def right := apply ``(sequent.right _) meta def split := apply ``(sequent.split _ _) meta def prove_mem := apply ``(rlist.mem.here) <|> (do apply ``(rlist.mem.there), prove_mem) meta def assumption := do apply ``(sequent.assumption _), prove_mem meta def apply (e : parse texpr) := do on_sequent_goal $ λ Γ P, do tactic.interactive.apply ``(sequent.apply_lemma %%Γ %%P %%e), repeat tactic.constructor meta def assert (e : parse texpr) := do on_sequent_goal $ λ Γ P, do tactic.interactive.apply ``(sequent.cut %%Γ %%P %%e) end sequent end tactic.interactive
1768822ea97bf8bcb5ff9976e2d23de19e2b2996
e4e5bde6f14c01a8a34267a9d7bb45e137735696
/src/exercises/theorem_proving_in_lean/exercises.lean
d4acc29b629bf5dd33a677736c97574e985422a0
[]
no_license
jamesdabbs/proofs
fb5dab6f3c4f3f5f952fca033ec649888ae787c6
00baf355b08e7aec00de34208e1b2cb4a8d7b701
refs/heads/master
1,645,645,735,797
1,569,559,636,000
1,569,559,636,000
211,238,170
0
0
null
null
null
null
UTF-8
Lean
false
false
20,021
lean
-- Chapter 2 namespace ch2 /- 1. Define the function Do_Twice -/ def Do_Twice (f: ℕ → ℕ) (n : ℕ) : ℕ := f (f n) #check Do_Twice #reduce Do_Twice (λ x, x * 3) 2 /- 2. Define the functions curry and uncurry -/ def curry (f : ℕ × ℕ → ℕ) (a b : ℕ) : ℕ := f (a, b) def uncurry (f : ℕ → ℕ → ℕ) (c : ℕ × ℕ) : ℕ := f c.1 c.2 /- 3. Above, we used the example vec α n for vectors of elements of type α of length n. Declare a constant vec_add that could represent a function that adds two vectors of natural numbers of the same length, and a constant vec_reverse that can represent a function that reverses its argument. Use implicit arguments for parameters that can be inferred. Declare some variables and check some expressions involving the constants that you have declared. -/ universe u variables {α : Type u} {n m o : ℕ} constant vector : Type u → ℕ -> Type u namespace vector constant empty : vector α 0 constant cons : α → vector α n → vector α (n + 1) #check empty #check cons 1 empty #check (cons 5 (cons 10 (cons 3 (empty)))) constant add : vector α n → vector α m -> vector α (n + m) #check add (cons 1 (cons 2 (empty))) (cons 3 (empty)) constant reverse : vector α n → vector α n #check reverse (cons 1 (cons 2 (empty))) end vector /- 4. Similarly, declare a constant matrix so that matrix α m n could represent the type of m by n matrices. Declare some constants to represent functions on this type, such as matrix addition and multiplication, and (using vec) multiplication of a matrix by a vector. Once again, declare some variables and check some expressions involving the constants that you have declared. -/ constant matrix : Type u → ℕ → ℕ → Type u namespace matrix end matrix constant add : matrix α n m → matrix α n m → matrix α n m constant mult : matrix α n m → matrix α m o → matrix α n o end ch2 -- Chapter 3 namespace ch3 /- 1. Prove as many identities from the previous section as you can, replacing the “sorry” placeholders with actual proofs. -/ universe u variables p q r s : Prop def id {α : Type u} (a : α) : α := a -- Explicit (de)structuring example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := iff.intro (assume h : (p ∧ q) ∧ r, show p ∧ (q ∧ r), from and.intro (and.left (and.left h)) (and.intro (and.right (and.left h)) (and.right h))) (assume h : p ∧ (q ∧ r), show (p ∧ q) ∧ r, from and.intro (and.intro (and.left h) (and.left (and.right h))) (and.right (and.right h))) #check @or.inr -- Alternate form example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := iff.intro (λ h, ⟨h.left.left, h.left.right, h.right⟩) (λ h, ⟨⟨h.left, h.right.left⟩, h.right.right⟩) #check p ∨ (q ∨ r) example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := iff.intro (assume h : (p ∨ q) ∨ r, h.elim (λ i, i.elim or.inl (or.inr ∘ or.inl)) (or.inr ∘ or.inr)) (assume h : p ∨ (q ∨ r), h.elim (or.inl ∘ or.inl) (λ i, i.elim (or.inl ∘ or.inr) or.inr)) example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := iff.intro (λ h, h.elim (λ i, i.elim or.inl (or.inr ∘ or.inl)) (or.inr ∘ or.inr)) (λ h, h.elim (or.inl ∘ or.inl) (λ i, i.elim (or.inl ∘ or.inr) or.inr)) example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := iff.intro (assume h : p ∧ (q ∨ r), have hp : p, from and.left h, have hqr : q ∨ r, from and.right h, show (p ∧ q) ∨ (p ∧ r), from hqr.elim (assume hq : q, or.inl ⟨hp, hq⟩) (assume hr : r, or.inr ⟨hp, hr⟩)) (assume h : (p ∧ q) ∨ (p ∧ r), show p ∧ (q ∨ r), from h.elim (assume i : p ∧ q, ⟨and.left i, or.inl (and.right i)⟩) (assume i : p ∧ r, ⟨and.left i, or.inr (and.right i)⟩)) example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := iff.intro (assume h : p ∨ (q ∧ r), h.elim (λ p, ⟨or.inl p, or.inl p⟩) (λ qr, ⟨or.inr (and.left qr), or.inr (and.right qr)⟩)) (assume h : (p ∨ q) ∧ (p ∨ r), h.left.elim or.inl (λ q', h.right.elim or.inl (λ r', or.inr ⟨q', r'⟩))) example: (p → (q → r)) ↔ (p ∧ q → r) := iff.intro (assume f, λ p, f p.1 p.2) (assume g, λ a, λ b, g ⟨a, b⟩) example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := iff.intro (assume f, ⟨f ∘ or.inl, f ∘ or.inr⟩) (assume h, λ pq, pq.elim h.left h.right) example: ¬(p ∨ q) ↔ ¬p ∧ ¬q := iff.intro (assume npq : ¬(p ∨ q), ⟨npq ∘ or.inl, npq ∘ or.inr⟩) (assume h : ¬p ∧ ¬q, assume pq, pq.elim h.left h.right) example: ¬p ∨ ¬q → ¬(p ∧ q) := assume h : ¬p ∨ ¬q, assume pq : p ∧ q, h.elim (λ np, np pq.left) (λ nq, nq pq.right) example : ¬(p ∧ ¬p) := λ h, absurd h.left h.right example: p ∧ ¬q → ¬(p → q) := λ pnq h, absurd (h pnq.left) pnq.right example: ¬p → (p → q) := λ np p, absurd p np example: (¬p ∨ q) → (p → q) := assume npq : ¬p ∨ q, assume hp : p, npq.elim (absurd hp) (λ q, q) example : p ∨ false ↔ p := iff.intro (λ h, h.elim (λ p, p) false.elim) or.inl example : p ∧ false ↔ false := iff.intro and.right false.elim example : (p → q) → (¬q → ¬p) := λ pq nq, nq ∘ pq namespace with_classical open classical example : ¬(p ↔ ¬p) := assume h : p ↔ ¬p, (em p).elim (λ p, h.mp p p) (λ np, absurd (h.mpr np) np) example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := assume f, (em r).elim (λ r, or.inl (λ _, r)) (λ nr, or.inr (λ p, (f p).elim (λ r, absurd r nr) (λ s, s))) example : ¬(p ∧ q) → ¬p ∨ ¬q := assume npq : ¬(p ∧ q), (em p).elim (λ hp, (em q).elim (λ hq, absurd (and.intro hp hq) npq) or.inr) or.inl example : ¬(p → q) → p ∧ ¬q := assume npq : ¬(p → q), (em p).elim -- (λ p, ⟨p, λ q, npq (λ _, q)⟩) (assume hp : p, have nq : ¬q, from (λ q', npq (λ _, q')), show p ∧ ¬q, from ⟨hp, nq⟩) (assume hnp : ¬p, have pq : p → q, from (λ p, absurd p hnp), absurd pq npq) example : (p → q) → (¬p ∨ q) := (em p).elim (λ p pq, or.inr (pq p)) (λ np _, or.inl np) example : (¬q → ¬p) → (p → q) := (em q).elim (λ q _ _, q) (λ nq nqp p, absurd p (nqp nq)) example : p ∨ ¬p := by exact (em p) example : (((p → q) → p) → p) := (em q).elim (λ q f, f (λ _, q)) ((em p).elim (λ p _ _, p) (λ np nq f, f (λ p', absurd p' np))) end with_classical /- 2. Prove ¬(p ↔ ¬p) without using classical logic. -/ example (p : Prop): ¬(p ↔ ¬p) := by simp -- TODO: Provide a direct proof example (p : Prop): ¬(p ↔ ¬p) := sorry end ch3 -- Chapter 4 namespace ch4 namespace ex1 /- Prove these equivalences. You should also try to understand why the reverse implication is not derivable in the last example. -/ variables (α : Type) (p q : α → Prop) example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (λ h, ⟨λ y, (h y).left, λ y, (h y).right⟩) (λ h x, ⟨h.left(x), h.right(x)⟩) example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := assume pq, assume p, assume x : α, show q x, from pq x (p x) example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := λ pq p x, pq x (p x) example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := λ h, h.elim (λ px x, or.inl (px x)) (λ qx x, or.inr (qx x)) end ex1 namespace ex2 /- It is often possible to bring a component of a formula outside a universal quantifier, when it does not depend on the quantified variable. Try proving these (one direction of the second of these requires classical logic): -/ variables (α : Type) (p q : α → Prop) variable r : Prop example : α → ((∀ x: α, r) ↔ r) := λ y, iff.intro (λ f, f y) (λ r _, r) open classical example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := iff.intro -- This branch requires classical reasoning (λ h, (em r).elim or.inr (λ nr, or.inl (λ x, (h x).elim id (λ r, absurd r nr)))) (λ h x, h.elim (λ px, or.inl(px x)) or.inr) example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := iff.intro (λ f r _, f _ r) (λ f _ r, f r _) end ex2 namespace ex3 /- Consider the “barber paradox,” that is, the claim that in a certain town there is a (male) barber that shaves all and only the men who do not shave themselves. Prove that this is a contradiction: -/ variables (men : Type) (barber : men) variable (shaves : men → men → Prop) open classical -- This is expedient, but not necessary; c.f. ex 3.2 example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false := (em (shaves barber barber)).elim (assume s : shaves barber barber, have ns : ¬shaves barber barber, from (h barber).mp(s), absurd s ns) (assume ns : ¬shaves barber barber, have s : shaves barber barber, from (h barber).mpr(ns), absurd s ns) end ex3 namespace ex4 /- Below, we have put definitions of divides and even in a special namespace to avoid conflicts with definitions in the library. The instance declaration make it possible to use the notation m | n for divides m n. Don’t worry about how it works; you will learn about that later. -/ def divides (m n: ℕ) : Prop := ∃ k, m * k = n instance : has_dvd nat := ⟨divides⟩ def even (n: ℕ) : Prop := 2 ∣ n variables m n : ℕ #check m ∣ n #check m ^ n #check even (m ^ n +3) /- Remember that, without any parameters, an expression of type Prop is just an assertion. Fill in the definitions of prime and Fermat_prime below, and construct the given assertion. For example, you can say that there are infinitely many primes by asserting that for every natural number n, there is a prime number greater than n. Goldbach’s weak conjecture states that every odd number greater than 5 is the sum of three primes. Look up the definition of a Fermat prime or any of the other statements, if necessary. -/ def prime (n : ℕ) : Prop := ∀m, m ∣ n → m = 1 ∨ m = n def infinitely_many_primes : Prop := ∀ n, ∃ k, k > n ∧ prime k def Fermat_prime (n : ℕ) : Prop := ∃ k : ℕ, n = 2 ^ (2 ^ k) ∧ prime n def infinitely_many_Fermat_primes : Prop := ∀ n, ∃ k, k > n ∧ Fermat_prime k def goldbach_conjecture : Prop := ∀ n, ∃ p₁ p₂, n = p₁ + p₂ ∧ prime p₁ ∧ prime p₂ def Goldbach's_weak_conjecture : Prop := ∀ n, ∃ p₁ p₂ p₃, n = p₁ + p₂ + p₃ ∧ prime p₁ ∧ prime p₂ def Fermat's_last_theorem : Prop := ∀ (a b c n : ℕ), a > 0 -> b > 0 -> c > 0 -> a^n + b^n = c^n -> n ≤ 2 end ex4 namespace ex5 /- Prove as many of the identities listed in Section 4.4 as you can. -/ variables (α : Type) (p q : α → Prop) variable a : α variable r : Prop example : (∃ x : α, r) → r := λ ⟨_, hr⟩, hr example : r → (∃ x : α, r) := λ r, exists.intro a r example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := iff.intro (λ ⟨x, pxar⟩, ⟨exists.intro x pxar.left, pxar.right⟩) (λ ⟨⟨x, px⟩, r⟩, exists.intro x ⟨px, r⟩) example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := iff.intro (λ ⟨x, pqx⟩, pqx.elim (or.inl ∘ exists.intro x) (or.inr ∘ exists.intro x)) (λ h, h.elim (λ ⟨x, px⟩, exists.intro x (or.inl px)) (λ ⟨x, qx⟩, exists.intro x (or.inr qx))) example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := iff.intro (λ nep x px, nep (exists.intro x px)) (λ nax ⟨x, px⟩, nax x px) example : (∀ x, p x → r) ↔ (∃ x, p x) → r := iff.intro (λ apxr ⟨x, px⟩, apxr x px) (λ epxr _ px, epxr (exists.intro _ px)) open classical -- TODO: do these all _require_ classical reasoning? example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := iff.intro (λ axpx ⟨_, npx,⟩, npx (axpx _)) (λ nexnpx x, by_contradiction (λ npx, nexnpx (exists.intro x npx))) example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := iff.intro (λ ⟨_, px⟩ axnpx, axnpx _ px) sorry example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := iff.intro (λ naxpx, sorry) (λ ⟨_, npx⟩ axpx, npx (axpx _)) example : (∃ x, p x → r) ↔ (∀ x, p x) → r := iff.intro (λ ⟨x, pxr⟩ y, pxr(y(x))) sorry example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := iff.intro (λ ⟨x, rpx⟩ r, exists.intro x (rpx r)) (λ repx, (em r).elim (λ hr, let ⟨x, px⟩ := repx hr in exists.intro x (λ _, px)) (λ nr, exists.intro a (λ r, absurd r nr))) end ex5 namespace ex6 /- Give a calculational proof of the theorem log_mul below. -/ variables (real : Type) [ordered_ring real] variables (log exp : real → real) variable log_exp_eq : ∀ x, log (exp x) = x variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x variable exp_pos : ∀ x, exp x > 0 variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- this ensures the assumptions are available in tactic proofs include log_exp_eq exp_log_eq exp_pos exp_add example (x y z : real) : exp (x + y + z) = exp x * exp y * exp z := by rw [exp_add, exp_add] example (y : real) (h : y > 0) : exp (log y) = y := exp_log_eq h theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := calc log (x * y) = log (exp (log x) * y) : by rw (exp_log_eq hx) ... = log (exp (log x) * exp (log y)) : by rw (exp_log_eq hy) ... = log (exp (log x + log y)) : by rw ←exp_add ... = log x + log y : by rw log_exp_eq end ex6 namespace ex7 /- Prove the theorem below, using only the ring properties of Z enumerated in Section 4.2 and the theorem sub_self -/ #check sub_self example (x: ℤ) : x * 0 = 0 := calc x * 0 = x * (1 - 1) : by rw ←sub_self ... = x * 1 - x * 1 : by rw mul_sub ... = 0 : by rw sub_self example (x: ℤ) : x * 0 = 0 := by simp [sub_self, mul_sub] end ex7 end ch4 namespace ch5 namespace scratch example (p q : Prop) : p ∨ q → q ∨ p := begin intro h, cases h with hp hq, right, exact hp, left, exact hq end example (p q : Prop) : p ∧ q → q ∧ p := begin intro h, cases h with hp hq, constructor, exact hq, exact hp end example (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin apply iff.intro, intro h, cases h with hp hqr, cases hqr with hq hr, left, constructor, repeat { assumption }, right, constructor, repeat { assumption }, intro h, cases h with hpq hpr, cases hpq with hp hq, constructor, exact hp, left, exact hq, cases hpr with hp hr, constructor, exact hp, right, exact hr end example (p q : ℕ → Prop) : (∃ x, p x) → ∃ x, p x ∨ q x := begin intro h, cases h with x px, constructor, left, exact px end example (p q : ℕ → Prop) : (∃ x, p x) → ∃ x, p x ∨ q x := begin intro h, cases h with x px, existsi x, left, exact px end example (p q: ℕ → Prop): (∃ x, p x ∧ q x) → ∃ x,q x ∧ p x := begin intro h, cases h with x hpq, cases hpq with hp hq, existsi x, split; assumption end universes u v def swap_pair {α : Type u} {β : Type v} : α × β → β × α := begin intro p, cases p with ha hb, split ; assumption end #reduce swap_pair (1, 2) def swap_sum {α : Type u} {β : Type v} : α ⊕ β → β ⊕ α := begin intro p, cases p with ha hb, right, exact ha, left, exact hb end open nat example (P : ℕ → Prop) (h₀ : P 0) (h₁ : ∀ n, P (succ n)) (m : ℕ) := begin cases m with m', exact h₀, exact h₁ m' end example (p q : Prop) : p ∧ ¬ p → q := begin intro h, cases h, contradiction end example (p q r : Prop) : p ∧ (q ∨ r) → (p ∧ q) ∨ (p ∧ r) := begin intro h, cases h with hp hqr, cases hqr with hq hr, left, exact ⟨hp, hq⟩, right, exact ⟨hp, hr⟩ end end scratch namespace ex1 /- Go back to the exercises in Chapter 3 and Chapter 4 and redo as many as you can now with tactic proofs, using also rw and simp as appropriate. -/ namespace from_chapter_3 universe u variables p q r s : Prop def id {α : Type u} (a : α) : α := a example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := begin apply iff.intro, intro h, cases h with hpq hr, cases hpq with hp hq, constructor, assumption, constructor; assumption, intro h, cases h with hp hqr, cases hqr with hq hr, repeat { constructor }; assumption end example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := begin apply iff.intro, intro h, cases h with hpq hr, cases hpq with hp hq, left, exact hp, right, left, exact hq, right, right, exact hr, intro h, cases h with hp hqr, left, left, exact hp, cases hqr with hq hr, left, right, exact hq, right, exact hr end example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := sorry example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := sorry example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := sorry example: (p → (q → r)) ↔ (p ∧ q → r) := sorry example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := sorry example: ¬(p ∨ q) ↔ ¬p ∧ ¬q := sorry example: ¬p ∨ ¬q → ¬(p ∧ q) := sorry example : ¬(p ∧ ¬p) := by simp example: p ∧ ¬q → ¬(p → q) := sorry example: ¬p → (p → q) := sorry example: (¬p ∨ q) → (p → q) := sorry example : p ∨ false ↔ p := by simp example : p ∧ false ↔ false := by simp example : (p → q) → (¬q → ¬p) := sorry namespace with_classical open classical example : ¬(p ↔ ¬p) := sorry example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := sorry example : ¬(p ∧ q) → ¬p ∨ ¬q := sorry example : ¬(p → q) → p ∧ ¬q := begin intro h, cases (em p) with hp np, constructor, exact hp, assume hq : q, have : p → q := λ _, hq, exact (h this), have : p → q, by { intro, contradiction }, contradiction end example : (p → q) → (¬p ∨ q) := sorry example : (¬q → ¬p) → (p → q) := sorry example : p ∨ ¬p := em p example : (((p → q) → p) → p) := sorry end with_classical end from_chapter_3 end ex1 namespace ex2 /- Use tactic combinators to obtain a one line proof of the following: -/ example (p q r : Prop) (hp : p) : (p ∨ q ∨ r) ∧ (q ∨ p ∨ r) ∧ (q ∨ r ∨ p) := by simp [hp] end ex2 end ch5 /- Chapter 6 -/ namespace ch6 namespace scratch namespace x universe u variables {α : Type u} (r : α → α → Prop) def reflexive : Prop := ∀ (a : α), r a a def symmetric : Prop := ∀ {a b : α}, r a b → r b a def transitive : Prop := ∀ {a b c : α}, r a b → r b c → r a c def euclidean : Prop := ∀ {a b c : α}, r a b → r a c → r b c variable {r} theorem th1 (reflr : reflexive r) (euclr : euclidean r) : symmetric r := assume (a b : α), assume : r a b, show r b a, from euclr this (reflr _) theorem th2 (symmr : symmetric r) (euclr : euclidean r) : transitive r := assume (a b c : α), assume rab : r a b, assume rbc : r b c, show r a c, from euclr (symmr rab) rbc theorem th3 (reflr : reflexive r) (euclr : euclidean r) : transitive r := @th2 _ _ (@th1 _ _ reflr @euclr) @euclr end x namespace y universe u variables {α : Type u} (r : α → α → Prop) def reflexive : Prop := ∀ (a : α), r a a def symmetric : Prop := ∀ ⦃ a b : α ⦄ , r a b → r b a def transitive : Prop := ∀ ⦃ a b c : α ⦄, r a b → r b c → r a c def euclidean : Prop := ∀ ⦃ a b c : α ⦄, r a b → r a c → r b c variable {r} theorem th1 (reflr : reflexive r) (euclr : euclidean r) : symmetric r := assume (a b : α), assume : r a b, show r b a, from euclr this (reflr _) theorem th2 (symmr : symmetric r) (euclr : euclidean r) : transitive r := assume (a b c : α), assume rab : r a b, assume rbc : r b c, show r a c, from euclr (symmr rab) rbc theorem th3 (reflr : reflexive r) (euclr : euclidean r) : transitive r := th2 (th1 reflr euclr) euclr end y end scratch end ch6
4c2294f5d101ff12a9309c59723cfcf71bcdc9ce
562dafcca9e8bf63ce6217723b51f32e89cdcc80
/src/super/resolution.lean
66976fb0e560b34e938fcc630605908214806e75
[]
no_license
digama0/super
660801ef3edab2c046d6a01ba9bbce53e41523e8
976957fe46128e6ef057bc771f532c27cce5a910
refs/heads/master
1,606,987,814,510
1,498,621,778,000
1,498,621,778,000
95,626,306
0
0
null
1,498,621,692,000
1,498,621,692,000
null
UTF-8
Lean
false
false
2,246
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state .utils open tactic monad namespace super variable gt : expr → expr → bool variables (ac1 ac2 : derived_clause) variables (c1 c2 : clause) variables (i1 i2 : nat) -- c1 : ... → ¬a → ... -- c2 : ... → a → ... meta def try_resolve : tactic clause := do qf1 ← c1.open_metan c1.num_quants, qf2 ← c2.open_metan c2.num_quants, -- FIXME: using default transparency unifies m*n with (x*y*z)*w here ??? unify (qf1.1.get_lit i1).formula (qf2.1.get_lit i2).formula transparency.reducible, qf1i ← qf1.1.inst_mvars, guard $ clause.is_maximal gt qf1i i1, op1 ← qf1.1.open_constn i1, op2 ← qf2.1.open_constn c2.num_lits, a_in_op2 ← (op2.2.nth i2).to_monad, clause.meta_closure (qf1.2 ++ qf2.2) $ (op1.1.inst (op2.1.close_const a_in_op2).proof).close_constn (op1.2 ++ op2.2.remove_nth i2) meta def try_add_resolvent : prover unit := do c' ← try_resolve gt ac1.c ac2.c i1 i2, inf_score 1 [ac1.sc, ac2.sc] >>= mk_derived c' >>= add_inferred meta def maybe_add_resolvent : prover unit := try_add_resolvent gt ac1 ac2 i1 i2 <|> return () meta def resolution_left_inf : inference := take given, do active ← get_active, sequence' $ do given_i ← given.selected, guard $ clause.literal.is_neg (given.c.get_lit given_i), other ← rb_map.values active, guard $ ¬given.sc.in_sos ∨ ¬other.sc.in_sos, other_i ← other.selected, guard $ clause.literal.is_pos (other.c.get_lit other_i), [maybe_add_resolvent gt other given other_i given_i] meta def resolution_right_inf : inference := take given, do active ← get_active, sequence' $ do given_i ← given.selected, guard $ clause.literal.is_pos (given.c.get_lit given_i), other ← rb_map.values active, guard $ ¬given.sc.in_sos ∨ ¬other.sc.in_sos, other_i ← other.selected, guard $ clause.literal.is_neg (other.c.get_lit other_i), [maybe_add_resolvent gt given other given_i other_i] @[super.inf] meta def resolution_inf : inf_decl := inf_decl.mk 40 $ take given, do gt ← get_term_order, resolution_left_inf gt given >> resolution_right_inf gt given end super
8f7a9cd013a86b45e2797af6f51e5e861f2a5c2e
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/hit/set_quotient.hlean
15eb1fcb3112999cac130d698a1f5f0a7fc7f3cf
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,823
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of set-quotients, i.e. quotient of a mere relation which is then set-truncated. -/ import .quotient .trunc function open eq is_trunc trunc quotient equiv namespace set_quotient section parameters {A : Type} (R : A → A → hprop) -- set-quotients are just truncations of (type) quotients definition set_quotient : Type := trunc 0 (quotient (λa a', trunctype.carrier (R a a'))) parameter {R} definition class_of (a : A) : set_quotient := tr (class_of _ a) definition eq_of_rel {a a' : A} (H : R a a') : class_of a = class_of a' := ap tr (eq_of_rel _ H) theorem is_hset_set_quotient : is_hset set_quotient := begin unfold set_quotient, exact _ end protected definition rec {P : set_quotient → Type} [Pt : Πaa, is_hset (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') (x : set_quotient) : P x := begin apply (@trunc.rec_on _ _ P x), { intro x', apply Pt}, { intro y, fapply (quotient.rec_on y), { exact Pc}, { intros, apply equiv.to_inv !(pathover_compose _ tr), apply Pp}} end protected definition rec_on [reducible] {P : set_quotient → Type} (x : set_quotient) [Pt : Πaa, is_hset (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') : P x := rec Pc Pp x theorem rec_eq_of_rel {P : set_quotient → Type} [Pt : Πaa, is_hset (P aa)] (Pc : Π(a : A), P (class_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[eq_of_rel H] Pc a') {a a' : A} (H : R a a') : apdo (rec Pc Pp) (eq_of_rel H) = Pp H := !is_hset.elimo protected definition elim {P : Type} [Pt : is_hset P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (x : set_quotient) : P := rec Pc (λa a' H, pathover_of_eq (Pp H)) x protected definition elim_on [reducible] {P : Type} (x : set_quotient) [Pt : is_hset P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') : P := elim Pc Pp x theorem elim_eq_of_rel {P : Type} [Pt : is_hset P] (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') {a a' : A} (H : R a a') : ap (elim Pc Pp) (eq_of_rel H) = Pp H := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (eq_of_rel H)), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑elim,rec_eq_of_rel], end /- there are no theorems to eliminate to the universe here, because the universe is generally not a set -/ end end set_quotient attribute set_quotient.class_of [constructor] attribute set_quotient.rec set_quotient.elim [unfold 7] [recursor 7] attribute set_quotient.rec_on set_quotient.elim_on [unfold 4] open sigma namespace set_quotient variables {A : Type} (R : A → A → hprop) definition is_surjective_class_of : is_surjective (class_of : A → set_quotient R) := λx, set_quotient.rec_on x (λa, tr (fiber.mk a idp)) (λa a' r, !is_hprop.elimo) /- non-dependent universal property -/ definition set_quotient_arrow_equiv (B : Type) [H : is_hset B] : (set_quotient R → B) ≃ (Σ(f : A → B), Π(a a' : A), R a a' → f a = f a') := begin fapply equiv.MK, { intro f, exact ⟨λa, f (class_of a), λa a' r, ap f (eq_of_rel r)⟩}, { intro v x, induction v with f p, exact set_quotient.elim_on x f p}, { intro v, induction v with f p, esimp, apply ap (sigma.mk f), apply eq_of_homotopy3, intro a a' r, apply elim_eq_of_rel}, { intro f, apply eq_of_homotopy, intro x, refine set_quotient.rec_on x _ _: esimp, intro a, reflexivity, intro a a' r, apply eq_pathover, apply hdeg_square, apply elim_eq_of_rel} end end set_quotient
d6deba3faab941fa5c25607c77c89271189e29ca
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/data/examples/vector.lean
b49b163c15e09212b3059f53db9813b2ee3ec763
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
13,174
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn, Leonardo de Moura This file demonstrates how to encode vectors using indexed inductive families. In standard library we do not use this approach. -/ import data.nat data.list data.fin open nat prod fin inductive vector (A : Type) : nat → Type := | nil {} : vector A zero | cons : Π {n}, A → vector A n → vector A (succ n) namespace vector notation a :: b := cons a b notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l variables {A B C : Type} protected definition is_inhabited [instance] [h : inhabited A] : ∀ (n : nat), inhabited (vector A n) | 0 := inhabited.mk [] | (n+1) := inhabited.mk (inhabited.value h :: inhabited.value (is_inhabited n)) theorem vector0_eq_nil : ∀ (v : vector A 0), v = [] | [] := rfl definition head : Π {n : nat}, vector A (succ n) → A | n (a::v) := a definition tail : Π {n : nat}, vector A (succ n) → vector A n | n (a::v) := v theorem head_cons {n : nat} (h : A) (t : vector A n) : head (h :: t) = h := rfl theorem tail_cons {n : nat} (h : A) (t : vector A n) : tail (h :: t) = t := rfl theorem eta : ∀ {n : nat} (v : vector A (succ n)), head v :: tail v = v | n (a::v) := rfl definition last : Π {n : nat}, vector A (succ n) → A | last [a] := a | last (a::v) := last v theorem last_singleton (a : A) : last [a] = a := rfl theorem last_cons {n : nat} (a : A) (v : vector A (succ n)) : last (a :: v) = last v := rfl definition const : Π (n : nat), A → vector A n | 0 a := [] | (succ n) a := a :: const n a theorem head_const (n : nat) (a : A) : head (const (succ n) a) = a := rfl theorem last_const : ∀ (n : nat) (a : A), last (const (succ n) a) = a | 0 a := rfl | (n+1) a := last_const n a definition nth : Π {n : nat}, vector A n → fin n → A | ⌞0⌟ [] i := elim0 i | ⌞n+1⌟ (a :: v) (mk 0 _) := a | ⌞n+1⌟ (a :: v) (mk (succ i) h) := nth v (mk_pred i h) lemma nth_zero {n : nat} (a : A) (v : vector A n) (h : 0 < succ n) : nth (a::v) (mk 0 h) = a := rfl lemma nth_succ {n : nat} (a : A) (v : vector A n) (i : nat) (h : succ i < succ n) : nth (a::v) (mk (succ i) h) = nth v (mk_pred i h) := rfl definition tabulate : Π {n : nat}, (fin n → A) → vector A n | 0 f := [] | (n+1) f := f (fin.zero n) :: tabulate (λ i : fin n, f (succ i)) theorem nth_tabulate : ∀ {n : nat} (f : fin n → A) (i : fin n), nth (tabulate f) i = f i | 0 f i := elim0 i | (n+1) f (mk 0 h) := by reflexivity | (n+1) f (mk (succ i) h) := begin change nth (f (fin.zero n) :: tabulate (λ i : fin n, f (succ i))) (mk (succ i) h) = f (mk (succ i) h), rewrite nth_succ, rewrite nth_tabulate end definition map (f : A → B) : Π {n : nat}, vector A n → vector B n | map [] := [] | map (a::v) := f a :: map v theorem map_nil (f : A → B) : map f [] = [] := rfl theorem map_cons {n : nat} (f : A → B) (h : A) (t : vector A n) : map f (h :: t) = f h :: map f t := rfl theorem nth_map (f : A → B) : ∀ {n : nat} (v : vector A n) (i : fin n), nth (map f v) i = f (nth v i) | 0 v i := elim0 i | (succ n) (a :: t) (mk 0 h) := by reflexivity | (succ n) (a :: t) (mk (succ i) h) := by rewrite [map_cons, *nth_succ, nth_map] section open function theorem map_id : ∀ {n : nat} (v : vector A n), map id v = v | 0 [] := rfl | (succ n) (x::xs) := by rewrite [map_cons, map_id] theorem map_map (g : B → C) (f : A → B) : ∀ {n :nat} (v : vector A n), map g (map f v) = map (g ∘ f) v | 0 [] := rfl | (succ n) (a :: l) := show (g ∘ f) a :: map g (map f l) = map (g ∘ f) (a :: l), by rewrite (map_map l) end definition map2 (f : A → B → C) : Π {n : nat}, vector A n → vector B n → vector C n | map2 [] [] := [] | map2 (a::va) (b::vb) := f a b :: map2 va vb theorem map2_nil (f : A → B → C) : map2 f [] [] = [] := rfl theorem map2_cons {n : nat} (f : A → B → C) (h₁ : A) (h₂ : B) (t₁ : vector A n) (t₂ : vector B n) : map2 f (h₁ :: t₁) (h₂ :: t₂) = f h₁ h₂ :: map2 f t₁ t₂ := rfl definition append : Π {n m : nat}, vector A n → vector A m → vector A (n ⊕ m) | 0 m [] w := w | (succ n) m (a::v) w := a :: (append v w) theorem append_nil_left {n : nat} (v : vector A n) : append [] v = v := rfl theorem append_cons {n m : nat} (h : A) (t : vector A n) (v : vector A m) : append (h::t) v = h :: (append t v) := rfl theorem map_append (f : A → B) : ∀ {n m : nat} (v : vector A n) (w : vector A m), map f (append v w) = append (map f v) (map f w) | 0 m [] w := rfl | (n+1) m (h :: t) w := begin change (f h :: map f (append t w) = f h :: append (map f t) (map f w)), rewrite map_append end definition unzip : Π {n : nat}, vector (A × B) n → vector A n × vector B n | unzip [] := ([], []) | unzip ((a, b) :: v) := (a :: pr₁ (unzip v), b :: pr₂ (unzip v)) theorem unzip_nil : unzip (@nil (A × B)) = ([], []) := rfl theorem unzip_cons {n : nat} (a : A) (b : B) (v : vector (A × B) n) : unzip ((a, b) :: v) = (a :: pr₁ (unzip v), b :: pr₂ (unzip v)) := rfl definition zip : Π {n : nat}, vector A n → vector B n → vector (A × B) n | zip [] [] := [] | zip (a::va) (b::vb) := ((a, b) :: zip va vb) theorem zip_nil_nil : zip (@nil A) (@nil B) = nil := rfl theorem zip_cons_cons {n : nat} (a : A) (b : B) (va : vector A n) (vb : vector B n) : zip (a::va) (b::vb) = ((a, b) :: zip va vb) := rfl theorem unzip_zip : ∀ {n : nat} (v₁ : vector A n) (v₂ : vector B n), unzip (zip v₁ v₂) = (v₁, v₂) | 0 [] [] := rfl | (n+1) (a::va) (b::vb) := calc unzip (zip (a :: va) (b :: vb)) = (a :: pr₁ (unzip (zip va vb)), b :: pr₂ (unzip (zip va vb))) : rfl ... = (a :: pr₁ (va, vb), b :: pr₂ (va, vb)) : by rewrite unzip_zip ... = (a :: va, b :: vb) : rfl theorem zip_unzip : ∀ {n : nat} (v : vector (A × B) n), zip (pr₁ (unzip v)) (pr₂ (unzip v)) = v | 0 [] := rfl | (n+1) ((a, b) :: v) := calc zip (pr₁ (unzip ((a, b) :: v))) (pr₂ (unzip ((a, b) :: v))) = (a, b) :: zip (pr₁ (unzip v)) (pr₂ (unzip v)) : rfl ... = (a, b) :: v : by rewrite zip_unzip /- Concat -/ definition concat : Π {n : nat}, vector A n → A → vector A (succ n) | concat [] a := [a] | concat (b::v) a := b :: concat v a theorem concat_nil (a : A) : concat [] a = [a] := rfl theorem concat_cons {n : nat} (b : A) (v : vector A n) (a : A) : concat (b :: v) a = b :: concat v a := rfl theorem last_concat : ∀ {n : nat} (v : vector A n) (a : A), last (concat v a) = a | 0 [] a := rfl | (n+1) (b::v) a := calc last (concat (b::v) a) = last (concat v a) : rfl ... = a : last_concat v a /- Reverse -/ definition reverse : Π {n : nat}, vector A n → vector A n | 0 [] := [] | (n+1) (x :: xs) := concat (reverse xs) x theorem reverse_concat : Π {n : nat} (xs : vector A n) (a : A), reverse (concat xs a) = a :: reverse xs | 0 [] a := rfl | (n+1) (x :: xs) a := begin change (concat (reverse (concat xs a)) x = a :: reverse (x :: xs)), rewrite reverse_concat end theorem reverse_reverse : Π {n : nat} (xs : vector A n), reverse (reverse xs) = xs | 0 [] := rfl | (n+1) (x :: xs) := begin change (reverse (concat (reverse xs) x) = x :: xs), rewrite [reverse_concat, reverse_reverse] end /- list <-> vector -/ definition of_list : Π (l : list A), vector A (list.length l) | list.nil := [] | (list.cons a l) := a :: (of_list l) definition to_list : Π {n : nat}, vector A n → list A | 0 [] := list.nil | (n+1) (a :: vs) := list.cons a (to_list vs) theorem to_list_of_list : ∀ (l : list A), to_list (of_list l) = l | list.nil := rfl | (list.cons a l) := begin change (list.cons a (to_list (of_list l)) = list.cons a l), rewrite to_list_of_list end theorem to_list_nil : to_list [] = (list.nil : list A) := rfl theorem length_to_list : ∀ {n : nat} (v : vector A n), list.length (to_list v) = n | 0 [] := rfl | (n+1) (a :: vs) := begin change (succ (list.length (to_list vs)) = succ n), rewrite length_to_list end theorem heq_of_list_eq : ∀ {n m} {v₁ : vector A n} {v₂ : vector A m}, to_list v₁ = to_list v₂ → n = m → v₁ == v₂ | 0 0 [] [] h₁ h₂ := !heq.refl | 0 (m+1) [] (y::ys) h₁ h₂ := by contradiction | (n+1) 0 (x::xs) [] h₁ h₂ := by contradiction | (n+1) (m+1) (x::xs) (y::ys) h₁ h₂ := assert e₁ : n = m, from succ.inj h₂, assert e₂ : x = y, begin unfold to_list at h₁, injection h₁, assumption end, have to_list xs = to_list ys, begin unfold to_list at h₁, injection h₁, assumption end, assert xs == ys, from heq_of_list_eq this e₁, assert y :: xs == y :: ys, begin clear heq_of_list_eq h₁ h₂, revert xs ys this, induction e₁, intro xs ys h, rewrite [heq.to_eq h] end, show x :: xs == y :: ys, by rewrite e₂; exact this theorem list_eq_of_heq {n m} {v₁ : vector A n} {v₂ : vector A m} : v₁ == v₂ → n = m → to_list v₁ = to_list v₂ := begin intro h₁ h₂, revert v₁ v₂ h₁, subst n, intro v₁ v₂ h₁, rewrite [heq.to_eq h₁] end theorem of_list_to_list {n : nat} (v : vector A n) : of_list (to_list v) == v := begin apply heq_of_list_eq, rewrite to_list_of_list, rewrite length_to_list end theorem to_list_append : ∀ {n m : nat} (v₁ : vector A n) (v₂ : vector A m), to_list (append v₁ v₂) = list.append (to_list v₁) (to_list v₂) | 0 m [] ys := rfl | (succ n) m (x::xs) ys := begin unfold append, unfold to_list at {1,2}, krewrite [to_list_append xs ys] end theorem to_list_map (f : A → B) : ∀ {n : nat} (v : vector A n), to_list (map f v) = list.map f (to_list v) | 0 [] := rfl | (succ n) (x::xs) := begin unfold [map, to_list], rewrite to_list_map end theorem to_list_concat : ∀ {n : nat} (v : vector A n) (a : A), to_list (concat v a) = list.concat a (to_list v) | 0 [] a := rfl | (succ n) (x::xs) a := begin unfold [concat, to_list], rewrite to_list_concat end theorem to_list_reverse : ∀ {n : nat} (v : vector A n), to_list (reverse v) = list.reverse (to_list v) | 0 [] := rfl | (succ n) (x::xs) := begin unfold [reverse], rewrite [to_list_concat, to_list_reverse] end theorem append_nil_right {n : nat} (v : vector A n) : append v [] == v := begin apply heq_of_list_eq, rewrite [to_list_append, to_list_nil, list.append_nil_right], rewrite [-add_eq_addl] end theorem append.assoc {n₁ n₂ n₃ : nat} (v₁ : vector A n₁) (v₂ : vector A n₂) (v₃ : vector A n₃) : append v₁ (append v₂ v₃) == append (append v₁ v₂) v₃ := begin apply heq_of_list_eq, rewrite [*to_list_append, list.append.assoc], rewrite [-*add_eq_addl, add.assoc] end theorem reverse_append {n m : nat} (v : vector A n) (w : vector A m) : reverse (append v w) == append (reverse w) (reverse v) := begin apply heq_of_list_eq, rewrite [to_list_reverse, to_list_append, list.reverse_append, to_list_append, *to_list_reverse], rewrite [-*add_eq_addl, add.comm] end theorem concat_eq_append {n : nat} (v : vector A n) (a : A) : concat v a == append v [a] := begin apply heq_of_list_eq, rewrite [to_list_concat, to_list_append, list.concat_eq_append], rewrite [-add_eq_addl] end /- decidable equality -/ open decidable definition decidable_eq [H : decidable_eq A] : ∀ {n : nat} (v₁ v₂ : vector A n), decidable (v₁ = v₂) | ⌞0⌟ [] [] := by left; reflexivity | ⌞n+1⌟ (a::v₁) (b::v₂) := match H a b with | inl Hab := match decidable_eq v₁ v₂ with | inl He := by left; congruence; repeat assumption | inr Hn := by right; intro h; injection h; contradiction end | inr Hnab := by right; intro h; injection h; contradiction end section open equiv function definition vector_equiv_of_equiv {A B : Type} : A ≃ B → ∀ n, vector A n ≃ vector B n | (mk f g l r) n := mk (map f) (map g) begin intros, rewrite [map_map, id_of_left_inverse l, map_id], reflexivity end begin intros, rewrite [map_map, id_of_right_inverse r, map_id], reflexivity end end end vector
f76859946769b1e6b37a3966404148c13848d88e
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/nat/prime.lean
0683e724fc0eed269d2e9c5ecc3b210bcfb03148
[ "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
14,827
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 Prime numbers. -/ import data.nat.sqrt data.nat.gcd data.list.basic data.list.perm open bool subtype namespace nat open decidable /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ def prime (p : ℕ) := p ≥ 2 ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.ge_two {p : ℕ} : prime p → p ≥ 2 := and.left theorem prime.gt_one {p : ℕ} : prime p → p > 1 := prime.ge_two theorem prime_def_lt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 theorem prime.pos {p : ℕ} (pp : prime p) : p > 0 := lt_of_succ_lt pp.gt_one theorem not_prime_zero : ¬ prime 0 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : pred p > 0 := lt_pred_of_succ_lt pp.gt_one theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_ge_two {p m : ℕ} (pp : prime p) (H : m ≥ 2) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.gt_one) $ le_of_dvd dec_trivial d section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ k * k > n) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ {n : ℕ} (n2 : n ≥ 2), min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 1 h := (dec_trivial : ¬ _).elim h | (n+2) h := by by_cases 2 ∣ n; simp [min_fac, (nat.dvd_add_iff_left (dvd_refl 2)).symm, h] private def min_fac_prop (n k : ℕ) := k ≥ 2 ∧ k ∣ n ∧ ∀ m ≥ 2, m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : n ≥ 2) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m ≥ 2, m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_ge_two pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq n2], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1] theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩ theorem min_fac_le_of_dvd (n : ℕ) : ∀ (m : ℕ), m ≥ 2 → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : min_fac n > 0 := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : n > 0) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ p ≥ 2 ∧ min_fac p = p := ⟨λ pp, ⟨pp.ge_two, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.gt_one in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : n ≥ 2) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).gt_one, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).ge_two, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : n ≥ 2) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ theorem exists_infinite_primes : ∀ n : ℕ, ∃ p, p ≥ n ∧ prime p := suffices ∀ {n}, n ≥ 2 → ∃ p, p ≥ n ∧ prime p, from λ n, let ⟨p, h, pp⟩ := this (nat.le_add_left 2 n) in ⟨p, le_trans (nat.le_add_right n 2) h, pp⟩, λ n n2, let p := min_fac (fact n + 1) in have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _, have pp : prime p, from min_fac_prime f1, have n ≤ p, from le_of_not_ge $ λ h, have p ∣ fact n, from dvd_fact (min_fac_pos _) h, have p ∣ 1, from (nat.dvd_add_iff_right this).2 (min_fac_dvd _), pp.not_dvd_one this, ⟨p, this, pp⟩ theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).gt_one /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := λ p, false.elim | 1 := λ p, false.elim | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 h, or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := (lt_irrefl _).elim | 1 := λ h, rfl | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show list.prod (m :: factors (n / m)) = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_ge_two pp m2).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, exact (pp.dvd_mul.1 h).elim IH id] theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_ge_two pq pp.ge_two theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end section open list lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) : ∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l | [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp) | (q :: l) := λ h₁ h₂, have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂, have hq : prime q := h₁ q (mem_cons_self _ _), or.cases_on ((prime.dvd_mul hp).1 h₃) (λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h; exact h ▸ mem_cons_self _ _) (λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)), (mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h))) lemma mem_factors_of_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) (h : p ∣ n) : p ∈ factors n := mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h) lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := (nat.mul_left_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $ by rwa [← prod_cons, ← prod_cons, ← prod_eq_of_perm hb], perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hl₁' hl₂')) hb.symm lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin rw h at *, clear h, induction l with a l hi, { exact absurd h₁ dec_trivial }, { rw prod_cons at h₁, exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm (hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ } end, perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _) end end nat
cbeaab0438b7263a76122bd231a80c2f485a2f4d
3bd26f8e9c7eeb6ae77ac4ba709b5b3c65b8d7cf
/ack.lean
9912104b99cb97762299797921d5685189e8012e
[]
no_license
koba-e964/lean-work
afac5677efef6905fce29cac44f36f309c3bcd62
6ab0506b9bd4e5a2e1ba6312d4ac6bdaf6ae1594
refs/heads/master
1,659,773,150,740
1,659,289,453,000
1,659,289,453,000
100,273,655
0
0
null
null
null
null
UTF-8
Lean
false
false
9,180
lean
def ack: nat -> nat -> nat | 0 n := n + 1 | (m + 1) 0 := ack m 1 | (m + 1) (n + 1) := ack m (ack (m + 1) n) lemma ack_2nd_lt_val: forall m n, n < ack m n := begin intro m, induction m with m' ih, show forall n, n < ack 0 n, { intro n, calc n < n + 1 : nat.le_refl _ ... = ack 0 n : by simp only [ack] }, show forall n, n < ack (m' + 1) n, { intro n, induction n with n' ih2, show 0 < ack (m' + 1) 0, { calc 0 < 1 : nat.le_refl 1 ... < ack m' 1 : ih 1 ... = ack (m' + 1) 0 : by simp [ack] }, show n' + 1 < ack (m' + 1) (n' + 1), { calc n' + 1 <= ack (m' + 1) n' : ih2 ... < ack m' (ack (m' + 1) n') : by apply ih ... = ack (m' + 1) (n' + 1) : by simp [ack] }, } end lemma ack_argsum_lt_val: forall m n, m + n < ack m n := begin intro m, induction m with m' ih, show forall n, 0 + n < ack 0 n, { intro n, rw nat.add_comm, apply ack_2nd_lt_val, }, show forall n, m' + 1 + n < ack (m' + 1) n, { intro n, induction n with n' ih2, show m' + 1 < ack (m'+ 1) 0, { calc m' + 1 < ack m' 1 : by apply ih ... = ack (m' + 1) 0 : by simp [ack] }, show m' + 1 + n' + 1 < ack (m' + 1) (n' + 1), { calc m' + 1 + n' + 1 <= m' + (m' + 1 + n' + 1) : by apply nat.le_add_left ... <= m' + ack (m' + 1) n' : by apply nat.add_le_add_left ih2 ... < ack m' (ack (m' + 1) n') : by apply ih ... = ack (m' + 1) (n' + 1) : by simp [ack] }, } end lemma ack_2nd_succ: forall m n, ack m n < ack m (n + 1) := begin intros m, induction m with m' ih, show forall n, ack 0 n < ack 0 (n + 1), { intro n, calc ack 0 n = n + 1 : by simp [ack] ... < n + 2 : by apply nat.le_refl ... = ack 0 (n + 1) : by simp [ack] }, show forall n, ack (m' + 1) n < ack (m' + 1) (n + 1), { intro n, calc ack (m' + 1) n < ack m' (ack (m' + 1) n) : by apply ack_2nd_lt_val ... = ack (m' + 1) (n + 1) : by simp [ack] } end lemma incr_of_succ : forall f: nat -> nat, (forall x, f x < f (x + 1)) -> forall m n, m < n -> f m < f n := begin intros f succ m n hlt, induction hlt with n' mlen' ih, show f m < f (m + 1), { apply succ }, show f m < f (n' + 1), calc f m < f n' : ih ... < f (n' + 1) : succ n' end lemma incr_eq_of_succ : forall f: nat -> nat, (forall x, f x < f (x + 1)) -> forall m n, m <= n -> f m <= f n := begin intros f succ m n hle, induction hle with n' _ ih, show f m <= f m, { reflexivity }, show f m <= f (n' + 1), calc f m <= f n' : ih ... <= f (n' + 1) : le_of_lt (succ n') end lemma ack_2nd_incr: forall m n p, n < p -> ack m n < ack m p := fun m n p, assume nltp: n < p, incr_of_succ (ack m) (ack_2nd_succ m) n p nltp lemma ack_2nd_incr_eq: forall m n p, n <= p -> ack m n <= ack m p := fun m n p, assume nlep: n <= p, incr_eq_of_succ (ack m) (ack_2nd_succ m) n p nlep lemma ack_1st_succ: forall m n, ack m n < ack (m + 1) n := begin intros m n, induction n with n' ih; simp [ack], show ack m 0 < ack m 1, { apply ack_2nd_succ }, show ack m (n' + 1) < ack m (ack (m + 1) n'), { calc ack m (n' + 1) <= ack m (m + 1 + n') : by apply ack_2nd_incr_eq; rw nat.succ_add; apply nat.le_add_left ... < ack m (ack (m + 1) n') : by apply ack_2nd_incr; apply ack_argsum_lt_val }, end lemma ack_1st_incr: forall l m n, l < m -> ack l n < ack m n := fun l m n, assume lltm: l < m, incr_of_succ (fun i, ack i n) (fun i, ack_1st_succ i n) l m lltm lemma ack_1st_incr_eq: forall l m n, l <= m -> ack l n <= ack m n := fun l m n, assume llem: l <= m, incr_eq_of_succ (fun i, ack i n) (fun i, ack_1st_succ i n) l m llem lemma ack_arg_1st_prior: forall m n, ack m (n + 1) <= ack (m + 1) n := begin intros m n, cases n with n', show ack m 1 <= ack (m + 1) 0, { simp [ack] }, show ack m (n' + 2) <= ack (m + 1) (n' + 1), { calc ack m (n' + 2) <= ack m (ack (m + 1) n') : begin apply ack_2nd_incr_eq, calc n' + 2 <= m + 1 + n' + 1 : by rw nat.succ_add; apply nat.le_add_left ... <= ack (m + 1) n' : by apply ack_argsum_lt_val end ... = ack (m + 1) (n' + 1) : by simp [ack] } end lemma ack_arg_1st_prior_any: forall m n p, ack m (n + p) <= ack (m + p) n := fun m n p, begin revert m n, induction p with p' ih, intros m n, reflexivity, intros m n, calc ack m (n + p' + 1) <= ack (m + 1) (n + p') : by apply ack_arg_1st_prior ... <= ack (m + 1 + p') n : by apply ih ... = ack (m + p' + 1) n : by rw nat.succ_add end lemma ack_dual_app: forall a b y, ack a (ack b y) <= ack (max a b + 1) (y + 1) := begin intros a b y, calc ack a (ack b y) <= ack a (ack (max a b + 1) y) : begin apply ack_2nd_incr_eq, apply ack_1st_incr_eq, calc b <= max a b : by apply le_max_right ... <= max a b + 1 : by apply nat.le_succ end ... <= ack (max a b) (ack (max a b + 1) y) : by apply ack_1st_incr_eq; apply le_max_left ... = ack (max a b + 1) (y + 1) : by simp only [ack] end @[simp] lemma ack_1_n: forall n, ack 1 n = n + 2 := begin intro n, induction n with n' ih, show ack 1 0 = 2, { simp [ack], }, show ack 1 (n' + 1) = n' + 3, calc ack 1 (n' + 1) = (ack 1 n') + 1 : by simp [ack] ... = n' + 3 : by rw ih end @[simp] lemma ack_2_n: forall n, ack 2 n = 2 * n + 3 := begin intro n, induction n with n' ih, show ack 2 0 = 3, { simp [ack], }, show ack 2 (n' + 1) = 2 * n' + 5, calc ack 2 (n' + 1) = ack 1 (ack 2 n') : by simp [ack] ... = ack 2 n' + 2 : by rw ack_1_n ... = 2 * n' + 5 : by rw ih end lemma ack_lemma_7: forall n x y, x >= 3 -> (n + 1) * ack x y <= ack x (y + n) := begin intros n x y hlt, induction n with n' ih2, show 1 * ack x y <= ack x y, { rw nat.one_mul }, show (n' + 2) * ack x y <= ack x (y + n' + 1), have h: {x': nat // x' + 1 = x}, { cases x with x', have hnotle: not (3 <= 0) := nat.not_succ_le_zero 2, contradiction, existsi x', reflexivity, }, cases h with x' xsucc, have x'ge2: x' >= 2, { apply nat.le_of_add_le_add_right, rw xsucc, exact hlt, }, calc (n' + 2) * ack x y <= 2 * (n' + 1) * ack x y : begin apply nat.mul_le_mul_right, calc n' + 2 <= 1 * n' + n' + 2 : by apply nat.le_add_left ... = 2 * n' + 2 : by rw nat.succ_mul 1 ... = 2 * (n' + 1) : by reflexivity, end ... = 2 * ((n' + 1) * ack x y) : by rw nat.mul_assoc ... <= 2 * ack x (y + n') : by apply nat.mul_le_mul_left; exact ih2 ... = 2 * ack (x' + 1) (y + n') : by rw xsucc ... <= ack 2 (ack (x' + 1) (y + n')) : by rw ack_2_n; apply nat.le_add_right ... <= ack x' (ack (x' + 1) (y + n')) : by apply ack_1st_incr_eq; exact x'ge2 ... = ack (x' + 1) (y + n' + 1) : by simp only [ack] ... = ack x (y + n' + 1) : by rw xsucc end lemma ack_lemma_8: forall m n, m >= 1 -> ack (m + 1) n > ack m (2 * n) := begin intros m n mge1, revert n, cases nat.eq_or_lt_of_le mge1 with heq hlt, cases heq, show forall n, ack 2 n > ack 1 (2 * n), { intro n, calc ack 2 n = 2 * n + 3 : by rw ack_2_n ... > 2 * n + 2 : by apply nat.le_refl ... = ack 1 (2 * n) : by rw ack_1_n }, show forall n, ack (m + 1) n > ack m (2 * n), intro n, induction n with n' ih2, show ack (m + 1) 0 > ack m 0, { apply ack_1st_succ }, show ack (m + 1) (n' + 1) > ack m (2 * n' + 2), calc ack (m + 1) (n' + 1) = ack m (ack (m + 1) n') : by simp [ack] ... > ack m (ack m (2 * n')) : by apply ack_2nd_incr; apply ih2 ... >= ack m (2 * n' + 2) : begin apply ack_2nd_incr_eq, calc ack m (2 * n') >= ack 1 (2 * n') : begin apply ack_1st_incr_eq, exact mge1 end ... = 2 * n' + 2 : by rw ack_1_n end end
587af80c2219da864227e8c715d9e38a8682c17a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/emptyc_errors.lean
f667e4d2fc86f729325459ab71abeab55c37bf7e
[ "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
600
lean
theorem {u} not_mem_empty1 {A : Type u} (x : A) : x ∉ (∅ : set A) := assume h, h theorem {u} not_mem_empty2 {A : Type u} (x : A) : x ∉ ∅ := -- ERROR here assume h, h theorem {u} not_mem_empty3 {A : Type u} (x : A) : x ∉ (∅ : set A) := assume h : x ∈ ∅, h theorem {u} not_mem_empty4 {A : Type u} (x : A) : x ∉ (∅ : set A) := assume h : x ∈ (∅ : set A), h theorem {u} not_mem_empty5 {A : Type u} (x : A) : x ∉ (∅ : set A) := begin intro h, exact h end open tactic theorem {u} not_mem_empty6 {A : Type u} (x : A) : x ∉ (∅ : set A) := by do h ← intro `h, exact h
32b11428d98c79f5a28998ff190b0e10fad03737
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/References.lean
44fb928f3cf50eae11b87718aa597907f614c30f
[ "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
12,292
lean
/- Copyright (c) 2021 Joscha Mennicken. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joscha Mennicken -/ import Lean.Data.Lsp.Internal import Lean.Server.Utils /-! # Representing collected and deduplicated definitions and usages -/ namespace Lean.Server open Lsp Lean.Elab Std structure Reference where ident : RefIdent /-- FVarIds that are logically identical to this reference -/ aliases : Array RefIdent := #[] range : Lsp.Range stx : Syntax ci : ContextInfo info : Info isBinder : Bool structure RefInfo where definition : Option Reference usages : Array Reference namespace RefInfo def empty : RefInfo := ⟨ none, #[] ⟩ def addRef : RefInfo → Reference → RefInfo | i@{ definition := none, .. }, ref@{ isBinder := true, .. } => { i with definition := ref } | i@{ usages, .. }, ref@{ isBinder := false, .. } => { i with usages := usages.push ref } | i, _ => i instance : Coe RefInfo Lsp.RefInfo where coe self := { definition := self.definition.map (·.range) usages := self.usages.map (·.range) } end RefInfo def ModuleRefs := HashMap RefIdent RefInfo namespace ModuleRefs def addRef (self : ModuleRefs) (ref : Reference) : ModuleRefs := let refInfo := self.findD ref.ident RefInfo.empty self.insert ref.ident (refInfo.addRef ref) instance : Coe ModuleRefs Lsp.ModuleRefs where coe self := HashMap.ofList <| List.map (fun (k, v) => (k, v)) <| self.toList end ModuleRefs end Lean.Server namespace Lean.Lsp.RefInfo open Server def empty : RefInfo := ⟨ none, #[] ⟩ def merge (a : RefInfo) (b : RefInfo) : RefInfo := { definition := b.definition.orElse fun _ => a.definition usages := a.usages.append b.usages } def contains (self : RefInfo) (pos : Lsp.Position) : Bool := Id.run do if let some range := self.definition then if contains range pos then return true for range in self.usages do if contains range pos then return true false where contains (range : Lsp.Range) (pos : Lsp.Position) : Bool := range.start <= pos && pos < range.end end Lean.Lsp.RefInfo namespace Lean.Lsp.ModuleRefs open Server def findAt (self : ModuleRefs) (pos : Lsp.Position) : Array RefIdent := Id.run do let mut result := #[] for (ident, info) in self.toList do if info.contains pos then result := result.push ident result end Lean.Lsp.ModuleRefs namespace Lean.Server open IO open Lsp open Elab /-- Content of individual `.ilean` files -/ structure Ilean where version : Nat := 1 module : Name references : Lsp.ModuleRefs deriving FromJson, ToJson namespace Ilean def load (path : System.FilePath) : IO Ilean := do let content ← FS.readFile path match Json.parse content >>= fromJson? with | Except.ok ilean => pure ilean | Except.error msg => throwServerError s!"Failed to load ilean at {path}: {msg}" end Ilean /-! # Collecting and deduplicating definitions and usages -/ def identOf : Info → Option (RefIdent × Bool) | Info.ofTermInfo ti => match ti.expr with | Expr.const n .. => some (RefIdent.const n, ti.isBinder) | Expr.fvar id .. => some (RefIdent.fvar id, ti.isBinder) | _ => none | Info.ofFieldInfo fi => some (RefIdent.const fi.projName, false) | Info.ofOptionInfo oi => some (RefIdent.const oi.declName, false) | _ => none def findReferences (text : FileMap) (trees : Array InfoTree) : Array Reference := Id.run <| StateT.run' (s := #[]) do for tree in trees do tree.visitM' (postNode := fun ci info _ => do if let some (ident, isBinder) := identOf info then if let some range := info.range? then if info.stx.getHeadInfo matches .original .. then -- we are not interested in canonical syntax here modify (·.push { ident, range := range.toLspRange text, stx := info.stx, ci, info, isBinder })) get /-- The `FVarId`s of a function parameter in the function's signature and body differ. However, they have `TermInfo` nodes with `binder := true` in the exact same position. Moreover, macros such as do-reassignment `x := e` may create chains of variable definitions where a helper definition overlaps with a use of a variable. This function changes every such group to use a single `FVarId` (the head of the chain/DAG) and gets rid of duplicate definitions. -/ partial def combineFvars (trees : Array InfoTree) (refs : Array Reference) : Array Reference := Id.run do -- Deduplicate definitions based on their exact range let mut posMap : HashMap Lsp.Range FVarId := HashMap.empty for ref in refs do if let { ident := RefIdent.fvar id, range, isBinder := true, .. } := ref then posMap := posMap.insert range id let idMap := buildIdMap posMap let mut refs' := #[] for ref in refs do match ref with | { ident := ident@(RefIdent.fvar id), .. } => if idMap.contains id then refs' := refs'.push { ref with ident := applyIdMap idMap ident, aliases := #[ident] } else if !idMap.contains id then refs' := refs'.push ref | _ => refs' := refs'.push ref refs' where findCanonicalBinder (idMap : HashMap FVarId FVarId) (id : FVarId) : FVarId := match idMap.find? id with | some id' => findCanonicalBinder idMap id' -- recursion depth is expected to be very low | none => id applyIdMap : HashMap FVarId FVarId → RefIdent → RefIdent | m, RefIdent.fvar id => RefIdent.fvar <| findCanonicalBinder m id | _, ident => ident buildIdMap posMap := Id.run <| StateT.run' (s := HashMap.empty) do -- map fvar defs to overlapping fvar defs/uses for ref in refs do if let { ident := RefIdent.fvar baseId, range, .. } := ref then if let some id := posMap.find? range then insertIdMap id baseId -- apply `FVarAliasInfo` trees.forM (·.visitM' (postNode := fun _ info _ => do if let .ofFVarAliasInfo ai := info then insertIdMap ai.id ai.baseId)) get -- NOTE: poor man's union-find; see also `findCanonicalBinder` insertIdMap id baseId := do let idMap ← get let id := findCanonicalBinder idMap id let baseId := findCanonicalBinder idMap baseId if baseId != id then modify (·.insert id baseId) def dedupReferences (refs : Array Reference) (allowSimultaneousBinderUse := false) : Array Reference := Id.run do let mut refsByIdAndRange : HashMap (RefIdent × Option Bool × Lsp.Range) Reference := HashMap.empty for ref in refs do let isBinder := if allowSimultaneousBinderUse then some ref.isBinder else none let key := (ref.ident, isBinder, ref.range) refsByIdAndRange := match refsByIdAndRange[key] with | some ref' => refsByIdAndRange.insert key { ref' with aliases := ref'.aliases ++ ref.aliases } | none => refsByIdAndRange.insert key ref let dedupedRefs := refsByIdAndRange.fold (init := #[]) fun refs _ ref => refs.push ref return dedupedRefs.qsort (·.range < ·.range) def findModuleRefs (text : FileMap) (trees : Array InfoTree) (localVars : Bool := true) (allowSimultaneousBinderUse := false) : ModuleRefs := Id.run do let mut refs := dedupReferences (allowSimultaneousBinderUse := allowSimultaneousBinderUse) <| combineFvars trees <| findReferences text trees if !localVars then refs := refs.filter fun | { ident := RefIdent.fvar _, .. } => false | _ => true refs.foldl (init := HashMap.empty) fun m ref => m.addRef ref /-! # Collecting and maintaining reference info from different sources -/ structure References where /-- References loaded from ilean files -/ ileans : HashMap Name (System.FilePath × Lsp.ModuleRefs) /-- References from workers, overriding the corresponding ilean files -/ workers : HashMap Name (Nat × Lsp.ModuleRefs) namespace References def empty : References := { ileans := HashMap.empty, workers := HashMap.empty } def addIlean (self : References) (path : System.FilePath) (ilean : Ilean) : References := { self with ileans := self.ileans.insert ilean.module (path, ilean.references) } def removeIlean (self : References) (path : System.FilePath) : References := let namesToRemove := self.ileans.toList.filter (fun (_, p, _) => p == path) |>.map (fun (n, _, _) => n) namesToRemove.foldl (init := self) fun self name => { self with ileans := self.ileans.erase name } def updateWorkerRefs (self : References) (name : Name) (version : Nat) (refs : Lsp.ModuleRefs) : References := Id.run do if let some (currVersion, _) := self.workers.find? name then if version > currVersion then return { self with workers := self.workers.insert name (version, refs) } if version == currVersion then let current := self.workers.findD name (version, HashMap.empty) let merged := refs.fold (init := current.snd) fun m ident info => m.findD ident Lsp.RefInfo.empty |>.merge info |> m.insert ident return { self with workers := self.workers.insert name (version, merged) } return self def finalizeWorkerRefs (self : References) (name : Name) (version : Nat) (refs : Lsp.ModuleRefs) : References := Id.run do if let some (currVersion, _) := self.workers.find? name then if version < currVersion then return self return { self with workers := self.workers.insert name (version, refs) } def removeWorkerRefs (self : References) (name : Name) : References := { self with workers := self.workers.erase name } def allRefs (self : References) : HashMap Name Lsp.ModuleRefs := let ileanRefs := self.ileans.toList.foldl (init := HashMap.empty) fun m (name, _, refs) => m.insert name refs self.workers.toList.foldl (init := ileanRefs) fun m (name, _, refs) => m.insert name refs def findAt (self : References) (module : Name) (pos : Lsp.Position) : Array RefIdent := Id.run do if let some refs := self.allRefs.find? module then return refs.findAt pos #[] def referringTo (self : References) (identModule : Name) (ident : RefIdent) (srcSearchPath : SearchPath) (includeDefinition : Bool := true) : IO (Array Location) := do let refsToCheck := match ident with | RefIdent.const _ => self.allRefs.toList | RefIdent.fvar _ => match self.allRefs.find? identModule with | none => [] | some refs => [(identModule, refs)] let mut result := #[] for (module, refs) in refsToCheck do if let some info := refs.find? ident then if let some path ← srcSearchPath.findModuleWithExt "lean" module then -- Resolve symlinks (such as `src` in the build dir) so that files are -- opened in the right folder let uri := System.Uri.pathToUri <| ← IO.FS.realPath path if includeDefinition then if let some range := info.definition then result := result.push ⟨uri, range⟩ for range in info.usages do result := result.push ⟨uri, range⟩ return result def definitionOf? (self : References) (ident : RefIdent) (srcSearchPath : SearchPath) : IO (Option Location) := do for (module, refs) in self.allRefs.toList do if let some info := refs.find? ident then if let some definition := info.definition then if let some path ← srcSearchPath.findModuleWithExt "lean" module then -- Resolve symlinks (such as `src` in the build dir) so that files are -- opened in the right folder let uri := System.Uri.pathToUri <| ← IO.FS.realPath path return some ⟨uri, definition⟩ return none def definitionsMatching (self : References) (srcSearchPath : SearchPath) (filter : Name → Option α) (maxAmount? : Option Nat := none) : IO $ Array (α × Location) := do let mut result := #[] for (module, refs) in self.allRefs.toList do if let some path ← srcSearchPath.findModuleWithExt "lean" module then let uri := System.Uri.pathToUri <| ← IO.FS.realPath path for (ident, info) in refs.toList do if let (RefIdent.const name, some definition) := (ident, info.definition) then if let some a := filter name then result := result.push (a, ⟨uri, definition⟩) if let some maxAmount := maxAmount? then if result.size >= maxAmount then return result return result end References end Lean.Server
3d35e835ca99dcc239ff850a7d502447b512023f
952248371e69ccae722eb20bfe6815d8641554a8
/src/datatypes/expr_form.lean
43a0c7fd19090654afb28e8c6f9c6a8467d413dd
[]
no_license
robertylewis/lean_polya
5fd079031bf7114449d58d68ccd8c3bed9bcbc97
1da14d60a55ad6cd8af8017b1b64990fccb66ab7
refs/heads/master
1,647,212,226,179
1,558,108,354,000
1,558,108,354,000
89,933,264
1
2
null
1,560,964,118,000
1,493,650,551,000
Lean
UTF-8
Lean
false
false
11,014
lean
import .comp namespace polya open native meta def sum_form := rb_map expr ℚ meta def expr_coeff_list_to_expr : list (expr × ℚ) → tactic expr | [] := return `(0 : ℚ) | [(e, q)] := tactic.to_expr ``(%%(↑q.reflect : expr)*%%e) | ((e, q)::t) := do e' ← expr_coeff_list_to_expr t, h ← tactic.to_expr ``(%%(q.reflect : expr)*%%e), tactic.to_expr ``(%%h + %%e') namespace sum_form protected meta def to_expr (sf : sum_form) : tactic expr := expr_coeff_list_to_expr sf.to_list private meta def lt_core (sf1 sf2 : sum_form) : bool := sf1.to_list < sf2.to_list meta def lt : sum_form → sum_form → Prop := λ sf1 sf2, ↑(lt_core sf1 sf2) meta instance has_lt : has_lt sum_form := ⟨lt⟩ meta instance lt_decidable : decidable_rel lt := by delta lt; apply_instance meta def cmp : sum_form → sum_form → ordering := cmp_using sum_form.lt meta instance : has_to_format sum_form := by delta sum_form; apply_instance meta def zero : sum_form := rb_map.mk _ _ meta instance : has_zero sum_form := ⟨sum_form.zero⟩ meta def of_expr (e : expr) : sum_form := mk_rb_map.insert e 1 meta def get_coeff (sf : sum_form) (e : expr) : ℚ := match sf.find e with | some q := q | none := 0 end meta def get_nonzero_factors (sf : sum_form) : list (expr × ℚ) := sf.to_list meta def add_coeff (sf : sum_form) (e : expr) (c : ℚ) : sum_form := if (sf.get_coeff e) + c = 0 then sf.erase e else sf.insert e ((sf.get_coeff e) + c) meta def add (lhs rhs : sum_form) : sum_form := rhs.fold lhs (λ e q sf, sf.add_coeff e q) meta def scale (sf : sum_form) (c : ℚ) : sum_form := sf.map (λ q, if q=1/c then 1 else c*q) -- replace this with a real implementation of ℚ meta def sub (lhs rhs : sum_form) : sum_form := lhs.add (rhs.scale (-1)) meta def negate (lhs : sum_form) : sum_form := lhs.scale (-1) meta instance : has_add sum_form := ⟨sum_form.add⟩ meta instance : has_sub sum_form := ⟨sum_form.sub⟩ meta def add_factor (lhs rhs : sum_form) (c : ℚ) : sum_form := lhs + (rhs.scale c) meta def normalize (sf : sum_form) : sum_form := match rb_map.to_list sf with | [] := sf | (_, m)::t := if abs m = 1 then sf else sf.scale (abs (1/m)) end meta def is_normalized (sd : sum_form) : bool := match rb_map.to_list sd with | [] := tt | (_, m)::t := abs m = 1 end meta def to_tactic_format (sf : sum_form) : tactic format := do exs ← sf.to_list.mmap (λ pr, do e ← to_string <$> tactic.pp pr.1, return $ e ++ " ← " ++ repr pr.2 ++ ", "), return $ "{ " ++ string.join exs ++ " }" end sum_form meta structure sum_form_comp := (sf : sum_form) (c : spec_comp) namespace sum_form_comp protected meta def to_expr (sfc : sum_form_comp) : tactic expr := do e ← sfc.sf.to_expr, sfc.c.to_comp.to_function e `(0 : ℚ) meta def order : sum_form_comp → sum_form_comp → ordering | ⟨_, spec_comp.lt⟩ ⟨_, spec_comp.le⟩ := ordering.lt | ⟨_, spec_comp.lt⟩ ⟨_, spec_comp.eq⟩ := ordering.lt | ⟨_, spec_comp.le⟩ ⟨_, spec_comp.eq⟩ := ordering.lt | ⟨sf1, _⟩ ⟨sf2, _⟩ := sum_form.cmp sf1.normalize sf2.normalize meta instance sum_form_comp.has_to_format : has_to_format sum_form_comp := ⟨λ sfc, "{" ++ to_fmt (sfc.sf) ++ to_fmt sfc.c ++ "0}"⟩ /-- This is only valid for positive m -/ meta def scale (m : ℚ) : sum_form_comp → sum_form_comp | ⟨sf, c⟩ := ⟨sf.scale m, c⟩ meta def normalize : sum_form_comp → sum_form_comp | ⟨sf, c⟩ := ⟨sf.normalize, c⟩ meta def is_normalized : sum_form_comp → bool | ⟨sf, _⟩ := sf.is_normalized meta def is_contr : sum_form_comp → bool | ⟨sf, c⟩ := (c = spec_comp.lt) && (sf.keys.length = 0) meta def of_ineq (lhs rhs : expr) (id : ineq) : sum_form_comp := match id.to_slope, spec_comp_and_flipped_of_comp id.to_comp with | slope.horiz, (cmp, flp) := ⟨if flp then (sum_form.of_expr rhs).negate else sum_form.of_expr rhs, cmp⟩ | slope.some m, (cmp, flp) := let nsfc := (sum_form.of_expr lhs).add_factor (sum_form.of_expr rhs) (-m) in ⟨if flp then nsfc.negate else nsfc, cmp⟩ end meta def of_eq (lhs rhs : expr) (c : ℚ) : sum_form_comp := ⟨(sum_form.of_expr lhs).add_factor (sum_form.of_expr rhs) (-c), spec_comp.eq⟩ meta def of_sign (e : expr) : gen_comp → sum_form_comp | gen_comp.ne := ⟨mk_rb_map, spec_comp.eq⟩ | gen_comp.eq := ⟨sum_form.of_expr e, spec_comp.eq⟩ | gen_comp.le := ⟨sum_form.of_expr e, spec_comp.le⟩ | gen_comp.lt := ⟨sum_form.of_expr e, spec_comp.lt⟩ | gen_comp.ge := ⟨(sum_form.of_expr e).scale (-1), spec_comp.le⟩ | gen_comp.gt := ⟨(sum_form.of_expr e).scale (-1), spec_comp.lt⟩ end sum_form_comp meta structure prod_form := (coeff : ℚ) (exps : rb_map expr ℤ) namespace prod_form private meta def expr_coeff_list_to_expr_aux : expr → list (expr × ℤ) → tactic expr | a [] := return a | a ((e, z)::t) := do h ← tactic.to_expr ``(rat.pow %%e %%(z.reflect : expr)), tmp ← tactic.to_expr ``(%%a * %%h), expr_coeff_list_to_expr_aux tmp t meta def expr_coeff_list_to_expr : list (expr × ℤ) → tactic expr | [] := return `(1 : ℚ) | ((e, z)::t) := do h ← tactic.to_expr ``(rat.pow %%e %%(z.reflect : expr)), expr_coeff_list_to_expr_aux h t /-meta def expr_coeff_list_to_expr : list (expr × ℤ) → tactic expr | [] := return `(1 : ℚ) | [(e, z)] := to_expr ``(rat.pow %%e %%(z.reflect : expr)) | ((e, z)::t) := do e' ← expr_coeff_list_to_expr t, h ← to_expr ``(rat.pow %%e %%(z.reflect : expr)), to_expr ``(%%h * %%e')-/ protected meta def to_expr (sf : prod_form) : tactic expr := do --trace "in prod_form.to_expr", exp ← expr_coeff_list_to_expr sf.exps.to_list, let cf : expr := sf.coeff.reflect, tactic.to_expr ``(%%cf * %%exp : ℚ) protected meta def one : prod_form := ⟨1, mk_rb_map⟩ meta instance : has_one prod_form := ⟨prod_form.one⟩ meta def get_exp (pf : prod_form) (e : expr) : ℤ := match pf.exps.find e with | some z := z | none := 0 end -- this assumes e ≠ 0 meta def mul_exp (pf : prod_form) (e : expr) (c : ℤ) : prod_form := if pf.get_exp e + c = 0 then {pf with exps := pf.exps.erase e} else {pf with exps := pf.exps.insert e ((pf.get_exp e) + c)} protected meta def mul (lhs rhs : prod_form) : prod_form := {rhs.exps.fold lhs (λ e q pf, pf.mul_exp e q) with coeff := lhs.coeff * rhs.coeff} meta def scale (pf : prod_form) (q : ℚ) : prod_form := {pf with coeff := pf.coeff * q} meta def pow (pf : prod_form) (z : ℤ) : prod_form := {coeff := if pf.coeff = 1 then pf.coeff else if z = 1 then pf.coeff else pf.coeff^z, exps := pf.exps.map (λ q, q*z)} meta instance : has_mul prod_form := ⟨prod_form.mul⟩ meta def of_expr (e : expr) : prod_form := {coeff := 1, exps := mk_rb_map.insert e 1} meta def get_nonone_factors (pf : prod_form) : list (expr × ℤ) := pf.exps.to_list meta instance : has_to_format prod_form := ⟨λ pf, to_fmt pf.coeff ++ "*" ++ to_fmt pf.exps⟩ private meta def lt_core (pf1 pf2 : prod_form) : bool := pf1.coeff < pf2.coeff ∨ (pf1.coeff = pf2.coeff ∧ pf1.exps.to_list < pf2.exps.to_list) meta def lt : prod_form → prod_form → Prop := λ pf1 pf2, ↑(lt_core pf1 pf2) meta instance has_lt : has_lt prod_form := ⟨lt⟩ meta instance lt_decidable : decidable_rel lt := by delta lt; apply_instance meta def cmp : prod_form → prod_form → ordering := cmp_using lt end prod_form meta structure prod_form_comp := (pf : prod_form) (c : spec_comp) namespace prod_form_comp meta def default : prod_form_comp := ⟨prod_form.one, spec_comp.eq⟩ meta instance has_to_format : has_to_format prod_form_comp := ⟨λ sfc, "{1" ++ to_fmt sfc.c ++ to_fmt sfc.pf.coeff ++ "*" ++ to_fmt (sfc.pf.exps) ++ "}"⟩ meta def is_contr : prod_form_comp → bool | ⟨sf, c⟩ := (sf.exps.keys.length = 0) && (((c = spec_comp.lt) && (sf.coeff ≥ 0)) || ((c = spec_comp.le) && (sf.coeff > 0))) /- -- assumes that lhs is positive meta def of_ineq_pos_lhs (lhs rhs : expr) (id : ineq) : prod_form_comp := match id.to_slope, spec_comp_and_flipped_of_comp id.to_comp with | slope.horiz, (cmp, flp) := default | slope.some m, (cmp, flp) := if m = 0 then default else let nsfc := ((prod_form.of_expr lhs).pow (-1)) * (prod_form.of_expr rhs) in ⟨if flp then (nsfc.scale m).pow (-1) else nsfc.scale m, cmp⟩ end -- assumes that lhs is negative meta def of_ineq_neg_lhs (lhs rhs : expr) (id : ineq) : prod_form_comp := match id.to_slope, spec_comp_and_flipped_of_comp id.to_comp with | slope.horiz, (cmp, flp) := default | slope.some m, (cmp, flp) := if m = 0 then default else let nsfc := ((prod_form.of_expr lhs).pow (-1)) * (prod_form.of_expr rhs) in ⟨if flp then nsfc.scale m else (nsfc.scale m).pow (-1), cmp⟩--⟨nsfc.scale (if flp then m else -m), cmp⟩ end -/ -- is_redundant_data cmp is_pos_coeff s_lhs s_rhs assumes lhs has sign s_lhs, rhs has sign s_rhs, c has sign is_pos_coeff, -- and returns true if lhs cmp 0 cmp c*rhs private meta def is_redundant_data (cmp : comp) (is_pos_coeff : bool) (s_lhs s_rhs : gen_comp) : bool := if s_lhs.is_less = s_rhs.is_less then if is_pos_coeff then ff else cmp.is_less else if s_lhs.is_less then if is_pos_coeff then cmp.is_less else ff else if is_pos_coeff then bnot cmp.is_less else ff -- lhs cl 0 and rhs cr 0, and iq lhs rhs. cl and cr should be strict ineqs meta def of_ineq (lhs rhs : expr) (cl cr : gen_comp) (iq : ineq) : prod_form_comp := match (/-trace_val-/ ("iq slope, lhs, rhs:", iq.to_slope, lhs, rhs)).2.1, (/-trace_val-/ ("iq comp:", iq.to_comp)).2 with | slope.horiz, _ := default | slope.some m, cmp := if (m = 0) || (is_redundant_data cmp (m > 0) cl cr) then (/-trace_val-/ ("redundant", default)).2 else let nsfc := /-trace_val $-/ (((prod_form.of_expr lhs).pow (-1)) * (prod_form.of_expr rhs)).scale m, (sc, flp) := spec_comp_and_flipped_of_comp cmp in ⟨if ((bnot cl.is_less) = flp) then nsfc.pow (-1) else nsfc, sc⟩ end meta def of_eq (lhs rhs : expr) (c : ℚ) : prod_form_comp := ⟨(((prod_form.of_expr lhs).pow (-1)) * (prod_form.of_expr rhs)).scale c, spec_comp.eq⟩ meta def pow (pfc : prod_form_comp) (z : ℤ) : prod_form_comp := ⟨pfc.pf.pow z, pfc.c⟩ end prod_form_comp meta inductive expr_form | sum_f : sum_form → expr_form | prod_f : prod_form → expr_form | atom_f : expr → expr_form namespace expr_form private meta def lt_core : expr_form → expr_form → bool | (sum_f s1) (sum_f s2) := s1 < s2 | (sum_f _) (prod_f _) := true | (prod_f _) (sum_f _) := false | (prod_f p1) (prod_f p2) := p1 < p2 | (atom_f e1) (atom_f e2) := e1 < e2 | (atom_f _) _ := true | _ (atom_f _) := false meta def lt : expr_form → expr_form → Prop := λ e1 e2, ↑(lt_core e1 e2) meta instance has_lt : has_lt expr_form := ⟨lt⟩ meta instance decidable_lt : decidable_rel lt := by delta lt; apply_instance meta def format : expr_form → format | (sum_f sf) := "sum:" ++ to_fmt sf | (prod_f pf) := "prod:" ++ to_fmt pf | (atom_f e) := "atom:" ++ to_fmt e meta instance has_to_format : has_to_format expr_form := ⟨format⟩ end expr_form end polya
8691942353e3d66ee948934fb9743b642ffb82dc
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/normed_space/basic.lean
1d493c820861be0d2222beb5a30e71a95c678dbf
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
25,943
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.algebra.pi import algebra.algebra.restrict_scalars import analysis.normed.field.basic import data.real.sqrt /-! # Normed spaces In this file we define (semi)normed spaces and algebras. We also prove some theorems about these definitions. -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} open filter metric function set open_locale topological_space big_operators nnreal ennreal uniformity pointwise section seminormed_add_comm_group section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `‖c • x‖ = ‖c‖ ‖x‖`. We require only `‖c • x‖ ≤ ‖c‖ ‖x‖` in the definition, then prove `‖c • x‖ = ‖c‖ ‖x‖` in `norm_smul`. Note that since this requires `seminormed_add_comm_group` and not `normed_add_comm_group`, this typeclass can be used for "semi normed spaces" too, just as `module` can be used for "semi modules". -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [seminormed_add_comm_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ‖a • b‖ ≤ ‖a‖ * ‖b‖) end prio variables [normed_field α] [seminormed_add_comm_group β] @[priority 100] -- see Note [lower instance priority] instance normed_space.has_bounded_smul [normed_space α β] : has_bounded_smul α β := { dist_smul_pair' := λ x y₁ y₂, by simpa [dist_eq_norm, smul_sub] using normed_space.norm_smul_le x (y₁ - y₂), dist_pair_smul' := λ x₁ x₂ y, by simpa [dist_eq_norm, sub_smul] using normed_space.norm_smul_le (x₁ - x₂) y } -- Shortcut instance, as otherwise this will be found by `normed_space.to_module` and be -- noncomputable. instance : module ℝ ℝ := by apply_instance instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ‖s • x‖ = ‖s‖ * ‖x‖ := begin by_cases h : s = 0, { simp [h] }, { refine le_antisymm (normed_space.norm_smul_le s x) _, calc ‖s‖ * ‖x‖ = ‖s‖ * ‖s⁻¹ • s • x‖ : by rw [inv_smul_smul₀ h] ... ≤ ‖s‖ * (‖s⁻¹‖ * ‖s • x‖) : mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _) ... = ‖s • x‖ : by rw [norm_inv, ← mul_assoc, mul_inv_cancel (mt norm_eq_zero.1 h), one_mul] } end lemma norm_zsmul (α) [normed_field α] [normed_space α β] (n : ℤ) (x : β) : ‖n • x‖ = ‖(n : α)‖ * ‖x‖ := by rw [← norm_smul, ← int.smul_one_eq_coe, smul_assoc, one_smul] @[simp] lemma abs_norm_eq_norm (z : β) : |‖z‖| = ‖z‖ := (abs_eq (norm_nonneg z)).mpr (or.inl rfl) lemma inv_norm_smul_mem_closed_unit_ball [normed_space ℝ β] (x : β) : ‖x‖⁻¹ • x ∈ closed_ball (0 : β) 1 := by simp only [mem_closed_ball_zero_iff, norm_smul, norm_inv, norm_norm, ← div_eq_inv_mul, div_self_le_one] lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ‖s‖ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : ‖s • x‖₊ = ‖s‖₊ * ‖x‖₊ := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = ‖s‖₊ * nndist x y := nnreal.eq $ dist_smul s x y lemma lipschitz_with_smul [normed_space α β] (s : α) : lipschitz_with ‖s‖₊ ((•) s : β → β) := lipschitz_with_iff_dist_le_mul.2 $ λ x y, by rw [dist_smul, coe_nnnorm] lemma norm_smul_of_nonneg [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ‖t • x‖ = t * ‖x‖ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} [seminormed_add_comm_group E] [normed_space α E] variables {F : Type*} [seminormed_add_comm_group F] [normed_space α F] theorem eventually_nhds_norm_smul_sub_lt (c : α) (x : E) {ε : ℝ} (h : 0 < ε) : ∀ᶠ y in 𝓝 x, ‖c • (y - x)‖ < ε := have tendsto (λ y, ‖c • (y - x)‖) (𝓝 x) (𝓝 0), from ((continuous_id.sub continuous_const).const_smul _).norm.tendsto' _ _ (by simp), this.eventually (gt_mem_nhds h) lemma filter.tendsto.zero_smul_is_bounded_under_le {f : ι → α} {g : ι → E} {l : filter ι} (hf : tendsto f l (𝓝 0)) (hg : is_bounded_under (≤) l (norm ∘ g)) : tendsto (λ x, f x • g x) l (𝓝 0) := hf.op_zero_is_bounded_under_le hg (•) (λ x y, (norm_smul x y).le) lemma filter.is_bounded_under.smul_tendsto_zero {f : ι → α} {g : ι → E} {l : filter ι} (hf : is_bounded_under (≤) l (norm ∘ f)) (hg : tendsto g l (𝓝 0)) : tendsto (λ x, f x • g x) l (𝓝 0) := hg.op_zero_is_bounded_under_le hf (flip (•)) (λ x y, ((norm_smul y x).trans (mul_comm _ _)).le) theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : closure (ball x r) = closed_ball x r := begin refine subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico zero_ne_one, zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, replace hr : 0 < r, from ((norm_nonneg _).trans hy).lt_of_ne hr.symm, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : interior (closed_ball x r) = ball x r := begin cases hr.lt_or_lt with hr hr, { rw [closed_ball_eq_empty.2 hr, ball_eq_empty.2 hr.le, interior_empty] }, refine subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases (mem_closed_ball.1 $ interior_subset hy).lt_or_eq with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] instance {E : Type*} [normed_add_comm_group E] [normed_space ℚ E] (e : E) : discrete_topology $ add_subgroup.zmultiples e := begin rcases eq_or_ne e 0 with rfl | he, { rw [add_subgroup.zmultiples_zero_eq_bot], apply_instance, }, { rw [discrete_topology_iff_open_singleton_zero, is_open_induced_iff], refine ⟨metric.ball 0 (‖e‖), metric.is_open_ball, _⟩, ext ⟨x, hx⟩, obtain ⟨k, rfl⟩ := add_subgroup.mem_zmultiples_iff.mp hx, rw [mem_preimage, mem_ball_zero_iff, add_subgroup.coe_mk, mem_singleton_iff, subtype.ext_iff, add_subgroup.coe_mk, add_subgroup.coe_zero, norm_zsmul ℚ k e, int.norm_cast_rat, int.norm_eq_abs, ← int.cast_abs, mul_lt_iff_lt_one_left (norm_pos_iff.mpr he), ← @int.cast_one ℝ _, int.cast_lt, int.abs_lt_one_iff, smul_eq_zero, or_iff_left he], }, end /-- A (semi) normed real vector space is homeomorphic to the unit ball in the same space. This homeomorphism sends `x : E` to `(1 + ‖x‖²)^(- ½) • x`. In many cases the actual implementation is not important, so we don't mark the projection lemmas `homeomorph_unit_ball_apply_coe` and `homeomorph_unit_ball_symm_apply` as `@[simp]`. See also `cont_diff_homeomorph_unit_ball` and `cont_diff_on_homeomorph_unit_ball_symm` for smoothness properties that hold when `E` is an inner-product space. -/ @[simps { attrs := [] }] noncomputable def homeomorph_unit_ball [normed_space ℝ E] : E ≃ₜ ball (0 : E) 1 := { to_fun := λ x, ⟨(1 + ‖x‖^2).sqrt⁻¹ • x, begin have : 0 < 1 + ‖x‖ ^ 2, by positivity, rw [mem_ball_zero_iff, norm_smul, real.norm_eq_abs, abs_inv, ← div_eq_inv_mul, div_lt_one (abs_pos.mpr $ real.sqrt_ne_zero'.mpr this), ← abs_norm_eq_norm x, ← sq_lt_sq, abs_norm_eq_norm, real.sq_sqrt this.le], exact lt_one_add _, end⟩, inv_fun := λ y, (1 - ‖(y : E)‖^2).sqrt⁻¹ • (y : E), left_inv := λ x, by field_simp [norm_smul, smul_smul, (zero_lt_one_add_norm_sq x).ne', real.sq_sqrt (zero_lt_one_add_norm_sq x).le, ← real.sqrt_div (zero_lt_one_add_norm_sq x).le], right_inv := λ y, begin have : 0 < 1 - ‖(y : E)‖ ^ 2 := by nlinarith [norm_nonneg (y : E), (mem_ball_zero_iff.1 y.2 : ‖(y : E)‖ < 1)], field_simp [norm_smul, smul_smul, this.ne', real.sq_sqrt this.le, ← real.sqrt_div this.le], end, continuous_to_fun := begin suffices : continuous (λ x, (1 + ‖x‖^2).sqrt⁻¹), from (this.smul continuous_id).subtype_mk _, refine continuous.inv₀ _ (λ x, real.sqrt_ne_zero'.mpr (by positivity)), continuity, end, continuous_inv_fun := begin suffices : ∀ (y : ball (0 : E) 1), (1 - ‖(y : E)‖ ^ 2).sqrt ≠ 0, { continuity, }, intros y, rw real.sqrt_ne_zero', nlinarith [norm_nonneg (y : E), (mem_ball_zero_iff.1 y.2 : ‖(y : E)‖ < 1)], end } @[simp] lemma coe_homeomorph_unit_ball_apply_zero [normed_space ℝ E] : (homeomorph_unit_ball (0 : E) : E) = 0 := by simp [homeomorph_unit_ball] open normed_field instance : normed_space α (ulift E) := { norm_smul_le := λ s x, (normed_space.norm_smul_le s x.down : _), ..ulift.normed_add_comm_group, ..ulift.module' } /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance prod.normed_space : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], ..prod.normed_add_comm_group, ..prod.module } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, seminormed_add_comm_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), ‖a • f b‖₊)) : ℝ) = ‖a‖₊ * ↑(finset.sup finset.univ (λ (b : ι), ‖f b‖₊)), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 R : Type*} [has_smul 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [seminormed_add_comm_group E] [normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } /-- If there is a scalar `c` with `‖c‖>1`, then any element with nonzero norm can be moved by scalar multiplication to any shell of width `‖c‖`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell_semi_normed {c : α} (hc : 1 < ‖c‖) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : ‖x‖ ≠ 0) : ∃d:α, d ≠ 0 ∧ ‖d • x‖ < ε ∧ (ε/‖c‖ ≤ ‖d • x‖) ∧ (‖d‖⁻¹ ≤ ε⁻¹ * ‖c‖ * ‖x‖) := begin have xεpos : 0 < ‖x‖/ε := div_pos ((ne.symm hx).le_iff_lt.1 (norm_nonneg x)) εpos, rcases exists_mem_Ico_zpow xεpos hc with ⟨n, hn⟩, have cpos : 0 < ‖c‖ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ‖c^(n+1)‖ := by { rw norm_zpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ‖(c ^ (n + 1))⁻¹ • x‖ < ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_zpow], exact (div_lt_iff εpos).1 (hn.2) }, show ε / ‖c‖ ≤ ‖(c ^ (n + 1))⁻¹ • x‖, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_zpow, zpow_add₀ (ne_of_gt cpos), zpow_one, mul_inv_rev, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (zpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ‖(c ^ (n + 1))⁻¹‖⁻¹ ≤ ε⁻¹ * ‖c‖ * ‖x‖, { have : ε⁻¹ * ‖c‖ * ‖x‖ = ε⁻¹ * ‖x‖ * ‖c‖, by ring, rw [norm_inv, inv_inv, norm_zpow, zpow_add₀ (ne_of_gt cpos), zpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end end seminormed_add_comm_group /-- A linear map from a `module` to a `normed_space` induces a `normed_space` structure on the domain, using the `seminormed_add_comm_group.induced` norm. See note [reducible non-instances] -/ @[reducible] def normed_space.induced {F : Type*} (α β γ : Type*) [normed_field α] [add_comm_group β] [module α β] [seminormed_add_comm_group γ] [normed_space α γ] [linear_map_class F α β γ] (f : F) : @normed_space α β _ (seminormed_add_comm_group.induced β γ f) := { norm_smul_le := λ a b, by {unfold norm, exact (map_smul f a b).symm ▸ (norm_smul a (f b)).le } } section normed_add_comm_group variables [normed_field α] variables {E : Type*} [normed_add_comm_group E] [normed_space α E] variables {F : Type*} [normed_add_comm_group F] [normed_space α F] open normed_field /-- While this may appear identical to `normed_space.to_module`, it contains an implicit argument involving `normed_add_comm_group.to_seminormed_add_comm_group` that typeclass inference has trouble inferring. Specifically, the following instance cannot be found without this `normed_space.to_module'`: ```lean example (𝕜 ι : Type*) (E : ι → Type*) [normed_field 𝕜] [Π i, normed_add_comm_group (E i)] [Π i, normed_space 𝕜 (E i)] : Π i, module 𝕜 (E i) := by apply_instance ``` [This Zulip thread](https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Typeclass.20resolution.20under.20binders/near/245151099) gives some more context. -/ @[priority 100] instance normed_space.to_module' : module α F := normed_space.to_module section surj variables (E) [normed_space ℝ E] [nontrivial E] lemma exists_norm_eq {c : ℝ} (hc : 0 ≤ c) : ∃ x : E, ‖x‖ = c := begin rcases exists_ne (0 : E) with ⟨x, hx⟩, rw ← norm_ne_zero_iff at hx, use c • ‖x‖⁻¹ • x, simp [norm_smul, real.norm_of_nonneg hc, hx] end @[simp] lemma range_norm : range (norm : E → ℝ) = Ici 0 := subset.antisymm (range_subset_iff.2 norm_nonneg) (λ _, exists_norm_eq E) lemma nnnorm_surjective : surjective (nnnorm : E → ℝ≥0) := λ c, (exists_norm_eq E c.coe_nonneg).imp $ λ x h, nnreal.eq h @[simp] lemma range_nnnorm : range (nnnorm : E → ℝ≥0) = univ := (nnnorm_surjective E).range_eq end surj theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases eq_or_ne r 0 with rfl|hr, { rw [closed_ball_zero, ball_zero, interior_singleton] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] variables {α} /-- If there is a scalar `c` with `‖c‖>1`, then any element can be moved by scalar multiplication to any shell of width `‖c‖`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ‖c‖) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ‖d • x‖ < ε ∧ (ε/‖c‖ ≤ ‖d • x‖) ∧ (‖d‖⁻¹ ≤ ε⁻¹ * ‖c‖ * ‖x‖) := rescale_to_shell_semi_normed hc εpos (ne_of_lt (norm_pos_iff.2 hx)).symm end normed_add_comm_group section nontrivially_normed_space variables (𝕜 E : Type*) [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [nontrivial E] include 𝕜 /-- If `E` is a nontrivial normed space over a nontrivially normed field `𝕜`, then `E` is unbounded: for any `c : ℝ`, there exists a vector `x : E` with norm strictly greater than `c`. -/ lemma normed_space.exists_lt_norm (c : ℝ) : ∃ x : E, c < ‖x‖ := begin rcases exists_ne (0 : E) with ⟨x, hx⟩, rcases normed_field.exists_lt_norm 𝕜 (c / ‖x‖) with ⟨r, hr⟩, use r • x, rwa [norm_smul, ← div_lt_iff], rwa norm_pos_iff end protected lemma normed_space.unbounded_univ : ¬bounded (univ : set E) := λ h, let ⟨R, hR⟩ := bounded_iff_forall_norm_le.1 h, ⟨x, hx⟩ := normed_space.exists_lt_norm 𝕜 E R in hx.not_le (hR x trivial) /-- A normed vector space over a nontrivially normed field is a noncompact space. This cannot be an instance because in order to apply it, Lean would have to search for `normed_space 𝕜 E` with unknown `𝕜`. We register this as an instance in two cases: `𝕜 = E` and `𝕜 = ℝ`. -/ protected lemma normed_space.noncompact_space : noncompact_space E := ⟨λ h, normed_space.unbounded_univ 𝕜 _ h.bounded⟩ @[priority 100] instance nontrivially_normed_field.noncompact_space : noncompact_space 𝕜 := normed_space.noncompact_space 𝕜 𝕜 omit 𝕜 @[priority 100] instance real_normed_space.noncompact_space [normed_space ℝ E] : noncompact_space E := normed_space.noncompact_space ℝ E end nontrivially_normed_space section normed_algebra /-- A normed algebra `𝕜'` over `𝕜` is normed module that is also an algebra. See the implementation notes for `algebra` for a discussion about non-unital algebras. Following the strategy there, a non-unital *normed* algebra can be written as: ```lean variables [normed_field 𝕜] [non_unital_semi_normed_ring 𝕜'] variables [normed_module 𝕜 𝕜'] [smul_comm_class 𝕜 𝕜' 𝕜'] [is_scalar_tower 𝕜 𝕜' 𝕜'] ``` -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_smul_le : ∀ (r : 𝕜) (x : 𝕜'), ‖r • x‖ ≤ ‖r‖ * ‖x‖) variables {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[priority 100] instance normed_algebra.to_normed_space : normed_space 𝕜 𝕜' := { norm_smul_le := normed_algebra.norm_smul_le } /-- While this may appear identical to `normed_algebra.to_normed_space`, it contains an implicit argument involving `normed_ring.to_semi_normed_ring` that typeclass inference has trouble inferring. Specifically, the following instance cannot be found without this `normed_space.to_module'`: ```lean example (𝕜 ι : Type*) (E : ι → Type*) [normed_field 𝕜] [Π i, normed_ring (E i)] [Π i, normed_algebra 𝕜 (E i)] : Π i, module 𝕜 (E i) := by apply_instance ``` See `normed_space.to_module'` for a similar situation. -/ @[priority 100] instance normed_algebra.to_normed_space' {𝕜'} [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := by apply_instance lemma norm_algebra_map (x : 𝕜) : ‖algebra_map 𝕜 𝕜' x‖ = ‖x‖ * ‖(1 : 𝕜')‖ := begin rw algebra.algebra_map_eq_smul_one, exact norm_smul _ _, end lemma nnnorm_algebra_map (x : 𝕜) : ‖algebra_map 𝕜 𝕜' x‖₊ = ‖x‖₊ * ‖(1 : 𝕜')‖₊ := subtype.ext $ norm_algebra_map 𝕜' x @[simp] lemma norm_algebra_map' [norm_one_class 𝕜'] (x : 𝕜) : ‖algebra_map 𝕜 𝕜' x‖ = ‖x‖ := by rw [norm_algebra_map, norm_one, mul_one] @[simp] lemma nnnorm_algebra_map' [norm_one_class 𝕜'] (x : 𝕜) : ‖algebra_map 𝕜 𝕜' x‖₊ = ‖x‖₊ := subtype.ext $ norm_algebra_map' _ _ section nnreal variables [norm_one_class 𝕜'] [normed_algebra ℝ 𝕜'] @[simp] lemma norm_algebra_map_nnreal (x : ℝ≥0) : ‖algebra_map ℝ≥0 𝕜' x‖ = x := (norm_algebra_map' 𝕜' (x : ℝ)).symm ▸ real.norm_of_nonneg x.prop @[simp] lemma nnnorm_algebra_map_nnreal (x : ℝ≥0) : ‖algebra_map ℝ≥0 𝕜' x‖₊ = x := subtype.ext $ norm_algebra_map_nnreal 𝕜' x end nnreal variables (𝕜 𝕜') /-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/ lemma algebra_map_isometry [norm_one_class 𝕜'] : isometry (algebra_map 𝕜 𝕜') := begin refine isometry.of_dist_eq (λx y, _), rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map'], end instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { .. normed_field.to_normed_space, .. algebra.id 𝕜} /-- Any normed characteristic-zero division ring that is a normed_algebra over the reals is also a normed algebra over the rationals. Phrased another way, if `𝕜` is a normed algebra over the reals, then `algebra_rat` respects that norm. -/ instance normed_algebra_rat {𝕜} [normed_division_ring 𝕜] [char_zero 𝕜] [normed_algebra ℝ 𝕜] : normed_algebra ℚ 𝕜 := { norm_smul_le := λ q x, by rw [←smul_one_smul ℝ q x, rat.smul_one_eq_coe, norm_smul, rat.norm_cast_real], } instance punit.normed_algebra : normed_algebra 𝕜 punit := { norm_smul_le := λ q x, by simp only [punit.norm_eq_zero, mul_zero] } instance : normed_algebra 𝕜 (ulift 𝕜') := { ..ulift.normed_space } /-- The product of two normed algebras is a normed algebra, with the sup norm. -/ instance prod.normed_algebra {E F : Type*} [semi_normed_ring E] [semi_normed_ring F] [normed_algebra 𝕜 E] [normed_algebra 𝕜 F] : normed_algebra 𝕜 (E × F) := { ..prod.normed_space } /-- The product of finitely many normed algebras is a normed algebra, with the sup norm. -/ instance pi.normed_algebra {E : ι → Type*} [fintype ι] [Π i, semi_normed_ring (E i)] [Π i, normed_algebra 𝕜 (E i)] : normed_algebra 𝕜 (Π i, E i) := { .. pi.normed_space, .. pi.algebra _ E } end normed_algebra /-- A non-unital algebra homomorphism from an `algebra` to a `normed_algebra` induces a `normed_algebra` structure on the domain, using the `semi_normed_ring.induced` norm. See note [reducible non-instances] -/ @[reducible] def normed_algebra.induced {F : Type*} (α β γ : Type*) [normed_field α] [ring β] [algebra α β] [semi_normed_ring γ] [normed_algebra α γ] [non_unital_alg_hom_class F α β γ] (f : F) : @normed_algebra α β _ (semi_normed_ring.induced β γ f) := { norm_smul_le := λ a b, by {unfold norm, exact (map_smul f a b).symm ▸ (norm_smul a (f b)).le } } instance subalgebra.to_normed_algebra {𝕜 A : Type*} [semi_normed_ring A] [normed_field 𝕜] [normed_algebra 𝕜 A] (S : subalgebra 𝕜 A) : normed_algebra 𝕜 S := @normed_algebra.induced _ 𝕜 S A _ (subring_class.to_ring S) S.algebra _ _ _ S.val section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [seminormed_add_comm_group E] [normed_space 𝕜' E] instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : seminormed_add_comm_group E] : seminormed_add_comm_group (restrict_scalars 𝕜 𝕜' E) := I instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_add_comm_group E] : normed_add_comm_group (restrict_scalars 𝕜 𝕜' E) := I /-- If `E` is a normed space over `𝕜'` and `𝕜` is a normed algebra over `𝕜'`, then `restrict_scalars.module` is additionally a `normed_space`. -/ instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := { norm_smul_le := λ c x, (normed_space.norm_smul_le (algebra_map 𝕜 𝕜' c) (_ : E)).trans_eq $ by rw norm_algebra_map', ..restrict_scalars.module 𝕜 𝕜' E } /-- The action of the original normed_field on `restrict_scalars 𝕜 𝕜' E`. This is not an instance as it would be contrary to the purpose of `restrict_scalars`. -/ -- If you think you need this, consider instead reproducing `restrict_scalars.lsmul` -- appropriately modified here. def module.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [seminormed_add_comm_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` and/or `restrict_scalars 𝕜 𝕜' E` instead. This definition allows the `restrict_scalars.normed_space` instance to be put directly on `E` rather on `restrict_scalars 𝕜 𝕜' E`. This would be a very bad instance; both because `𝕜'` cannot be inferred, and because it is likely to create instance diamonds. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := restrict_scalars.normed_space _ 𝕜' _ end restrict_scalars
f7d45ac09d79707a259d96d290b93aa7cd4059ae
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love13_rational_and_real_numbers_demo.lean
d50e97df909f67ad97e69660ac23beec62bdf4af
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,959
lean
import .lovelib /- # LoVe Demo 13: Rational and Real Numbers We review the construction of `ℚ` and `ℝ` as quotient types. A procedure to construct types with specific properties: 1. Create a new type that can represent all elements, but not necessarily in a unique manner. 2. Quotient this representation, equating elements that should be equal. 3. Define operators on the quotient type by lifting functions from the base type and prove that they are compatible with the quotient relation. We used this approach in lecture 11 to construct `ℤ`. It can be used for `ℚ` and `ℝ` as well. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Rational Numbers **Step 1:** A rational number is a number that can be expressed as a fraction `n / d` of integers `n` and `d ≠ 0`: -/ structure fraction := (num : ℤ) (denom : ℤ) (denom_ne_zero : denom ≠ 0) /- The number `n` is called the numerator, and the number `d` is called the denominator. The representation of a rational number as a fraction is not unique—e.g., `1 / 2 = 2 / 4 = -1 / -2`. **Step 2:** Two fractions `n₁ / d₁` and `n₂ / d₂` represent the same rational number if the ratio between numerator and denominator are the same—i.e., `n₁ * d₂ = n₂ * d₁`. This will be our equivalence relation `≈` on fractions. -/ namespace fraction @[instance] def setoid : setoid fraction := { r := λa b : fraction, num a * denom b = num b * denom a, iseqv := begin repeat { apply and.intro }, { intros a; refl }, { intros a b h; cc }, { intros a b c eq_ab eq_bc, apply int.eq_of_mul_eq_mul_right (denom_ne_zero b), cc } end } lemma setoid_iff (a b : fraction) : a ≈ b ↔ num a * denom b = num b * denom a := by refl /- **Step 3:** Define `0 := 0 / 1`, `1 := 1 / 1`, addition, multiplication, etc. `n₁ / d₁ + n₂ / d₂` := `(n₁ * d₂ + n₂ * d₁) / (d₁ * d₂)` `(n₁ / d₁) * (n₂ / d₂)` := `(n₁ * n₂) / (d₁ * d₂)` Then show that they are compatible with `≈`. -/ def of_int (i : ℤ) : fraction := { num := i, denom := 1, denom_ne_zero := by simp } @[instance] def has_zero : has_zero fraction := { zero := of_int 0 } @[instance] def has_one : has_one fraction := { one := of_int 1 } @[instance] def has_add : has_add fraction := { add := λa b : fraction, { num := num a * denom b + num b * denom a, denom := denom a * denom b, denom_ne_zero := by apply mul_ne_zero; exact denom_ne_zero _ } } @[simp] lemma add_num (a b : fraction) : num (a + b) = num a * denom b + num b * denom a := by refl @[simp] lemma add_denom (a b : fraction) : denom (a + b) = denom a * denom b := by refl lemma add_equiv_add {a a' b b' : fraction} (ha : a ≈ a') (hb : b ≈ b') : a + b ≈ a' + b' := begin simp [setoid_iff, add_denom, add_num] at *, calc (num a * denom b + num b * denom a) * (denom a' * denom b') = num a * denom a' * denom b * denom b' + num b * denom b' * denom a * denom a' : by simp [add_mul, mul_add]; ac_refl ... = num a' * denom a * denom b * denom b' + num b' * denom b * denom a * denom a' : by simp [*] ... = (num a' * denom b' + num b' * denom a') * (denom a * denom b) : by simp [add_mul, mul_add]; ac_refl end @[instance] def has_neg : has_neg fraction := { neg := λa : fraction, { num := - num a, ..a } } @[simp] lemma neg_num (a : fraction) : num (- a) = - num a := by refl @[simp] lemma neg_denom (a : fraction) : denom (- a) = denom a := by refl lemma setoid_neg {a a' : fraction} (hab : a ≈ a') : - a ≈ - a' := by simp [setoid_iff] at hab ⊢; exact hab @[instance] def has_mul : has_mul fraction := { mul := λa b : fraction, { num := num a * num b, denom := denom a * denom b, denom_ne_zero := mul_ne_zero (denom_ne_zero a) (denom_ne_zero b) } } @[simp] lemma mul_num (a b : fraction) : num (a * b) = num a * num b := by refl @[simp] lemma mul_denom (a b : fraction) : denom (a * b) = denom a * denom b := by refl lemma setoid_mul {a a' b b' : fraction} (ha : a ≈ a') (hb : b ≈ b') : a * b ≈ a' * b' := by simp [setoid_iff] at ha hb ⊢; cc @[instance] def has_inv : has_inv fraction := { inv := λa : fraction, if ha : num a = 0 then 0 else { num := denom a, denom := num a, denom_ne_zero := ha } } lemma inv_def (a : fraction) (ha : num a ≠ 0) : a⁻¹ = { num := denom a, denom := num a, denom_ne_zero := ha } := dif_neg ha lemma inv_zero (a : fraction) (ha : num a = 0) : a⁻¹ = 0 := dif_pos ha @[simp] lemma inv_num (a : fraction) (ha : num a ≠ 0) : num (a⁻¹) = denom a := by rw inv_def a ha @[simp] lemma inv_denom (a : fraction) (ha : num a ≠ 0) : denom (a⁻¹) = num a := by rw inv_def a ha lemma setoid_inv {a a' : fraction} (ha : a ≈ a') : a⁻¹ ≈ a'⁻¹ := begin cases' classical.em (num a = 0), case inl : ha0 { cases' classical.em (num a' = 0), case inl : ha'0 { simp [ha0, ha'0, inv_zero] }, case inr : ha'0 { simp [ha0, ha'0, setoid_iff, denom_ne_zero] at ha, cc } }, case inr : ha0 { cases' classical.em (num a' = 0), case inl : ha'0 { simp [setoid_iff, ha'0, denom_ne_zero] at ha, cc }, case inr : ha'0 { simp [setoid_iff, ha0, ha'0] at ha ⊢, cc } } end end fraction def rat : Type := quotient fraction.setoid namespace rat @[instance] def has_zero : has_zero rat := { zero := ⟦0⟧ } @[instance] def has_one : has_one rat := { one := ⟦1⟧ } @[instance] def has_add : has_add rat := { add := quotient.lift₂ (λa b : fraction, ⟦a + b⟧) begin intros a b a' b' ha hb, apply quotient.sound, exact fraction.add_equiv_add ha hb end } @[instance] def has_neg : has_neg rat := { neg := quotient.lift (λa : fraction, ⟦- a⟧) begin intros a a' ha, apply quotient.sound, exact fraction.setoid_neg ha end } @[instance] def has_mul : has_mul rat := { mul := quotient.lift₂ (λa b : fraction, ⟦a * b⟧) begin intros a b a' b' ha hb, apply quotient.sound, exact fraction.setoid_mul ha hb end } @[instance] def has_inv : has_inv rat := { inv := quotient.lift (λa : fraction, ⟦a⁻¹⟧) begin intros a a' ha, apply quotient.sound, exact fraction.setoid_inv ha end } end rat /- ### Alternative Definitions of `ℚ` **Alternative 1:** Define `ℚ` as a subtype of `fraction`, with the requirement that the numerator and the denominator have no common divisors except `1` and `-1`: -/ namespace alternative_1 def rat.is_canonical (a : fraction) : Prop := nat.coprime (int.nat_abs (fraction.num a)) (int.nat_abs (fraction.denom a)) def rat := {a : fraction // rat.is_canonical a} end alternative_1 /- This is more or less the `mathlib` definition. Advantages: * no quotient required; * more efficient computation; * more properties are syntactic equalities up to computation. Disadvantage: * more complicated function definitions. **Alternative 2**: Define all elements syntactically, including the desired operations: -/ namespace alternative_2 inductive pre_rat : Type | zero : pre_rat | one : pre_rat | add : pre_rat → pre_rat → pre_rat | sub : pre_rat → pre_rat → pre_rat | mul : pre_rat → pre_rat → pre_rat | div : pre_rat → pre_rat → pre_rat /- Then quotient `pre_rat` to enforce congruence rules and the field axioms: -/ inductive rat.rel : pre_rat → pre_rat → Prop | add_congr {a b c d : pre_rat} : rat.rel a b → rat.rel c d → rat.rel (pre_rat.add a c) (pre_rat.add b d) | add_assoc {a b c : pre_rat} : rat.rel (pre_rat.add a (pre_rat.add b c)) (pre_rat.add (pre_rat.add a b) c) | zero_add {a : pre_rat} : rat.rel (pre_rat.add pre_rat.zero a) a -- etc. def rat : Type := quot rat.rel end alternative_2 /- Advantages: * no dependency on `ℤ`; * easy proofs of the field axioms; * general recipe reusable for other algebraic constructions (e.g., free monoids, free groups). Disadvantage: * the definition of orders and lemmas about them are more complicated. ### Real Numbers Some sequences of rational numbers seem to converge because the numbers in the sequence get closer and closer to each other, and yet do not converge to a rational number. Example: `a₀ = 1` `a₁ = 1.4` `a₂ = 1.41` `a₃ = 1.414` `a₄ = 1.4142` `a₅ = 1.41421` `a₆ = 1.414213` `a₇ = 1.4142135` ⋮ This sequence seems to converge because each `a_n` is at most `10^-n` away from any of the following numbers. But the limit is `√2`, which is not a rational number. The rational numbers are incomplete, and the reals are their __completion__. To construct the reals, we need to fill in the gaps that are revealed by these sequences that seem to converge, but do not. Mathematically, a sequence `a₀, a₁, …` of rational numbers is __Cauchy__ if for any `ε > 0`, there exists an `N ∈ ℕ` such that for all `m ≥ N`, we have `|a_N - a_m| < ε`. In other words, no matter how small we choose `ε`, we can always find a point in the sequence from which all following numbers deviate less than by `ε`. -/ def is_cau_seq (f : ℕ → ℚ) : Prop := ∀ε > 0, ∃N, ∀m ≥ N, abs (f N - f m) < ε /- Not every sequence is a Cauchy sequence: -/ lemma id_not_cau_seq : ¬ is_cau_seq (λn : ℕ, (n : ℚ)) := begin rw is_cau_seq, intro h, cases' h 1 zero_lt_one with i hi, have hi_succi := hi (i + 1) (by simp), simp [←sub_sub] at hi_succi, linarith end /- We define a type of Cauchy sequences as a subtype: -/ def cau_seq : Type := {f : ℕ → ℚ // is_cau_seq f} def seq_of (f : cau_seq) : ℕ → ℚ := subtype.val f /- Cauchy sequences represent real numbers: * `a_n = 1 / n` represents the real number `0`; * `1, 1.4, 1.41, …` represents the real number `√2`; * `a_n = 0` also represents the real number `0`. Since different Cauchy sequences can represent the same real number, we need to take the quotient. Formally, two sequences represent the same real number when their difference converges to zero: -/ namespace cau_seq @[instance] def setoid : setoid cau_seq := { r := λf g : cau_seq, ∀ε > 0, ∃N, ∀m ≥ N, abs (seq_of f m - seq_of g m) < ε, iseqv := begin apply and.intro, { intros f ε hε, apply exists.intro 0, finish }, apply and.intro, { intros f g hfg ε hε, cases' hfg ε hε with N hN, apply exists.intro N, intros m hm, rw abs_sub, apply hN m hm }, { intros f g h hfg hgh ε hε, cases' hfg (ε / 2) (half_pos hε) with N₁ hN₁, cases' hgh (ε / 2) (half_pos hε) with N₂ hN₂, apply exists.intro (max N₁ N₂), intros m hm, calc abs (seq_of f m - seq_of h m) ≤ abs (seq_of f m - seq_of g m) + abs (seq_of g m - seq_of h m) : by apply abs_sub_le ... < ε / 2 + ε / 2 : add_lt_add (hN₁ m (le_of_max_le_left hm)) (hN₂ m (le_of_max_le_right hm)) ... = ε : by simp } end } lemma setoid_iff (f g : cau_seq) : f ≈ g ↔ ∀ε > 0, ∃N, ∀m ≥ N, abs (seq_of f m - seq_of g m) < ε := by refl /- We can define constants such as `0` and `1` as a constant sequence. Any constant sequence is a Cauchy sequence: -/ def const (q : ℚ) : cau_seq := subtype.mk (λ_ : ℕ, q) (by rw is_cau_seq; intros ε hε; finish) /- Defining addition of real numbers requires a little more effort. We define addition on Cauchy sequences as pairwise addition: -/ @[instance] def has_add : has_add cau_seq := { add := λf g : cau_seq, subtype.mk (λn : ℕ, seq_of f n + seq_of g n) sorry } /- Above, we omit the proof that the addition of two Cauchy sequences is again a Cauchy sequence. Next, we need to show that this addition is compatible with `≈`: -/ lemma add_equiv_add {f f' g g' : cau_seq} (hf : f ≈ f') (hg : g ≈ g') : f + g ≈ f' + g' := begin intros ε₀ hε₀, simp [setoid_iff], cases' hf (ε₀ / 2) (half_pos hε₀) with Nf hNf, cases' hg (ε₀ / 2) (half_pos hε₀) with Ng hNg, apply exists.intro (max Nf Ng), intros m hm, calc abs (seq_of (f + g) m - seq_of (f' + g') m) = abs ((seq_of f m + seq_of g m) - (seq_of f' m + seq_of g' m)) : by refl ... = abs ((seq_of f m - seq_of f' m) + (seq_of g m - seq_of g' m)) : begin have arg_eq : seq_of f m + seq_of g m - (seq_of f' m + seq_of g' m) = seq_of f m - seq_of f' m + (seq_of g m - seq_of g' m), by linarith, rw arg_eq end ... ≤ abs (seq_of f m - seq_of f' m) + abs (seq_of g m - seq_of g' m) : by apply abs_add ... < ε₀ / 2 + ε₀ / 2 : add_lt_add (hNf m (le_of_max_le_left hm)) (hNg m (le_of_max_le_right hm)) ... = ε₀ : by simp end end cau_seq /- The real numbers are the quotient: -/ def real : Type := quotient cau_seq.setoid namespace real @[instance] def has_zero : has_zero real := { zero := ⟦cau_seq.const 0⟧ } @[instance] def has_one : has_one real := { one := ⟦cau_seq.const 1⟧ } @[instance] def has_add : has_add real := { add := quotient.lift₂ (λa b : cau_seq, ⟦a + b⟧) begin intros a b a' b' ha hb, apply quotient.sound, exact cau_seq.add_equiv_add ha hb, end } end real /- ### Alternative Definitions of `ℝ` * Dedekind cuts: `r : ℝ` is represented essentially as `{x : ℚ | x < r}`. * Binary sequences `ℕ → bool` can represent the interval `[0, 1]`. This can be used to build `ℝ`. -/ end LoVe
35be9a9361d51086818d0dd386dee49ae948edb2
618003631150032a5676f229d13a079ac875ff77
/test/lint_simp_var_head.lean
e634961be2b9e224c730c2086b861f06aadc3eea
[ "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
589
lean
import tactic.lint -- The following simp lemma has the variable `f` as head symbol of the left-hand side: @[simp] axiom const_zero_eq_zero (f : ℕ → ℕ) (x) : f x = 0 example (f : ℕ → ℕ) : f 42 = 0 := begin -- Hence it doesn't work: success_if_fail {simp}, -- BTW, rw doesn't work either: success_if_fail {rw const_zero_eq_zero}, -- It only works if explicitly instantiate with `f`: simp only [const_zero_eq_zero f] end open tactic #eval do decl ← get_decl ``const_zero_eq_zero, res ← linter.simp_var_head.test decl, -- linter complains guard $ res.is_some
03f0100f695b01a3163f29141f99853e19f7ebb8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/clifford_algebra/basic.lean
45eada9e874ede87d9a6341db2147a650e381ad2
[ "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
13,784
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Utensil Song -/ import algebra.ring_quot import linear_algebra.tensor_algebra.basic import linear_algebra.quadratic_form.isometry /-! # Clifford Algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We construct the Clifford algebra of a module `M` over a commutative ring `R`, equipped with a quadratic_form `Q`. ## Notation The Clifford algebra of the `R`-module `M` equipped with a quadratic_form `Q` is an `R`-algebra denoted `clifford_algebra Q`. Given a linear morphism `f : M → A` from a module `M` to another `R`-algebra `A`, such that `cond : ∀ m, f m * f m = algebra_map _ _ (Q m)`, there is a (unique) lift of `f` to an `R`-algebra morphism from `clifford_algebra Q` to `A`, which is denoted `clifford_algebra.lift Q f cond`. The canonical linear map `M → clifford_algebra Q` is denoted `clifford_algebra.ι Q`. ## Theorems The main theorems proved ensure that `clifford_algebra Q` satisfies the universal property of the Clifford algebra. 1. `ι_comp_lift` is the fact that the composition of `ι Q` with `lift Q f cond` agrees with `f`. 2. `lift_unique` ensures the uniqueness of `lift Q f cond` with respect to 1. Additionally, when `Q = 0` an `alg_equiv` to the `exterior_algebra` is provided as `as_exterior`. ## Implementation details The Clifford algebra of `M` is constructed as a quotient of the tensor algebra, as follows. 1. We define a relation `clifford_algebra.rel Q` on `tensor_algebra R M`. This is the smallest relation which identifies squares of elements of `M` with `Q m`. 2. The Clifford algebra is the quotient of the tensor algebra by this relation. This file is almost identical to `linear_algebra/exterior_algebra.lean`. -/ variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables (Q : quadratic_form R M) variable {n : ℕ} namespace clifford_algebra open tensor_algebra /-- `rel` relates each `ι m * ι m`, for `m : M`, with `Q m`. The Clifford algebra of `M` is defined as the quotient modulo this relation. -/ inductive rel : tensor_algebra R M → tensor_algebra R M → Prop | of (m : M) : rel (ι R m * ι R m) (algebra_map R _ (Q m)) end clifford_algebra /-- The Clifford algebra of an `R`-module `M` equipped with a quadratic_form `Q`. -/ @[derive [inhabited, ring, algebra R]] def clifford_algebra := ring_quot (clifford_algebra.rel Q) namespace clifford_algebra /-- The canonical linear map `M →ₗ[R] clifford_algebra Q`. -/ def ι : M →ₗ[R] clifford_algebra Q := (ring_quot.mk_alg_hom R _).to_linear_map.comp (tensor_algebra.ι R) /-- As well as being linear, `ι Q` squares to the quadratic form -/ @[simp] theorem ι_sq_scalar (m : M) : ι Q m * ι Q m = algebra_map R _ (Q m) := begin erw [←alg_hom.map_mul, ring_quot.mk_alg_hom_rel R (rel.of m), alg_hom.commutes], refl, end variables {Q} {A : Type*} [semiring A] [algebra R A] @[simp] theorem comp_ι_sq_scalar (g : clifford_algebra Q →ₐ[R] A) (m : M) : g (ι Q m) * g (ι Q m) = algebra_map _ _ (Q m) := by rw [←alg_hom.map_mul, ι_sq_scalar, alg_hom.commutes] variables (Q) /-- Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition: `cond : ∀ m : M, f m * f m = Q(m)`, this is the canonical lift of `f` to a morphism of `R`-algebras from `clifford_algebra Q` to `A`. -/ @[simps symm_apply] def lift : {f : M →ₗ[R] A // ∀ m, f m * f m = algebra_map _ _ (Q m)} ≃ (clifford_algebra Q →ₐ[R] A) := { to_fun := λ f, ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : M →ₗ[R] A), (λ x y (h : rel Q x y), by { induction h, rw [alg_hom.commutes, alg_hom.map_mul, tensor_algebra.lift_ι_apply, f.prop], })⟩, inv_fun := λ F, ⟨F.to_linear_map.comp (ι Q), λ m, by rw [ linear_map.comp_apply, alg_hom.to_linear_map_apply, comp_ι_sq_scalar]⟩, left_inv := λ f, by { ext, simp only [ι, alg_hom.to_linear_map_apply, function.comp_app, linear_map.coe_comp, subtype.coe_mk, ring_quot.lift_alg_hom_mk_alg_hom_apply, tensor_algebra.lift_ι_apply] }, right_inv := λ F, by { ext, simp only [ι, alg_hom.comp_to_linear_map, alg_hom.to_linear_map_apply, function.comp_app, linear_map.coe_comp, subtype.coe_mk, ring_quot.lift_alg_hom_mk_alg_hom_apply, tensor_algebra.lift_ι_apply] } } variables {Q} @[simp] theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) : (lift Q ⟨f, cond⟩).to_linear_map.comp (ι Q) = f := (subtype.mk_eq_mk.mp $ (lift Q).symm_apply_apply ⟨f, cond⟩) @[simp] theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) (x) : lift Q ⟨f, cond⟩ (ι Q x) = f x := (linear_map.ext_iff.mp $ ι_comp_lift f cond) x @[simp] theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m : M, f m * f m = algebra_map _ _ (Q m)) (g : clifford_algebra Q →ₐ[R] A) : g.to_linear_map.comp (ι Q) = f ↔ g = lift Q ⟨f, cond⟩ := begin convert (lift Q).symm_apply_eq, rw lift_symm_apply, simp only, end attribute [irreducible] clifford_algebra ι lift @[simp] theorem lift_comp_ι (g : clifford_algebra Q →ₐ[R] A) : lift Q ⟨g.to_linear_map.comp (ι Q), comp_ι_sq_scalar _⟩ = g := begin convert (lift Q).apply_symm_apply g, rw lift_symm_apply, refl, end /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {A : Type*} [semiring A] [algebra R A] {f g : clifford_algebra Q →ₐ[R] A} : f.to_linear_map.comp (ι Q) = g.to_linear_map.comp (ι Q) → f = g := begin intro h, apply (lift Q).symm.injective, rw [lift_symm_apply, lift_symm_apply], simp only [h], end /-- If `C` holds for the `algebra_map` of `r : R` into `clifford_algebra Q`, the `ι` of `x : M`, and is preserved under addition and muliplication, then it holds for all of `clifford_algebra Q`. See also the stronger `clifford_algebra.left_induction` and `clifford_algebra.right_induction`. -/ -- This proof closely follows `tensor_algebra.induction` @[elab_as_eliminator] lemma induction {C : clifford_algebra Q → Prop} (h_grade0 : ∀ r, C (algebra_map R (clifford_algebra Q) r)) (h_grade1 : ∀ x, C (ι Q x)) (h_mul : ∀ a b, C a → C b → C (a * b)) (h_add : ∀ a b, C a → C b → C (a + b)) (a : clifford_algebra Q) : C a := begin -- the arguments are enough to construct a subalgebra, and a mapping into it from M let s : subalgebra R (clifford_algebra Q) := { carrier := C, mul_mem' := h_mul, add_mem' := h_add, algebra_map_mem' := h_grade0, }, let of : { f : M →ₗ[R] s // ∀ m, f m * f m = algebra_map _ _ (Q m) } := ⟨(ι Q).cod_restrict s.to_submodule h_grade1, λ m, subtype.eq $ ι_sq_scalar Q m ⟩, -- the mapping through the subalgebra is the identity have of_id : alg_hom.id R (clifford_algebra Q) = s.val.comp (lift Q of), { ext, simp [of], }, -- finding a proof is finding an element of the subalgebra convert subtype.prop (lift Q of a), exact alg_hom.congr_fun of_id a, end /-- The symmetric product of vectors is a scalar -/ lemma ι_mul_ι_add_swap (a b : M) : ι Q a * ι Q b + ι Q b * ι Q a = algebra_map R _ (quadratic_form.polar Q a b) := calc ι Q a * ι Q b + ι Q b * ι Q a = ι Q (a + b) * ι Q (a + b) - ι Q a * ι Q a - ι Q b * ι Q b : by { rw [(ι Q).map_add, mul_add, add_mul, add_mul], abel, } ... = algebra_map R _ (Q (a + b)) - algebra_map R _ (Q a) - algebra_map R _ (Q b) : by rw [ι_sq_scalar, ι_sq_scalar, ι_sq_scalar] ... = algebra_map R _ (Q (a + b) - Q a - Q b) : by rw [←ring_hom.map_sub, ←ring_hom.map_sub] ... = algebra_map R _ (quadratic_form.polar Q a b) : rfl lemma ι_mul_comm (a b : M) : ι Q a * ι Q b = algebra_map R _ (quadratic_form.polar Q a b) - ι Q b * ι Q a := eq_sub_of_add_eq (ι_mul_ι_add_swap a b) /-- $aba$ is a vector. -/ lemma ι_mul_ι_mul_ι (a b : M) : ι Q a * ι Q b * ι Q a = ι Q (quadratic_form.polar Q a b • a - Q a • b) := by rw [ι_mul_comm, sub_mul, mul_assoc, ι_sq_scalar, ←algebra.smul_def, ←algebra.commutes, ←algebra.smul_def, ←map_smul, ←map_smul, ←map_sub] @[simp] lemma ι_range_map_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = algebra_map _ _ (Q m)) : (ι Q).range.map (lift Q ⟨f, cond⟩).to_linear_map = f.range := by rw [←linear_map.range_comp, ι_comp_lift] section map variables {M₁ M₂ M₃ : Type*} variables [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₃] variables [module R M₁] [module R M₂] [module R M₃] variables (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) (Q₃ : quadratic_form R M₃) /-- Any linear map that preserves the quadratic form lifts to an `alg_hom` between algebras. See `clifford_algebra.equiv_of_isometry` for the case when `f` is a `quadratic_form.isometry`. -/ def map (f : M₁ →ₗ[R] M₂) (hf : ∀ m, Q₂ (f m) = Q₁ m) : clifford_algebra Q₁ →ₐ[R] clifford_algebra Q₂ := clifford_algebra.lift Q₁ ⟨(clifford_algebra.ι Q₂).comp f, λ m, (ι_sq_scalar _ _).trans $ ring_hom.congr_arg _ $ hf m⟩ @[simp] lemma map_comp_ι (f : M₁ →ₗ[R] M₂) (hf) : (map Q₁ Q₂ f hf).to_linear_map.comp (ι Q₁) = (ι Q₂).comp f := ι_comp_lift _ _ @[simp] lemma map_apply_ι (f : M₁ →ₗ[R] M₂) (hf) (m : M₁): map Q₁ Q₂ f hf (ι Q₁ m) = ι Q₂ (f m) := lift_ι_apply _ _ m @[simp] lemma map_id : map Q₁ Q₁ (linear_map.id : M₁ →ₗ[R] M₁) (λ m, rfl) = alg_hom.id R (clifford_algebra Q₁) := by { ext m, exact map_apply_ι _ _ _ _ m } @[simp] lemma map_comp_map (f : M₂ →ₗ[R] M₃) (hf) (g : M₁ →ₗ[R] M₂) (hg) : (map Q₂ Q₃ f hf).comp (map Q₁ Q₂ g hg) = map Q₁ Q₃ (f.comp g) (λ m, (hf _).trans $ hg m) := begin ext m, dsimp only [linear_map.comp_apply, alg_hom.comp_apply, alg_hom.to_linear_map_apply, alg_hom.id_apply], rw [map_apply_ι, map_apply_ι, map_apply_ι, linear_map.comp_apply], end @[simp] lemma ι_range_map_map (f : M₁ →ₗ[R] M₂) (hf : ∀ m, Q₂ (f m) = Q₁ m) : (ι Q₁).range.map (map Q₁ Q₂ f hf).to_linear_map = f.range.map (ι Q₂) := (ι_range_map_lift _ _).trans (linear_map.range_comp _ _) variables {Q₁ Q₂ Q₃} /-- Two `clifford_algebra`s are equivalent as algebras if their quadratic forms are equivalent. -/ @[simps apply] def equiv_of_isometry (e : Q₁.isometry Q₂) : clifford_algebra Q₁ ≃ₐ[R] clifford_algebra Q₂ := alg_equiv.of_alg_hom (map Q₁ Q₂ e e.map_app) (map Q₂ Q₁ e.symm e.symm.map_app) ((map_comp_map _ _ _ _ _ _ _).trans $ begin convert map_id _ using 2, ext m, exact e.to_linear_equiv.apply_symm_apply m, end) ((map_comp_map _ _ _ _ _ _ _).trans $ begin convert map_id _ using 2, ext m, exact e.to_linear_equiv.symm_apply_apply m, end) @[simp] lemma equiv_of_isometry_symm (e : Q₁.isometry Q₂) : (equiv_of_isometry e).symm = equiv_of_isometry e.symm := rfl @[simp] lemma equiv_of_isometry_trans (e₁₂ : Q₁.isometry Q₂) (e₂₃ : Q₂.isometry Q₃) : (equiv_of_isometry e₁₂).trans (equiv_of_isometry e₂₃) = equiv_of_isometry (e₁₂.trans e₂₃) := by { ext x, exact alg_hom.congr_fun (map_comp_map Q₁ Q₂ Q₃ _ _ _ _) x } @[simp] lemma equiv_of_isometry_refl : (equiv_of_isometry $ quadratic_form.isometry.refl Q₁) = alg_equiv.refl := by { ext x, exact alg_hom.congr_fun (map_id Q₁) x } end map variables (Q) /-- If the quadratic form of a vector is invertible, then so is that vector. -/ def invertible_ι_of_invertible (m : M) [invertible (Q m)] : invertible (ι Q m) := { inv_of := ι Q (⅟(Q m) • m), inv_of_mul_self := by rw [map_smul, smul_mul_assoc, ι_sq_scalar, algebra.smul_def, ←map_mul, inv_of_mul_self, map_one], mul_inv_of_self := by rw [map_smul, mul_smul_comm, ι_sq_scalar, algebra.smul_def, ←map_mul, inv_of_mul_self, map_one] } /-- For a vector with invertible quadratic form, $v^{-1} = \frac{v}{Q(v)}$ -/ lemma inv_of_ι (m : M) [invertible (Q m)] [invertible (ι Q m)] : ⅟(ι Q m) = ι Q (⅟(Q m) • m) := begin letI := invertible_ι_of_invertible Q m, convert (rfl : ⅟(ι Q m) = _), end lemma is_unit_ι_of_is_unit {m : M} (h : is_unit (Q m)) : is_unit (ι Q m) := begin casesI h.nonempty_invertible, letI := invertible_ι_of_invertible Q m, exactI is_unit_of_invertible (ι Q m), end /-- $aba^{-1}$ is a vector. -/ lemma ι_mul_ι_mul_inv_of_ι (a b : M) [invertible (ι Q a)] [invertible (Q a)] : ι Q a * ι Q b * ⅟(ι Q a) = ι Q ((⅟(Q a) * quadratic_form.polar Q a b) • a - b) := by rw [inv_of_ι, map_smul, mul_smul_comm, ι_mul_ι_mul_ι, ←map_smul, smul_sub, smul_smul, smul_smul, inv_of_mul_self, one_smul] /-- $a^{-1}ba$ is a vector. -/ lemma inv_of_ι_mul_ι_mul_ι (a b : M) [invertible (ι Q a)] [invertible (Q a)] : ⅟(ι Q a) * ι Q b * ι Q a = ι Q ((⅟(Q a) * quadratic_form.polar Q a b) • a - b) := by rw [inv_of_ι, map_smul, smul_mul_assoc, smul_mul_assoc, ι_mul_ι_mul_ι, ←map_smul, smul_sub, smul_smul, smul_smul, inv_of_mul_self, one_smul] end clifford_algebra namespace tensor_algebra variables {Q} /-- The canonical image of the `tensor_algebra` in the `clifford_algebra`, which maps `tensor_algebra.ι R x` to `clifford_algebra.ι Q x`. -/ def to_clifford : tensor_algebra R M →ₐ[R] clifford_algebra Q := tensor_algebra.lift R (clifford_algebra.ι Q) @[simp] lemma to_clifford_ι (m : M) : (tensor_algebra.ι R m).to_clifford = clifford_algebra.ι Q m := by simp [to_clifford] end tensor_algebra
75b5782db8f4a2fa5f2e527e7719555955845dae
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/hott/apply_class_issue.hlean
1824583c3b083c6a284541e17d917968887b244a
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
305
hlean
open is_trunc context parameters {P : Π(A : Type), A → Type} definition my_contr {A : Type} [H : is_contr A] (a : A) : P A a := sorry definition foo2 (A : Type) (B : A → Type) (a : A) (x : B a) (H : Π (a : A), is_contr (B a)) --(H : is_contr (B a)) : P (B a) x := by apply (@my_contr _ _) end
daa37c5d7542fff189a5300f0d705b83c858cc26
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/discrete_category.lean
f246653059dfd64d68d3d81f944a97f2cc60d988
[ "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
5,145
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.eq_to_hom namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- A type synonym for promoting any type to a category, with the only morphisms being equalities. -/ def discrete (α : Type u₁) := α /-- The "discrete" category on a type, whose morphisms are equalities. Because we do not allow morphisms in `Prop` (only in `Type`), somewhat annoyingly we have to define `X ⟶ Y` as `ulift (plift (X = Y))`. See https://stacks.math.columbia.edu/tag/001A -/ instance discrete_category (α : Type u₁) : small_category (discrete α) := { hom := λ X Y, ulift (plift (X = Y)), id := λ X, ulift.up (plift.up rfl), comp := λ X Y Z g f, by { rcases f with ⟨⟨rfl⟩⟩, exact g } } namespace discrete variables {α : Type u₁} instance [inhabited α] : inhabited (discrete α) := by { dsimp [discrete], apply_instance } instance [subsingleton α] : subsingleton (discrete α) := by { dsimp [discrete], apply_instance } /-- Extract the equation from a morphism in a discrete category. -/ lemma eq_of_hom {X Y : discrete α} (i : X ⟶ Y) : X = Y := i.down.down @[simp] lemma id_def (X : discrete α) : ulift.up (plift.up (eq.refl X)) = 𝟙 X := rfl variables {C : Type u₂} [category.{v₂} C] instance {I : Type u₁} {i j : discrete I} (f : i ⟶ j) : is_iso f := ⟨eq_to_hom (eq_of_hom f).symm, by tidy⟩ /-- Any function `I → C` gives a functor `discrete I ⥤ C`. -/ def functor {I : Type u₁} (F : I → C) : discrete I ⥤ C := { obj := F, map := λ X Y f, begin cases f, cases f, cases f, exact 𝟙 (F X) end } @[simp] lemma functor_obj {I : Type u₁} (F : I → C) (i : I) : (discrete.functor F).obj i = F i := rfl lemma functor_map {I : Type u₁} (F : I → C) {i : discrete I} (f : i ⟶ i) : (discrete.functor F).map f = 𝟙 (F i) := by { cases f, cases f, cases f, refl } /-- For functors out of a discrete category, a natural transformation is just a collection of maps, as the naturality squares are trivial. -/ def nat_trans {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) : F ⟶ G := { app := f } @[simp] lemma nat_trans_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) (i) : (discrete.nat_trans f).app i = f i := rfl /-- For functors out of a discrete category, a natural isomorphism is just a collection of isomorphisms, as the naturality squares are trivial. -/ def nat_iso {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) : F ≅ G := nat_iso.of_components f (by tidy) @[simp] lemma nat_iso_hom_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).hom.app i = (f i).hom := rfl @[simp] lemma nat_iso_inv_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).inv.app i = (f i).inv := rfl @[simp] lemma nat_iso_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) (i : I) : (discrete.nat_iso f).app i = f i := by tidy /-- Every functor `F` from a discrete category is naturally isomorphic (actually, equal) to `discrete.functor (F.obj)`. -/ def nat_iso_functor {I : Type u₁} {F : discrete I ⥤ C} : F ≅ discrete.functor (F.obj) := nat_iso $ λ i, iso.refl _ /-- We can promote a type-level `equiv` to an equivalence between the corresponding `discrete` categories. -/ @[simps] def equivalence {I J : Type u₁} (e : I ≃ J) : discrete I ≌ discrete J := { functor := discrete.functor (e : I → J), inverse := discrete.functor (e.symm : J → I), unit_iso := discrete.nat_iso (λ i, eq_to_iso (by simp)), counit_iso := discrete.nat_iso (λ j, eq_to_iso (by simp)), } /-- We can convert an equivalence of `discrete` categories to a type-level `equiv`. -/ @[simps] def equiv_of_equivalence {α β : Type u₁} (h : discrete α ≌ discrete β) : α ≃ β := { to_fun := h.functor.obj, inv_fun := h.inverse.obj, left_inv := λ a, eq_of_hom (h.unit_iso.app a).2, right_inv := λ a, eq_of_hom (h.counit_iso.app a).1 } end discrete namespace discrete variables {J : Type v₁} open opposite /-- A discrete category is equivalent to its opposite category. -/ protected def opposite (α : Type u₁) : (discrete α)ᵒᵖ ≌ discrete α := let F : discrete α ⥤ (discrete α)ᵒᵖ := discrete.functor (λ x, op x) in begin refine equivalence.mk (functor.left_op F) F _ (discrete.nat_iso $ λ X, by simp [F]), refine nat_iso.of_components (λ X, by simp [F]) _, tidy end variables {C : Type u₂} [category.{v₂} C] @[simp] lemma functor_map_id (F : discrete J ⥤ C) {j : discrete J} (f : j ⟶ j) : F.map f = 𝟙 (F.obj j) := begin have h : f = 𝟙 j, { cases f, cases f, ext, }, rw h, simp, end end discrete end category_theory
2035e99bda98d3ef54928f8df79e9d4bebc4363b
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/envExtensionSealed.lean
248f3d72d9044064b1bf722385c6c1a0f25d68fc
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
257
lean
#lang lean4 import Lean namespace Lean def ex1 : CoreM Nat := do let env ← getEnv pure $ privateExt.getState env #eval ex1 def ex2 : CoreM Nat := do let env ← getEnv pure $ { privateExt with idx := 3 }.getState env -- Error -- #eval ex2 end Lean
3c2e87fe2b4b0549e5e296913ebdb3141a38bc50
a19a4fce1e5677f4d20cbfdf60c04b6386ab8210
/hott/types/prod.hlean
d5140792a75125480ab87c0d13762f7c94d4dc1d
[ "Apache-2.0" ]
permissive
nthomas103/lean
9c341a316e7d9faa00546462f90a8aa402e17eac
04eaf184a92606a56e54d0d6c8d59437557263fc
refs/heads/master
1,586,061,106,806
1,454,640,115,000
1,454,641,279,000
51,127,143
0
0
null
1,454,648,683,000
1,454,648,683,000
null
UTF-8
Lean
false
false
8,456
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about products -/ open eq equiv is_equiv is_trunc prod prod.ops unit equiv.ops variables {A A' B B' C D : Type} {P Q : A → Type} {a a' a'' : A} {b b₁ b₂ b' b'' : B} {u v w : A × B} namespace prod /- Paths in a product space -/ protected definition eta [unfold 3] (u : A × B) : (pr₁ u, pr₂ u) = u := by cases u; apply idp definition pair_eq [unfold 7 8] (pa : a = a') (pb : b = b') : (a, b) = (a', b') := by cases pa; cases pb; apply idp definition prod_eq [unfold 3 4 5 6] (H₁ : u.1 = v.1) (H₂ : u.2 = v.2) : u = v := by cases u; cases v; exact pair_eq H₁ H₂ definition eq_pr1 [unfold 5] (p : u = v) : u.1 = v.1 := ap pr1 p definition eq_pr2 [unfold 5] (p : u = v) : u.2 = v.2 := ap pr2 p namespace ops postfix `..1`:(max+1) := eq_pr1 postfix `..2`:(max+1) := eq_pr2 end ops open ops protected definition ap_pr1 (p : u = v) : ap pr1 p = p..1 := idp protected definition ap_pr2 (p : u = v) : ap pr2 p = p..2 := idp definition pair_prod_eq (p : u.1 = v.1) (q : u.2 = v.2) : ((prod_eq p q)..1, (prod_eq p q)..2) = (p, q) := by induction u; induction v; esimp at *; induction p; induction q; reflexivity definition prod_eq_pr1 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..1 = p := (pair_prod_eq p q)..1 definition prod_eq_pr2 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..2 = q := (pair_prod_eq p q)..2 definition prod_eq_eta (p : u = v) : prod_eq (p..1) (p..2) = p := by induction p; induction u; reflexivity -- the uncurried version of prod_eq. We will prove that this is an equivalence definition prod_eq_unc (H : u.1 = v.1 × u.2 = v.2) : u = v := by cases H with H₁ H₂;exact prod_eq H₁ H₂ definition pair_prod_eq_unc : Π(pq : u.1 = v.1 × u.2 = v.2), ((prod_eq_unc pq)..1, (prod_eq_unc pq)..2) = pq | pair_prod_eq_unc (pq₁, pq₂) := pair_prod_eq pq₁ pq₂ definition prod_eq_unc_pr1 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..1 = pq.1 := (pair_prod_eq_unc pq)..1 definition prod_eq_unc_pr2 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..2 = pq.2 := (pair_prod_eq_unc pq)..2 definition prod_eq_unc_eta (p : u = v) : prod_eq_unc (p..1, p..2) = p := prod_eq_eta p definition is_equiv_prod_eq [instance] [constructor] (u v : A × B) : is_equiv (prod_eq_unc : u.1 = v.1 × u.2 = v.2 → u = v) := adjointify prod_eq_unc (λp, (p..1, p..2)) prod_eq_unc_eta pair_prod_eq_unc definition prod_eq_equiv [constructor] (u v : A × B) : (u = v) ≃ (u.1 = v.1 × u.2 = v.2) := (equiv.mk prod_eq_unc _)⁻¹ᵉ /- Groupoid structure -/ definition prod_eq_inv (p : a = a') (q : b = b') : (prod_eq p q)⁻¹ = prod_eq p⁻¹ q⁻¹ := by cases p; cases q; reflexivity definition prod_eq_concat (p : a = a') (p' : a' = a'') (q : b = b') (q' : b' = b'') : prod_eq p q ⬝ prod_eq p' q' = prod_eq (p ⬝ p') (q ⬝ q') := by cases p; cases q; cases p'; cases q'; reflexivity /- Transport -/ definition prod_transport (p : a = a') (u : P a × Q a) : p ▸ u = (p ▸ u.1, p ▸ u.2) := by induction p; induction u; reflexivity definition prod_eq_transport (p : a = a') (q : b = b') {R : A × B → Type} (r : R (a, b)) : (prod_eq p q) ▸ r = p ▸ q ▸ r := by induction p; induction q; reflexivity /- Pathovers -/ definition etao (p : a = a') (bc : P a × Q a) : bc =[p] (p ▸ bc.1, p ▸ bc.2) := by induction p; induction bc; apply idpo definition prod_pathover (p : a = a') (u : P a × Q a) (v : P a' × Q a') (r : u.1 =[p] v.1) (s : u.2 =[p] v.2) : u =[p] v := begin induction u, induction v, esimp at *, induction r, induction s using idp_rec_on, apply idpo end /- TODO: * define the projections from the type u =[p] v * show that the uncurried version of prod_pathover is an equivalence -/ /- Functorial action -/ variables (f : A → A') (g : B → B') definition prod_functor [unfold 7] (u : A × B) : A' × B' := (f u.1, g u.2) definition ap_prod_functor (p : u.1 = v.1) (q : u.2 = v.2) : ap (prod_functor f g) (prod_eq p q) = prod_eq (ap f p) (ap g q) := by induction u; induction v; esimp at *; induction p; induction q; reflexivity /- Equivalences -/ definition is_equiv_prod_functor [instance] [constructor] [H : is_equiv f] [H : is_equiv g] : is_equiv (prod_functor f g) := begin apply adjointify _ (prod_functor f⁻¹ g⁻¹), intro u, induction u, rewrite [▸*,right_inv f,right_inv g], intro u, induction u, rewrite [▸*,left_inv f,left_inv g], end definition prod_equiv_prod_of_is_equiv [constructor] [H : is_equiv f] [H : is_equiv g] : A × B ≃ A' × B' := equiv.mk (prod_functor f g) _ definition prod_equiv_prod [constructor] (f : A ≃ A') (g : B ≃ B') : A × B ≃ A' × B' := equiv.mk (prod_functor f g) _ definition prod_equiv_prod_left [constructor] (g : B ≃ B') : A × B ≃ A × B' := prod_equiv_prod equiv.refl g definition prod_equiv_prod_right [constructor] (f : A ≃ A') : A × B ≃ A' × B := prod_equiv_prod f equiv.refl /- Symmetry -/ definition is_equiv_flip [instance] [constructor] (A B : Type) : is_equiv (flip : A × B → B × A) := adjointify flip flip (λu, destruct u (λb a, idp)) (λu, destruct u (λa b, idp)) definition prod_comm_equiv [constructor] (A B : Type) : A × B ≃ B × A := equiv.mk flip _ /- Associativity -/ definition prod_assoc_equiv [constructor] (A B C : Type) : A × (B × C) ≃ (A × B) × C := begin fapply equiv.MK, { intro z, induction z with a z, induction z with b c, exact (a, b, c)}, { intro z, induction z with z c, induction z with a b, exact (a, (b, c))}, { intro z, induction z with z c, induction z with a b, reflexivity}, { intro z, induction z with a z, induction z with b c, reflexivity}, end definition prod_contr_equiv [constructor] (A B : Type) [H : is_contr B] : A × B ≃ A := equiv.MK pr1 (λx, (x, !center)) (λx, idp) (λx, by cases x with a b; exact pair_eq idp !center_eq) definition prod_unit_equiv [constructor] (A : Type) : A × unit ≃ A := !prod_contr_equiv /- Universal mapping properties -/ definition is_equiv_prod_rec [instance] [constructor] (P : A × B → Type) : is_equiv (prod.rec : (Πa b, P (a, b)) → Πu, P u) := adjointify _ (λg a b, g (a, b)) (λg, eq_of_homotopy (λu, by induction u;reflexivity)) (λf, idp) definition equiv_prod_rec [constructor] (P : A × B → Type) : (Πa b, P (a, b)) ≃ (Πu, P u) := equiv.mk prod.rec _ definition imp_imp_equiv_prod_imp (A B C : Type) : (A → B → C) ≃ (A × B → C) := !equiv_prod_rec definition prod_corec_unc [unfold 4] {P Q : A → Type} (u : (Πa, P a) × (Πa, Q a)) (a : A) : P a × Q a := (u.1 a, u.2 a) definition is_equiv_prod_corec [constructor] (P Q : A → Type) : is_equiv (prod_corec_unc : (Πa, P a) × (Πa, Q a) → Πa, P a × Q a) := adjointify _ (λg, (λa, (g a).1, λa, (g a).2)) (by intro g; apply eq_of_homotopy; intro a; esimp; induction (g a); reflexivity) (by intro h; induction h with f g; reflexivity) definition equiv_prod_corec [constructor] (P Q : A → Type) : ((Πa, P a) × (Πa, Q a)) ≃ (Πa, P a × Q a) := equiv.mk _ !is_equiv_prod_corec definition imp_prod_imp_equiv_imp_prod [constructor] (A B C : Type) : (A → B) × (A → C) ≃ (A → (B × C)) := !equiv_prod_corec theorem is_trunc_prod (A B : Type) (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B] : is_trunc n (A × B) := begin revert A B HA HB, induction n with n IH, all_goals intro A B HA HB, { fapply is_contr.mk, exact (!center, !center), intro u, apply prod_eq, all_goals apply center_eq}, { apply is_trunc_succ_intro, intro u v, apply is_trunc_equiv_closed_rev, apply prod_eq_equiv, exact IH _ _ _ _} end end prod attribute prod.is_trunc_prod [instance] [priority 1510] definition tprod [constructor] {n : trunc_index} (A B : n-Type) : n-Type := trunctype.mk (A × B) _ infixr `×t`:30 := tprod
a71130f100a1dd9f6ef63f41e55a2de4f62948c1
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/convex/integral.lean
224b5b0f9c6e4855761c404966046f1503376b02
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
21,864
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.convex.function import analysis.convex.strict_convex_space import measure_theory.function.ae_eq_of_integral import measure_theory.integral.average /-! # Jensen's inequality for integrals In this file we prove several forms of Jensen's inequality for integrals. - for convex sets: `convex.average_mem`, `convex.set_average_mem`, `convex.integral_mem`; - for convex functions: `convex.on.average_mem_epigraph`, `convex_on.map_average_le`, `convex_on.set_average_mem_epigraph`, `convex_on.map_set_average_le`, `convex_on.map_integral_le`; - for strictly convex sets: `strict_convex.ae_eq_const_or_average_mem_interior`; - for a closed ball in a strictly convex normed space: `ae_eq_const_or_norm_integral_lt_of_norm_le_const`; - for strictly convex functions: `strict_convex_on.ae_eq_const_or_map_average_lt`. ## TODO - Use a typeclass for strict convexity of a closed ball. ## Tags convex, integral, center mass, average value, Jensen's inequality -/ open measure_theory measure_theory.measure metric set filter topological_space function open_locale topological_space big_operators ennreal convex variables {α E F : Type*} {m0 : measurable_space α} [normed_group E] [normed_space ℝ E] [complete_space E] [normed_group F] [normed_space ℝ F] [complete_space F] {μ : measure α} {s : set E} /-! ### Non-strict Jensen's inequality -/ /-- If `μ` is a probability measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the expected value of `f` belongs to `s`: `∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this lemma. -/ lemma convex.integral_mem [is_probability_measure μ] {s : set E} (hs : convex ℝ s) (hsc : is_closed s) {f : α → E} (hf : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : ∫ x, f x ∂μ ∈ s := begin borelize E, rcases hfi.ae_strongly_measurable with ⟨g, hgm, hfg⟩, haveI : separable_space (range g ∩ s : set E) := (hgm.is_separable_range.mono (inter_subset_left _ _)).separable_space, obtain ⟨y₀, h₀⟩ : (range g ∩ s).nonempty, { rcases (hf.and hfg).exists with ⟨x₀, h₀⟩, exact ⟨f x₀, by simp only [h₀.2, mem_range_self], h₀.1⟩ }, rw [integral_congr_ae hfg], rw [integrable_congr hfg] at hfi, have hg : ∀ᵐ x ∂μ, g x ∈ closure (range g ∩ s), { filter_upwards [hfg.rw (λ x y, y ∈ s) hf] with x hx, apply subset_closure, exact ⟨mem_range_self _, hx⟩ }, set G : ℕ → simple_func α E := simple_func.approx_on _ hgm.measurable (range g ∩ s) y₀ h₀, have : tendsto (λ n, (G n).integral μ) at_top (𝓝 $ ∫ x, g x ∂μ), from tendsto_integral_approx_on_of_measurable hfi _ hg _ (integrable_const _), refine hsc.mem_of_tendsto this (eventually_of_forall $ λ n, hs.sum_mem _ _ _), { exact λ _ _, ennreal.to_real_nonneg }, { rw [← ennreal.to_real_sum, (G n).sum_range_measure_preimage_singleton, measure_univ, ennreal.one_to_real], exact λ _ _, measure_ne_top _ _ }, { simp only [simple_func.mem_range, forall_range_iff], assume x, apply inter_subset_right (range g), exact simple_func.approx_on_mem hgm.measurable _ _ _ }, end /-- If `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`: `⨍ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. -/ lemma convex.average_mem [is_finite_measure μ] {s : set E} (hs : convex ℝ s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : ⨍ x, f x ∂μ ∈ s := begin haveI : is_probability_measure ((μ univ)⁻¹ • μ), from is_probability_measure_smul hμ, refine hs.integral_mem hsc (ae_mono' _ hfs) hfi.to_average, exact absolutely_continuous.smul (refl _) _ end /-- If `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`: `⨍ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. -/ lemma convex.set_average_mem {t : set α} {s : set E} (hs : convex ℝ s) (hsc : is_closed s) (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) {f : α → E} (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) : ⨍ x in t, f x ∂μ ∈ s := begin haveI : fact (μ t < ∞) := ⟨ht.lt_top⟩, refine hs.average_mem hsc _ hfs hfi, rwa [ne.def, restrict_eq_zero] end /-- If `μ` is a non-zero finite measure on `α`, `s` is a convex set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `closure s`: `⨍ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. -/ lemma convex.set_average_mem_closure {t : set α} {s : set E} (hs : convex ℝ s) (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) {f : α → E} (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) : ⨍ x in t, f x ∂μ ∈ closure s := hs.closure.set_average_mem is_closed_closure h0 ht (hfs.mono $ λ x hx, subset_closure hx) hfi lemma convex_on.average_mem_epigraph [is_finite_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : (⨍ x, f x ∂μ, ⨍ x, g (f x) ∂μ) ∈ {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2} := have ht_mem : ∀ᵐ x ∂μ, (f x, g (f x)) ∈ {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2}, from hfs.mono (λ x hx, ⟨hx, le_rfl⟩), by simpa only [average_pair hfi hgi] using hg.convex_epigraph.average_mem (hsc.epigraph hgc) hμ ht_mem (hfi.prod_mk hgi) lemma concave_on.average_mem_hypograph [is_finite_measure μ] {s : set E} {g : E → ℝ} (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : (⨍ x, f x ∂μ, ⨍ x, g (f x) ∂μ) ∈ {p : E × ℝ | p.1 ∈ s ∧ p.2 ≤ g p.1} := by simpa only [mem_set_of_eq, pi.neg_apply, average_neg, neg_le_neg_iff] using hg.neg.average_mem_epigraph hgc.neg hsc hμ hfs hfi hgi.neg /-- **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the average value of `f` is less than or equal to the average value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex_on.map_center_mass_le` for a finite sum version of this lemma. -/ lemma convex_on.map_average_le [is_finite_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : g (⨍ x, f x ∂μ) ≤ ⨍ x, g (f x) ∂μ := (hg.average_mem_epigraph hgc hsc hμ hfs hfi hgi).2 /-- **Jensen's inequality**: if a function `g : E → ℝ` is concave and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the average value of `g ∘ f` is less than or equal to the value of `g` at the average value of `f` provided that both `f` and `g ∘ f` are integrable. See also `concave_on.le_map_center_mass` for a finite sum version of this lemma. -/ lemma concave_on.le_map_average [is_finite_measure μ] {s : set E} {g : E → ℝ} (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : ⨍ x, g (f x) ∂μ ≤ g (⨍ x, f x ∂μ) := (hg.average_mem_hypograph hgc hsc hμ hfs hfi hgi).2 /-- **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points of a set `t` to `s`, then the value of `g` at the average value of `f` over `t` is less than or equal to the average value of `g ∘ f` over `t` provided that both `f` and `g ∘ f` are integrable. -/ lemma convex_on.set_average_mem_epigraph {s : set E} {g : E → ℝ} (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {t : set α} (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) {f : α → E} (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) (hgi : integrable_on (g ∘ f) t μ) : (⨍ x in t, f x ∂μ, ⨍ x in t, g (f x) ∂μ) ∈ {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2} := begin haveI : fact (μ t < ∞) := ⟨ht.lt_top⟩, refine hg.average_mem_epigraph hgc hsc _ hfs hfi hgi, rwa [ne.def, restrict_eq_zero] end /-- **Jensen's inequality**: if a function `g : E → ℝ` is concave and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points of a set `t` to `s`, then the average value of `g ∘ f` over `t` is less than or equal to the value of `g` at the average value of `f` over `t` provided that both `f` and `g ∘ f` are integrable. -/ lemma concave_on.set_average_mem_hypograph {s : set E} {g : E → ℝ} (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {t : set α} (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) {f : α → E} (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) (hgi : integrable_on (g ∘ f) t μ) : (⨍ x in t, f x ∂μ, ⨍ x in t, g (f x) ∂μ) ∈ {p : E × ℝ | p.1 ∈ s ∧ p.2 ≤ g p.1} := by simpa only [mem_set_of_eq, pi.neg_apply, average_neg, neg_le_neg_iff] using hg.neg.set_average_mem_epigraph hgc.neg hsc h0 ht hfs hfi hgi.neg /-- **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points of a set `t` to `s`, then the value of `g` at the average value of `f` over `t` is less than or equal to the average value of `g ∘ f` over `t` provided that both `f` and `g ∘ f` are integrable. -/ lemma convex_on.map_set_average_le {s : set E} {g : E → ℝ} (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {t : set α} (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) {f : α → E} (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) (hgi : integrable_on (g ∘ f) t μ) : g (⨍ x in t, f x ∂μ) ≤ ⨍ x in t, g (f x) ∂μ := (hg.set_average_mem_epigraph hgc hsc h0 ht hfs hfi hgi).2 /-- **Jensen's inequality**: if a function `g : E → ℝ` is concave and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points of a set `t` to `s`, then the average value of `g ∘ f` over `t` is less than or equal to the value of `g` at the average value of `f` over `t` provided that both `f` and `g ∘ f` are integrable. -/ lemma concave_on.le_map_set_average {s : set E} {g : E → ℝ} (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {t : set α} (h0 : μ t ≠ 0) (ht : μ t ≠ ∞) {f : α → E} (hfs : ∀ᵐ x ∂μ.restrict t, f x ∈ s) (hfi : integrable_on f t μ) (hgi : integrable_on (g ∘ f) t μ) : ⨍ x in t, g (f x) ∂μ ≤ g (⨍ x in t, f x ∂μ) := (hg.set_average_mem_hypograph hgc hsc h0 ht hfs hfi hgi).2 /-- **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the expected value of `f` is less than or equal to the expected value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex_on.map_center_mass_le` for a finite sum version of this lemma. -/ lemma convex_on.map_integral_le [is_probability_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : g (∫ x, f x ∂μ) ≤ ∫ x, g (f x) ∂μ := by simpa only [average_eq_integral] using hg.map_average_le hgc hsc (is_probability_measure.ne_zero μ) hfs hfi hgi /-- **Jensen's inequality**: if a function `g : E → ℝ` is concave and continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the expected value of `g ∘ f` is less than or equal to the value of `g` at the expected value of `f` provided that both `f` and `g ∘ f` are integrable. -/ lemma concave_on.le_map_integral [is_probability_measure μ] {s : set E} {g : E → ℝ} (hg : concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : ∫ x, g (f x) ∂μ ≤ g (∫ x, f x ∂μ) := by simpa only [average_eq_integral] using hg.le_map_average hgc hsc (is_probability_measure.ne_zero μ) hfs hfi hgi /-! ### Strict Jensen's inequality -/ /-- If `f : α → E` is an integrable function, then either it is a.e. equal to the constant `⨍ x, f x ∂μ` or there exists a measurable set such that `μ s ≠ 0`, `μ sᶜ ≠ 0`, and the average values of `f` over `s` and `sᶜ` are different. -/ lemma measure_theory.integrable.ae_eq_const_or_exists_average_ne_compl [is_finite_measure μ] {f : α → E} (hfi : integrable f μ) : (f =ᵐ[μ] const α (⨍ x, f x ∂μ)) ∨ ∃ s, measurable_set s ∧ μ s ≠ 0 ∧ μ sᶜ ≠ 0 ∧ ⨍ x in s, f x ∂μ ≠ ⨍ x in sᶜ, f x ∂μ := begin refine or_iff_not_imp_right.mpr (λ H, _), push_neg at H, refine hfi.ae_eq_of_forall_set_integral_eq _ _ (integrable_const _) (λ s hs hs', _), clear hs', simp only [const_apply, set_integral_const], by_cases h₀ : μ s = 0, { rw [restrict_eq_zero.2 h₀, integral_zero_measure, h₀, ennreal.zero_to_real, zero_smul] }, by_cases h₀' : μ sᶜ = 0, { rw ← ae_eq_univ at h₀', rw [restrict_congr_set h₀', restrict_univ, measure_congr h₀', measure_smul_average] }, have := average_mem_open_segment_compl_self hs.null_measurable_set h₀ h₀' hfi, rw [← H s hs h₀ h₀', open_segment_same, mem_singleton_iff] at this, rw [this, measure_smul_set_average _ (measure_ne_top μ _)] end /-- If an integrable function `f : α → E` takes values in a convex set `s` and for some set `t` of positive measure, the average value of `f` over `t` belongs to the interior of `s`, then the average of `f` over the whole space belongs to the interior of `s`. -/ lemma convex.average_mem_interior_of_set [is_finite_measure μ] {t : set α} {s : set E} (hs : convex ℝ s) (h0 : μ t ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (ht : ⨍ x in t, f x ∂μ ∈ interior s) : ⨍ x, f x ∂μ ∈ interior s := begin rw ← measure_to_measurable at h0, rw ← restrict_to_measurable (measure_ne_top μ t) at ht, by_cases h0' : μ (to_measurable μ t)ᶜ = 0, { rw ← ae_eq_univ at h0', rwa [restrict_congr_set h0', restrict_univ] at ht }, exact hs.open_segment_interior_closure_subset_interior ht (hs.set_average_mem_closure h0' (measure_ne_top _ _) (ae_restrict_of_ae hfs) hfi.integrable_on) (average_mem_open_segment_compl_self (measurable_set_to_measurable μ t).null_measurable_set h0 h0' hfi) end /-- If an integrable function `f : α → E` takes values in a strictly convex closed set `s`, then either it is a.e. equal to its average value, or its average value belongs to the interior of `s`. -/ lemma strict_convex.ae_eq_const_or_average_mem_interior [is_finite_measure μ] {s : set E} (hs : strict_convex ℝ s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : f =ᵐ[μ] const α (⨍ x, f x ∂μ) ∨ ⨍ x, f x ∂μ ∈ interior s := begin have : ∀ {t}, μ t ≠ 0 → ⨍ x in t, f x ∂μ ∈ s, from λ t ht, hs.convex.set_average_mem hsc ht (measure_ne_top _ _) (ae_restrict_of_ae hfs) hfi.integrable_on, refine hfi.ae_eq_const_or_exists_average_ne_compl.imp_right _, rintro ⟨t, hm, h₀, h₀', hne⟩, exact hs.open_segment_subset (this h₀) (this h₀') hne (average_mem_open_segment_compl_self hm.null_measurable_set h₀ h₀' hfi) end /-- **Jensen's inequality**, strict version: if an integrable function `f : α → E` takes values in a convex closed set `s`, and `g : E → ℝ` is continuous and strictly convex on `s`, then either `f` is a.e. equal to its average value, or `g (⨍ x, f x ∂μ) < ⨍ x, g (f x) ∂μ`. -/ lemma strict_convex_on.ae_eq_const_or_map_average_lt [is_finite_measure μ] {s : set E} {g : E → ℝ} (hg : strict_convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : f =ᵐ[μ] const α (⨍ x, f x ∂μ) ∨ g (⨍ x, f x ∂μ) < ⨍ x, g (f x) ∂μ := begin have : ∀ {t}, μ t ≠ 0 → ⨍ x in t, f x ∂μ ∈ s ∧ g (⨍ x in t, f x ∂μ) ≤ ⨍ x in t, g (f x) ∂μ, from λ t ht, hg.convex_on.set_average_mem_epigraph hgc hsc ht (measure_ne_top _ _) (ae_restrict_of_ae hfs) hfi.integrable_on hgi.integrable_on, refine hfi.ae_eq_const_or_exists_average_ne_compl.imp_right _, rintro ⟨t, hm, h₀, h₀', hne⟩, rcases average_mem_open_segment_compl_self hm.null_measurable_set h₀ h₀' (hfi.prod_mk hgi) with ⟨a, b, ha, hb, hab, h_avg⟩, simp only [average_pair hfi hgi, average_pair hfi.integrable_on hgi.integrable_on, prod.smul_mk, prod.mk_add_mk, prod.mk.inj_iff, (∘)] at h_avg, rw [← h_avg.1, ← h_avg.2], calc g (a • ⨍ x in t, f x ∂μ + b • ⨍ x in tᶜ, f x ∂μ) < a * g (⨍ x in t, f x ∂μ) + b * g (⨍ x in tᶜ, f x ∂μ) : hg.2 (this h₀).1 (this h₀').1 hne ha hb hab ... ≤ a * ⨍ x in t, g (f x) ∂μ + b * ⨍ x in tᶜ, g (f x) ∂μ : add_le_add (mul_le_mul_of_nonneg_left (this h₀).2 ha.le) (mul_le_mul_of_nonneg_left (this h₀').2 hb.le) end /-- **Jensen's inequality**, strict version: if an integrable function `f : α → E` takes values in a convex closed set `s`, and `g : E → ℝ` is continuous and strictly concave on `s`, then either `f` is a.e. equal to its average value, or `⨍ x, g (f x) ∂μ < g (⨍ x, f x ∂μ)`. -/ lemma strict_concave_on.ae_eq_const_or_lt_map_average [is_finite_measure μ] {s : set E} {g : E → ℝ} (hg : strict_concave_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : f =ᵐ[μ] const α (⨍ x, f x ∂μ) ∨ ⨍ x, g (f x) ∂μ < g (⨍ x, f x ∂μ) := by simpa only [pi.neg_apply, average_neg, neg_lt_neg_iff] using hg.neg.ae_eq_const_or_map_average_lt hgc.neg hsc hfs hfi hgi.neg /-- If `E` is a strictly normed space and `f : α → E` is a function such that `∥f x∥ ≤ C` a.e., then either this function is a.e. equal to its average value, or the norm of its average value is strictly less than `C`. -/ lemma ae_eq_const_or_norm_average_lt_of_norm_le_const [strict_convex_space ℝ E] {f : α → E} {C : ℝ} (h_le : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : (f =ᵐ[μ] const α ⨍ x, f x ∂μ) ∨ ∥⨍ x, f x ∂μ∥ < C := begin cases le_or_lt C 0 with hC0 hC0, { have : f =ᵐ[μ] 0, from h_le.mono (λ x hx, norm_le_zero_iff.1 (hx.trans hC0)), simp only [average_congr this, pi.zero_apply, average_zero], exact or.inl this }, by_cases hfi : integrable f μ, swap, by simp [average_def', integral_undef hfi, hC0, ennreal.to_real_pos_iff], cases (le_top : μ univ ≤ ∞).eq_or_lt with hμt hμt, { simp [average_def', hμt, hC0] }, haveI : is_finite_measure μ := ⟨hμt⟩, replace h_le : ∀ᵐ x ∂μ, f x ∈ closed_ball (0 : E) C, by simpa only [mem_closed_ball_zero_iff], simpa only [interior_closed_ball _ hC0.ne', mem_ball_zero_iff] using (strict_convex_closed_ball ℝ (0 : E) C).ae_eq_const_or_average_mem_interior is_closed_ball h_le hfi end /-- If `E` is a strictly normed space and `f : α → E` is a function such that `∥f x∥ ≤ C` a.e., then either this function is a.e. equal to its average value, or the norm of its integral is strictly less than `(μ univ).to_real * C`. -/ lemma ae_eq_const_or_norm_integral_lt_of_norm_le_const [strict_convex_space ℝ E] [is_finite_measure μ] {f : α → E} {C : ℝ} (h_le : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : (f =ᵐ[μ] const α ⨍ x, f x ∂μ) ∨ ∥∫ x, f x ∂μ∥ < (μ univ).to_real * C := begin cases eq_or_ne μ 0 with h₀ h₀, { left, simp [h₀] }, have hμ : 0 < (μ univ).to_real, by simp [ennreal.to_real_pos_iff, pos_iff_ne_zero, h₀, measure_lt_top], refine (ae_eq_const_or_norm_average_lt_of_norm_le_const h_le).imp_right (λ H, _), rwa [average_def', norm_smul, norm_inv, real.norm_eq_abs, abs_of_pos hμ, ← div_eq_inv_mul, div_lt_iff' hμ] at H end
5bd6aa3e600223a53c5ae20d1dea266f6a9f204c
4727251e0cd73359b15b664c3170e5d754078599
/src/data/finsupp/pwo.lean
0334cc2d8fcd6a293d8f537b8c4dfef4f9ae8ee8
[ "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
1,294
lean
/- Copyright (c) 2022 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best -/ import data.finsupp.order import order.well_founded_set /-! # Partial well ordering on finsupps This file contains the fact that finitely supported functions from a fintype are partially well ordered when the codomain is a linear order that is well ordered. It is in a separate file for now so as to not add imports to the file `order.well_founded_set`. ## Main statements * `finsupp.is_pwo` - finitely supported functions from a fintype are partially well ordered when the codomain is a linear order that is well ordered ## Tags Dickson, order, partial well order -/ /-- A version of **Dickson's lemma** any subset of functions `σ →₀ α` is partially well ordered, when `σ` is a `fintype` and `α` is a linear well order. This version uses finsupps on a fintype as it is intended for use with `mv_power_series`. -/ lemma finsupp.is_pwo {α σ : Type*} [has_zero α] [linear_order α] [is_well_order α (<)] [fintype σ] (S : set (σ →₀ α)) : S.is_pwo := begin rw ← finsupp.equiv_fun_on_fintype.symm.image_preimage S, refine set.partially_well_ordered_on.image_of_monotone_on (pi.is_pwo _) (λ a b ha hb, id), end
849a6aca3d1ee6acc54336ac46f292a9361ce3a9
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/module.lean
5de639beb1be526d750dd3da5f669826d85ddbaf
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
24,661
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro Modules over a ring. ## Implementation notes Throughout the `linear_map` section implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `linear_map`. When they can be inferred from the type it is faster to use this method than to use type class inference -/ import algebra.ring algebra.big_operators group_theory.subgroup group_theory.group_action open function universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} -- /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ -- class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) -- infixr ` • `:73 := has_scalar.smul section prio set_option default_priority 100 -- see Note [default priority] /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class semimodule (α : Type u) (β : Type v) [semiring α] [add_comm_monoid β] extends distrib_mul_action α β := (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (zero_smul : ∀x : β, (0 : α) • x = 0) end prio section semimodule variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β) include R theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (α) @[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul x variable {α} lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : x = 0 := by rw [←one_smul α x, ←zero_eq_one, zero_smul] instance smul.is_add_monoid_hom (x : β) : is_add_monoid_hom (λ r:α, r • x) := { map_zero := zero_smul _ x, map_add := λ r₁ r₂, add_smul r₁ r₂ x } lemma list.sum_smul {l : list α} {x : β} : l.sum • x = (l.map (λ r, r • x)).sum := show (λ r, r • x) l.sum = (l.map (λ r, r • x)).sum, from (list.sum_hom _ _).symm lemma multiset.sum_smul {l : multiset α} {x : β} : l.sum • x = (l.map (λ r, r • x)).sum := show (λ r, r • x) l.sum = (l.map (λ r, r • x)).sum, from (multiset.sum_hom _ _).symm lemma finset.sum_smul {f : γ → α} {s : finset γ} {x : β} : s.sum f • x = s.sum (λ r, (f r) • x) := show (λ r, r • x) (s.sum f) = s.sum (λ r, (f r) • x), from (finset.sum_hom _ _).symm end semimodule section prio set_option default_priority 100 -- see Note [default priority] /-- A module is a generalization of vector spaces to a scalar ring. It consists of a scalar ring `α` and an additive group of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β end prio /-- To prove two module structures on a fixed `add_comm_group` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `module ℤ M` is a subsingleton. @[ext] lemma module_ext {R : Type*} [ring R] {M : Type*} [add_comm_group M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin resetI, rcases P with ⟨⟨⟨⟨⟨P⟩⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨⟨Q⟩⟩⟩⟩⟩, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) /-- Define `module` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `module.core`. -/ def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β := by letI := M.to_has_scalar; exact { zero_smul := λ x, have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp, add_left_cancel this, smul_zero := λ r, have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp, add_left_cancel this, ..M } section module variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (α) theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp variables {α} @[simp] theorem smul_neg : r • (-x) = -(r • x) := by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by simp [smul_add, sub_eq_add_neg]; rw smul_neg theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E] {c : R} {x : E} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨λ h, classical.by_cases or.inl (λ hc, or.inr $ by rw [← one_smul R x, ← inv_mul_cancel hc, mul_smul, h, smul_zero]), λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩ end module instance semiring.to_semimodule [r : semiring α] : semimodule α α := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero, ..r } @[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl instance ring.to_module [r : ring α] : module α α := { ..semiring.to_semimodule } /-- A ring homomorphism `f : α →+* β` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_module [ring α] [ring β] (f : α →+* β) : module α β := module.of_core { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul] } class is_linear_map (α : Type u) {β : Type v} {γ : Type w} [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] (f : β → γ) : Prop := (add [] : ∀ x y, f (x + y) = f x + f y) (smul [] : ∀ (c : α) x, f (c • x) = c • f x) structure linear_map (α : Type u) (β : Type v) (γ : Type w) [ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] := (to_fun : β → γ) (add : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation β ` →ₗ[`:25 α:25 `] `:0 γ:0 := linear_map α β γ namespace linear_map variables {rα : ring α} {gβ : add_comm_group β} {gγ : add_comm_group γ} {gδ : add_comm_group δ} variables {mβ : module α β} {mγ : module α γ} {mδ : module α δ} variables (f g : β →ₗ[α] γ) include α mβ mγ instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : β → γ) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : β →ₗ[α] γ) : β → γ) = f := rfl @[simp] lemma to_fun_eq_coe (f : β →ₗ[α] γ) : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map α f := {..f} @[ext] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x := ⟨by rintro rfl; simp, ext⟩ @[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y @[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul α, map_smul f 0 0, zero_smul] instance : is_add_group_hom f := { map_add := map_add f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom (f : β →ₗ[α] γ) : β →+ γ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe (f : β →ₗ[α] γ) : ((f.to_add_monoid_hom) : β → γ) = (f : β → γ) := rfl @[simp] lemma map_neg (x : β) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} : f (t.sum g) = t.sum (λi, f (g i)) := f.to_add_monoid_hom.map_sum _ _ include mδ /-- Composition of two linear maps is a linear map -/ def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl omit mγ mδ variables [rα] [gβ] [mβ] /-- Identity map as a `linear_map` -/ def id : β →ₗ[α] β := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ @[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl end linear_map namespace is_linear_map variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] include α /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H} @[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) : mk' f H x = f x := rfl lemma is_linear_map_neg : is_linear_map α (λ (z : β), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) lemma is_linear_map_smul {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (c : R) : is_linear_map R (λ (z : α), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp [smul_smul], ac_refl end --TODO: move lemma is_linear_map_smul' {α R : Type*} [add_comm_group α] [ring R] [module R α] (a : α) : is_linear_map R (λ (c : R), c • a) := begin refine is_linear_map.mk (λ x y, add_smul x y a) _, intros _ _, simp [smul_smul] end variables {f : β → γ} (lin : is_linear_map α f) include β γ lin lemma map_zero : f (0 : β) = (0 : γ) := (lin.mk' f).map_zero lemma map_add : ∀ x y, f (x + y) = f x + f y := lin.add lemma map_neg (x : β) : 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 lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := (lin.mk' f).map_smul c x end is_linear_map abbreviation module.End (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] := M →ₗ[R] M /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (α : Type u) (β : Type v) [ring α] [add_comm_group β] [module α β] : Type v := (carrier : set β) (zero : (0:β) ∈ carrier) (add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier) (smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier) namespace submodule variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] variables (p p' : submodule α β) variables {r : α} {x y : β} instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩ instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩ @[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t := by cases s; cases t; congr' protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t := ⟨ext', λ h, h ▸ rfl⟩ @[ext] theorem ext {s t : submodule α β} (h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h @[simp] lemma zero_mem : (0 : β) ∈ p := p.zero lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂ lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy) lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by simpa using neg_mem p h, neg_mem p⟩ lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩ lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p := ⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩ lemma sum_mem {ι : Type w} {t : finset ι} {f : ι → β} : (∀c∈t, f c ∈ p) → t.sum f ∈ p := begin classical, exact finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt}) end lemma smul_mem_iff' (u : units α) : (u:α) • x ∈ p ↔ x ∈ p := ⟨λ h, by simpa only [smul_smul, u.inv_mul, one_smul] using p.smul_mem ↑u⁻¹ h, p.smul_mem u⟩ instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩ @[simp, move_cast] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl @[simp, elim_cast] lemma coe_zero : ((0 : p) : β) = 0 := rfl @[simp, move_cast] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl @[simp, move_cast] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl @[simp, elim_cast] lemma coe_mk (x : β) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : β) = x := rfl @[simp] protected lemma eta (x : p) (hx : (x : β) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx instance : add_comm_group p := by refine {add := (+), zero := 0, neg := has_neg.neg, ..}; { intros, apply set_coe.ext, simp [add_comm, add_left_comm] } instance submodule_is_add_subgroup : is_add_subgroup (p : set β) := { zero_mem := p.zero, add_mem := p.add, neg_mem := λ _, p.neg_mem } @[simp, move_cast] lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := rfl instance : module α p := by refine {smul := (•), ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } protected def subtype : p →ₗ[α] β := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val (p : submodule α β) : ((submodule.subtype p) : p → β) = subtype.val := rfl end submodule @[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _ lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h end ideal /-- Vector spaces are defined as an `abbreviation` for modules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparant for type class inference, which means that all instances for modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces an sich, in definitions such as `normed_space`. The solution is to extend `module` instead. -/ library_note "vector space definition" /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ abbreviation vector_space (α : Type u) (β : Type v) [field α] [add_comm_group β] := module α β instance field.to_vector_space {α : Type*} [field α] : vector_space α α := { .. ring.to_module } /-- Subspace of a vector space. Defined to equal `submodule`. -/ @[reducible] def subspace (α : Type u) (β : Type v) [field α] [add_comm_group β] [vector_space α β] : Type v := submodule α β instance subspace.vector_space {α β} {f : field α} [add_comm_group β] [vector_space α β] (p : subspace α β) : vector_space α p := {..submodule.module p} namespace submodule variables {R : division_ring α} [add_comm_group β] [module α β] variables (p : submodule α β) {r : α} {x y : β} include R set_option class.instance_max_depth 36 theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p := p.smul_mem_iff' (units.mk0 r r0) end submodule namespace add_comm_monoid open add_monoid variables {M : Type*} [add_comm_monoid M] /-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/ -- We don't make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℕ`. def nat_semimodule : semimodule ℕ M := { smul := smul, smul_add := λ _ _ _, smul_add _ _ _, add_smul := λ _ _ _, add_smul _ _ _, mul_smul := λ _ _ _, mul_smul _ _ _, one_smul := one_smul, zero_smul := zero_smul, smul_zero := smul_zero } end add_comm_monoid namespace add_comm_group variables {M : Type*} [add_comm_group M] /-- The natural ℤ-module structure on any `add_comm_group`. -/ -- We don't immediately make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℤ`. -- We do turn it into a global instance, but only at the end of this file, -- and I remain dubious whether this is a good idea. def int_module : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } instance : subsingleton (module ℤ M) := begin split, intros P Q, ext, -- isn't that lovely: `r • m = r • m` have one_smul : by { haveI := P, exact (1 : ℤ) • m } = by { haveI := Q, exact (1 : ℤ) • m }, begin rw [@one_smul ℤ _ _ (by { haveI := P, apply_instance, }) m], rw [@one_smul ℤ _ _ (by { haveI := Q, apply_instance, }) m], end, have nat_smul : ∀ n : ℕ, by { haveI := P, exact (n : ℤ) • m } = by { haveI := Q, exact (n : ℤ) • m }, begin intro n, induction n with n ih, { erw [zero_smul, zero_smul], }, { rw [int.coe_nat_succ, add_smul, add_smul], erw ih, rw [one_smul], } end, cases r, { rw [int.of_nat_eq_coe, nat_smul], }, { rw [int.neg_succ_of_nat_coe, neg_smul, neg_smul, nat_smul], } end end add_comm_group section local attribute [instance] add_comm_monoid.nat_semimodule lemma semimodule.smul_eq_smul (R : Type*) [semiring R] {β : Type*} [add_comm_group β] [semimodule R β] (n : ℕ) (b : β) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { change (n + 1) • b = (n + 1 : R) • b, rw [add_smul, add_smul, one_smul, ih, one_smul] } end lemma semimodule.add_monoid_smul_eq_smul (R : Type*) [semiring R] {β : Type*} [add_comm_group β] [semimodule R β] (n : ℕ) (b : β) : add_monoid.smul n b = (n : R) • b := semimodule.smul_eq_smul R n b lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) : n • x = add_monoid.smul n x := rfl end section local attribute [instance] add_comm_group.int_module lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl lemma module.gsmul_eq_smul_cast (R : Type*) [ring R] {β : Type*} [add_comm_group β] [module R β] (n : ℤ) (b : β) : gsmul n b = (n : R) • b := begin cases n, { apply semimodule.add_monoid_smul_eq_smul, }, { dsimp, rw semimodule.add_monoid_smul_eq_smul R, push_cast, rw neg_smul, } end lemma module.gsmul_eq_smul {β : Type*} [add_comm_group β] [module ℤ β] (n : ℤ) (b : β) : gsmul n b = n • b := by rw [module.gsmul_eq_smul_cast ℤ, int.cast_id] end -- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here -- come from whatever the local `module ℤ` structure actually is. lemma add_monoid_hom.map_int_module_smul {α : Type*} {β : Type*} [add_comm_group α] [add_comm_group β] [module ℤ α] [module ℤ β] (f : α →+ β) (x : ℤ) (a : α) : f (x • a) = x • f a := by simp only [← module.gsmul_eq_smul, f.map_gsmul] lemma add_monoid_hom.map_int_cast_smul {R : Type*} [ring R] {α : Type*} {β : Type*} [add_comm_group α] [add_comm_group β] [module R α] [module R β] (f : α →+ β) (x : ℤ) (a : α) : f ((x : R) • a) = (x : R) • f a := by simp only [← module.gsmul_eq_smul_cast, f.map_gsmul] lemma add_monoid_hom.map_nat_cast_smul {R : Type*} [semiring R] {α : Type*} {β : Type*} [add_comm_group α] [add_comm_group β] [semimodule R α] [semimodule R β] (f : α →+ β) (x : ℕ) (a : α) : f ((x : R) • a) = (x : R) • f a := by simp only [← semimodule.add_monoid_smul_eq_smul, f.map_smul] lemma add_monoid_hom.map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma add_monoid_hom.map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x -- We finally turn on these instances globally: attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group α] [add_comm_group β] (f : α →+ β) : α →ₗ[ℤ] β := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group α] [vector_space ℚ α] [add_comm_group β] [vector_space ℚ β] (f : α →+ β) : α →ₗ[ℚ] β := ⟨f, f.map_add, f.map_rat_module_smul⟩ namespace finset lemma sum_const' {α : Type*} (R : Type*) [ring R] {β : Type*} [add_comm_group β] [module R β] {s : finset α} (b : β) : finset.sum s (λ (a : α), b) = (finset.card s : R) • b := by rw [finset.sum_const, ← semimodule.smul_eq_smul]; refl variables {M : Type*} [decidable_linear_ordered_cancel_add_comm_monoid M] {s : finset α} (f : α → M) theorem exists_card_smul_le_sum (hs : s.nonempty) : ∃ i ∈ s, s.card • f i ≤ s.sum f := exists_le_of_sum_le hs $ by rw [sum_const, ← nat.smul_def, smul_sum] theorem exists_card_smul_ge_sum (hs : s.nonempty) : ∃ i ∈ s, s.sum f ≤ s.card • f i := exists_le_of_sum_le hs $ by rw [sum_const, ← nat.smul_def, smul_sum] end finset
cc890b4e403b93c67da042b3464aa8d962cf276c
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/homotopy/chain_complex.hlean
f77195bbe1afcae3f514f624f8d82ef812cbea9e
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
21,332
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Chain complexes. We define chain complexes in a general way as a sequence X of types indexes over an arbitrary type N with a successor S. There are maps X (S n) → X n for n : N. We can vary N to have chain complexes indexed by ℕ, ℤ, a finite type or something else, and for both ℕ and ℤ we can choose the maps to go up or down. We also use the indexing ℕ × 3 for the LES of homotopy groups, because then it computes better (see [LES_of_homotopy_groups]). We have two separate notions of chain complexes: - type_chain_complex: sequence of types, where exactness is formulated using pure existence. - chain_complex: sequence of sets, where exactness is formulated using mere existence. -/ import types.int algebra.group_theory types.fin open eq pointed int unit is_equiv equiv is_trunc trunc function algebra group sigma.ops sum prod nat bool fin structure succ_str : Type := (carrier : Type) (succ : carrier → carrier) attribute succ_str.carrier [coercion] definition succ_str.S {X : succ_str} : X → X := succ_str.succ X open succ_str definition snat [reducible] [constructor] : succ_str := succ_str.mk ℕ nat.succ definition snat' [reducible] [constructor] : succ_str := succ_str.mk ℕ nat.pred definition sint [reducible] [constructor] : succ_str := succ_str.mk ℤ int.succ definition sint' [reducible] [constructor] : succ_str := succ_str.mk ℤ int.pred notation `+ℕ` := snat notation `-ℕ` := snat' notation `+ℤ` := sint notation `-ℤ` := sint' definition stratified_type [reducible] (N : succ_str) (n : ℕ) : Type₀ := N × fin (succ n) definition stratified_succ {N : succ_str} {n : ℕ} (x : stratified_type N n) : stratified_type N n := (if val (pr2 x) = n then S (pr1 x) else pr1 x, cyclic_succ (pr2 x)) definition stratified [reducible] [constructor] (N : succ_str) (n : ℕ) : succ_str := succ_str.mk (stratified_type N n) stratified_succ notation `+3ℕ` := stratified +ℕ 2 notation `-3ℕ` := stratified -ℕ 2 notation `+3ℤ` := stratified +ℤ 2 notation `-3ℤ` := stratified -ℤ 2 notation `+6ℕ` := stratified +ℕ 5 notation `-6ℕ` := stratified -ℕ 5 notation `+6ℤ` := stratified +ℤ 5 notation `-6ℤ` := stratified -ℤ 5 namespace chain_complex /- We define "type chain complexes" which are chain complexes without the "set"-requirement. Exactness is formulated without propositional truncation. -/ structure type_chain_complex (N : succ_str) : Type := (car : N → Type*) (fn : Π(n : N), car (S n) →* car n) (is_chain_complex : Π(n : N) (x : car (S (S n))), fn n (fn (S n) x) = pt) section variables {N : succ_str} (X : type_chain_complex N) (n : N) definition tcc_to_car [unfold 2] [coercion] := @type_chain_complex.car definition tcc_to_fn [unfold 2] : X (S n) →* X n := type_chain_complex.fn X n definition tcc_is_chain_complex [unfold 2] : Π(x : X (S (S n))), tcc_to_fn X n (tcc_to_fn X (S n) x) = pt := type_chain_complex.is_chain_complex X n -- important: these notions are shifted by one! (this is to avoid transports) definition is_exact_at_t [reducible] /- X n -/ : Type := Π(x : X (S n)), tcc_to_fn X n x = pt → fiber (tcc_to_fn X (S n)) x definition is_exact_t [reducible] /- X -/ : Type := Π(n : N), is_exact_at_t X n -- A chain complex on +ℕ can be trivially extended to a chain complex on +ℤ definition type_chain_complex_from_left (X : type_chain_complex +ℕ) : type_chain_complex +ℤ := type_chain_complex.mk (int.rec X (λn, punit)) begin intro n, fconstructor, { induction n with n n, { exact tcc_to_fn X n}, { esimp, intro x, exact star}}, { induction n with n n, { apply respect_pt}, { reflexivity}} end begin intro n, induction n with n n, { exact tcc_is_chain_complex X n}, { esimp, intro x, reflexivity} end definition is_exact_t_from_left {X : type_chain_complex +ℕ} {n : ℕ} (H : is_exact_at_t X n) : is_exact_at_t (type_chain_complex_from_left X) (of_nat n) := H /- Given a natural isomorphism between a chain complex and any other sequence, we can give the other sequence the structure of a chain complex, which is exact at the positions where the original sequence is. -/ definition transfer_type_chain_complex [constructor] /- X -/ {Y : N → Type*} (g : Π{n : N}, Y (S n) →* Y n) (e : Π{n}, X n ≃* Y n) (p : Π{n} (x : X (S n)), e (tcc_to_fn X n x) = g (e x)) : type_chain_complex N := type_chain_complex.mk Y @g abstract begin intro n, apply equiv_rect (equiv_of_pequiv e), intro x, refine ap g (p x)⁻¹ ⬝ _, refine (p _)⁻¹ ⬝ _, refine ap e (tcc_is_chain_complex X n _) ⬝ _, apply respect_pt end end theorem is_exact_at_t_transfer {X : type_chain_complex N} {Y : N → Type*} {g : Π{n : N}, Y (S n) →* Y n} (e : Π{n}, X n ≃* Y n) (p : Π{n} (x : X (S n)), e (tcc_to_fn X n x) = g (e x)) {n : N} (H : is_exact_at_t X n) : is_exact_at_t (transfer_type_chain_complex X @g @e @p) n := begin intro y q, esimp at *, have H2 : tcc_to_fn X n (e⁻¹ᵉ* y) = pt, begin refine (inv_commute (λn, equiv_of_pequiv e) _ _ @p _)⁻¹ᵖ ⬝ _, refine ap _ q ⬝ _, exact respect_pt e⁻¹ᵉ* end, cases (H _ H2) with x r, refine fiber.mk (e x) _, refine (p x)⁻¹ ⬝ _, refine ap e r ⬝ _, apply right_inv end /- We want a theorem which states that if we have a chain complex, but with some where the maps are composed by an equivalences, we want to remove this equivalence. The following two theorems give sufficient conditions for when this is allowed. We use this to transform the LES of homotopy groups where on the odd levels we have maps -πₙ(...) into the LES of homotopy groups where we remove the minus signs (which represents composition with path inversion). -/ definition type_chain_complex_cancel_aut [constructor] /- X -/ (g : Π{n : N}, X (S n) →* X n) (e : Π{n}, X n ≃* X n) (r : Π{n}, X n →* X n) (p : Π{n : N} (x : X (S n)), g (e x) = tcc_to_fn X n x) (pr : Π{n : N} (x : X (S n)), g x = r (g (e x))) : type_chain_complex N := type_chain_complex.mk X @g abstract begin have p' : Π{n : N} (x : X (S n)), g x = tcc_to_fn X n (e⁻¹ x), from λn, homotopy_inv_of_homotopy_pre e _ _ p, intro n x, refine ap g !p' ⬝ !pr ⬝ _, refine ap r !p ⬝ _, refine ap r (tcc_is_chain_complex X n _) ⬝ _, apply respect_pt end end theorem is_exact_at_t_cancel_aut {X : type_chain_complex N} {g : Π{n : N}, X (S n) →* X n} {e : Π{n}, X n ≃* X n} {r : Π{n}, X n →* X n} (l : Π{n}, X n →* X n) (p : Π{n : N} (x : X (S n)), g (e x) = tcc_to_fn X n x) (pr : Π{n : N} (x : X (S n)), g x = r (g (e x))) (pl : Π{n : N} (x : X (S n)), g (l x) = e (g x)) (H : is_exact_at_t X n) : is_exact_at_t (type_chain_complex_cancel_aut X @g @e @r @p @pr) n := begin intro y q, esimp at *, have H2 : tcc_to_fn X n (e⁻¹ y) = pt, from (homotopy_inv_of_homotopy_pre e _ _ p _)⁻¹ ⬝ q, cases (H _ H2) with x s, refine fiber.mk (l (e x)) _, refine !pl ⬝ _, refine ap e (!p ⬝ s) ⬝ _, apply right_inv end /- A more general transfer theorem. Here the base type can also change by an equivalence. -/ definition transfer_type_chain_complex2 [constructor] {M : succ_str} {Y : M → Type*} (f : M ≃ N) (c : Π(m : M), S (f m) = f (S m)) (g : Π{m : M}, Y (S m) →* Y m) (e : Π{m}, X (f m) ≃* Y m) (p : Π{m} (x : X (S (f m))), e (tcc_to_fn X (f m) x) = g (e (cast (ap (λx, X x) (c m)) x))) : type_chain_complex M := type_chain_complex.mk Y @g begin intro m, apply equiv_rect (equiv_of_pequiv e), apply equiv_rect (equiv_of_eq (ap (λx, X x) (c (S m)))), esimp, apply equiv_rect (equiv_of_eq (ap (λx, X (S x)) (c m))), esimp, intro x, refine ap g (p _)⁻¹ ⬝ _, refine ap g (ap e (fn_cast_eq_cast_fn (c m) (tcc_to_fn X) x)) ⬝ _, refine (p _)⁻¹ ⬝ _, refine ap e (tcc_is_chain_complex X (f m) _) ⬝ _, apply respect_pt end definition is_exact_at_t_transfer2 {X : type_chain_complex N} {M : succ_str} {Y : M → Type*} (f : M ≃ N) (c : Π(m : M), S (f m) = f (S m)) (g : Π{m : M}, Y (S m) →* Y m) (e : Π{m}, X (f m) ≃* Y m) (p : Π{m} (x : X (S (f m))), e (tcc_to_fn X (f m) x) = g (e (cast (ap (λx, X x) (c m)) x))) {m : M} (H : is_exact_at_t X (f m)) : is_exact_at_t (transfer_type_chain_complex2 X f c @g @e @p) m := begin intro y q, esimp at *, have H2 : tcc_to_fn X (f m) ((equiv_of_eq (ap (λx, X x) (c m)))⁻¹ᵉ (e⁻¹ y)) = pt, begin refine _ ⬝ ap e⁻¹ᵉ* q ⬝ (respect_pt (e⁻¹ᵉ*)), apply eq_inv_of_eq, clear q, revert y, apply inv_homotopy_of_homotopy_pre e, apply inv_homotopy_of_homotopy_pre, apply p end, induction (H _ H2) with x r, refine fiber.mk (e (cast (ap (λx, X x) (c (S m))) (cast (ap (λx, X (S x)) (c m)) x))) _, refine (p _)⁻¹ ⬝ _, refine ap e (fn_cast_eq_cast_fn (c m) (tcc_to_fn X) x) ⬝ _, refine ap (λx, e (cast _ x)) r ⬝ _, esimp [equiv.symm], rewrite [-ap_inv], refine ap e !cast_cast_inv ⬝ _, apply right_inv end end /- actual (set) chain complexes -/ structure chain_complex (N : succ_str) : Type := (car : N → Set*) (fn : Π(n : N), car (S n) →* car n) (is_chain_complex : Π(n : N) (x : car (S (S n))), fn n (fn (S n) x) = pt) section variables {N : succ_str} (X : chain_complex N) (n : N) definition cc_to_car [unfold 2] [coercion] := @chain_complex.car definition cc_to_fn [unfold 2] : X (S n) →* X n := @chain_complex.fn N X n definition cc_is_chain_complex [unfold 2] : Π(x : X (S (S n))), cc_to_fn X n (cc_to_fn X (S n) x) = pt := @chain_complex.is_chain_complex N X n -- important: these notions are shifted by one! (this is to avoid transports) definition is_exact_at [reducible] /- X n -/ : Type := Π(x : X (S n)), cc_to_fn X n x = pt → image (cc_to_fn X (S n)) x definition is_exact [reducible] /- X -/ : Type := Π(n : N), is_exact_at X n definition chain_complex_from_left (X : chain_complex +ℕ) : chain_complex +ℤ := chain_complex.mk (int.rec X (λn, punit)) begin intro n, fconstructor, { induction n with n n, { exact cc_to_fn X n}, { esimp, intro x, exact star}}, { induction n with n n, { apply respect_pt}, { reflexivity}} end begin intro n, induction n with n n, { exact cc_is_chain_complex X n}, { esimp, intro x, reflexivity} end definition is_exact_from_left {X : chain_complex +ℕ} {n : ℕ} (H : is_exact_at X n) : is_exact_at (chain_complex_from_left X) (of_nat n) := H definition transfer_chain_complex [constructor] {Y : N → Set*} (g : Π{n : N}, Y (S n) →* Y n) (e : Π{n}, X n ≃* Y n) (p : Π{n} (x : X (S n)), e (cc_to_fn X n x) = g (e x)) : chain_complex N := chain_complex.mk Y @g abstract begin intro n, apply equiv_rect (equiv_of_pequiv e), intro x, refine ap g (p x)⁻¹ ⬝ _, refine (p _)⁻¹ ⬝ _, refine ap e (cc_is_chain_complex X n _) ⬝ _, apply respect_pt end end theorem is_exact_at_transfer {X : chain_complex N} {Y : N → Set*} (g : Π{n : N}, Y (S n) →* Y n) (e : Π{n}, X n ≃* Y n) (p : Π{n} (x : X (S n)), e (cc_to_fn X n x) = g (e x)) {n : N} (H : is_exact_at X n) : is_exact_at (transfer_chain_complex X @g @e @p) n := begin intro y q, esimp at *, have H2 : cc_to_fn X n (e⁻¹ᵉ* y) = pt, begin refine (inv_commute (λn, equiv_of_pequiv e) _ _ @p _)⁻¹ᵖ ⬝ _, refine ap _ q ⬝ _, exact respect_pt e⁻¹ᵉ* end, induction (H _ H2) with x r, refine image.mk (e x) _, refine (p x)⁻¹ ⬝ _, refine ap e r ⬝ _, apply right_inv end /- A type chain complex can be set-truncated to a chain complex -/ definition trunc_chain_complex [constructor] (X : type_chain_complex N) : chain_complex N := chain_complex.mk (λn, ptrunc 0 (X n)) (λn, ptrunc_functor 0 (tcc_to_fn X n)) begin intro n x, esimp at *, refine @trunc.rec _ _ _ (λH, !is_trunc_eq) _ x, clear x, intro x, esimp, exact ap tr (tcc_is_chain_complex X n x) end definition is_exact_at_trunc (X : type_chain_complex N) {n : N} (H : is_exact_at_t X n) : is_exact_at (trunc_chain_complex X) n := begin intro x p, esimp at *, induction x with x, esimp at *, note q := !tr_eq_tr_equiv p, induction q with q, induction H x q with y r, refine image.mk (tr y) _, esimp, exact ap tr r end definition transfer_chain_complex2 [constructor] {M : succ_str} {Y : M → Set*} (f : N ≃ M) (c : Π(n : N), f (S n) = S (f n)) (g : Π{m : M}, Y (S m) →* Y m) (e : Π{n}, X n ≃* Y (f n)) (p : Π{n} (x : X (S n)), e (cc_to_fn X n x) = g (c n ▸ e x)) : chain_complex M := chain_complex.mk Y @g begin refine equiv_rect f _ _, intro n, have H : Π (x : Y (f (S (S n)))), g (c n ▸ g (c (S n) ▸ x)) = pt, begin apply equiv_rect (equiv_of_pequiv e), intro x, refine ap (λx, g (c n ▸ x)) (@p (S n) x)⁻¹ᵖ ⬝ _, refine (p _)⁻¹ ⬝ _, refine ap e (cc_is_chain_complex X n _) ⬝ _, apply respect_pt end, refine pi.pi_functor _ _ H, { intro x, exact (c (S n))⁻¹ ▸ (c n)⁻¹ ▸ x}, -- with implicit arguments, this is: -- transport (λx, Y x) (c (S n))⁻¹ (transport (λx, Y (S x)) (c n)⁻¹ x) { intro x, intro p, refine _ ⬝ p, rewrite [tr_inv_tr, fn_tr_eq_tr_fn (c n)⁻¹ @g, tr_inv_tr]} end definition is_exact_at_transfer2 {X : chain_complex N} {M : succ_str} {Y : M → Set*} (f : N ≃ M) (c : Π(n : N), f (S n) = S (f n)) (g : Π{m : M}, Y (S m) →* Y m) (e : Π{n}, X n ≃* Y (f n)) (p : Π{n} (x : X (S n)), e (cc_to_fn X n x) = g (c n ▸ e x)) {n : N} (H : is_exact_at X n) : is_exact_at (transfer_chain_complex2 X f c @g @e @p) (f n) := begin intro y q, esimp at *, have H2 : cc_to_fn X n (e⁻¹ᵉ* ((c n)⁻¹ ▸ y)) = pt, begin refine (inv_commute (λn, equiv_of_pequiv e) _ _ @p _)⁻¹ᵖ ⬝ _, rewrite [tr_inv_tr, q], exact respect_pt e⁻¹ᵉ* end, induction (H _ H2) with x r, refine image.mk (c n ▸ c (S n) ▸ e x) _, rewrite [fn_tr_eq_tr_fn (c n) @g], refine ap (λx, c n ▸ x) (p x)⁻¹ ⬝ _, refine ap (λx, c n ▸ e x) r ⬝ _, refine ap (λx, c n ▸ x) !right_inv ⬝ _, apply tr_inv_tr, end /- This is a start of a development of chain complexes consisting only on groups. This might be useful to have in stable algebraic topology, but in the unstable case it's less useful, since the smallest terms usually don't have a group structure. We don't use it yet, so it's commented out for now -/ -- structure group_chain_complex : Type := -- (car : N → Group) -- (fn : Π(n : N), car (S n) →g car n) -- (is_chain_complex : Π{n : N} (x : car ((S n) + 1)), fn n (fn (S n) x) = 1) -- structure group_chain_complex : Type := -- chain complex on the naturals with maps going down -- (car : N → Group) -- (fn : Π(n : N), car (S n) →g car n) -- (is_chain_complex : Π{n : N} (x : car ((S n) + 1)), fn n (fn (S n) x) = 1) -- structure right_group_chain_complex : Type := -- chain complex on the naturals with maps going up -- (car : N → Group) -- (fn : Π(n : N), car n →g car (S n)) -- (is_chain_complex : Π{n : N} (x : car n), fn (S n) (fn n x) = 1) -- definition gcc_to_car [unfold 1] [coercion] := @group_chain_complex.car -- definition gcc_to_fn [unfold 1] := @group_chain_complex.fn -- definition gcc_is_chain_complex [unfold 1] := @group_chain_complex.is_chain_complex -- definition lgcc_to_car [unfold 1] [coercion] := @left_group_chain_complex.car -- definition lgcc_to_fn [unfold 1] := @left_group_chain_complex.fn -- definition lgcc_is_chain_complex [unfold 1] := @left_group_chain_complex.is_chain_complex -- definition rgcc_to_car [unfold 1] [coercion] := @right_group_chain_complex.car -- definition rgcc_to_fn [unfold 1] := @right_group_chain_complex.fn -- definition rgcc_is_chain_complex [unfold 1] := @right_group_chain_complex.is_chain_complex -- -- important: these notions are shifted by one! (this is to avoid transports) -- definition is_exact_at_g [reducible] (X : group_chain_complex) (n : N) : Type := -- Π(x : X (S n)), gcc_to_fn X n x = 1 → image (gcc_to_fn X (S n)) x -- definition is_exact_at_lg [reducible] (X : left_group_chain_complex) (n : N) : Type := -- Π(x : X (S n)), lgcc_to_fn X n x = 1 → image (lgcc_to_fn X (S n)) x -- definition is_exact_at_rg [reducible] (X : right_group_chain_complex) (n : N) : Type := -- Π(x : X (S n)), rgcc_to_fn X (S n) x = 1 → image (rgcc_to_fn X n) x -- definition is_exact_g [reducible] (X : group_chain_complex) : Type := -- Π(n : N), is_exact_at_g X n -- definition is_exact_lg [reducible] (X : left_group_chain_complex) : Type := -- Π(n : N), is_exact_at_lg X n -- definition is_exact_rg [reducible] (X : right_group_chain_complex) : Type := -- Π(n : N), is_exact_at_rg X n -- definition group_chain_complex_from_left (X : left_group_chain_complex) : group_chain_complex := -- group_chain_complex.mk (int.rec X (λn, G0)) -- begin -- intro n, fconstructor, -- { induction n with n n, -- { exact @lgcc_to_fn X n}, -- { esimp, intro x, exact star}}, -- { induction n with n n, -- { apply respect_mul}, -- { intro g h, reflexivity}} -- end -- begin -- intro n, induction n with n n, -- { exact lgcc_is_chain_complex X}, -- { esimp, intro x, reflexivity} -- end -- definition is_exact_g_from_left {X : left_group_chain_complex} {n : N} (H : is_exact_at_lg X n) -- : is_exact_at_g (group_chain_complex_from_left X) n := -- H -- definition transfer_left_group_chain_complex [constructor] (X : left_group_chain_complex) -- {Y : N → Group} (g : Π{n : N}, Y (S n) →g Y n) (e : Π{n}, X n ≃* Y n) -- (p : Π{n} (x : X (S n)), e (lgcc_to_fn X n x) = g (e x)) : left_group_chain_complex := -- left_group_chain_complex.mk Y @g -- begin -- intro n, apply equiv_rect (pequiv_of_equiv e), intro x, -- refine ap g (p x)⁻¹ ⬝ _, -- refine (p _)⁻¹ ⬝ _, -- refine ap e (lgcc_is_chain_complex X _) ⬝ _, -- exact respect_pt -- end -- definition is_exact_at_t_transfer {X : left_group_chain_complex} {Y : N → Type*} -- {g : Π{n : N}, Y (S n) →* Y n} (e : Π{n}, X n ≃* Y n) -- (p : Π{n} (x : X (S n)), e (lgcc_to_fn X n x) = g (e x)) {n : N} -- (H : is_exact_at_lg X n) : is_exact_at_lg (transfer_left_group_chain_complex X @g @e @p) n := -- begin -- intro y q, esimp at *, -- have H2 : lgcc_to_fn X n (e⁻¹ᵉ* y) = pt, -- begin -- refine (inv_commute (λn, equiv_of_pequiv e) _ _ @p _)⁻¹ᵖ ⬝ _, -- refine ap _ q ⬝ _, -- exact respect_pt e⁻¹ᵉ* -- end, -- cases (H _ H2) with x r, -- refine image.mk (e x) _, -- refine (p x)⁻¹ ⬝ _, -- refine ap e r ⬝ _, -- apply right_inv -- end /- The following theorems state that in a chain complex, if certain types are contractible, and the chain complex is exact at the right spots, a map in the chain complex is an embedding/surjection/equivalence. For the first and third we also need to assume that the map is a group homomorphism (and hence that the two types around it are groups). -/ definition is_embedding_of_trivial (X : chain_complex N) {n : N} (H : is_exact_at X n) [HX : is_contr (X (S (S n)))] [pgroup (X n)] [pgroup (X (S n))] [is_homomorphism (cc_to_fn X n)] : is_embedding (cc_to_fn X n) := begin apply is_embedding_homomorphism, intro g p, induction H g p with x q, have r : pt = x, from !is_prop.elim, induction r, refine q⁻¹ ⬝ _, apply respect_pt end definition is_surjective_of_trivial (X : chain_complex N) {n : N} (H : is_exact_at X n) [HX : is_contr (X n)] : is_surjective (cc_to_fn X (S n)) := begin intro g, refine trunc.elim _ (H g !is_prop.elim), apply tr end definition is_equiv_of_trivial (X : chain_complex N) {n : N} (H1 : is_exact_at X n) (H2 : is_exact_at X (S n)) [HX1 : is_contr (X n)] [HX2 : is_contr (X (S (S (S n))))] [pgroup (X (S n))] [pgroup (X (S (S n)))] [is_homomorphism (cc_to_fn X (S n))] : is_equiv (cc_to_fn X (S n)) := begin apply is_equiv_of_is_surjective_of_is_embedding, { apply is_embedding_of_trivial X, apply H2}, { apply is_surjective_of_trivial X, apply H1}, end end end chain_complex
e81197ec55f60001d45eedf78f6af6e930a55364
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/compare.lean
03de3a0ec82acc2033aac26539236aba8cf3acc6
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
8,332
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import order.synonym /-! # Comparison This file provides basic results about orderings and comparison in linear orders. ## Definitions * `cmp_le`: An `ordering` from `≤`. * `ordering.compares`: Turns an `ordering` into `<` and `=` propositions. * `linear_order_of_compares`: Constructs a `linear_order` instance from the fact that any two elements that are not one strictly less than the other either way are equal. -/ variables {α : Type*} /-- Like `cmp`, but uses a `≤` on the type instead of `<`. Given two elements `x` and `y`, returns a three-way comparison result `ordering`. -/ def cmp_le {α} [has_le α] [@decidable_rel α (≤)] (x y : α) : ordering := if x ≤ y then if y ≤ x then ordering.eq else ordering.lt else ordering.gt lemma cmp_le_swap {α} [has_le α] [is_total α (≤)] [@decidable_rel α (≤)] (x y : α) : (cmp_le x y).swap = cmp_le y x := begin by_cases xy : x ≤ y; by_cases yx : y ≤ x; simp [cmp_le, *, ordering.swap], cases not_or xy yx (total_of _ _ _) end lemma cmp_le_eq_cmp {α} [preorder α] [is_total α (≤)] [@decidable_rel α (≤)] [@decidable_rel α (<)] (x y : α) : cmp_le x y = cmp x y := begin by_cases xy : x ≤ y; by_cases yx : y ≤ x; simp [cmp_le, lt_iff_le_not_le, *, cmp, cmp_using], cases not_or xy yx (total_of _ _ _) end namespace ordering /-- `compares o a b` means that `a` and `b` have the ordering relation `o` between them, assuming that the relation `a < b` is defined. -/ @[simp] def compares [has_lt α] : ordering → α → α → Prop | lt a b := a < b | eq a b := a = b | gt a b := a > b lemma compares_swap [has_lt α] {a b : α} {o : ordering} : o.swap.compares a b ↔ o.compares b a := by { cases o, exacts [iff.rfl, eq_comm, iff.rfl] } alias compares_swap ↔ compares.of_swap compares.swap @[simp] theorem swap_inj (o₁ o₂ : ordering) : o₁.swap = o₂.swap ↔ o₁ = o₂ := by cases o₁; cases o₂; dec_trivial lemma swap_eq_iff_eq_swap {o o' : ordering} : o.swap = o' ↔ o = o'.swap := by rw [←swap_inj, swap_swap] lemma compares.eq_lt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = lt ↔ a < b) | lt a b h := ⟨λ _, h, λ _, rfl⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h' h).elim⟩ | gt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ lemma compares.ne_lt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o ≠ lt ↔ b ≤ a) | lt a b h := ⟨absurd rfl, λ h', (not_le_of_lt h h').elim⟩ | eq a b h := ⟨λ _, ge_of_eq h, λ _ h, by injection h⟩ | gt a b h := ⟨λ _, le_of_lt h, λ _ h, by injection h⟩ lemma compares.eq_eq [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = eq ↔ a = b) | lt a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h h').elim⟩ | eq a b h := ⟨λ _, h, λ _, rfl⟩ | gt a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h h').elim⟩ lemma compares.eq_gt [preorder α] {o} {a b : α} (h : compares o a b) : (o = gt ↔ b < a) := swap_eq_iff_eq_swap.symm.trans h.swap.eq_lt lemma compares.ne_gt [preorder α] {o} {a b : α} (h : compares o a b) : (o ≠ gt ↔ a ≤ b) := (not_congr swap_eq_iff_eq_swap.symm).trans h.swap.ne_lt lemma compares.le_total [preorder α] {a b : α} : ∀ {o}, compares o a b → a ≤ b ∨ b ≤ a | lt h := or.inl (le_of_lt h) | eq h := or.inl (le_of_eq h) | gt h := or.inr (le_of_lt h) lemma compares.le_antisymm [preorder α] {a b : α} : ∀ {o}, compares o a b → a ≤ b → b ≤ a → a = b | lt h _ hba := (not_le_of_lt h hba).elim | eq h _ _ := h | gt h hab _ := (not_le_of_lt h hab).elim lemma compares.inj [preorder α] {o₁} : ∀ {o₂} {a b : α}, compares o₁ a b → compares o₂ a b → o₁ = o₂ | lt a b h₁ h₂ := h₁.eq_lt.2 h₂ | eq a b h₁ h₂ := h₁.eq_eq.2 h₂ | gt a b h₁ h₂ := h₁.eq_gt.2 h₂ lemma compares_iff_of_compares_impl {β : Type*} [linear_order α] [preorder β] {a b : α} {a' b' : β} (h : ∀ {o}, compares o a b → compares o a' b') (o) : compares o a b ↔ compares o a' b' := begin refine ⟨h, λ ho, _⟩, cases lt_trichotomy a b with hab hab, { change compares ordering.lt a b at hab, rwa [ho.inj (h hab)] }, { cases hab with hab hab, { change compares ordering.eq a b at hab, rwa [ho.inj (h hab)] }, { change compares ordering.gt a b at hab, rwa [ho.inj (h hab)] } } end lemma swap_or_else (o₁ o₂) : (or_else o₁ o₂).swap = or_else o₁.swap o₂.swap := by cases o₁; try {refl}; cases o₂; refl lemma or_else_eq_lt (o₁ o₂) : or_else o₁ o₂ = lt ↔ o₁ = lt ∨ (o₁ = eq ∧ o₂ = lt) := by cases o₁; cases o₂; exact dec_trivial end ordering open ordering order_dual @[simp] lemma to_dual_compares_to_dual [has_lt α] {a b : α} {o : ordering} : compares o (to_dual a) (to_dual b) ↔ compares o b a := by { cases o, exacts [iff.rfl, eq_comm, iff.rfl] } @[simp] lemma of_dual_compares_of_dual [has_lt α] {a b : αᵒᵈ} {o : ordering} : compares o (of_dual a) (of_dual b) ↔ compares o b a := by { cases o, exacts [iff.rfl, eq_comm, iff.rfl] } lemma cmp_compares [linear_order α] (a b : α) : (cmp a b).compares a b := by obtain h | h | h := lt_trichotomy a b; simp [cmp, cmp_using, h, h.not_lt] lemma ordering.compares.cmp_eq [linear_order α] {a b : α} {o : ordering} (h : o.compares a b) : cmp a b = o := (cmp_compares a b).inj h @[simp] lemma cmp_swap [preorder α] [@decidable_rel α (<)] (a b : α) : (cmp a b).swap = cmp b a := begin unfold cmp cmp_using, by_cases a < b; by_cases h₂ : b < a; simp [h, h₂, ordering.swap], exact lt_asymm h h₂ end @[simp] lemma cmp_le_to_dual [has_le α] [@decidable_rel α (≤)] (x y : α) : cmp_le (to_dual x) (to_dual y) = cmp_le y x := rfl @[simp] lemma cmp_le_of_dual [has_le α] [@decidable_rel α (≤)] (x y : αᵒᵈ) : cmp_le (of_dual x) (of_dual y) = cmp_le y x := rfl @[simp] lemma cmp_to_dual [has_lt α] [@decidable_rel α (<)] (x y : α) : cmp (to_dual x) (to_dual y) = cmp y x := rfl @[simp] lemma cmp_of_dual [has_lt α] [@decidable_rel α (<)] (x y : αᵒᵈ) : cmp (of_dual x) (of_dual y) = cmp y x := rfl /-- Generate a linear order structure from a preorder and `cmp` function. -/ def linear_order_of_compares [preorder α] (cmp : α → α → ordering) (h : ∀ a b, (cmp a b).compares a b) : linear_order α := { le_antisymm := λ a b, (h a b).le_antisymm, le_total := λ a b, (h a b).le_total, decidable_le := λ a b, decidable_of_iff _ (h a b).ne_gt, decidable_lt := λ a b, decidable_of_iff _ (h a b).eq_lt, decidable_eq := λ a b, decidable_of_iff _ (h a b).eq_eq, .. ‹preorder α› } variables [linear_order α] (x y : α) @[simp] lemma cmp_eq_lt_iff : cmp x y = ordering.lt ↔ x < y := ordering.compares.eq_lt (cmp_compares x y) @[simp] lemma cmp_eq_eq_iff : cmp x y = ordering.eq ↔ x = y := ordering.compares.eq_eq (cmp_compares x y) @[simp] lemma cmp_eq_gt_iff : cmp x y = ordering.gt ↔ y < x := ordering.compares.eq_gt (cmp_compares x y) @[simp] lemma cmp_self_eq_eq : cmp x x = ordering.eq := by rw cmp_eq_eq_iff variables {x y} {β : Type*} [linear_order β] {x' y' : β} lemma cmp_eq_cmp_symm : cmp x y = cmp x' y' ↔ cmp y x = cmp y' x' := ⟨λ h, by rwa [←cmp_swap x', ←cmp_swap, swap_inj], λ h, by rwa [←cmp_swap y', ←cmp_swap, swap_inj]⟩ lemma lt_iff_lt_of_cmp_eq_cmp (h : cmp x y = cmp x' y') : x < y ↔ x' < y' := by rw [←cmp_eq_lt_iff, ←cmp_eq_lt_iff, h] lemma le_iff_le_of_cmp_eq_cmp (h : cmp x y = cmp x' y') : x ≤ y ↔ x' ≤ y' := by { rw [←not_lt, ←not_lt], apply not_congr, apply lt_iff_lt_of_cmp_eq_cmp, rwa cmp_eq_cmp_symm } lemma eq_iff_eq_of_cmp_eq_cmp (h : cmp x y = cmp x' y') : x = y ↔ x' = y' := by rw [le_antisymm_iff, le_antisymm_iff, le_iff_le_of_cmp_eq_cmp h, le_iff_le_of_cmp_eq_cmp (cmp_eq_cmp_symm.1 h)] lemma has_lt.lt.cmp_eq_lt (h : x < y) : cmp x y = ordering.lt := (cmp_eq_lt_iff _ _).2 h lemma has_lt.lt.cmp_eq_gt (h : x < y) : cmp y x = ordering.gt := (cmp_eq_gt_iff _ _).2 h lemma eq.cmp_eq_eq (h : x = y) : cmp x y = ordering.eq := (cmp_eq_eq_iff _ _).2 h lemma eq.cmp_eq_eq' (h : x = y) : cmp y x = ordering.eq := h.symm.cmp_eq_eq
7c141d90304a76730ffc0d8357e179526cf854da
618003631150032a5676f229d13a079ac875ff77
/src/topology/metric_space/lipschitz.lean
e5c2ccd7b053785a636246fbaa342d5ba67a8460
[ "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
11,375
lean
/- Copyright (c) 2018 Rohan Mitta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov -/ import topology.metric_space.basic import category_theory.endomorphism import category_theory.types /-! # Lipschitz continuous functions A map `f : α → β` between two (extended) metric spaces is called *Lipschitz continuous* with constant `K ≥ 0` if for all `x, y` we have `edist (f x) (f y) ≤ K * edist x y`. For a metric space, the latter inequality is equivalent to `dist (f x) (f y) ≤ K * dist x y`. In this file we provide various ways to prove that various combinations of Lipschitz continuous functions are Lipschitz continuous. We also prove that Lipschitz continuous functions are uniformly continuous. ## Implementation notes The parameter `K` has type `nnreal`. This way we avoid conjuction in the definition and have coercions both to `ℝ` and `ennreal`. Constructors whose names end with `'` take `K : ℝ` as an argument, and return `lipschitz_with (nnreal.of_real K) f`. -/ universes u v w x open filter function open_locale topological_space nnreal variables {α : Type u} {β : Type v} {γ : Type w} {ι : Type x} /-- A function `f` is Lipschitz continuous with constant `K ≥ 0` if for all `x, y` we have `dist (f x) (f y) ≤ K * dist x y` -/ def lipschitz_with [emetric_space α] [emetric_space β] (K : ℝ≥0) (f : α → β) := ∀x y, edist (f x) (f y) ≤ K * edist x y lemma lipschitz_with_iff_dist_le_mul [metric_space α] [metric_space β] {K : ℝ≥0} {f : α → β} : lipschitz_with K f ↔ ∀ x y, dist (f x) (f y) ≤ K * dist x y := by { simp only [lipschitz_with, edist_nndist, dist_nndist], norm_cast } alias lipschitz_with_iff_dist_le_mul ↔ lipschitz_with.dist_le_mul lipschitz_with.of_dist_le_mul namespace lipschitz_with section emetric variables [emetric_space α] [emetric_space β] [emetric_space γ] {K : ℝ≥0} {f : α → β} lemma edist_le_mul (h : lipschitz_with K f) (x y : α) : edist (f x) (f y) ≤ K * edist x y := h x y lemma edist_lt_top (hf : lipschitz_with K f) {x y : α} (h : edist x y < ⊤) : edist (f x) (f y) < ⊤ := lt_of_le_of_lt (hf x y) $ ennreal.mul_lt_top ennreal.coe_lt_top h lemma mul_edist_le (h : lipschitz_with K f) (x y : α) : (K⁻¹ : ennreal) * edist (f x) (f y) ≤ edist x y := begin have := h x y, rw [mul_comm] at this, replace := ennreal.div_le_of_le_mul this, rwa [ennreal.div_def, mul_comm] at this end protected lemma of_edist_le (h : ∀ x y, edist (f x) (f y) ≤ edist x y) : lipschitz_with 1 f := λ x y, by simp only [ennreal.coe_one, one_mul, h] protected lemma weaken (hf : lipschitz_with K f) {K' : ℝ≥0} (h : K ≤ K') : lipschitz_with K' f := assume x y, le_trans (hf x y) $ ennreal.mul_right_mono (ennreal.coe_le_coe.2 h) lemma ediam_image_le (hf : lipschitz_with K f) (s : set α) : emetric.diam (f '' s) ≤ K * emetric.diam s := begin apply emetric.diam_le_of_forall_edist_le, rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, calc edist (f x) (f y) ≤ ↑K * edist x y : hf.edist_le_mul x y ... ≤ ↑K * emetric.diam s : ennreal.mul_left_mono (emetric.edist_le_diam_of_mem hx hy) end /-- A Lipschitz function is uniformly continuous -/ protected lemma uniform_continuous (hf : lipschitz_with K f) : uniform_continuous f := begin refine emetric.uniform_continuous_iff.2 (λε εpos, _), use [ε/K, canonically_ordered_semiring.mul_pos.2 ⟨εpos, ennreal.inv_pos.2 $ ennreal.coe_ne_top⟩], assume x y Dxy, apply lt_of_le_of_lt (hf.edist_le_mul x y), rw [mul_comm], exact ennreal.mul_lt_of_lt_div Dxy end /-- A Lipschitz function is continuous -/ protected lemma continuous (hf : lipschitz_with K f) : continuous f := hf.uniform_continuous.continuous protected lemma const (b : β) : lipschitz_with 0 (λa:α, b) := assume x y, by simp only [edist_self, zero_le] protected lemma id : lipschitz_with 1 (@id α) := lipschitz_with.of_edist_le $ assume x y, le_refl _ protected lemma subtype_val (s : set α) : lipschitz_with 1 (subtype.val : s → α) := lipschitz_with.of_edist_le $ assume x y, le_refl _ protected lemma subtype_coe (s : set α) : lipschitz_with 1 (coe : s → α) := lipschitz_with.subtype_val s protected lemma restrict (hf : lipschitz_with K f) (s : set α) : lipschitz_with K (s.restrict f) := λ x y, hf x y protected lemma comp {Kf Kg : ℝ≥0} {f : β → γ} {g : α → β} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf * Kg) (f ∘ g) := assume x y, calc edist (f (g x)) (f (g y)) ≤ Kf * edist (g x) (g y) : hf _ _ ... ≤ Kf * (Kg * edist x y) : ennreal.mul_left_mono (hg _ _) ... = (Kf * Kg : ℝ≥0) * edist x y : by rw [← mul_assoc, ennreal.coe_mul] protected lemma prod_fst : lipschitz_with 1 (@prod.fst α β) := lipschitz_with.of_edist_le $ assume x y, le_max_left _ _ protected lemma prod_snd : lipschitz_with 1 (@prod.snd α β) := lipschitz_with.of_edist_le $ assume x y, le_max_right _ _ protected lemma prod {f : α → β} {Kf : ℝ≥0} (hf : lipschitz_with Kf f) {g : α → γ} {Kg : ℝ≥0} (hg : lipschitz_with Kg g) : lipschitz_with (max Kf Kg) (λ x, (f x, g x)) := begin assume x y, rw [ennreal.coe_mono.map_max, prod.edist_eq, ennreal.max_mul], exact max_le_max (hf x y) (hg x y) end protected lemma uncurry {f : α → β → γ} {Kα Kβ : ℝ≥0} (hα : ∀ b, lipschitz_with Kα (λ a, f a b)) (hβ : ∀ a, lipschitz_with Kβ (f a)) : lipschitz_with (Kα + Kβ) (function.uncurry f) := begin rintros ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, simp only [function.uncurry, ennreal.coe_add, add_mul], apply le_trans (edist_triangle _ (f a₂ b₁) _), exact add_le_add' (le_trans (hα _ _ _) $ ennreal.mul_left_mono $ le_max_left _ _) (le_trans (hβ _ _ _) $ ennreal.mul_left_mono $ le_max_right _ _) end protected lemma iterate {f : α → α} (hf : lipschitz_with K f) : ∀n, lipschitz_with (K ^ n) (f^[n]) | 0 := lipschitz_with.id | (n + 1) := by rw [pow_succ']; exact (iterate n).comp hf lemma edist_iterate_succ_le_geometric {f : α → α} (hf : lipschitz_with K f) (x n) : edist (f^[n] x) (f^[n + 1] x) ≤ edist x (f x) * K ^ n := begin rw [iterate_succ, mul_comm], simpa only [ennreal.coe_pow] using (hf.iterate n) x (f x) end open category_theory protected lemma mul {f g : End α} {Kf Kg} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf * Kg) (f * g : End α) := hf.comp hg /-- The product of a list of Lipschitz continuous endomorphisms is a Lipschitz continuous endomorphism. -/ protected lemma list_prod (f : ι → End α) (K : ι → ℝ≥0) (h : ∀ i, lipschitz_with (K i) (f i)) : ∀ l : list ι, lipschitz_with (l.map K).prod (l.map f).prod | [] := by simp [types_id, lipschitz_with.id] | (i :: l) := by { simp only [list.map_cons, list.prod_cons], exact (h i).mul (list_prod l) } protected lemma pow {f : End α} {K} (h : lipschitz_with K f) : ∀ n : ℕ, lipschitz_with (K^n) (f^n : End α) | 0 := lipschitz_with.id | (n + 1) := h.mul (pow n) end emetric section metric variables [metric_space α] [metric_space β] [metric_space γ] {K : ℝ≥0} protected lemma of_dist_le' {f : α → β} {K : ℝ} (h : ∀ x y, dist (f x) (f y) ≤ K * dist x y) : lipschitz_with (nnreal.of_real K) f := of_dist_le_mul $ λ x y, le_trans (h x y) $ mul_le_mul_of_nonneg_right (nnreal.le_coe_of_real K) dist_nonneg protected lemma mk_one {f : α → β} (h : ∀ x y, dist (f x) (f y) ≤ dist x y) : lipschitz_with 1 f := of_dist_le_mul $ by simpa only [nnreal.coe_one, one_mul] using h /-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version doesn't assume `0≤K`. -/ protected lemma of_le_add_mul' {f : α → ℝ} (K : ℝ) (h : ∀x y, f x ≤ f y + K * dist x y) : lipschitz_with (nnreal.of_real K) f := have I : ∀ x y, f x - f y ≤ K * dist x y, from assume x y, sub_le_iff_le_add'.2 (h x y), lipschitz_with.of_dist_le' $ assume x y, abs_sub_le_iff.2 ⟨I x y, dist_comm y x ▸ I y x⟩ /-- For functions to `ℝ`, it suffices to prove `f x ≤ f y + K * dist x y`; this version assumes `0≤K`. -/ protected lemma of_le_add_mul {f : α → ℝ} (K : ℝ≥0) (h : ∀x y, f x ≤ f y + K * dist x y) : lipschitz_with K f := by simpa only [nnreal.of_real_coe] using lipschitz_with.of_le_add_mul' K h protected lemma of_le_add {f : α → ℝ} (h : ∀ x y, f x ≤ f y + dist x y) : lipschitz_with 1 f := lipschitz_with.of_le_add_mul 1 $ by simpa only [nnreal.coe_one, one_mul] protected lemma le_add_mul {f : α → ℝ} {K : ℝ≥0} (h : lipschitz_with K f) (x y) : f x ≤ f y + K * dist x y := sub_le_iff_le_add'.1 $ le_trans (le_abs_self _) $ h.dist_le_mul x y protected lemma iff_le_add_mul {f : α → ℝ} {K : ℝ≥0} : lipschitz_with K f ↔ ∀ x y, f x ≤ f y + K * dist x y := ⟨lipschitz_with.le_add_mul, lipschitz_with.of_le_add_mul K⟩ lemma nndist_le {f : α → β} (hf : lipschitz_with K f) (x y : α) : nndist (f x) (f y) ≤ K * nndist x y := hf.dist_le_mul x y lemma diam_image_le {f : α → β} (hf : lipschitz_with K f) (s : set α) (hs : metric.bounded s) : metric.diam (f '' s) ≤ K * metric.diam s := begin apply metric.diam_le_of_forall_dist_le (mul_nonneg K.coe_nonneg metric.diam_nonneg), rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, calc dist (f x) (f y) ≤ ↑K * dist x y : hf.dist_le_mul x y ... ≤ ↑K * metric.diam s : mul_le_mul_of_nonneg_left (metric.dist_le_diam_of_mem hs hx hy) K.2 end protected lemma dist_left (y : α) : lipschitz_with 1 (λ x, dist x y) := lipschitz_with.of_le_add $ assume x z, by { rw [add_comm], apply dist_triangle } protected lemma dist_right (x : α) : lipschitz_with 1 (dist x) := lipschitz_with.of_le_add $ assume y z, dist_triangle_right _ _ _ protected lemma dist : lipschitz_with 2 (function.uncurry $ @dist α _) := lipschitz_with.uncurry lipschitz_with.dist_left lipschitz_with.dist_right lemma dist_iterate_succ_le_geometric {f : α → α} (hf : lipschitz_with K f) (x n) : dist (f^[n] x) (f^[n + 1] x) ≤ dist x (f x) * K ^ n := begin rw [iterate_succ, mul_comm], simpa only [nnreal.coe_pow] using (hf.iterate n).dist_le_mul x (f x) end end metric end lipschitz_with open metric /-- If a function is locally Lipschitz around a point, then it is continuous at this point. -/ lemma continuous_at_of_locally_lipschitz [metric_space α] [metric_space β] {f : α → β} {x : α} {r : ℝ} (hr : 0 < r) (K : ℝ) (h : ∀y, dist y x < r → dist (f y) (f x) ≤ K * dist y x) : continuous_at f x := begin refine (nhds_basis_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, ⟨min r (ε / max K 1), _, λ y hy, _⟩), { simp [hr, div_pos εpos, zero_lt_one] }, have A : max K 1 ≠ 0 := ne_of_gt (lt_max_iff.2 (or.inr zero_lt_one)), calc dist (f y) (f x) ≤ K * dist y x : h y (lt_of_lt_of_le hy (min_le_left _ _)) ... ≤ max K 1 * dist y x : mul_le_mul_of_nonneg_right (le_max_left K 1) dist_nonneg ... ≤ max K 1 * (ε / max K 1) : mul_le_mul_of_nonneg_left (le_of_lt (lt_of_lt_of_le hy (min_le_right _ _))) (le_trans zero_le_one (le_max_right K 1)) ... = ε : mul_div_cancel' _ A end
2bd245626ce9f3a81c2070e1664b61f097e4c6e8
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/computability/halting.lean
863fa43cf68896dc37fd5e27aa56264c258ff6cd
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
14,206
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import computability.partrec_code /-! # Computability theory and the halting problem A universal partial recursive function, Rice's theorem, and the halting problem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable namespace nat.partrec open computable roption theorem merge' {f g} (hf : nat.partrec f) (hg : nat.partrec g) : ∃ h, nat.partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).dom ↔ (f a).dom ∨ (g a).dom) := begin obtain ⟨cf, rfl⟩ := code.exists_code.1 hf, obtain ⟨cg, rfl⟩ := code.exists_code.1 hg, have : nat.partrec (λ n, (nat.rfind_opt (λ k, cf.evaln k n <|> cg.evaln k n))) := partrec.nat_iff.1 (partrec.rfind_opt $ primrec.option_orelse.to_comp.comp (code.evaln_prim.to_comp.comp $ (snd.pair (const cf)).pair fst) (code.evaln_prim.to_comp.comp $ (snd.pair (const cg)).pair fst)), refine ⟨_, this, λ n, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw nat.rfind_opt_dom, simp only [dom_iff_mem, code.evaln_complete, option.mem_def] at h, obtain ⟨x, k, e⟩ | ⟨x, k, e⟩ := h, { refine ⟨k, x, _⟩, simp only [e, option.some_orelse, option.mem_def] }, { refine ⟨k, _⟩, cases cf.evaln k n with y, { exact ⟨x, by simp only [e, option.mem_def, option.none_orelse]⟩ }, { exact ⟨y, by simp only [option.some_orelse, option.mem_def]⟩ } } }, intros x h, obtain ⟨k, e⟩ := nat.rfind_opt_spec h, revert e, simp only [option.mem_def]; cases e' : cf.evaln k n with y; simp; intro, { exact or.inr (code.evaln_sound e) }, { subst y, exact or.inl (code.evaln_sound e') } end end nat.partrec namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable roption nat.partrec (code) nat.partrec.code theorem merge' {f g : α →. σ} (hf : partrec f) (hg : partrec g) : ∃ k : α →. σ, partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).dom ↔ (f a).dom ∨ (g a).dom) := let ⟨k, hk, H⟩ := nat.partrec.merge' (bind_decode₂_iff.1 hf) (bind_decode₂_iff.1 hg) in begin let k' := λ a, (k (encode a)).bind (λ n, decode σ n), refine ⟨k', ((nat_iff.2 hk).comp computable.encode).bind (computable.decode.of_option.comp snd).to₂, λ a, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw bind_dom, have hk : (k (encode a)).dom := (H _).2.2 (by simpa only [encodek₂, bind_some, coe_some] using h), existsi hk, simp only [exists_prop, mem_map_iff, mem_coe, mem_bind_iff, option.mem_def] at H, obtain ⟨a', ha', y, hy, e⟩ | ⟨a', ha', y, hy, e⟩ := (H _).1 _ ⟨hk, rfl⟩; { simp only [e.symm, encodek] } }, intros x h', simp only [k', exists_prop, mem_coe, mem_bind_iff, option.mem_def] at h', obtain ⟨n, hn, hx⟩ := h', have := (H _).1 _ hn, simp [mem_decode₂, encode_injective.eq_iff] at this, obtain ⟨a', ha, rfl⟩ | ⟨a', ha, rfl⟩ := this; simp only [encodek] at hx; rw hx at ha, { exact or.inl ha }, exact or.inr ha end theorem merge {f g : α →. σ} (hf : partrec f) (hg : partrec g) (H : ∀ a (x ∈ f a) (y ∈ g a), x = y) : ∃ k : α →. σ, partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg in ⟨k, hk, λ a x, ⟨(K _).1 _, λ h, begin have : (k a).dom := (K _).2.2 (h.imp Exists.fst Exists.fst), refine ⟨this, _⟩, cases h with h h; cases (K _).1 _ ⟨this, rfl⟩ with h' h', { exact mem_unique h' h }, { exact (H _ _ h _ h').symm }, { exact H _ _ h' _ h }, { exact mem_unique h' h } end⟩⟩ theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} (hc : computable c) (hf : partrec f) (hg : partrec g) : partrec (λ a, cond (c a) (f a) (g a)) := let ⟨cf, ef⟩ := exists_code.1 hf, ⟨cg, eg⟩ := exists_code.1 hg in ((eval_part.comp (computable.cond hc (const cf) (const cg)) computable.id).bind ((@computable.decode σ _).comp snd).of_option.to₂).of_eq $ λ a, by cases c a; simp [ef, eg, encodek] theorem sum_cases {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : computable f) (hg : partrec₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (sum_cases hf (const tt).to₂ (const ff).to₂) (sum_cases_left hf (option_some_iff.2 hg).to₂ (const option.none).to₂) (sum_cases_right hf (const option.none).to₂ (option_some_iff.2 hh).to₂)) .of_eq $ λ a, by cases f a; simp only [bool.cond_tt, bool.cond_ff] end partrec /-- A computable predicate is one whose indicator function is computable. -/ def computable_pred {α} [primcodable α] (p : α → Prop) := ∃ [D : decidable_pred p], by exactI computable (λ a, to_bool (p a)) /-- A recursively enumerable predicate is one which is the domain of a computable partial function. -/ def re_pred {α} [primcodable α] (p : α → Prop) := partrec (λ a, roption.assert (p a) (λ _, roption.some ())) theorem computable_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : computable_pred p) (H : ∀ a, p a ↔ q a) : computable_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp namespace computable_pred variables {α : Type*} {σ : Type*} variables [primcodable α] [primcodable σ] open nat.partrec (code) nat.partrec.code computable theorem computable_iff {p : α → Prop} : computable_pred p ↔ ∃ f : α → bool, computable f ∧ p = λ a, f a := ⟨λ ⟨D, h⟩, by exactI ⟨_, h, funext $ λ a, propext (to_bool_iff _).symm⟩, by rintro ⟨f, h, rfl⟩; exact ⟨by apply_instance, by simpa using h⟩⟩ protected theorem not {p : α → Prop} (hp : computable_pred p) : computable_pred (λ a, ¬ p a) := by obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp; exact ⟨by apply_instance, (cond hf (const ff) (const tt)).of_eq (λ n, by {dsimp, cases f n; refl})⟩ theorem to_re {p : α → Prop} (hp : computable_pred p) : re_pred p := begin obtain ⟨f, hf, rfl⟩ := computable_iff.1 hp, unfold re_pred, refine (partrec.cond hf (decidable.partrec.const' (roption.some ())) partrec.none).of_eq (λ n, roption.ext $ λ a, _), cases a, cases f n; simp end theorem rice (C : set (ℕ →. ℕ)) (h : computable_pred (λ c, eval c ∈ C)) {f g} (hf : nat.partrec f) (hg : nat.partrec g) (fC : f ∈ C) : g ∈ C := begin cases h with _ h, resetI, obtain ⟨c, e⟩ := fixed_point₂ (partrec.cond (h.comp fst) ((partrec.nat_iff.2 hg).comp snd).to₂ ((partrec.nat_iff.2 hf).comp snd).to₂).to₂, simp at e, by_cases H : eval c ∈ C, { simp only [H, if_true] at e, rwa ← e }, { simp only [H, if_false] at e, rw e at H, contradiction } end theorem rice₂ (C : set code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : computable_pred (λ c, c ∈ C) ↔ C = ∅ ∨ C = set.univ := by classical; exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C, from λ f, ⟨set.mem_image_of_mem _, λ ⟨g, hg, e⟩, (H _ _ e).1 hg⟩, ⟨λ h, or_iff_not_imp_left.2 $ λ C0, set.eq_univ_of_forall $ λ cg, let ⟨cf, fC⟩ := set.ne_empty_iff_nonempty.1 C0 in (hC _).2 $ rice (eval '' C) (h.of_eq hC) (partrec.nat_iff.1 $ eval_part.comp (const cf) computable.id) (partrec.nat_iff.1 $ eval_part.comp (const cg) computable.id) ((hC _).1 fC), λ h, by obtain rfl | rfl := h; simp [computable_pred, set.mem_empty_eq]; exact ⟨by apply_instance, computable.const _⟩⟩ theorem halting_problem (n) : ¬ computable_pred (λ c, (eval c n).dom) | h := rice {f | (f n).dom} h nat.partrec.zero nat.partrec.none trivial -- Post's theorem on the equivalence of r.e., co-r.e. sets and -- computable sets. The assumption that p is decidable is required -- unless we assume Markov's principle or LEM. @[nolint decidable_classical] theorem computable_iff_re_compl_re {p : α → Prop} [decidable_pred p] : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := ⟨λ h, ⟨h.to_re, h.not.to_re⟩, λ ⟨h₁, h₂⟩, ⟨‹_›, begin obtain ⟨k, pk, hk⟩ := partrec.merge (h₁.map (computable.const tt).to₂) (h₂.map (computable.const ff).to₂) _, { refine partrec.of_eq pk (λ n, roption.eq_some_iff.2 _), rw hk, simp, apply decidable.em }, { intros a x hx y hy, simp at hx hy, cases hy.1 hx.1 } end⟩⟩ end computable_pred namespace nat open vector roption /-- A simplified basis for `partrec`. -/ inductive partrec' : ∀ {n}, (vector ℕ n →. ℕ) → Prop | prim {n f} : @primrec' n f → @partrec' n f | comp {m n f} (g : fin n → vector ℕ m →. ℕ) : partrec' f → (∀ i, partrec' (g i)) → partrec' (λ v, m_of_fn (λ i, g i v) >>= f) | rfind {n} {f : vector ℕ (n+1) → ℕ} : @partrec' (n+1) f → partrec' (λ v, rfind (λ n, some (f (n ::ᵥ v) = 0))) end nat namespace nat.partrec' open vector partrec computable nat (partrec') nat.partrec' theorem to_part {n f} (pf : @partrec' n f) : partrec f := begin induction pf, case nat.partrec'.prim : n f hf { exact hf.to_prim.to_comp }, case nat.partrec'.comp : m n f g _ _ hf hg { exact (vector_m_of_fn (λ i, hg i)).bind (hf.comp snd) }, case nat.partrec'.rfind : n f _ hf { have := ((primrec.eq.comp primrec.id (primrec.const 0)).to_comp.comp (hf.comp (vector_cons.comp snd fst))).to₂.part, exact this.rfind }, end theorem of_eq {n} {f g : vector ℕ n →. ℕ} (hf : partrec' f) (H : ∀ i, f i = g i) : partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : vector ℕ n → ℕ} (hf : primrec f) : @partrec' n f := prim (nat.primrec'.of_prim hf) theorem head {n : ℕ} : @partrec' n.succ (@head ℕ n) := prim nat.primrec'.head theorem tail {n f} (hf : @partrec' n f) : @partrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @prim _ _ $ nat.primrec'.nth i.succ)).of_eq $ λ v, by simp; rw [← of_fn_nth v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).bind (λ a, g (a ::ᵥ v))) := (@comp n (n+1) g (λ i, fin.cases f (λ i v, some (v.nth i)) i) hg (λ i, begin refine fin.cases _ (λ i, _) i; simp *, exact prim (nat.primrec'.nth _) end)).of_eq $ λ v, by simp [m_of_fn, roption.bind_assoc, pure] protected theorem map {n f} {g : vector ℕ (n+1) → ℕ} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).map (λ a, g (a ::ᵥ v))) := by simp [(roption.bind_some_eq_map _ _).symm]; exact hf.bind hg /-- Analogous to `nat.partrec'` for `ℕ`-valued functions, a predicate for partial recursive vector-valued functions.-/ def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, partrec' (λ v, (f v).nth i) theorem vec.prim {n m f} (hf : @nat.primrec'.vec n m f) : vec f := λ i, prim $ hf i protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m} {f : vector ℕ n → ℕ} {g} (hf : @partrec' n f) (hg : @vec n m g) : vec (λ v, f v ::ᵥ g v) := λ i, fin.cases (by simp *) (λ i, by simp only [hg i, nth_cons_succ]) i theorem idv {n} : @vec n n id := vec.prim nat.primrec'.idv theorem comp' {n m f g} (hf : @partrec' m f) (hg : @vec n m g) : partrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : vector ℕ n → ℕ} (hf : @partrec' 1 (λ v, f v.head)) (hg : @partrec' n g) : @partrec' n (λ v, f (g v)) := by simpa using hf.comp' (partrec'.cons hg partrec'.nil) theorem rfind_opt {n} {f : vector ℕ (n+1) → ℕ} (hf : @partrec' (n+1) f) : @partrec' n (λ v, nat.rfind_opt (λ a, of_nat (option ℕ) (f (a ::ᵥ v)))) := ((rfind $ (of_prim (primrec.nat_sub.comp (primrec.const 1) primrec.vector_head)) .comp₁ (λ n, roption.some (1 - n)) hf) .bind ((prim nat.primrec'.pred).comp₁ nat.pred hf)).of_eq $ λ v, roption.ext $ λ b, begin simp [nat.rfind_opt, -nat.mem_rfind], refine exists_congr (λ a, (and_congr (iff_of_eq _) iff.rfl).trans (and_congr_right (λ h, _))), { congr; funext n, simp, cases f (n ::ᵥ v); simp [nat.succ_ne_zero]; refl }, { have := nat.rfind_spec h, simp at this, cases f (a ::ᵥ v) with c, {cases this}, rw [← option.some_inj, eq_comm], refl } end open nat.partrec.code theorem of_part : ∀ {n f}, partrec f → @partrec' n f := suffices ∀ f, nat.partrec f → @partrec' 1 (λ v, f v.head), from λ n f hf, begin let g, swap, exact (comp₁ g (this g hf) (prim nat.primrec'.encode)).of_eq (λ i, by dsimp only [g]; simp [encodek, roption.map_id']), end, λ f hf, begin obtain ⟨c, rfl⟩ := exists_code.1 hf, simpa [eval_eq_rfind_opt] using (rfind_opt $ of_prim $ primrec.encode_iff.2 $ evaln_prim.comp $ (primrec.vector_head.pair (primrec.const c)).pair $ primrec.vector_head.comp primrec.vector_tail) end theorem part_iff {n f} : @partrec' n f ↔ partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : @partrec' 1 (λ v, f v.head) ↔ partrec f := part_iff.trans ⟨ λ h, (h.comp $ (primrec.vector_of_fn $ λ i, primrec.id).to_comp).of_eq (λ v, by simp only [id.def, head_of_fn]), λ h, h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : @partrec' 2 (λ v, f v.head v.tail.head) ↔ partrec₂ f := part_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (const nil)).of_eq (λ v, by simp only [cons_head, cons_tail]), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ computable f := ⟨λ h, by simpa only [of_fn_nth] using vector_of_fn (λ i, to_part (h i)), λ h i, of_part $ vector_nth.comp h (const i)⟩ end nat.partrec'
5d17f366acd98f98df91c0a865278a02e5d025b7
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/MetavarContext.lean
5ae7d7a634b055fd5de88476f0969c63bb34bd32
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51,940
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.Util.MonadCache import Lean.LocalContext namespace Lean /- The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown aaa. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called tmp metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we want to allow TC to invoke tactics. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the sythesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variables `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contatins `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction betwen temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ structure LocalInstance where className : Name fvar : Expr deriving Inhabited abbrev LocalInstances := Array LocalInstance instance : BEq LocalInstance where beq i₁ i₂ := i₁.fvar == i₂.fvar /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts inductive MetavarKind where | natural | synthetic | syntheticOpaque deriving Inhabited def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false structure MetavarDecl where userName : Name := Name.anonymous lctx : LocalContext type : Expr depth : Nat localInstances : LocalInstances kind : MetavarKind numScopeArgs : Nat := 0 -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` deriving Inhabited @[export lean_mk_metavar_decl] def mkMetavarDeclEx (userName : Name) (lctx : LocalContext) (type : Expr) (depth : Nat) (localInstances : LocalInstances) (kind : MetavarKind) : MetavarDecl := { userName := userName, lctx := lctx, type := type, depth := depth, localInstances := localInstances, kind := kind } /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`. Note that `fvars` may not be defined in the local context for `?m`. - TODO: after we delete the old frontend, we can remove the field `lctx`. This field is only used in old C++ implementation. -/ structure DelayedMetavarAssignment where lctx : LocalContext fvars : Array Expr val : Expr open Std (HashMap PersistentHashMap) structure MetavarContext where depth : Nat := 0 lDepth : PersistentHashMap MVarId Nat := {} decls : PersistentHashMap MVarId MetavarDecl := {} lAssignment : PersistentHashMap MVarId Level := {} eAssignment : PersistentHashMap MVarId Expr := {} dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {} class MonadMCtx (m : Type → Type) where getMCtx : m MetavarContext modifyMCtx : (MetavarContext → MetavarContext) → m Unit export MonadMCtx (getMCtx modifyMCtx) instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where getMCtx := liftM (getMCtx : m _) modifyMCtx := fun f => liftM (modifyMCtx f : m _) namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with decls := mctx.decls.insert mvarId { userName := userName, lctx := lctx, localInstances := localInstances, type := type, depth := mctx.depth, kind := kind, numScopeArgs := numScopeArgs } } @[export lean_metavar_ctx_mk_decl] def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } @[export lean_metavar_ctx_find_decl] def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := let search : Except MVarId Unit := mctx.decls.forM fun mvarId decl => if decl.userName == userName then throw mvarId else pure () match search with | Except.ok _ => none | Except.error mvarId => some mvarId def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } } /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with type := type } } def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (newUserName : Name) : MetavarContext := match mctx.findDecl? mvarId with | none => panic! "unknown metavariable" | some mvarDecl => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with userName := newUserName } } @[export lean_metavar_ctx_assign_level] def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext := { m with lAssignment := m.lAssignment.insert mvarId val } @[export lean_metavar_ctx_assign_expr] def assignExprCore (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } @[export lean_metavar_ctx_assign_delayed] def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext := { m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } } @[export lean_metavar_ctx_get_level_assignment] def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level := m.lAssignment.find? mvarId @[export lean_metavar_ctx_get_expr_assignment] def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId @[export lean_metavar_ctx_get_delayed_assignment] def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment := m.dAssignment.find? mvarId @[export lean_metavar_ctx_is_level_assigned] def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.lAssignment.contains mvarId @[export lean_metavar_ctx_is_expr_assigned] def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.eAssignment.contains mvarId @[export lean_metavar_ctx_is_delayed_assigned] def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.dAssignment.contains mvarId @[export lean_metavar_ctx_erase_delayed] def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext := { m with dAssignment := m.dAssignment.erase mvarId } /- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedRoot (m : MetavarContext) : MVarId → MVarId | mvarId => match getDelayedAssignment? m mvarId with | some d => match d.val.getAppFn with | Expr.mvar mvarId _ => getDelayedRoot m mvarId | _ => mvarId | none => mvarId def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.lDepth.find? mvarId with | some d => d == mctx.depth | _ => panic! "unknown universe metavariable" def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := let decl := mctx.getDecl mvarId decl.depth == mctx.depth def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssigned mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx) | Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignedMVar mctx f) || (a.hasMVar && hasAssignedMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar mctx t) || (v.hasMVar && hasAssignedMVar mctx v) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssignable mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx) | Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignableMVar mctx f) || (a.hasMVar && hasAssignableMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar mctx t) || (v.hasMVar && hasAssignableMVar mctx v) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssignable mvarId partial def instantiateLevelMVars {m} [Monad m] [MonadMCtx m] : Level → m Level | lvl@(Level.succ lvl₁ _) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvl₂ _) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.imax lvl₁ lvl₂ _) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.mvar mvarId _) => do match getLevelAssignment? (← getMCtx) mvarId with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl modifyMCtx fun mctx => mctx.assignLevel mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars {m ω} [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT Expr Expr m Expr := if !e.hasMVar then pure e else checkCache e fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← instantiateExprMVars s) | Expr.forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | Expr.const _ lvls _ => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | Expr.sort lvl _ => return e.updateSort! (← instantiateLevelMVars lvl) | Expr.mdata _ b _ => return e.updateMData! (← instantiateExprMVars b) | Expr.app .. => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT Expr Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT Expr Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | Expr.mvar mvarId _ => let mctx ← getMCtx match mctx.getDelayedAssignment? mvarId with | none => instApp | some { fvars := fvars, val := val, .. } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars val if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure result | _ => instApp | e@(Expr.mvar mvarId _) => checkCache e fun _ => do let mctx ← getMCtx match mctx.getExprAssignment? mvarId with | some newE => do let newE' ← instantiateExprMVars newE modifyMCtx fun mctx => mctx.assignExpr mvarId newE' pure newE' | none => pure e | e => pure e instance {ω} : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := if !e.hasMVar then (e, mctx) else let instantiate {ω} (e : Expr) : (MonadCacheT Expr Expr $ StateRefT MetavarContext $ ST ω) Expr := instantiateExprMVars e runST fun _ => instantiate e |>.run |>.run mctx def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext := lctx.foldl (init := ({}, mctx)) fun (lctx, mctx) ldecl => match ldecl with | LocalDecl.cdecl _ fvarId userName type bi => let (type, mctx) := mctx.instantiateMVars type (lctx.mkLocalDecl fvarId userName type bi, mctx) | LocalDecl.ldecl _ fvarId userName type value nonDep => let (type, mctx) := mctx.instantiateMVars type let (value, mctx) := mctx.instantiateMVars value (lctx.mkLetDecl fvarId userName type value nonDep, mctx) def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := let mvarDecl := mctx.getDecl mvarId let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx let (type, mctx) := mctx.instantiateMVars mvarDecl.type { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } } namespace DependsOn private abbrev M := StateM ExprSet private def shouldVisit (e : Expr) : M Bool := do if !e.hasMVar && !e.hasFVar then return false else if (← get).contains e then return false else modify fun s => s.insert e return true @[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitMain : Expr → M Bool | Expr.proj _ _ s _ => visit s | Expr.forallE _ d b _ => visit d <||> visit b | Expr.lam _ d b _ => visit d <||> visit b | Expr.letE _ t v b _ => visit t <||> visit v <||> visit b | Expr.mdata _ b _ => visit b | Expr.app f a _ => visit a <||> if f.isApp then visitMain f else visit f | Expr.mvar mvarId _ => match mctx.getExprAssignment? mvarId with | some a => visit a | none => let lctx := (mctx.getDecl mvarId).lctx return lctx.any fun decl => p decl.fvarId | Expr.fvar fvarId _ => return p fvarId | e => pure false visit e @[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`. For each metavariable `?m` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool := DependsOn.main mctx p e |>.run' {} /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `p x` is `true`. -/ @[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool := match localDecl with | LocalDecl.cdecl _ _ _ type _ => findExprDependsOn mctx type p | LocalDecl.ldecl _ _ _ type value _ => (DependsOn.main mctx p type <||> DependsOn.main mctx p value).run' {} def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool := findExprDependsOn mctx e fun fvarId' => fvarId == fvarId' def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool := findLocalDeclDependsOn mctx localDecl fun fvarId' => fvarId == fvarId' namespace MkBinding inductive Exception where | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl) instance : ToString Exception where toString | Exception.revertFailure _ lctx toRevert decl => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)" /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State where mctx : MetavarContext ngen : NameGenerator cache : HashMap Expr Expr := {} abbrev MCore := EStateM Exception State abbrev M := ReaderT Bool (EStateM Exception State) def preserveOrder : M Bool := read instance : MonadHashMapCacheAdapter Expr Expr M where getCache := do let s ← get; pure s.cache modifyCache := fun f => modify fun s => { s with cache := f s.cache } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := do let mut d : LocalDecl := lctx.getFVar! xs[0] for i in [1:xs.size] do let curr := lctx.getFVar! xs[i] if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) := do if toRevert.size == 0 then pure toRevert else if preserveOrder then -- Make sure none of `toRevert` is an AuxDecl -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i] let decl := lctx.getFVar! fvar i.forM fun j => do let prevFVar := toRevert[j] let prevDecl := lctx.getFVar! prevFVar if localDeclDependsOn mctx prevDecl fvar.fvarId! then throw (Exception.revertFailure mctx lctx toRevert prevDecl) let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => if initSize.any fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert else if toRevert.any fun x => decl.fvarId == x.fvarId! then pure (newToRevert.push decl.toExpr) else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any fun x => x.fvarId! == fvarId) then pure (newToRevert.push decl.toExpr) else pure newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ private def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (init := lctx) fun x lctx => lctx.erase x.fvarId! @[inline] private def getMCtx : M MetavarContext := return (← get).mctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (init := #[]) fun scope x => if lctx.contains x.fvarId! then scope.push x else scope /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache {α} (x : M α) : M α := do let cache ← modifyGet fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (init := mvar) fun e x => match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x /-- Return true iff some `e` in `es` depends on `fvarId` -/ private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => exprDependsOn mctx e fvarId mutual private partial def visit (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache e fun _ => elim xs e private partial def elim (xs : Array Expr) (e : Expr) : M Expr := match e with | Expr.proj _ _ s _ => return e.updateProj! (← visit xs s) | Expr.forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b) | Expr.letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b) | Expr.mdata _ b _ => return e.updateMData! (← visit xs b) | Expr.app _ _ _ => e.withApp fun f args => elimApp xs f args | Expr.mvar mvarId _ => elimApp xs e #[] | e => return e private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (init := e) fun i e => let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => do let type := type.headBeta let type ← abstractRangeAux xs i type pure <| Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => do let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 pure <| mkForall n BinderInfo.default type e | _ => pure e where abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim xs e pure (e.abstractRange i xs) private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do let mctx ← getMCtx let mvarDecl := mctx.getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then let args ← args.mapM (visit xs) return (mkAppN (mkMVar mvarId) args, #[]) else let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment ``` ?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`. Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]` -/ let rec cont (nestedFVars : Array Expr) : M (Expr × Array Expr) := do let args ← args.mapM (visit xs) let preserve ← preserveOrder match collectDeps mctx mvarLCtx toRevert preserve with | Except.error ex => throw ex | Except.ok toRevert => let newMVarLCtx := reduceLocalContext mvarLCtx toRevert let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x -- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs` let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId ← get >>= fun s => pure s.ngen.curr let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } match newMVarKind with | MetavarKind.syntheticOpaque => modify fun s => { s with mctx := assignDelayed s.mctx newMVarId mvarLCtx (toRevert ++ nestedFVars) (mkAppN (mkMVar mvarId) nestedFVars) } | _ => modify fun s => { s with mctx := assignExpr s.mctx mvarId result } return (mkAppN result args, toRevert) if !mvarDecl.kind.isSyntheticOpaque then cont #[] else match mctx.getDelayedAssignment? mvarId with | none => cont #[] | some { fvars := fvars, .. } => cont fvars private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId _ => match (← getMCtx).getExprAssignment? mvarId with | some newF => if newF.isLambda then let args ← args.mapM (visit xs) elim xs <| newF.betaRev args.reverse else elimApp xs newF args | none => return (← elimMVar xs mvarId args).1 | _ => return mkAppN (← visit xs f) (← args.mapM (visit xs)) end partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else withFreshCache do elim xs e partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) := withFreshCache do elimMVar xs mvarId #[] /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] private def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` are created only for used variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : M (Expr × Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (fun i (p : Expr × Nat) => do let (e, num) := p; let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then pure (Lean.mkLambda n bi type e, num + 1) else pure (Lean.mkForall n bi type e, num + 1) else pure (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => if e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value pure (mkLet n type value e nonDep, num + 1) else pure (e.lowerLooseBVars 1 1, num)) (e, 0) end MkBinding abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun _ => MkBinding.elimMVarDeps xs e preserveOrder def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun _ => MkBinding.revert xs mvarId preserveOrder def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) : MkBindingM (Expr × Nat) := fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly false @[inline] def mkLambda (xs : Array Expr) (e : Expr) : MkBindingM Expr := do let (e, _) ← mkBinding true xs e pure e @[inline] def mkForall (xs : Array Expr) (e : Expr) : MkBindingM Expr := do let (e, _) ← mkBinding false xs e pure e @[inline] def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MkBindingM (Expr × Nat) := do mkBinding false xs e true /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool | Expr.mdata _ e _ => isWellFormed mctx lctx e | Expr.proj _ _ e _ => isWellFormed mctx lctx e | e@(Expr.app f a _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx f && isWellFormed mctx lctx a) | e@(Expr.lam _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.forallE _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.letE _ t v b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx t && isWellFormed mctx lctx v && isWellFormed mctx lctx b) | Expr.const .. => true | Expr.bvar .. => true | Expr.sort .. => true | Expr.lit .. => true | Expr.mvar mvarId _ => let mvarDecl := mctx.getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then true else match mctx.getExprAssignment? mvarId with | none => false | some v => isWellFormed mctx lctx v | Expr.fvar fvarId _ => lctx.contains fvarId namespace LevelMVarToParam structure Context where paramNamePrefix : Name alreadyUsedPred : Name → Bool structure State where mctx : MetavarContext paramNames : Array Name := #[] nextParamIdx : Nat abbrev M := ReaderT Context $ StateM State partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | Level.succ v _ => return u.updateSucc! (← visitLevel v) | Level.max v₁ v₂ _ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂) | Level.imax v₁ v₂ _ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂) | Level.zero _ => pure u | Level.param .. => pure u | Level.mvar mvarId _ => let s ← get match s.mctx.getLevelAssignment? mvarId with | some v => visitLevel v | none => let p ← mkParamName let p := mkLevelParam p modify fun s => { s with mctx := s.mctx.assignLevel mvarId p } pure p partial def main (e : Expr) : M Expr := do if !e.hasMVar then pure e else match e with | Expr.proj _ _ s _ => return e.updateProj! (← main s) | Expr.forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | Expr.lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | Expr.letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | Expr.app f a _ => return e.updateApp! (← main f) (← main a) | Expr.mdata _ b _ => return e.updateMData! (← main b) | Expr.const _ us _ => return e.updateConst! (← us.mapM visitLevel) | Expr.sort u _ => return e.updateSort! (← visitLevel u) | Expr.mvar mvarId _ => let s ← get match s.mctx.getExprAssignment? mvarId with | some v => main v | none => pure e | e => pure e end LevelMVarToParam structure UnivMVarParamResult where mctx : MetavarContext newParamNames : Array Name nextParamIdx : Nat expr : Expr def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx } { mctx := s.mctx, newParamNames := s.paramNames, nextParamIdx := s.nextParamIdx, expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId end MetavarContext end Lean
113df8f9a669eff0d835ab67d9c705a68160bba3
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/equiv/mul_add.lean
4701f976cf4a6c1abe28c78fb29c07ef7c68e816
[ "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
23,275
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, Callum Sutton, Yury Kudryashov -/ import algebra.group.hom import algebra.group.type_tags import algebra.group.units_hom import algebra.group_with_zero /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. ## Notations * ``infix ` ≃* `:25 := mul_equiv`` * ``infix ` ≃+ `:25 := add_equiv`` The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. ## Tags equiv, mul_equiv, add_equiv -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {G : Type*} {H : Type*} /-- Makes a multiplicative inverse from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive inverse from a bijection which preserves addition."] def mul_hom.inverse [has_mul M] [has_mul N] (f : mul_hom M N) (g : N → M) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : mul_hom N M := { to_fun := g, map_mul' := λ x y, calc g (x * y) = g (f (g x) * f (g y)) : by rw [h₂ x, h₂ y] ... = g (f (g x * g y)) : by rw f.map_mul ... = g x * g y : h₁ _, } /-- The inverse of a bijective `monoid_hom` is a `monoid_hom`. -/ @[to_additive "The inverse of a bijective `add_monoid_hom` is an `add_monoid_hom`.", simps] def monoid_hom.inverse {A B : Type*} [monoid A] [monoid B] (f : A →* B) (g : B → A) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : B →* A := { to_fun := g, map_one' := by rw [← f.map_one, h₁], .. (f : mul_hom A B).inverse g h₁ h₂, } set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ @[ancestor equiv add_hom] structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- The `add_hom` underlying a `add_equiv`. -/ add_decl_doc add_equiv.to_add_hom /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[ancestor equiv mul_hom, to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv /-- The `mul_hom` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_mul_hom infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) := ⟨_, mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] [has_mul Q] @[simp, to_additive] lemma to_fun_eq_coe {f : M ≃* N} : f.to_fun = f := rfl @[simp, to_additive] lemma coe_to_equiv {f : M ≃* N} : ⇑f.to_equiv = f := rfl @[simp, to_additive] lemma coe_to_mul_hom {f : M ≃* N} : ⇑f.to_mul_hom = f := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp, to_additive] lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul' /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ @[to_additive] protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective @[to_additive] protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective @[to_additive] protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} @[to_additive] instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := (h.to_mul_hom.inverse h.to_equiv.symm h.left_inv h.right_inv).map_mul, .. h.to_equiv.symm} /-- See Note [custom simps projection] -/ -- we don't hyperlink the note in the additive version, since that breaks syntax highlighting -- in the whole file. @[to_additive "See Note custom simps projection"] def simps.symm_apply (e : M ≃* N) : N → M := e.symm initialize_simps_projections add_equiv (to_fun → apply, inv_fun → symm_apply) initialize_simps_projections mul_equiv (to_fun → apply, inv_fun → symm_apply) @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] lemma symm_symm : ∀ (f : M ≃* N), f.symm.symm = f | ⟨f, g, h₁, h₂, h₃⟩ := rfl @[to_additive] lemma symm_bijective : function.bijective (symm : (M ≃* N) → (N ≃* M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp, to_additive] theorem symm_mk (f : M → N) (g h₁ h₂ h₃) : (mul_equiv.mk f g h₁ h₂ h₃).symm = { to_fun := g, inv_fun := f, ..(mul_equiv.mk f g h₁ h₂ h₃).symm} := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp, to_additive] theorem symm_comp_self (e : M ≃* N) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp, to_additive] theorem self_comp_symm (e : M ≃* N) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp, to_additive] theorem coe_refl : ⇑(refl M) = id := rfl @[to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem coe_trans (e₁ : M ≃* N) (e₂ : N ≃* P) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[to_additive] theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl @[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y := e.injective.eq_iff @[to_additive] lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply @[to_additive] lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq @[to_additive] lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end attribute [ext] add_equiv.ext @[to_additive] lemma ext_iff {f g : mul_equiv M N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ @[simp, to_additive] lemma mk_coe (e : M ≃* N) (e' h₁ h₂ h₃) : (⟨e, e', h₁, h₂, h₃⟩ : M ≃* N) = e := ext $ λ _, rfl @[simp, to_additive] lemma mk_coe' (e : M ≃* N) (f h₁ h₂ h₃) : (mul_equiv.mk f ⇑e h₁ h₂ h₃ : N ≃* M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[to_additive] protected lemma congr_arg {f : mul_equiv M N} : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl @[to_additive] protected lemma congr_fun {f g : mul_equiv M N} (h : f = g) (x : M) : f x = g x := h ▸ rfl /-- The `mul_equiv` between two monoids with a unique element. -/ @[to_additive "The `add_equiv` between two add_monoids with a unique element."] def mul_equiv_of_unique_of_unique {M N} [unique M] [unique N] [has_mul M] [has_mul N] : M ≃* N := { map_mul' := λ _ _, subsingleton.elim _ _, ..equiv_of_unique_of_unique } /-- There is a unique monoid homomorphism between two monoids with a unique element. -/ @[to_additive] instance {M N} [unique M] [unique N] [has_mul M] [has_mul N] : unique (M ≃* N) := { default := mul_equiv_of_unique_of_unique , uniq := λ _, ext $ λ x, subsingleton.elim _ _} /-! ## Monoids -/ /-- A multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism). -/ @[simp, to_additive] lemma map_one {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one ▸ h.to_equiv.apply_eq_iff_eq @[to_additive] lemma map_ne_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- A bijective `monoid` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"] noncomputable def of_bijective {M N} [mul_one_class M] [mul_one_class N] (f : M →* N) (hf : function.bijective f) : M ≃* N := { map_mul' := f.map_mul', ..equiv.of_bijective f hf } /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma coe_to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (e : M ≃* N) : ⇑e.to_monoid_hom = e := rfl @[to_additive] lemma to_monoid_hom_injective {M N} [mul_one_class M] [mul_one_class N] : function.injective (to_monoid_hom : (M ≃* N) → M →* N) := λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h) /-- A multiplicative analogue of `equiv.arrow_congr`, where the equivalence between the targets is multiplicative. -/ @[to_additive "An additive analogue of `equiv.arrow_congr`, where the equivalence between the targets is additive.", simps apply] def arrow_congr {M N P Q : Type*} [mul_one_class P] [mul_one_class Q] (f : M ≃ N) (g : P ≃* Q) : (M → P) ≃* (N → Q) := { to_fun := λ h n, g (h (f.symm n)), inv_fun := λ k m, g.symm (k (f m)), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A multiplicative analogue of `equiv.arrow_congr`, for multiplicative maps from a monoid to a commutative monoid. -/ @[to_additive "An additive analogue of `equiv.arrow_congr`, for additive maps from an additive monoid to a commutative additive monoid.", simps apply] def monoid_hom_congr {M N P Q} [mul_one_class M] [mul_one_class N] [comm_monoid P] [comm_monoid Q] (f : M ≃* N) (g : P ≃* Q) : (M →* P) ≃* (N →* Q) := { to_fun := λ h, g.to_monoid_hom.comp (h.comp f.symm.to_monoid_hom), inv_fun := λ k, g.symm.to_monoid_hom.comp (k.comp f.to_monoid_hom), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A family of multiplicative equivalences `Π j, (Ms j ≃* Ns j)` generates a multiplicative equivalence between `Π j, Ms j` and `Π j, Ns j`. This is the `mul_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `mul_equiv.arrow_congr`. -/ @[to_additive add_equiv.Pi_congr_right "A family of additive equivalences `Π j, (Ms j ≃+ Ns j)` generates an additive equivalence between `Π j, Ms j` and `Π j, Ns j`. This is the `add_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `add_equiv.arrow_congr`.", simps apply] def Pi_congr_right {η : Type*} {Ms Ns : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] (es : ∀ j, Ms j ≃* Ns j) : (Π j, Ms j) ≃* (Π j, Ns j) := { to_fun := λ x j, es j (x j), inv_fun := λ x j, (es j).symm (x j), map_mul' := λ x y, funext $ λ j, (es j).map_mul (x j) (y j), .. equiv.Pi_congr_right (λ j, (es j).to_equiv) } @[simp] lemma Pi_congr_right_refl {η : Type*} {Ms : η → Type*} [Π j, mul_one_class (Ms j)] : Pi_congr_right (λ j, mul_equiv.refl (Ms j)) = mul_equiv.refl _ := rfl @[simp] lemma Pi_congr_right_symm {η : Type*} {Ms Ns : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] (es : ∀ j, Ms j ≃* Ns j) : (Pi_congr_right es).symm = (Pi_congr_right $ λ i, (es i).symm) := rfl @[simp] lemma Pi_congr_right_trans {η : Type*} {Ms Ns Ps : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] [Π j, mul_one_class (Ps j)] (es : ∀ j, Ms j ≃* Ns j) (fs : ∀ j, Ns j ≃* Ps j) : (Pi_congr_right es).trans (Pi_congr_right fs) = (Pi_congr_right $ λ i, (es i).trans (fs i)) := rfl /-! # Groups -/ /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp, to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x end mul_equiv -- We don't use `to_additive` to generate definition because it fails to tell Lean about -- equational lemmas /-- Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive monoid homomorphisms. -/ def add_monoid_hom.to_add_equiv [add_zero_class M] [add_zero_class N] (f : M →+ N) (g : N →+ M) (h₁ : g.comp f = add_monoid_hom.id _) (h₂ : f.comp g = add_monoid_hom.id _) : M ≃+ N := { to_fun := f, inv_fun := g, left_inv := add_monoid_hom.congr_fun h₁, right_inv := add_monoid_hom.congr_fun h₂, map_add' := f.map_add } /-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/ @[to_additive, simps {fully_applied := ff}] def monoid_hom.to_mul_equiv [mul_one_class M] [mul_one_class N] (f : M →* N) (g : N →* M) (h₁ : g.comp f = monoid_hom.id _) (h₂ : f.comp g = monoid_hom.id _) : M ≃* N := { to_fun := f, inv_fun := g, left_inv := monoid_hom.congr_fun h₁, right_inv := monoid_hom.congr_fun h₂, map_mul' := f.map_mul } /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y /-- A group is isomorphic to its group of units. -/ @[to_additive to_add_units "An additive group is isomorphic to its group of additive units"] def to_units {G} [group G] : G ≃* units G := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } protected lemma group.is_unit {G} [group G] (x : G) : is_unit x := (to_units x).is_unit namespace units variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type.", simps apply {fully_applied := ff}] def mul_left (u : units M) : equiv.perm M := { to_fun := λx, u * x, inv_fun := λx, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ λ x, rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type.", simps apply {fully_applied := ff}] def mul_right (u : units M) : equiv.perm M := { to_fun := λx, x * u, inv_fun := λx, x * ↑u⁻¹, left_inv := λ x, mul_inv_cancel_right x u, right_inv := λ x, inv_mul_cancel_right x u } @[simp, to_additive] lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ λ x, rfl end units namespace equiv section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_left_symm_apply (a : G) : ((equiv.mul_left a).symm : G → G) = (*) a⁻¹ := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ λ x, rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ λ x, rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_right_symm_apply (a : G) : ((equiv.mul_right a).symm : G → G) = λ x, x * a⁻¹ := rfl attribute [nolint simp_nf] add_left_symm_apply add_right_symm_apply variable (G) /-- Inversion on a `group` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type.", simps apply {fully_applied := ff}] protected def inv : perm G := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } variable {G} @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl end group section group_with_zero variables [group_with_zero G] /-- Left multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_left' (a : G) (ha : a ≠ 0) : perm G := { to_fun := λ x, a * x, inv_fun := λ x, a⁻¹ * x, left_inv := λ x, by { dsimp, rw [← mul_assoc, inv_mul_cancel ha, one_mul] }, right_inv := λ x, by { dsimp, rw [← mul_assoc, mul_inv_cancel ha, one_mul] } } /-- Right multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_right' (a : G) (ha : a ≠ 0) : perm G := { to_fun := λ x, x * a, inv_fun := λ x, x * a⁻¹, left_inv := λ x, by { dsimp, rw [mul_assoc, mul_inv_cancel ha, mul_one] }, right_inv := λ x, by { dsimp, rw [mul_assoc, inv_mul_cancel ha, mul_one] } } end group_with_zero end equiv /-- When the group is commutative, `equiv.inv` is a `mul_equiv`. There is a variant of this `mul_equiv.inv' G : G ≃* Gᵒᵖ` for the non-commutative case. -/ @[to_additive "When the `add_group` is commutative, `equiv.neg` is an `add_equiv`."] def mul_equiv.inv (G : Type*) [comm_group G] : G ≃* G := { to_fun := has_inv.inv, inv_fun := has_inv.inv, map_mul' := mul_inv, ..equiv.inv G} section type_tags /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_zero_class G] [add_zero_class H] : (G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [mul_one_class G] [mul_one_class H] : (G ≃* H) ≃ (additive G ≃+ additive H) := { to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' [mul_one_class G] [add_zero_class H] : (additive G ≃+ H) ≃ (G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' [mul_one_class G] [add_zero_class H] : (G ≃* multiplicative H) ≃ (additive G ≃+ H) := add_equiv.to_multiplicative'.symm /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' [add_zero_class G] [mul_one_class H] : (G ≃+ additive H) ≃ (multiplicative G ≃* H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' [add_zero_class G] [mul_one_class H] : (multiplicative G ≃* H) ≃ (G ≃+ additive H) := add_equiv.to_multiplicative''.symm end type_tags
58322a1db9b86e4c3e4571ec2b5db242015d6ae6
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/opens.lean
d8385f302131de62566286762521c131058440c0
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
5,933
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 Subtype of open subsets in a topological space. -/ import topology.bases topology.subset_properties topology.constructions open filter lattice variables {α : Type*} [topological_space α] namespace topological_space variable (α) /-- The type of open subsets of a topological space. -/ def opens := {s : set α // _root_.is_open s} /-- The type of closed subsets of a topological space. -/ def closeds := {s : set α // is_closed s} /-- The type of non-empty compact subsets of a topological space. The non-emptiness will be useful in metric spaces, as we will be able to put a distance (and not merely an edistance) on this space. -/ def nonempty_compacts := {s : set α // s ≠ ∅ ∧ compact s} section nonempty_compacts open topological_space set variable {α} instance nonempty_compacts.to_compact_space {p : nonempty_compacts α} : compact_space p.val := ⟨compact_iff_compact_univ.1 p.property.2⟩ instance nonempty_compacts.to_nonempty {p : nonempty_compacts α} : nonempty p.val := nonempty_subtype.2 $ ne_empty_iff_exists_mem.1 p.property.1 /-- Associate to a nonempty compact subset the corresponding closed subset -/ def nonempty_compacts.to_closeds [t2_space α] (s : nonempty_compacts α) : closeds α := ⟨s.val, closed_of_compact _ s.property.2⟩ end nonempty_compacts variable {α} namespace opens instance : has_coe (opens α) (set α) := { coe := subtype.val } instance : has_subset (opens α) := { subset := λ U V, U.val ⊆ V.val } instance : has_mem α (opens α) := { mem := λ a U, a ∈ U.val } @[extensionality] lemma ext {U V : opens α} (h : U.val = V.val) : U = V := subtype.ext.mpr h instance : partial_order (opens α) := subtype.partial_order _ def interior (s : set α) : opens α := ⟨interior s, is_open_interior⟩ def gc : galois_connection (subtype.val : opens α → set α) interior := λ U s, ⟨λ h, interior_maximal h U.property, λ h, le_trans h interior_subset⟩ def gi : @galois_insertion (order_dual (set α)) (order_dual (opens α)) _ _ interior (subtype.val) := { choice := λ s hs, ⟨s, interior_eq_iff_open.mp $ le_antisymm interior_subset hs⟩, gc := gc.dual, le_l_u := λ _, interior_subset, choice_eq := λ s hs, le_antisymm interior_subset hs } @[simp] lemma gi_choice_val {s : order_dual (set α)} {hs} : (gi.choice s hs).val = s := rfl instance : complete_lattice (opens α) := complete_lattice.copy (@order_dual.lattice.complete_lattice _ (@galois_insertion.lift_complete_lattice (order_dual (set α)) (order_dual (opens α)) _ interior (subtype.val : opens α → set α) _ gi)) /- le -/ (λ U V, U.1 ⊆ V.1) rfl /- top -/ ⟨set.univ, _root_.is_open_univ⟩ (subtype.ext.mpr interior_univ.symm) /- bot -/ ⟨∅, is_open_empty⟩ rfl /- sup -/ (λ U V, ⟨U.1 ∪ V.1, _root_.is_open_union U.2 V.2⟩) rfl /- inf -/ (λ U V, ⟨U.1 ∩ V.1, _root_.is_open_inter U.2 V.2⟩) begin funext, apply subtype.ext.mpr, symmetry, apply interior_eq_of_open, exact (_root_.is_open_inter U.2 V.2), end /- Sup -/ (λ Us, ⟨⋃₀ (subtype.val '' Us), _root_.is_open_sUnion $ λ U hU, by { rcases hU with ⟨⟨V, hV⟩, h, h'⟩, dsimp at h', subst h', exact hV}⟩) begin funext, apply subtype.ext.mpr, simp [Sup_range], refl, end /- Inf -/ _ rfl instance : has_inter (opens α) := ⟨λ U V, U ⊓ V⟩ instance : has_union (opens α) := ⟨λ U V, U ⊔ V⟩ instance : has_emptyc (opens α) := ⟨⊥⟩ @[simp] lemma inter_eq (U V : opens α) : U ∩ V = U ⊓ V := rfl @[simp] lemma union_eq (U V : opens α) : U ∪ V = U ⊔ V := rfl @[simp] lemma empty_eq : (∅ : opens α) = ⊥ := rfl @[simp] lemma Sup_s {Us : set (opens α)} : (Sup Us).val = ⋃₀ (subtype.val '' Us) := begin rw [@galois_connection.l_Sup (opens α) (set α) _ _ (subtype.val : opens α → set α) interior gc Us, set.sUnion_image], congr end def is_basis (B : set (opens α)) : Prop := is_topological_basis (subtype.val '' B) lemma is_basis_iff_nbhd {B : set (opens α)} : is_basis B ↔ ∀ {U : opens α} {x}, x ∈ U → ∃ U' ∈ B, x ∈ U' ∧ U' ⊆ U := begin split; intro h, { rintros ⟨sU, hU⟩ x hx, rcases (mem_nhds_of_is_topological_basis h).mp (mem_nhds_sets hU hx) with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩, refine ⟨V, H₁, _⟩, cases V, dsimp at H₂, subst H₂, exact hsV }, { refine is_topological_basis_of_open_of_nhds _ _, { rintros sU ⟨U, ⟨H₁, H₂⟩⟩, subst H₂, exact U.property }, { intros x sU hx hsU, rcases @h (⟨sU, hsU⟩ : opens α) x hx with ⟨V, hV, H⟩, exact ⟨V, ⟨V, hV, rfl⟩, H⟩ } } end lemma is_basis_iff_cover {B : set (opens α)} : is_basis B ↔ ∀ U : opens α, ∃ Us ⊆ B, U = Sup Us := begin split, { intros hB U, rcases sUnion_basis_of_is_open hB U.property with ⟨sUs, H, hU⟩, existsi {U : opens α | U ∈ B ∧ U.val ∈ sUs}, split, { intros U hU, exact hU.left }, { apply ext, rw [Sup_s, hU], congr, ext s; split; intro hs, { rcases H hs with ⟨V, hV⟩, rw ← hV.right at hs, refine ⟨V, ⟨⟨hV.left, hs⟩, hV.right⟩⟩ }, { rcases hs with ⟨V, ⟨⟨H₁, H₂⟩, H₃⟩⟩, subst H₃, exact H₂ } } }, { intro h, rw is_basis_iff_nbhd, intros U x hx, rcases h U with ⟨Us, hUs, H⟩, replace H := congr_arg subtype.val H, rw Sup_s at H, change x ∈ U.val at hx, rw H at hx, rcases set.mem_sUnion.mp hx with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩, refine ⟨V,hUs H₁,_⟩, cases V with V hV, dsimp at H₂, subst H₂, refine ⟨hsV,_⟩, change V ⊆ U.val, rw H, exact set.subset_sUnion_of_mem ⟨⟨V, _⟩, ⟨H₁, rfl⟩⟩ } end end opens end topological_space
aea1f801bdd9278a376cb3791319fbf969d74e92
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Data/SMap.lean
8bfc7b7393c4c51f76412b9622215061393ab654
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,074
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.HashMap import Init.Data.PersistentHashMap universes u v w w' namespace Lean /- Staged map for implementing the Environment. The idea is to store imported entries into a hashtable and local entries into a persistent hashtable. Hypotheses: - The number of entries (i.e., declarations) coming from imported files is much bigger than the number of entries in the current file. - HashMap is faster than PersistentHashMap. - When we are reading imported files, we have exclusive access to the map, and efficient destructive updates are performed. Remarks: - We never remove declarations from the Environment. In principle, we could support deletion by using `(PHashMap α (Option β))` where the value `none` would indicate that an entry was "removed" from the hashtable. - We do not need additional bookkeeping for extracting the local entries. -/ structure SMap (α : Type u) (β : Type v) [HasBeq α] [Hashable α] := (stage₁ : Bool := true) (map₁ : HashMap α β := {}) (map₂ : PHashMap α β := {}) namespace SMap variables {α : Type u} {β : Type v} [HasBeq α] [Hashable α] instance : Inhabited (SMap α β) := ⟨{}⟩ def empty : SMap α β := {} instance : HasEmptyc (SMap α β) := ⟨SMap.empty⟩ @[specialize] def insert : SMap α β → α → β → SMap α β | ⟨true, m₁, m₂⟩, k, v => ⟨true, m₁.insert k v, m₂⟩ | ⟨false, m₁, m₂⟩, k, v => ⟨false, m₁, m₂.insert k v⟩ @[specialize] def find? : SMap α β → α → Option β | ⟨true, m₁, _⟩, k => m₁.find? k | ⟨false, m₁, m₂⟩, k => (m₂.find? k).orelse (m₁.find? k) @[inline] def findD (m : SMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : SMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" @[specialize] def contains : SMap α β → α → Bool | ⟨true, m₁, _⟩, k => m₁.contains k | ⟨false, m₁, m₂⟩, k => m₁.contains k || m₂.contains k /- Similar to `find?`, but searches for result in the hashmap first. So, the result is correct only if we never "overwrite" `map₁` entries using `map₂`. -/ @[specialize] def find?' : SMap α β → α → Option β | ⟨true, m₁, _⟩, k => m₁.find? k | ⟨false, m₁, m₂⟩, k => (m₁.find? k).orelse (m₂.find? k) /- Move from stage 1 into stage 2. -/ def switch (m : SMap α β) : SMap α β := if m.stage₁ then { m with stage₁ := false } else m @[inline] def foldStage2 {σ : Type w} (f : σ → α → β → σ) (s : σ) (m : SMap α β) : σ := m.map₂.foldl f s def size (m : SMap α β) : Nat := m.map₁.size + m.map₂.size def stageSizes (m : SMap α β) : Nat × Nat := (m.map₁.size, m.map₂.size) def numBuckets (m : SMap α β) : Nat := m.map₁.numBuckets end SMap end Lean
e2b234338ac7b9fa1548107ce85fa8004f21a8ef
3446e92e64a5de7ed1f2109cfb024f83cd904c34
/src/game/world3/level11.lean
c14ad0e4e1d65357b8e47da677b34125036256cd
[]
no_license
kckennylau/natural_number_game
019f4a5f419c9681e65234ecd124c564f9a0a246
ad8c0adaa725975be8a9f978c8494a39311029be
refs/heads/master
1,598,784,137,722
1,571,905,156,000
1,571,905,156,000
218,354,686
0
0
null
1,572,373,319,000
1,572,373,318,000
null
UTF-8
Lean
false
false
692
lean
import game.world3.level10 -- hide import game.world2.level7 -- succ ne zero -- hide import game.world2.level13 -- add_left_eq_zero -- hide namespace mynat -- hide /- # Multiplication World ## Level 11: `mul_eq_zero_iff` Now you have `eq_zero_or_eq_zero_of_mul_eq_zero` this is pretty straightforward. -/ /- Theorem $a * b = 0$, if and only if at least one of $a$ or $b$ is equal to zero. -/ theorem mul_eq_zero_iff : ∀ (a b : mynat), a * b = 0 ↔ a = 0 ∨ b = 0 := begin [less_leaky] intros a b, split, swap, intro hab, cases hab, rw hab, rw zero_mul, refl, rw hab, rw mul_zero, refl, intro h, exact eq_zero_or_eq_zero_of_mul_eq_zero h, end end mynat -- hide
abed4c6324e680c509578550430efcc12acdffdc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/manifold/algebra/left_invariant_derivation.lean
eb5dd7aff269220c0b0f6a6131ebc84e73b27cb4
[ "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,027
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import ring_theory.derivation.lie import geometry.manifold.derivation_bundle /-! # Left invariant derivations > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define the concept of left invariant derivation for a Lie group. The concept is analogous to the more classical concept of left invariant vector fields, and it holds that the derivation associated to a vector field is left invariant iff the field is. Moreover we prove that `left_invariant_derivation I G` has the structure of a Lie algebra, hence implementing one of the possible definitions of the Lie algebra attached to a Lie group. -/ noncomputable theory open_locale lie_group manifold derivation variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (G : Type*) [topological_space G] [charted_space H G] [monoid G] [has_smooth_mul I G] (g h : G) -- Generate trivial has_sizeof instance. It prevents weird type class inference timeout problems local attribute [nolint instance_priority, instance, priority 10000] private def disable_has_sizeof {α} : has_sizeof α := ⟨λ _, 0⟩ /-- Left-invariant global derivations. A global derivation is left-invariant if it is equal to its pullback along left multiplication by an arbitrary element of `G`. -/ structure left_invariant_derivation extends derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯ := (left_invariant'' : ∀ g, 𝒅ₕ(smooth_left_mul_one I g) (derivation.eval_at 1 to_derivation) = derivation.eval_at g to_derivation) variables {I G} namespace left_invariant_derivation instance : has_coe (left_invariant_derivation I G) (derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) := ⟨λ X, X.to_derivation⟩ instance : has_coe_to_fun (left_invariant_derivation I G) (λ _, C^∞⟮I, G; 𝕜⟯ → C^∞⟮I, G; 𝕜⟯) := ⟨λ X, X.to_derivation.to_fun⟩ variables {M : Type*} [topological_space M] [charted_space H M] {x : M} {r : 𝕜} {X Y : left_invariant_derivation I G} {f f' : C^∞⟮I, G; 𝕜⟯} lemma to_fun_eq_coe : X.to_fun = ⇑X := rfl lemma coe_to_linear_map : ⇑(X : C^∞⟮I, G; 𝕜⟯ →ₗ[𝕜] C^∞⟮I, G; 𝕜⟯) = X := rfl @[simp] lemma to_derivation_eq_coe : X.to_derivation = X := rfl lemma coe_injective : @function.injective (left_invariant_derivation I G) (_ → C^⊤⟮I, G; 𝕜⟯) coe_fn := λ X Y h, by { cases X, cases Y, congr', exact derivation.coe_injective h } @[ext] theorem ext (h : ∀ f, X f = Y f) : X = Y := coe_injective $ funext h variables (X Y f) lemma coe_derivation : ⇑(X : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = (X : C^∞⟮I, G; 𝕜⟯ → C^∞⟮I, G; 𝕜⟯) := rfl lemma coe_derivation_injective : function.injective (coe : left_invariant_derivation I G → derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) := λ X Y h, by { cases X, cases Y, congr, exact h } /-- Premature version of the lemma. Prefer using `left_invariant` instead. -/ lemma left_invariant' : 𝒅ₕ (smooth_left_mul_one I g) (derivation.eval_at (1 : G) ↑X) = derivation.eval_at g ↑X := left_invariant'' X g @[simp] lemma map_add : X (f + f') = X f + X f' := derivation.map_add X f f' @[simp] lemma map_zero : X 0 = 0 := derivation.map_zero X @[simp] lemma map_neg : X (-f) = -X f := derivation.map_neg X f @[simp] lemma map_sub : X (f - f') = X f - X f' := derivation.map_sub X f f' @[simp] lemma map_smul : X (r • f) = r • X f := derivation.map_smul X r f @[simp] lemma leibniz : X (f * f') = f • X f' + f' • X f := X.leibniz' _ _ instance : has_zero (left_invariant_derivation I G) := ⟨⟨0, λ g, by simp only [linear_map.map_zero, derivation.coe_zero]⟩⟩ instance : inhabited (left_invariant_derivation I G) := ⟨0⟩ instance : has_add (left_invariant_derivation I G) := { add := λ X Y, ⟨X + Y, λ g, by simp only [linear_map.map_add, derivation.coe_add, left_invariant', pi.add_apply]⟩ } instance : has_neg (left_invariant_derivation I G) := { neg := λ X, ⟨-X, λ g, by simp [left_invariant']⟩ } instance : has_sub (left_invariant_derivation I G) := { sub := λ X Y, ⟨X - Y, λ g, by simp [left_invariant']⟩ } @[simp] lemma coe_add : ⇑(X + Y) = X + Y := rfl @[simp] lemma coe_zero : ⇑(0 : left_invariant_derivation I G) = 0 := rfl @[simp] lemma coe_neg : ⇑(-X) = -X := rfl @[simp] lemma coe_sub : ⇑(X - Y) = X - Y := rfl @[simp, norm_cast] lemma lift_add : (↑(X + Y) : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = X + Y := rfl @[simp, norm_cast] lemma lift_zero : (↑(0 : left_invariant_derivation I G) : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = 0 := rfl instance has_nat_scalar : has_smul ℕ (left_invariant_derivation I G) := { smul := λ r X, ⟨r • X, λ g, by simp_rw [linear_map.map_smul_of_tower, left_invariant']⟩ } instance has_int_scalar : has_smul ℤ (left_invariant_derivation I G) := { smul := λ r X, ⟨r • X, λ g, by simp_rw [linear_map.map_smul_of_tower, left_invariant']⟩ } instance : add_comm_group (left_invariant_derivation I G) := coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance : has_smul 𝕜 (left_invariant_derivation I G) := { smul := λ r X, ⟨r • X, λ g, by simp_rw [linear_map.map_smul, left_invariant']⟩ } variables (r X) @[simp] lemma coe_smul : ⇑(r • X) = r • X := rfl @[simp] lemma lift_smul (k : 𝕜) : (↑(k • X) : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) = k • X := rfl variables (I G) /-- The coercion to function is a monoid homomorphism. -/ @[simps] def coe_fn_add_monoid_hom : (left_invariant_derivation I G) →+ (C^∞⟮I, G; 𝕜⟯ → C^∞⟮I, G; 𝕜⟯) := ⟨λ X, X.to_derivation.to_fun, coe_zero, coe_add⟩ variables {I G} instance : module 𝕜 (left_invariant_derivation I G) := coe_injective.module _ (coe_fn_add_monoid_hom I G) coe_smul /-- Evaluation at a point for left invariant derivation. Same thing as for generic global derivations (`derivation.eval_at`). -/ def eval_at : (left_invariant_derivation I G) →ₗ[𝕜] (point_derivation I g) := { to_fun := λ X, derivation.eval_at g ↑X, map_add' := λ X Y, rfl, map_smul' := λ k X, rfl } lemma eval_at_apply : eval_at g X f = (X f) g := rfl @[simp] lemma eval_at_coe : derivation.eval_at g ↑X = eval_at g X := rfl lemma left_invariant : 𝒅ₕ(smooth_left_mul_one I g) (eval_at (1 : G) X) = eval_at g X := (X.left_invariant'' g) lemma eval_at_mul : eval_at (g * h) X = 𝒅ₕ(L_apply I g h) (eval_at h X) := by { ext f, rw [←left_invariant, apply_hfdifferential, apply_hfdifferential, L_mul, fdifferential_comp, apply_fdifferential, linear_map.comp_apply, apply_fdifferential, ←apply_hfdifferential, left_invariant] } lemma comp_L : (X f).comp (𝑳 I g) = X (f.comp (𝑳 I g)) := by ext h; rw [cont_mdiff_map.comp_apply, L_apply, ←eval_at_apply, eval_at_mul, apply_hfdifferential, apply_fdifferential, eval_at_apply] instance : has_bracket (left_invariant_derivation I G) (left_invariant_derivation I G) := { bracket := λ X Y, ⟨⁅(X : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯), Y⁆, λ g, begin ext f, have hX := derivation.congr_fun (left_invariant' g X) (Y f), have hY := derivation.congr_fun (left_invariant' g Y) (X f), rw [apply_hfdifferential, apply_fdifferential, derivation.eval_at_apply] at hX hY ⊢, rw comp_L at hX hY, rw [derivation.commutator_apply, smooth_map.coe_sub, pi.sub_apply, coe_derivation], rw coe_derivation at hX hY ⊢, rw [hX, hY], refl end⟩ } @[simp] lemma commutator_coe_derivation : ⇑⁅X, Y⁆ = (⁅(X : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯), Y⁆ : derivation 𝕜 C^∞⟮I, G; 𝕜⟯ C^∞⟮I, G; 𝕜⟯) := rfl lemma commutator_apply : ⁅X, Y⁆ f = X (Y f) - Y (X f) := rfl instance : lie_ring (left_invariant_derivation I G) := { add_lie := λ X Y Z, by { ext1, simp only [commutator_apply, coe_add, pi.add_apply, linear_map.map_add, left_invariant_derivation.map_add], ring }, lie_add := λ X Y Z, by { ext1, simp only [commutator_apply, coe_add, pi.add_apply, linear_map.map_add, left_invariant_derivation.map_add], ring }, lie_self := λ X, by { ext1, simp only [commutator_apply, sub_self], refl }, leibniz_lie := λ X Y Z, by { ext1, simp only [commutator_apply, coe_add, coe_sub, map_sub, pi.add_apply], ring, } } instance : lie_algebra 𝕜 (left_invariant_derivation I G) := { lie_smul := λ r Y Z, by { ext1, simp only [commutator_apply, map_smul, smul_sub, coe_smul, pi.smul_apply] } } end left_invariant_derivation
a5a516002316251db5ceb895eb4cffde7a88648f
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/buffer/parser/basic.lean
f441a8aa34eeba30b74f6806c50fdd41a264107b
[ "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
110,135
lean
/- Copyright (c) 2020 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.string.basic import data.buffer.basic import data.nat.digits /-! # Parsers `parser α` is the type that describes a computation that can ingest a `char_buffer` and output, if successful, a term of type `α`. This file expands on the definitions in the core library, proving that all the core library parsers are `mono`. There are also lemmas on the composability of parsers. ## Main definitions * `parse_result.pos` : The position of a `char_buffer` at which a `parser α` has finished. * `parser.mono` : The property that a parser only moves forward within a buffer, in both cases of success or failure. ## Implementation details Lemmas about how parsers are mono are in the `mono` namespace. That allows using projection notation for shorter term proofs that are parallel to the definitions of the parsers in structure. -/ open parser parse_result /-- For some `parse_result α`, give the position at which the result was provided, in either the `done` or the `fail` case. -/ @[simp] def parse_result.pos {α} : parse_result α → ℕ | (done n _) := n | (fail n _) := n namespace parser section defn_lemmas variables {α β : Type} (msgs : thunk (list string)) (msg : thunk string) variables (p q : parser α) (cb : char_buffer) (n n' : ℕ) {err : dlist string} variables {a : α} {b : β} /-- A `p : parser α` is defined to be `mono` if the result `p cb n` it gives, for some `cb : char_buffer` and `n : ℕ`, (whether `done` or `fail`), is always at a `parse_result.pos` that is at least `n`. The `mono` property is used mainly for proper `orelse` behavior. -/ class mono : Prop := (le' : ∀ (cb : char_buffer) (n : ℕ), n ≤ (p cb n).pos) lemma mono.le [p.mono] : n ≤ (p cb n).pos := mono.le' cb n /-- A `parser α` is defined to be `static` if it does not move on success. -/ class static : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n = n') /-- A `parser α` is defined to be `err_static` if it does not move on error. -/ class err_static : Prop := (of_fail : ∀ {cb : char_buffer} {n n' : ℕ} {err : dlist string}, p cb n = fail n' err → n = n') /-- A `parser α` is defined to be `step` if it always moves exactly one char forward on success. -/ class step : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n' = n + 1) /-- A `parser α` is defined to be `prog` if it always moves forward on success. -/ class prog : Prop := (of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n < n') /-- A `parser a` is defined to be `bounded` if it produces a `fail` `parse_result` when it is parsing outside the provided `char_buffer`. -/ class bounded : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, cb.size ≤ n → ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err) lemma bounded.exists (p : parser α) [p.bounded] {cb : char_buffer} {n : ℕ} (h : cb.size ≤ n) : ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err := bounded.ex' h /-- A `parser a` is defined to be `unfailing` if it always produces a `done` `parse_result`. -/ class unfailing : Prop := (ex' : ∀ (cb : char_buffer) (n : ℕ), ∃ (n' : ℕ) (a : α), p cb n = done n' a) /-- A `parser a` is defined to be `conditionally_unfailing` if it produces a `done` `parse_result` as long as it is parsing within the provided `char_buffer`. -/ class conditionally_unfailing : Prop := (ex' : ∀ {cb : char_buffer} {n : ℕ}, n < cb.size → ∃ (n' : ℕ) (a : α), p cb n = done n' a) lemma fail_iff : (∀ pos' result, p cb n ≠ done pos' result) ↔ ∃ (pos' : ℕ) (err : dlist string), p cb n = fail pos' err := by cases p cb n; simp lemma success_iff : (∀ pos' err, p cb n ≠ fail pos' err) ↔ ∃ (pos' : ℕ) (result : α), p cb n = done pos' result := by cases p cb n; simp variables {p q cb n n' msgs msg} lemma mono.of_done [p.mono] (h : p cb n = done n' a) : n ≤ n' := by simpa [h] using mono.le p cb n lemma mono.of_fail [p.mono] (h : p cb n = fail n' err) : n ≤ n' := by simpa [h] using mono.le p cb n lemma bounded.of_done [p.bounded] (h : p cb n = done n' a) : n < cb.size := begin contrapose! h, obtain ⟨np, err, hp⟩ := bounded.exists p h, simp [hp] end lemma static.iff : static p ↔ (∀ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a → n = n') := ⟨λ h _ _ _ _ hp, by { haveI := h, exact static.of_done hp}, λ h, ⟨h⟩⟩ lemma exists_done (p : parser α) [p.unfailing] (cb : char_buffer) (n : ℕ) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := unfailing.ex' cb n lemma unfailing.of_fail [p.unfailing] (h : p cb n = fail n' err) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done cb n, simpa [hp] using h end @[priority 100] -- see Note [lower instance priority] instance conditionally_unfailing_of_unfailing [p.unfailing] : conditionally_unfailing p := ⟨λ _ _ _, p.exists_done _ _⟩ lemma exists_done_in_bounds (p : parser α) [p.conditionally_unfailing] {cb : char_buffer} {n : ℕ} (h : n < cb.size) : ∃ (n' : ℕ) (a : α), p cb n = done n' a := conditionally_unfailing.ex' h lemma conditionally_unfailing.of_fail [p.conditionally_unfailing] (h : p cb n = fail n' err) (hn : n < cb.size) : false := begin obtain ⟨np, a, hp⟩ := p.exists_done_in_bounds hn, simpa [hp] using h end lemma decorate_errors_fail (h : p cb n = fail n' err) : @decorate_errors α msgs p cb n = fail n ((dlist.lazy_of_list (msgs ()))) := by simp [decorate_errors, h] lemma decorate_errors_success (h : p cb n = done n' a) : @decorate_errors α msgs p cb n = done n' a := by simp [decorate_errors, h] lemma decorate_error_fail (h : p cb n = fail n' err) : @decorate_error α msg p cb n = fail n ((dlist.lazy_of_list ([msg ()]))) := decorate_errors_fail h lemma decorate_error_success (h : p cb n = done n' a) : @decorate_error α msg p cb n = done n' a := decorate_errors_success h @[simp] lemma decorate_errors_eq_done : @decorate_errors α msgs p cb n = done n' a ↔ p cb n = done n' a := by cases h : p cb n; simp [decorate_errors, h] @[simp] lemma decorate_error_eq_done : @decorate_error α msg p cb n = done n' a ↔ p cb n = done n' a := decorate_errors_eq_done @[simp] lemma decorate_errors_eq_fail : @decorate_errors α msgs p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list (msgs ()) ∧ ∃ np err', p cb n = fail np err' := by cases h : p cb n; simp [decorate_errors, h, eq_comm] @[simp] lemma decorate_error_eq_fail : @decorate_error α msg p cb n = fail n' err ↔ n = n' ∧ err = dlist.lazy_of_list ([msg ()]) ∧ ∃ np err', p cb n = fail np err' := decorate_errors_eq_fail @[simp] lemma return_eq_pure : (@return parser _ _ a) = pure a := rfl lemma pure_eq_done : (@pure parser _ _ a) = λ _ n, done n a := rfl @[simp] lemma pure_ne_fail : (pure a : parser α) cb n ≠ fail n' err := by simp [pure_eq_done] section bind variable (f : α → parser β) @[simp] lemma bind_eq_bind : p.bind f = p >>= f := rfl variable {f} @[simp] lemma bind_eq_done : (p >>= f) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = done n' b := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma bind_eq_fail : (p >>= f) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = fail n' err) := by cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc] @[simp] lemma and_then_eq_bind {α β : Type} {m : Type → Type} [monad m] (a : m α) (b : m β) : a >> b = a >>= (λ _, b) := rfl lemma and_then_fail : (p >> return ()) cb n = parse_result.fail n' err ↔ p cb n = fail n' err := by simp [pure_eq_done] lemma and_then_success : (p >> return ()) cb n = parse_result.done n' () ↔ ∃ a, p cb n = done n' a:= by simp [pure_eq_done] end bind section map variable {f : α → β} @[simp] lemma map_eq_done : (f <$> p) cb n = done n' b ↔ ∃ (a : α), p cb n = done n' a ∧ f a = b := by cases hp : p cb n; simp [←is_lawful_monad.bind_pure_comp_eq_map, hp, and_assoc, pure_eq_done] @[simp] lemma map_eq_fail : (f <$> p) cb n = fail n' err ↔ p cb n = fail n' err := by simp [←bind_pure_comp_eq_map, pure_eq_done] @[simp] lemma map_const_eq_done {b'} : (b <$ p) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := by simp [map_const_eq] @[simp] lemma map_const_eq_fail : (b <$ p) cb n = fail n' err ↔ p cb n = fail n' err := by simp only [map_const_eq, map_eq_fail] lemma map_const_rev_eq_done {b'} : (p $> b) cb n = done n' b' ↔ ∃ (a : α), p cb n = done n' a ∧ b = b' := map_const_eq_done lemma map_rev_const_eq_fail : (p $> b) cb n = fail n' err ↔ p cb n = fail n' err := map_const_eq_fail end map @[simp] lemma orelse_eq_orelse : p.orelse q = (p <|> q) := rfl @[simp] lemma orelse_eq_done : (p <|> q) cb n = done n' a ↔ (p cb n = done n' a ∨ (q cb n = done n' a ∧ ∃ err, p cb n = fail n err)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hn, hq, H, not_lt_of_lt H, lt_irrefl, ←orelse_eq_orelse, parser.orelse] <|> simp [hp, hn, hq, lt_irrefl, ←orelse_eq_orelse, parser.orelse] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end @[simp] lemma orelse_eq_fail_eq : (p <|> q) cb n = fail n err ↔ (p cb n = fail n err ∧ ∃ (nq errq), n < nq ∧ q cb n = fail nq errq) ∨ (∃ (errp errq), p cb n = fail n errp ∧ q cb n = fail n errq ∧ errp ++ errq = err) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases hn : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|rfl|H; simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, H, ne_of_gt H, ne_of_lt H, not_lt_of_lt H] <|> simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, lt_irrefl] } }, { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_not_mono_lt (hn : n' < n) : (p <|> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (q cb n = fail n' err ∧ (∃ (errp), p cb n = fail n errp)) := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, ne_of_gt hn, ←orelse_eq_orelse, parser.orelse] }, { rcases lt_trichotomy nq n with H|H|H, { simp [hp, hq, h, H, ne_of_gt hn, not_lt_of_lt H, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, H, ne_of_gt (hn.trans H), ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } } end lemma orelse_eq_fail_of_mono_ne [q.mono] (hn : n ≠ n') : (p <|> q) cb n = fail n' err ↔ p cb n = fail n' err := begin cases hp : p cb n with np resp np errp, { simp [hp, ←orelse_eq_orelse, parser.orelse] }, { by_cases h : np = n, { cases hq : q cb n with nq resq nq errq, { simp [hp, h, hn, hq, hn, ←orelse_eq_orelse, parser.orelse] }, { have : n ≤ nq := mono.of_fail hq, rcases eq_or_lt_of_le this with rfl|H, { simp [hp, hq, h, hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] }, { simp [hp, hq, h, hn, H, ←orelse_eq_orelse, parser.orelse] } } }, { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } }, end @[simp] lemma failure_eq_failure : @parser.failure α = failure := rfl @[simp] lemma failure_def : (failure : parser α) cb n = fail n dlist.empty := rfl lemma not_failure_eq_done : ¬ (failure : parser α) cb n = done n' a := by simp lemma failure_eq_fail : (failure : parser α) cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [eq_comm] lemma seq_eq_done {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = done n' b ↔ ∃ (nf : ℕ) (f' : α → β) (a : α), f cb n = done nf f' ∧ p cb nf = done n' a ∧ f' a = b := by simp [seq_eq_bind_map] lemma seq_eq_fail {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = fail n' err ↔ (f cb n = fail n' err) ∨ (∃ (nf : ℕ) (f' : α → β), f cb n = done nf f' ∧ p cb nf = fail n' err) := by simp [seq_eq_bind_map] lemma seq_left_eq_done {p : parser α} {q : parser β} : (p <* q) cb n = done n' a ↔ ∃ (np : ℕ) (b : β), p cb n = done np a ∧ q cb np = done n' b := begin have : ∀ (p q : ℕ → α → Prop), (∃ (np : ℕ) (x : α), p np x ∧ q np x ∧ x = a) ↔ ∃ (np : ℕ), p np a ∧ q np a := λ _ _, ⟨λ ⟨np, x, hp, hq, rfl⟩, ⟨np, hp, hq⟩, λ ⟨np, hp, hq⟩, ⟨np, a, hp, hq, rfl⟩⟩, simp [seq_left_eq, seq_eq_done, map_eq_done, this] end lemma seq_left_eq_fail {p : parser α} {q : parser β} : (p <* q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_left_eq, seq_eq_fail] lemma seq_right_eq_done {p : parser α} {q : parser β} : (p *> q) cb n = done n' b ↔ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = done n' b := by simp [seq_right_eq, seq_eq_done, map_eq_done, and.comm, and.assoc] lemma seq_right_eq_fail {p : parser α} {q : parser β} : (p *> q) cb n = fail n' err ↔ (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) := by simp [seq_right_eq, seq_eq_fail] lemma mmap_eq_done {f : α → parser β} {a : α} {l : list α} {b : β} {l' : list β} : (a :: l).mmap f cb n = done n' (b :: l') ↔ ∃ (np : ℕ), f a cb n = done np b ∧ l.mmap f cb np = done n' l' := by simp [mmap, and.comm, and.assoc, and.left_comm, pure_eq_done] lemma mmap'_eq_done {f : α → parser β} {a : α} {l : list α} : (a :: l).mmap' f cb n = done n' () ↔ ∃ (np : ℕ) (b : β), f a cb n = done np b ∧ l.mmap' f cb np = done n' () := by simp [mmap'] lemma guard_eq_done {p : Prop} [decidable p] {u : unit} : @guard parser _ p _ cb n = done n' u ↔ p ∧ n = n' := by { by_cases hp : p; simp [guard, hp, pure_eq_done] } lemma guard_eq_fail {p : Prop} [decidable p] : @guard parser _ p _ cb n = fail n' err ↔ (¬ p) ∧ n = n' ∧ err = dlist.empty := by { by_cases hp : p; simp [guard, hp, eq_comm, pure_eq_done] } namespace mono variables {sep : parser unit} instance pure : mono (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.mono] [∀ a, (f a).mono] : (p >>= f).mono := begin constructor, intros cb n, cases hx : (p >>= f) cb n, { obtain ⟨n', a, h, h'⟩ := bind_eq_done.mp hx, refine le_trans (of_done h) _, simpa [h'] using of_done h' }, { obtain h | ⟨n', a, h, h'⟩ := bind_eq_fail.mp hx, { simpa [h] using of_fail h }, { refine le_trans (of_done h) _, simpa [h'] using of_fail h' } } end instance and_then {q : parser β} [p.mono] [q.mono] : (p >> q).mono := mono.bind instance map [p.mono] {f : α → β} : (f <$> p).mono := mono.bind instance seq {f : parser (α → β)} [f.mono] [p.mono] : (f <*> p).mono := mono.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.bind, { exact h _ (list.mem_cons_self _ _) }, { intro, convert mono.map, convert mmap, exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono], (l.mmap' f).mono | [] _ _ := mono.pure | (a :: l) f h := begin convert mono.and_then, { exact h _ (list.mem_cons_self _ _) }, { convert mmap', exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) } end instance failure : (failure : parser α).mono := ⟨by simp [le_refl]⟩ instance guard {p : Prop} [decidable p] : mono (guard p) := ⟨by { by_cases h : p; simp [h, pure_eq_done, le_refl] }⟩ instance orelse [p.mono] [q.mono] : (p <|> q).mono := begin constructor, intros cb n, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; simpa [h] using of_done h }, { by_cases h : n = posx, { simp [hx, h] }, { simp only [orelse_eq_fail_of_mono_ne h] at hx, exact of_fail hx } } end instance decorate_errors [p.mono] : (@decorate_errors α msgs p).mono := begin constructor, intros cb n, cases h : p cb n, { simpa [decorate_errors, h] using of_done h }, { simp [decorate_errors, h] } end instance decorate_error [p.mono] : (@decorate_error α msg p).mono := mono.decorate_errors instance any_char : mono any_char := begin constructor, intros cb n, by_cases h : n < cb.size; simp [any_char, h], end instance sat {p : char → Prop} [decidable_pred p] : mono (sat p) := begin constructor, intros cb n, simp only [sat], split_ifs; simp end instance eps : mono eps := mono.pure instance ch {c : char} : mono (ch c) := mono.decorate_error instance char_buf {s : char_buffer} : mono (char_buf s) := mono.decorate_error instance one_of {cs : list char} : (one_of cs).mono := mono.decorate_errors instance one_of' {cs : list char} : (one_of' cs).mono := mono.and_then instance str {s : string} : (str s).mono := mono.decorate_error instance remaining : remaining.mono := ⟨λ _ _, le_refl _⟩ instance eof : eof.mono := mono.decorate_error instance foldr_core {f : α → β → β} {b : β} [p.mono] : ∀ {reps : ℕ}, (foldr_core f p b reps).mono | 0 := mono.failure | (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, @mono.bind _ _ _ _ foldr_core _ } }, { exact mono.pure } end instance foldr {f : α → β → β} [p.mono] : mono (foldr f p b) := ⟨λ _ _, by { convert mono.le (foldr_core f p b _) _ _, exact mono.foldr_core }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.mono] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).mono | _ 0 := mono.failure | _ (reps + 1) := begin convert mono.orelse, { convert mono.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact mono.pure } end instance foldl {f : α → β → α} {p : parser β} [p.mono] : mono (foldl f a p) := ⟨λ _ _, by { convert mono.le (foldl_core f a p _) _ _, exact mono.foldl_core }⟩ instance many [p.mono] : p.many.mono := mono.foldr instance many_char {p : parser char} [p.mono] : p.many_char.mono := mono.map instance many' [p.mono] : p.many'.mono := mono.and_then instance many1 [p.mono] : p.many1.mono := mono.seq instance many_char1 {p : parser char} [p.mono] : p.many_char1.mono := mono.map instance sep_by1 [p.mono] [sep.mono] : mono (sep_by1 sep p) := mono.seq instance sep_by [p.mono] [hs : sep.mono] : mono (sep_by sep p) := mono.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : ∀ (max_depth : ℕ), mono (fix_core F max_depth) | 0 := mono.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.mono := mono.decorate_error instance nat : nat.mono := mono.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) : mono (fix F) := ⟨λ _ _, by { convert mono.le (parser.fix_core F _) _ _, exact fix_core hF _ }⟩ end mono @[simp] lemma orelse_pure_eq_fail : (p <|> pure a) cb n = fail n' err ↔ p cb n = fail n' err ∧ n ≠ n' := begin by_cases hn : n = n', { simp [hn, pure_eq_done] }, { simp [orelse_eq_fail_of_mono_ne, hn] } end end defn_lemmas section done variables {α β : Type} {cb : char_buffer} {n n' : ℕ} {a a' : α} {b : β} {c : char} {u : unit} {err : dlist string} lemma any_char_eq_done : any_char cb n = done n' c ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin simp_rw [any_char], split_ifs with h; simp [h, eq_comm] end lemma any_char_eq_fail : any_char cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ cb.size ≤ n := begin simp_rw [any_char], split_ifs with h; simp [←not_lt, h, eq_comm] end lemma sat_eq_done {p : char → Prop} [decidable_pred p] : sat p cb n = done n' c ↔ ∃ (hn : n < cb.size), p c ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := begin by_cases hn : n < cb.size, { by_cases hp : p (cb.read ⟨n, hn⟩), { simp only [sat, hn, hp, dif_pos, if_true, exists_prop_of_true], split, { rintro ⟨rfl, rfl⟩, simp [hp] }, { rintro ⟨-, rfl, rfl⟩, simp } }, { simp only [sat, hn, hp, dif_pos, false_iff, not_and, exists_prop_of_true, if_false], rintro H - rfl, exact hp H } }, { simp [sat, hn] } end lemma sat_eq_fail {p : char → Prop} [decidable_pred p] : sat p cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ ∀ (h : n < cb.size), ¬ p (cb.read ⟨n, h⟩) := begin dsimp only [sat], split_ifs; simp [*, eq_comm] end lemma eps_eq_done : eps cb n = done n' u ↔ n = n' := by simp [eps, pure_eq_done] lemma ch_eq_done : ch c cb n = done n' u ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [ch, eps_eq_done, sat_eq_done, and.comm, @eq_comm _ n'] lemma char_buf_eq_done {cb' : char_buffer} : char_buf cb' cb n = done n' u ↔ n + cb'.size = n' ∧ cb'.to_list <+: (cb.to_list.drop n) := begin simp only [char_buf, decorate_error_eq_done, ne.def, ←buffer.length_to_list], induction cb'.to_list with hd tl hl generalizing cb n n', { simp [pure_eq_done, mmap'_eq_done, -buffer.length_to_list, list.nil_prefix] }, { simp only [ch_eq_done, and.comm, and.assoc, and.left_comm, hl, mmap', and_then_eq_bind, bind_eq_done, list.length, exists_and_distrib_left, exists_const], split, { rintro ⟨np, h, rfl, rfl, hn, rfl⟩, simp only [add_comm, add_left_comm, h, true_and, eq_self_iff_true, and_true], have : n < cb.to_list.length := by simpa using hn, rwa [←buffer.nth_le_to_list _ this, ←list.cons_nth_le_drop_succ this, list.prefix_cons_inj] }, { rintro ⟨h, rfl⟩, by_cases hn : n < cb.size, { have : n < cb.to_list.length := by simpa using hn, rw [←list.cons_nth_le_drop_succ this, list.cons_prefix_iff] at h, use [n + 1, h.right], simpa [buffer.nth_le_to_list, add_comm, add_left_comm, add_assoc, hn] using h.left.symm }, { have : cb.to_list.length ≤ n := by simpa using hn, rw list.drop_eq_nil_of_le this at h, simpa using h } } } end lemma one_of_eq_done {cs : list char} : one_of cs cb n = done n' c ↔ ∃ (hn : n < cb.size), c ∈ cs ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c := by simp [one_of, sat_eq_done] lemma one_of'_eq_done {cs : list char} : one_of' cs cb n = done n' u ↔ ∃ (hn : n < cb.size), cb.read ⟨n, hn⟩ ∈ cs ∧ n' = n + 1 := begin simp only [one_of', one_of_eq_done, eps_eq_done, and.comm, and_then_eq_bind, bind_eq_done, exists_eq_left, exists_and_distrib_left], split, { rintro ⟨c, hc, rfl, hn, rfl⟩, exact ⟨rfl, hn, hc⟩ }, { rintro ⟨rfl, hn, hc⟩, exact ⟨cb.read ⟨n, hn⟩, hc, rfl, hn, rfl⟩ } end lemma str_eq_char_buf (s : string) : str s = char_buf s.to_list.to_buffer := begin ext cb n, rw [str, char_buf], congr, { simp [buffer.to_string, string.as_string_inv_to_list] }, { simp } end lemma str_eq_done {s : string} : str s cb n = done n' u ↔ n + s.length = n' ∧ s.to_list <+: (cb.to_list.drop n) := by simp [str_eq_char_buf, char_buf_eq_done] lemma remaining_eq_done {r : ℕ} : remaining cb n = done n' r ↔ n = n' ∧ cb.size - n = r := by simp [remaining] lemma remaining_ne_fail : remaining cb n ≠ fail n' err := by simp [remaining] lemma eof_eq_done {u : unit} : eof cb n = done n' u ↔ n = n' ∧ cb.size ≤ n := by simp [eof, guard_eq_done, remaining_eq_done, nat.sub_eq_zero_iff_le, and_comm, and_assoc] @[simp] lemma foldr_core_zero_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr_core f p b 0 cb n ≠ done n' b' := by simp [foldr_core] lemma foldr_core_eq_done {f : α → β → β} {p : parser α} {reps : ℕ} {b' : β} : foldr_core f p b (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α) (xs : β), p cb n = done np a ∧ foldr_core f p b reps cb np = done n' xs ∧ f a xs = b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n err)) := by simp [foldr_core, and.comm, and.assoc, pure_eq_done] @[simp] lemma foldr_core_zero_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr_core f p b 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldr_core, eq_comm] lemma foldr_core_succ_eq_fail {f : α → β → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldr_core f p b (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n' err) := by simp [foldr_core, and_comm] lemma foldr_eq_done {f : α → β → β} {p : parser α} {b' : β} : foldr f p b cb n = done n' b' ↔ ((∃ (np : ℕ) (a : α) (x : β), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = done n' x ∧ f a x = b') ∨ (n = n' ∧ b = b' ∧ (∃ (err), p cb n = parse_result.fail n err ∨ ∃ (np : ℕ) (x : α), p cb n = done np x ∧ foldr_core f p b (cb.size - n) cb np = fail n err))) := by simp [foldr, foldr_core_eq_done] lemma foldr_eq_fail_iff_mono_at_end {f : α → β → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldr f p b cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := nat.sub_eq_zero_of_le hc, simp only [foldr, foldr_core_succ_eq_fail, this, and.left_comm, foldr_core_zero_eq_fail, ne_iff_lt_iff_le, exists_and_distrib_right, exists_eq_left, and.congr_left_iff, exists_and_distrib_left], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma foldr_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} : foldr f p b cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = fail n' err) := by simp [foldr, foldr_core_succ_eq_fail] @[simp] lemma foldl_core_zero_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl_core f b p 0 cb n = done n' b' ↔ false := by simp [foldl_core] lemma foldl_core_eq_done {f : β → α → β} {p : parser α} {reps : ℕ} {b' : β} : foldl_core f b p (reps + 1) cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n err)) := by simp [foldl_core, and.assoc, pure_eq_done] @[simp] lemma foldl_core_zero_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl_core f b p 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty := by simp [foldl_core, eq_comm] lemma foldl_core_succ_eq_fail {f : β → α → β} {p : parser α} {reps : ℕ} {err : dlist string} : foldl_core f b p (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n' err) := by simp [foldl_core, and_comm] lemma foldl_eq_done {f : β → α → β} {p : parser α} {b' : β} : foldl f b p cb n = done n' b' ↔ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = done n' b') ∨ (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n err)) := by simp [foldl, foldl_core_eq_done] lemma foldl_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} : foldl f b p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p (cb.size - n) cb np = fail n' err) := by simp [foldl, foldl_core_succ_eq_fail] lemma foldl_eq_fail_iff_mono_at_end {f : β → α → β} {p : parser α} {err : dlist string} [p.mono] (hc : cb.size ≤ n) : foldl f b p cb n = fail n' err ↔ n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) := begin have : cb.size - n = 0 := nat.sub_eq_zero_of_le hc, simp only [foldl, foldl_core_succ_eq_fail, this, and.left_comm, ne_iff_lt_iff_le, exists_eq_left, exists_and_distrib_right, and.congr_left_iff, exists_and_distrib_left, foldl_core_zero_eq_fail], rintro (h | ⟨⟨a, h⟩, rfl⟩), { exact mono.of_fail h }, { exact mono.of_done h } end lemma many_eq_done_nil {p : parser α} : many p cb n = done n' (@list.nil α) ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many, foldr_eq_done] lemma many_eq_done {p : parser α} {x : α} {xs : list α} : many p cb n = done n' (x :: xs) ↔ ∃ (np : ℕ), p cb n = done np x ∧ foldr_core list.cons p [] (cb.size - n) cb np = done n' xs := by simp [many, foldr_eq_done, and.comm, and.assoc, and.left_comm] lemma many_eq_fail {p : parser α} {err : dlist string} : many p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n' err) := by simp [many, foldr_eq_fail] lemma many_char_eq_done_empty {p : parser char} : many_char p cb n = done n' string.empty ↔ n = n' ∧ ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (c : char), p cb n = done np c ∧ foldr_core list.cons p [] (cb.size - n) cb np = fail n err := by simp [many_char, many_eq_done_nil, map_eq_done, list.as_string_eq] lemma many_char_eq_done_not_empty {p : parser char} {s : string} (h : s ≠ "") : many_char p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ foldr_core list.cons p list.nil (buffer.size cb - n) cb np = done n' (s.popn 1).to_list := by simp [many_char, list.as_string_eq, string.to_list_nonempty h, many_eq_done] lemma many_char_eq_many_of_to_list {p : parser char} {s : string} : many_char p cb n = done n' s ↔ many p cb n = done n' s.to_list := by simp [many_char, list.as_string_eq] lemma many'_eq_done {p : parser α} : many' p cb n = done n' u ↔ many p cb n = done n' [] ∨ ∃ (np : ℕ) (a : α) (l : list α), many p cb n = done n' (a :: l) ∧ p cb n = done np a ∧ foldr_core list.cons p [] (buffer.size cb - n) cb np = done n' l := begin simp only [many', eps_eq_done, many, foldr, and_then_eq_bind, exists_and_distrib_right, bind_eq_done, exists_eq_right], split, { rintro ⟨_ | ⟨hd, tl⟩, hl⟩, { exact or.inl hl }, { have hl2 := hl, simp only [foldr_core_eq_done, or_false, exists_and_distrib_left, and_false, false_and, exists_eq_right_right] at hl, obtain ⟨np, hp, h⟩ := hl, refine or.inr ⟨np, _, _, hl2, hp, h⟩ } }, { rintro (h | ⟨np, a, l, hp, h⟩), { exact ⟨[], h⟩ }, { refine ⟨a :: l, hp⟩ } } end @[simp] lemma many1_ne_done_nil {p : parser α} : many1 p cb n ≠ done n' [] := by simp [many1, seq_eq_done] lemma many1_eq_done {p : parser α} {l : list α} : many1 p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ many p cb np = done n' l := by simp [many1, seq_eq_done, map_eq_done] lemma many1_eq_fail {p : parser α} {err : dlist string} : many1 p cb n = fail n' err ↔ p cb n = fail n' err ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ many p cb np = fail n' err) := by simp [many1, seq_eq_fail] @[simp] lemma many_char1_ne_empty {p : parser char} : many_char1 p cb n ≠ done n' "" := by simp [many_char1, ←string.nil_as_string_eq_empty] lemma many_char1_eq_done {p : parser char} {s : string} (h : s ≠ "") : many_char1 p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧ many_char p cb np = done n' (s.popn 1) := by simp [many_char1, list.as_string_eq, string.to_list_nonempty h, many1_eq_done, many_char_eq_many_of_to_list] @[simp] lemma sep_by1_ne_done_nil {sep : parser unit} {p : parser α} : sep_by1 sep p cb n ≠ done n' [] := by simp [sep_by1, seq_eq_done] lemma sep_by1_eq_done {sep : parser unit} {p : parser α} {l : list α} : sep_by1 sep p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧ (sep >> p).many cb np = done n' l := by simp [sep_by1, seq_eq_done] lemma sep_by_eq_done_nil {sep : parser unit} {p : parser α} : sep_by sep p cb n = done n' [] ↔ n = n' ∧ ∃ (err), sep_by1 sep p cb n = fail n err := by simp [sep_by, pure_eq_done] @[simp] lemma fix_core_ne_done_zero {F : parser α → parser α} : fix_core F 0 cb n ≠ done n' a := by simp [fix_core] lemma fix_core_eq_done {F : parser α → parser α} {max_depth : ℕ} : fix_core F (max_depth + 1) cb n = done n' a ↔ F (fix_core F max_depth) cb n = done n' a := by simp [fix_core] lemma digit_eq_done {k : ℕ} : digit cb n = done n' k ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ k ≤ 9 ∧ (cb.read ⟨n, hn⟩).to_nat - '0'.to_nat = k ∧ '0' ≤ cb.read ⟨n, hn⟩ ∧ cb.read ⟨n, hn⟩ ≤ '9' := begin have c9 : '9'.to_nat - '0'.to_nat = 9 := rfl, have l09 : '0'.to_nat ≤ '9'.to_nat := dec_trivial, have le_iff_le : ∀ {c c' : char}, c ≤ c' ↔ c.to_nat ≤ c'.to_nat := λ _ _, iff.rfl, split, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9], rintro ⟨np, c, ⟨hn, ⟨ge0, le9⟩, rfl, rfl⟩, rfl, rfl⟩, simpa [hn, ge0, le9, true_and, and_true, eq_self_iff_true, exists_prop_of_true, nat.sub_le_sub_right_iff, l09] using (le_iff_le.mp le9) }, { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9, le_iff_le], rintro ⟨hn, rfl, -, rfl, ge0, le9⟩, use [n + 1, cb.read ⟨n, hn⟩], simp [hn, ge0, le9] } end lemma digit_eq_fail : digit cb n = fail n' err ↔ n = n' ∧ err = dlist.of_list ["<digit>"] ∧ ∀ (h : n < cb.size), ¬ ((λ c, '0' ≤ c ∧ c ≤ '9') (cb.read ⟨n, h⟩)) := by simp [digit, sat_eq_fail] end done namespace static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = done n' a) (hne : n ≠ n') : ¬ static p := by { introI, exact hne (of_done h) } instance pure : static (pure a) := ⟨λ _ _ _ _, by { simp_rw pure_eq_done, rw [and.comm], simp }⟩ instance bind {f : α → parser β} [p.static] [∀ a, (f a).static] : (p >>= f).static := ⟨λ _ _ _ _, by { rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact trans (of_done hp) (of_done hf) }⟩ instance and_then {q : parser β} [p.static] [q.static] : (p >> q).static := static.bind instance map [p.static] {f : α → β} : (f <$> p).static := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.static] [p.static] : (f <*> p).static := static.bind instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.bind, { exact h _ }, { intro, convert static.bind, { convert mmap, exact h }, { exact λ _, static.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap' f).static | [] _ _ := static.pure | (a :: l) _ h := begin convert static.and_then, { exact h _ }, { convert mmap', exact h } end instance failure : @parser.static α failure := ⟨λ _ _ _ _, by simp⟩ instance guard {p : Prop} [decidable p] : static (guard p) := ⟨λ _ _ _ _, by simp [guard_eq_done]⟩ instance orelse [p.static] [q.static] : (p <|> q).static := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ instance decorate_errors [p.static] : (@decorate_errors α msgs p).static := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ instance decorate_error [p.static] : (@decorate_error α msg p).static := static.decorate_errors lemma any_char : ¬ static any_char := begin have : any_char "s".to_char_buffer 0 = done 1 's', { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [any_char_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma sat_iff {p : char → Prop} [decidable_pred p] : static (sat p) ↔ ∀ c, ¬ p c := begin split, { introI, intros c hc, have : sat p [c].to_buffer 0 = done 1 c := by simp [sat_eq_done, hc], exact zero_ne_one (of_done this) }, { contrapose!, simp only [iff, sat_eq_done, and_imp, exists_prop, exists_and_distrib_right, exists_and_distrib_left, exists_imp_distrib, not_forall], rintros _ _ _ a h hne rfl hp -, exact ⟨a, hp⟩ } end instance sat : static (sat (λ _, false)) := by { apply sat_iff.mpr, simp } instance eps : static eps := static.pure lemma ch (c : char) : ¬ static (ch c) := begin have : ch c [c].to_buffer 0 = done 1 (), { have : 0 < [c].to_buffer.size := dec_trivial, simp [ch_eq_done, this] }, exact not_of_ne this zero_ne_one end lemma char_buf_iff {cb' : char_buffer} : static (char_buf cb') ↔ cb' = buffer.nil := begin rw ←buffer.size_eq_zero_iff, have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], cases hc : cb'.size with n, { simp only [eq_self_iff_true, iff_true], exact ⟨λ _ _ _ _ h, by simpa [hc] using (char_buf_eq_done.mp h).left⟩ }, { rw hc at this, simpa [nat.succ_ne_zero] using not_of_ne this (nat.succ_ne_zero n).symm } end lemma one_of_iff {cs : list char} : static (one_of cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of, static.decorate_errors] }, { have : one_of (hd :: tl) (hd :: tl).to_buffer 0 = done 1 hd, { simp [one_of_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma one_of'_iff {cs : list char} : static (one_of' cs) ↔ cs = [] := begin cases cs with hd tl, { simp [one_of', static.bind], }, { have : one_of' (hd :: tl) (hd :: tl).to_buffer 0 = done 1 (), { simp [one_of'_eq_done] }, simpa using not_of_ne this zero_ne_one } end instance one_of' : static (one_of []) := by { apply one_of_iff.mpr, refl } lemma str_iff {s : string} : static (str s) ↔ s = "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] instance remaining : remaining.static := ⟨λ _ _ _ _ h, (remaining_eq_done.mp h).left⟩ instance eof : eof.static := static.decorate_error instance foldr_core {f : α → β → β} [p.static] : ∀ {b : β} {reps : ℕ}, (foldr_core f p b reps).static | _ 0 := static.failure | _ (reps + 1) := begin simp_rw parser.foldr_core, convert static.orelse, { convert static.bind, { apply_instance }, { intro, convert static.bind, { exact foldr_core }, { apply_instance } } }, { exact static.pure } end instance foldr {f : α → β → β} [p.static] : static (foldr f p b) := ⟨λ _ _ _ _, by { dsimp [foldr], exact of_done }⟩ instance foldl_core {f : α → β → α} {p : parser β} [p.static] : ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).static | _ 0 := static.failure | _ (reps + 1) := begin convert static.orelse, { convert static.bind, { apply_instance }, { exact λ _, foldl_core } }, { exact static.pure } end instance foldl {f : α → β → α} {p : parser β} [p.static] : static (foldl f a p) := ⟨λ _ _ _ _, by { dsimp [foldl], exact of_done }⟩ instance many [p.static] : p.many.static := static.foldr instance many_char {p : parser char} [p.static] : p.many_char.static := static.map instance many' [p.static] : p.many'.static := static.and_then instance many1 [p.static] : p.many1.static := static.seq instance many_char1 {p : parser char} [p.static] : p.many_char1.static := static.map instance sep_by1 [p.static] [sep.static] : static (sep_by1 sep p) := static.seq instance sep_by [p.static] [sep.static] : static (sep_by sep p) := static.orelse lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : ∀ (max_depth : ℕ), static (fix_core F max_depth) | 0 := static.failure | (max_depth + 1) := hF _ (fix_core _) lemma digit : ¬ digit.static := begin have : digit "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma nat : ¬ nat.static := begin have : nat "1".to_char_buffer 0 = done 1 1, { have : 0 < "s".to_char_buffer.size := dec_trivial, simpa [this] }, exact not_of_ne this zero_ne_one end lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) : static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact static.of_done h }⟩ end static namespace bounded variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} lemma done_of_unbounded (h : ¬p.bounded) : ∃ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a ∧ cb.size ≤ n := begin contrapose! h, constructor, intros cb n hn, cases hp : p cb n, { exact absurd hn (h _ _ _ _ hp).not_le }, { simp [hp] } end lemma pure : ¬ bounded (pure a) := begin introI, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end instance bind {f : α → parser β} [p.bounded] : (p >>= f).bounded := begin constructor, intros cb n hn, obtain ⟨_, _, hp⟩ := bounded.exists p hn, simp [hp] end instance and_then {q : parser β} [p.bounded] : (p >> q).bounded := bounded.bind instance map [p.bounded] {f : α → β} : (f <$> p).bounded := bounded.bind instance seq {f : parser (α → β)} [f.bounded] : (f <*> p).bounded := bounded.bind instance mmap {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap f).bounded := bounded.bind instance mmap' {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] : ((a :: l).mmap' f).bounded := bounded.and_then instance failure : @parser.bounded α failure := ⟨by simp⟩ lemma guard_iff {p : Prop} [decidable p] : bounded (guard p) ↔ ¬ p := by simpa [guard, apply_ite bounded, pure, failure] using λ _, bounded.failure instance orelse [p.bounded] [q.bounded] : (p <|> q).bounded := begin constructor, intros cb n hn, cases hx : (p <|> q) cb n with posx resx posx errx, { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx; exact absurd hn (of_done h).not_le }, { simp } end instance decorate_errors [p.bounded] : (@decorate_errors α msgs p).bounded := begin constructor, intros _ _, simpa using bounded.exists p end lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).bounded ↔ p.bounded := begin split, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists (@parser.decorate_errors α msgs p) hn, simp [decorate_errors_eq_fail] at h, exact h.right.right }, { introI, constructor, intros _ _ hn, obtain ⟨_, _, h⟩ := bounded.exists p hn, simp [h] } end instance decorate_error [p.bounded] : (@decorate_error α msg p).bounded := bounded.decorate_errors lemma decorate_error_iff : (@parser.decorate_error α msg p).bounded ↔ p.bounded := decorate_errors_iff instance any_char : bounded any_char := ⟨λ cb n hn, by simp [any_char, hn]⟩ instance sat {p : char → Prop} [decidable_pred p] : bounded (sat p) := ⟨λ cb n hn, by simp [sat, hn]⟩ lemma eps : ¬ bounded eps := pure instance ch {c : char} : bounded (ch c) := bounded.decorate_error lemma char_buf_iff {cb' : char_buffer} : bounded (char_buf cb') ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, decorate_error_iff, this], cases cb'.to_list, { simp [pure, ch] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).bounded := bounded.decorate_errors instance one_of' {cs : list char} : (one_of' cs).bounded := bounded.and_then lemma str_iff {s : string} : (str s).bounded ↔ s ≠ "" := begin rw [str, decorate_error_iff], cases hs : s.to_list, { have : s = "", { cases s, rw [string.to_list] at hs, simpa [hs] }, simp [pure, this] }, { have : s ≠ "", { intro H, simpa [H] using hs }, simp only [this, iff_true, ne.def, not_false_iff], apply_instance } end lemma remaining : ¬ remaining.bounded := begin introI, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end lemma eof : ¬ eof.bounded := begin introI, have : eof buffer.nil 0 = done 0 () := by simp [eof_eq_done], exact absurd (bounded.of_done this) (lt_irrefl _) end section fold instance foldr_core_zero {f : α → β → β} : (foldr_core f p b 0).bounded := bounded.failure instance foldl_core_zero {f : β → α → β} {b : β} : (foldl_core f b p 0).bounded := bounded.failure variables {reps : ℕ} [hpb : p.bounded] (he : ∀ cb n n' err, p cb n = fail n' err → n ≠ n') include hpb he lemma foldr_core {f : α → β → β} : (foldr_core f p b reps).bounded := begin cases reps, { exact bounded.foldr_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldr_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldr {f : α → β → β} : bounded (foldr f p b) := begin constructor, intros cb n hn, haveI : (parser.foldr_core f p b (cb.size - n + 1)).bounded := foldr_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldr_core f p b (cb.size - n + 1)) hn, simp [foldr, hp] end lemma foldl_core {f : β → α → β} : (foldl_core f b p reps).bounded := begin cases reps, { exact bounded.foldl_core_zero }, constructor, intros cb n hn, obtain ⟨np, errp, hp⟩ := bounded.exists p hn, simpa [foldl_core_succ_eq_fail, hp] using he cb n np errp, end lemma foldl {f : β → α → β} : bounded (foldl f b p) := begin constructor, intros cb n hn, haveI : (parser.foldl_core f b p (cb.size - n + 1)).bounded := foldl_core he, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldl_core f b p (cb.size - n + 1)) hn, simp [foldl, hp] end lemma many : p.many.bounded := foldr he omit hpb lemma many_char {pc : parser char} [pc.bounded] (he : ∀ cb n n' err, pc cb n = fail n' err → n ≠ n'): pc.many_char.bounded := by { convert bounded.map, exact many he } include hpb lemma many' : p.many'.bounded := by { convert bounded.and_then, exact many he } end fold instance many1 [p.bounded] : p.many1.bounded := bounded.seq instance many_char1 {p : parser char} [p.bounded] : p.many_char1.bounded := bounded.map instance sep_by1 {sep : parser unit} [p.bounded] : bounded (sep_by1 sep p) := bounded.seq lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : ∀ (max_depth : ℕ), bounded (fix_core F max_depth) | 0 := bounded.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.bounded := bounded.decorate_error instance nat : nat.bounded := bounded.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) : bounded (fix F) := begin constructor, intros cb n hn, haveI : (parser.fix_core F (cb.size - n + 1)).bounded := fix_core hF _, obtain ⟨np, errp, hp⟩ := bounded.exists (parser.fix_core F (cb.size - n + 1)) hn, simp [fix, hp] end end bounded namespace unfailing variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma of_bounded [p.bounded] : ¬ unfailing p := begin introI, cases h : p buffer.nil 0, { simpa [lt_irrefl] using bounded.of_done h }, { exact of_fail h } end instance pure : unfailing (pure a) := ⟨λ _ _, by simp [pure_eq_done]⟩ instance bind {f : α → parser β} [p.unfailing] [∀ a, (f a).unfailing] : (p >>= f).unfailing := ⟨λ cb n, begin obtain ⟨np, a, hp⟩ := exists_done p cb n, simpa [hp, and.comm, and.left_comm, and.assoc] using exists_done (f a) cb np end⟩ instance and_then {q : parser β} [p.unfailing] [q.unfailing] : (p >> q).unfailing := unfailing.bind instance map [p.unfailing] {f : α → β} : (f <$> p).unfailing := unfailing.bind instance seq {f : parser (α → β)} [f.unfailing] [p.unfailing] : (f <*> p).unfailing := unfailing.bind instance mmap {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end instance mmap' {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap' f).unfailing := begin constructor, induction l with hd tl hl, { intros, simp [pure_eq_done] }, { intros, obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n, obtain ⟨n', b, hf⟩ := hl cb np, simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] } end lemma failure : ¬ @parser.unfailing α failure := begin introI h, have : (failure : parser α) buffer.nil 0 = fail 0 dlist.empty := by simp, exact of_fail this end instance guard_true : unfailing (guard true) := unfailing.pure lemma guard : ¬ unfailing (guard false) := unfailing.failure instance orelse [p.unfailing] : (p <|> q).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_errors [p.unfailing] : (@decorate_errors α msgs p).unfailing := ⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩ instance decorate_error [p.unfailing] : (@decorate_error α msg p).unfailing := unfailing.decorate_errors instance any_char : conditionally_unfailing any_char := ⟨λ _ _ hn, by simp [success_iff, any_char_eq_done, hn]⟩ lemma sat : conditionally_unfailing (sat (λ _, true)) := ⟨λ _ _ hn, by simp [success_iff, sat_eq_done, hn]⟩ instance eps : unfailing eps := unfailing.pure instance remaining : remaining.unfailing := ⟨λ _ _, by simp [success_iff, remaining_eq_done]⟩ lemma foldr_core_zero {f : α → β → β} {b : β} : ¬ (foldr_core f p b 0).unfailing := unfailing.failure instance foldr_core_of_static {f : α → β → β} {b : β} {reps : ℕ} [p.static] [p.unfailing] : (foldr_core f p b (reps + 1)).unfailing := begin induction reps with reps hr, { constructor, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { constructor, haveI := hr, intros cb n, obtain ⟨np, a, h⟩ := p.exists_done cb n, have : n = np := static.of_done h, subst this, obtain ⟨np, b', hf⟩ := exists_done (foldr_core f p b (reps + 1)) cb n, have : n = np := static.of_done hf, subst this, refine ⟨n, f a b', _⟩, rw foldr_core_eq_done, simp [h, hf, and.comm, and.left_comm, and.assoc] } end instance foldr_core_one_of_err_static {f : α → β → β} {b : β} [p.static] [p.err_static] : (foldr_core f p b 1).unfailing := begin constructor, intros cb n, cases h : p cb n, { simpa [foldr_core_eq_done, h] using (static.of_done h).symm }, { simpa [foldr_core_eq_done, h] using (err_static.of_fail h).symm } end -- TODO: add foldr and foldl, many, etc, fix_core lemma digit : ¬ digit.unfailing := of_bounded lemma nat : ¬ nat.unfailing := of_bounded end unfailing namespace err_static variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_of_ne (h : p cb n = fail n' err) (hne : n ≠ n') : ¬ err_static p := by { introI, exact hne (of_fail h) } instance pure : err_static (pure a) := ⟨λ _ _ _ _, by { simp [pure_eq_done] }⟩ instance bind {f : α → parser β} [p.static] [p.err_static] [∀ a, (f a).err_static] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact trans (static.of_done hp) (of_fail hf) } end⟩ instance bind_of_unfailing {f : α → parser β} [p.err_static] [∀ a, (f a).unfailing] : (p >>= f).err_static := ⟨λ cb n n' err, begin rw bind_eq_fail, rintro (hp | ⟨_, _, hp, hf⟩), { exact of_fail hp }, { exact false.elim (unfailing.of_fail hf) } end⟩ instance and_then {q : parser β} [p.static] [p.err_static] [q.err_static] : (p >> q).err_static := err_static.bind instance and_then_of_unfailing {q : parser β} [p.err_static] [q.unfailing] : (p >> q).err_static := err_static.bind_of_unfailing instance map [p.err_static] {f : α → β} : (f <$> p).err_static := ⟨λ _ _ _ _, by { rw map_eq_fail, exact of_fail }⟩ instance seq {f : parser (α → β)} [f.static] [f.err_static] [p.err_static] : (f <*> p).err_static := err_static.bind instance seq_of_unfailing {f : parser (α → β)} [f.err_static] [p.unfailing] : (f <*> p).err_static := err_static.bind_of_unfailing instance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind, { exact h _ }, { exact h' _ }, { intro, convert err_static.bind, { convert static.mmap, exact h }, { apply mmap, { exact h }, { exact h' } }, { exact λ _, err_static.pure } } end instance mmap_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.bind_of_unfailing, { exact h' _ }, { intro, convert unfailing.bind, { convert unfailing.mmap, exact h }, { exact λ _, unfailing.pure } } end instance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then, { exact h _ }, { exact h' _ }, { convert mmap', { exact h }, { exact h' } } end instance mmap'_of_unfailing : Π {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap' f).err_static | [] _ _ _ := err_static.pure | (a :: l) _ h h' := begin convert err_static.and_then_of_unfailing, { exact h' _ }, { convert unfailing.mmap', exact h } end instance failure : @parser.err_static α failure := ⟨λ _ _ _ _ h, (failure_eq_fail.mp h).left⟩ instance guard {p : Prop} [decidable p] : err_static (guard p) := ⟨λ _ _ _ _ h, (guard_eq_fail.mp h).right.left⟩ instance orelse [p.err_static] [q.mono] : (p <|> q).err_static := ⟨λ _ n n' _, begin by_cases hn : n = n', { exact λ _, hn }, { rw orelse_eq_fail_of_mono_ne hn, { exact of_fail }, { apply_instance } } end⟩ instance decorate_errors : (@decorate_errors α msgs p).err_static := ⟨λ _ _ _ _ h, (decorate_errors_eq_fail.mp h).left⟩ instance decorate_error : (@decorate_error α msg p).err_static := err_static.decorate_errors instance any_char : err_static any_char := ⟨λ _ _ _ _, by { rw [any_char_eq_fail, and.comm], simp }⟩ instance sat_iff {p : char → Prop} [decidable_pred p] : err_static (sat p) := ⟨λ _ _ _ _ h, (sat_eq_fail.mp h).left⟩ instance eps : err_static eps := err_static.pure instance ch (c : char) : err_static (ch c) := err_static.decorate_error instance char_buf {cb' : char_buffer} : err_static (char_buf cb') := err_static.decorate_error instance one_of {cs : list char} : err_static (one_of cs) := err_static.decorate_errors instance one_of' {cs : list char} : err_static (one_of' cs) := err_static.and_then_of_unfailing instance str {s : string} : err_static (str s) := err_static.decorate_error instance remaining : remaining.err_static := ⟨λ _ _ _ _, by simp [remaining_ne_fail]⟩ instance eof : eof.err_static := err_static.decorate_error -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : ∀ (max_depth : ℕ), err_static (fix_core F max_depth) | 0 := err_static.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.err_static := err_static.decorate_error instance nat : nat.err_static := err_static.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) : err_static (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact err_static.of_fail h }⟩ end err_static namespace step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma not_step_of_static_done [static p] (h : ∃ cb n n' a, p cb n = done n' a) : ¬ step p := begin introI, rcases h with ⟨cb, n, n', a, h⟩, have hs := static.of_done h, simpa [←hs] using of_done h end lemma pure (a : α) : ¬ step (pure a) := begin apply not_step_of_static_done, simp [pure_eq_done] end instance bind {f : α → parser β} [p.step] [∀ a, (f a).static] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact (static.of_done hf) ▸ (of_done hp) }⟩ instance bind' {f : α → parser β} [p.static] [∀ a, (f a).step] : (p >>= f).step := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, rw static.of_done hp, exact of_done hf }⟩ instance and_then {q : parser β} [p.step] [q.static] : (p >> q).step := step.bind instance and_then' {q : parser β} [p.static] [q.step] : (p >> q).step := step.bind' instance map [p.step] {f : α → β} : (f <$> p).step := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.step] [p.static] : (f <*> p).step := step.bind instance seq' {f : parser (α → β)} [f.static] [p.step] : (f <*> p).step := step.bind' instance mmap {f : α → parser β} [(f a).step] : ([a].mmap f).step := begin convert step.bind, { apply_instance }, { intro, convert static.bind, { exact static.pure }, { exact λ _, static.pure } } end instance mmap' {f : α → parser β} [(f a).step] : ([a].mmap' f).step := begin convert step.and_then, { apply_instance }, { exact static.pure } end instance failure : @parser.step α failure := ⟨λ _ _ _ _, by simp⟩ lemma guard_true : ¬ step (guard true) := pure _ instance guard : step (guard false) := step.failure instance orelse [p.step] [q.step] : (p <|> q).step := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).step ↔ p.step := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.step] : (@decorate_errors α msgs p).step := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).step ↔ p.step := decorate_errors_iff instance decorate_error [p.step] : (@decorate_error α msg p).step := step.decorate_errors instance any_char : step any_char := begin constructor, intros cb n, simp_rw [any_char_eq_done], rintro _ _ ⟨_, rfl, -⟩, simp end instance sat {p : char → Prop} [decidable_pred p] : step (sat p) := begin constructor, intros cb n, simp_rw [sat_eq_done], rintro _ _ ⟨_, _, rfl, -⟩, simp end lemma eps : ¬ step eps := step.pure () instance ch {c : char} : step (ch c) := step.decorate_error lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').step ↔ cb'.size = 1 := begin have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done], split, { introI, simpa using of_done this }, { intro h, constructor, intros cb n n' _, rw [char_buf_eq_done, h], rintro ⟨rfl, -⟩, refl } end instance one_of {cs : list char} : (one_of cs).step := step.decorate_errors instance one_of' {cs : list char} : (one_of' cs).step := step.and_then lemma str_iff {s : string} : (str s).step ↔ s.length = 1 := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.step := begin apply not_step_of_static_done, simp [remaining_eq_done] end lemma eof : ¬ eof.step := begin apply not_step_of_static_done, simp only [eof_eq_done, exists_eq_left', exists_const], use [buffer.nil, 0], simp end -- TODO: add foldr and foldl, many, etc, fix_core lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : ∀ (max_depth : ℕ), step (fix_core F max_depth) | 0 := step.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.step := step.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) : step (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end step section step variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} lemma many1_eq_done_iff_many_eq_done [p.step] [p.bounded] {x : α} {xs : list α} : many1 p cb n = done n' (x :: xs) ↔ many p cb n = done n' (x :: xs) := begin induction hx : (x :: xs) with hd tl IH generalizing x xs n n', { simpa using hx }, split, { simp only [many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (nat.sub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { rw ←@IH hd' tl' at hm, swap, refl, simp only [many1_eq_done, many, foldr] at hm, obtain ⟨np, hp', hf⟩ := hm, have : np = n + 1 + 1 := step.of_done hp', subst this, simpa [nat.sub_succ, many_eq_done, hp, hk, foldr_core_eq_done, hp'] using hf } }, { simp only [many_eq_done, many1_eq_done, and_imp, exists_imp_distrib], intros np hp hm, have : np = n + 1 := step.of_done hp, have hn : n < cb.size := bounded.of_done hp, subst this, obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 := nat.exists_eq_succ_of_ne_zero (ne_of_gt (nat.sub_pos_of_lt hn)), cases k, { cases tl; simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, cases tl with hd' tl', { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm }, { simp [hp], rw ←@IH hd' tl' (n + 1) n', swap, refl, rw [hk, foldr_core_eq_done, or.comm] at hm, obtain (hm | ⟨np, hd', tl', hp', hf, hm⟩) := hm, { simpa using hm }, simp only at hm, obtain ⟨rfl, rfl⟩ := hm, have : np = n + 1 + 1 := step.of_done hp', subst this, simp [nat.sub_succ, many, many1_eq_done, hp, hk, foldr_core_eq_done, hp', ←hf, foldr] } } end end step namespace prog variables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string} {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit} @[priority 100] -- see Note [lower instance priority] instance of_step [step p] : prog p := ⟨λ _ _ _ _ h, by { rw step.of_done h, exact nat.lt_succ_self _ }⟩ lemma pure (a : α) : ¬ prog (pure a) := begin introI h, have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end instance bind {f : α → parser β} [p.prog] [∀ a, (f a).mono] : (p >>= f).prog := ⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact lt_of_lt_of_le (of_done hp) (mono.of_done hf) }⟩ instance and_then {q : parser β} [p.prog] [q.mono] : (p >> q).prog := prog.bind instance map [p.prog] {f : α → β} : (f <$> p).prog := ⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩ instance seq {f : parser (α → β)} [f.prog] [p.mono] : (f <*> p).prog := prog.bind instance mmap {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap f).prog := begin constructor, simp only [and_imp, bind_eq_done, return_eq_pure, mmap, exists_imp_distrib, pure_eq_done], rintro _ _ _ _ _ _ h _ _ hp rfl rfl, exact lt_of_lt_of_le (of_done h) (mono.of_done hp) end instance mmap' {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] : ((a :: l).mmap' f).prog := begin constructor, simp only [and_imp, bind_eq_done, mmap', exists_imp_distrib, and_then_eq_bind], intros _ _ _ _ _ _ h hm, exact lt_of_lt_of_le (of_done h) (mono.of_done hm) end instance failure : @parser.prog α failure := prog.of_step lemma guard_true : ¬ prog (guard true) := pure _ instance guard : prog (guard false) := prog.failure instance orelse [p.prog] [q.prog] : (p <|> q).prog := ⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩ lemma decorate_errors_iff : (@parser.decorate_errors α msgs p).prog ↔ p.prog := begin split, { introI, constructor, intros cb n n' a h, have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h, exact of_done this }, { introI, constructor, intros _ _ _ _ h, rw decorate_errors_eq_done at h, exact of_done h } end instance decorate_errors [p.prog] : (@decorate_errors α msgs p).prog := ⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩ lemma decorate_error_iff : (@parser.decorate_error α msg p).prog ↔ p.prog := decorate_errors_iff instance decorate_error [p.prog] : (@decorate_error α msg p).prog := prog.decorate_errors instance any_char : prog any_char := prog.of_step instance sat {p : char → Prop} [decidable_pred p] : prog (sat p) := prog.of_step lemma eps : ¬ prog eps := prog.pure () instance ch {c : char} : prog (ch c) := prog.of_step lemma char_buf_iff {cb' : char_buffer} : (char_buf cb').prog ↔ cb' ≠ buffer.nil := begin have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] := not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩, rw [char_buf, this, decorate_error_iff], cases cb'.to_list, { simp [pure] }, { simp only [iff_true, ne.def, not_false_iff], apply_instance } end instance one_of {cs : list char} : (one_of cs).prog := prog.decorate_errors instance one_of' {cs : list char} : (one_of' cs).prog := prog.and_then lemma str_iff {s : string} : (str s).prog ↔ s ≠ "" := by simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff] lemma remaining : ¬ remaining.prog := begin introI h, have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end lemma eof : ¬ eof.prog := begin introI h, have : eof buffer.nil 0 = done 0 () := by simpa [remaining_eq_done], replace this : 0 < 0 := prog.of_done this, exact (lt_irrefl _) this end -- TODO: add foldr and foldl, many, etc, fix_core instance many1 [p.mono] [p.prog] : p.many1.prog := begin constructor, rintro cb n n' (_ | ⟨hd, tl⟩), { simp }, { rw many1_eq_done, rintro ⟨np, hp, h⟩, exact (of_done hp).trans_le (mono.of_done h) } end lemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : ∀ (max_depth : ℕ), prog (fix_core F max_depth) | 0 := prog.failure | (max_depth + 1) := hF _ (fix_core _) instance digit : digit.prog := prog.of_step instance nat : nat.prog := prog.decorate_error lemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) : prog (fix F) := ⟨λ cb n _ _ h, by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩ end prog variables {α β : Type} {msgs : thunk (list string)} {msg : thunk string} variables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string} variables {a : α} {b : β} section many -- TODO: generalize to p.prog instead of p.step lemma many_sublist_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : ∀ k < n' - n, p.many cb (n + k) = done n' (l.drop k) := begin induction l with hd tl hl generalizing n, { rw many_eq_done_nil at h, simp [h.left] }, intros m hm, cases m, { exact h }, rw [list.drop, nat.add_succ, ←nat.succ_add], apply hl, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, convert h, exact (step.of_done hp).symm }, { exact nat.lt_pred_iff.mpr hm }, end lemma many_eq_nil_of_done [p.step] [p.bounded] {l : list α} (h : p.many cb n = done n' l) : p.many cb n' = done n' [] := begin induction l with hd tl hl generalizing n, { convert h, rw many_eq_done_nil at h, exact h.left.symm }, { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h, obtain ⟨_, -, h⟩ := h, exact hl h } end lemma many_eq_nil_of_out_of_bound [p.bounded] {l : list α} (h : p.many cb n = done n' l) (hn : cb.size < n) : n' = n ∧ l = [] := begin cases l, { rw many_eq_done_nil at h, exact ⟨h.left.symm, rfl⟩ }, { rw many_eq_done at h, obtain ⟨np, hp, -⟩ := h, exact absurd (bounded.of_done hp) hn.not_lt } end lemma many1_length_of_done [p.mono] [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : l.length = n' - n := begin induction l with hd tl hl generalizing n n', { simpa using h }, { obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done h), subst hk, simp only [many1_eq_done] at h, obtain ⟨_, hp, h⟩ := h, have := step.of_done hp, subst this, cases tl, { simp only [many_eq_done_nil, add_left_inj, exists_and_distrib_right, self_eq_add_right] at h, rcases h with ⟨rfl, -⟩, simp }, rw ←many1_eq_done_iff_many_eq_done at h, specialize hl h, simp [hl, add_comm, add_assoc, nat.sub_succ] } end lemma many1_bounded_of_done [p.step] [p.bounded] {l : list α} (h : many1 p cb n = done n' l) : n' ≤ cb.size := begin induction l with hd tl hl generalizing n n', { simpa using h }, { simp only [many1_eq_done] at h, obtain ⟨np, hp, h⟩ := h, have := step.of_done hp, subst this, cases tl, { simp only [many_eq_done_nil, exists_and_distrib_right] at h, simpa [←h.left] using bounded.of_done hp }, { rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } } end end many section nat /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`. The number of characters parsed in is necessarily `n' - n`. This is one of the directions of `nat_eq_done`. -/ lemma nat_of_done {val : ℕ} (h : nat cb n = done n' val) : val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) := begin /- The parser `parser.nat` that generates a decimal number from a string of digit characters does several things. First it ingests in as many digits as it can with `many1 digit`. Then, it folds over the resulting `list ℕ` using a helper function that keeps track of both the running sum an and the magnitude so far, using a `(sum, magnitude) : (ℕ × ℕ)` pair. The final sum is extracted using a `prod.fst`. To prove that the value that `parser.nat` produces, after moving precisely `n' - n` steps, is precisely what `nat.of_digits` would give, if supplied the string that is in the ingested `char_buffer` (modulo conversion from `char` to `ℕ ), we need to induct over the length `n' - n` of `cb : char_buffer` ingested, and prove that the parser must have terminated due to hitting either the end of the `char_buffer` or a non-digit character. The statement of the lemma is phrased using a combination of `list.drop` and `list.map` because there is no currently better way to extract an "interval" from a `char_buffer`. Additionally, the statement uses a `list.reverse` because `nat.of_digits` is little-endian. We try to stop referring to the `cb : char_buffer` as soon as possible, so that we can instead regard a `list char` instead, which lends itself better to proofs via induction. -/ /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` with -- the function above. We use this lemma later when we finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We convert the hypothesis that `parser.nat` has succeeded into an existential that there is -- some list of digits that it has parsed in, and that those digits, when folded over by the -- function above, give the value at hand. simp only [nat, pure_eq_done, natm, decorate_error_eq_done, bind_eq_done] at h, obtain ⟨n', l, hp, rfl, rfl⟩ := h, -- We now want to stop working with the `cb : char_buffer` and parse positions `n` and `n'`, -- and just deal with the parsed digit list `l : list ℕ`. To do so, we have to show that -- this is precisely the list that could have been parsed in, no smaller and no greater. induction l with lhd ltl IH generalizing n n' cb, { -- Base case: we parsed in no digits whatsoever. But this is impossible because `parser.many1` -- must produce a list that is not `list.nil`, by `many1_ne_done_nil`. simpa using hp }, -- Inductive case: -- We must prove that the first digit parsed in `lhd : ℕ` is precisely the digit that is -- represented by the character at position `n` in `cb : char_buffer`. -- We will also prove the correspondence between the subsequent digits `ltl : list ℕ` and the -- remaining characters past position `n` up to position `n'`. cases hx : (list.drop n (buffer.to_list cb)) with chd ctl, { -- Are there even characters left to parse, at position `n` in the `cb : char_buffer`? In other -- words, are we already out of bounds, and thus could not have parsed in any value -- successfully. But this must be a contradiction because `parser.digit` is a `bounded` parser, -- (due to its being defined via `parser.decorate_error`), which means it only succeeds -- in-bounds, and the `many1` parser combinator retains that property. have : cb.size ≤ n := by simpa using list.drop_eq_nil_iff_le.mp hx, exact absurd (bounded.of_done hp) this.not_lt }, -- We prove that the first digit parsed in is precisely the digit that is represented by the -- character at position `n`, which we now call `chd : char`. have chdh : chd.to_nat - '0'.to_nat = lhd, { simp only [many1_eq_done] at hp, -- We know that `parser.digit` succeeded, so it has moved to a possibly different position. -- In fact, we know that this new position is `n + 1`, by the `step` property of -- `parser.digit`. obtain ⟨_, hp, -⟩ := hp, have := step.of_done hp, subst this, -- We now unfold what it means for `parser.digit` to succeed, which means that the character -- parsed in was "numeric" (for some definition of that property), and, more importantly, -- that the `n`th character of `cb`, let's say `c`, when converted to a `ℕ` via -- `char.to_nat c - '0'.to_nat`, must be equal to the resulting value, `lhd` in our case. simp only [digit_eq_done, buffer.read_eq_nth_le_to_list, hx, buffer.length_to_list, true_and, add_left_inj, list.length, list.nth_le, eq_self_iff_true, exists_and_distrib_left, fin.coe_mk] at hp, rcases hp with ⟨_, hn, rfl, _, _⟩, -- But we already know the list corresponding to `cb : char_buffer` from position `n` and on -- is equal to `(chd :: ctl) : list char`, so our `c` above must satisfy `c = chd`. have hn' : n < cb.to_list.length := by simpa using hn, rw ←list.cons_nth_le_drop_succ hn' at hx, -- We can ignore proving any correspondence of `ctl : list char` to the other portions of the -- `cb : char_buffer`. simp only at hx, simp [hx] }, -- We know that we parsed in more than one character because of the `prog` property of -- `parser.digit`, which the `many1` parser combinator retains. In other words, we know that -- `n < n'`, and so, the list of digits `ltl` must correspond to the list of digits that -- `digit.many1 cb (n + 1)` would produce. We know that the shift of `1` in `n ↦ n + 1` holds -- due to the `step` property of `parser.digit`. -- We also get here `k : ℕ` which will indicate how many characters we parsed in past position -- `n`. We will prove later that this must be the number of digits we produced as well in `ltl`. obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done hp), have hdm : ltl = [] ∨ digit.many1 cb (n + 1) = done n' ltl, { cases ltl, { simp }, { rw many1_eq_done at hp, obtain ⟨_, hp, hp'⟩ := hp, simpa [step.of_done hp, many1_eq_done_iff_many_eq_done] using hp' } }, -- Now we case on the two possibilities, that there was only a single digit parsed in, and -- `ltl = []`, or, had we started parsing at `n + 1` instead, we'd parse in the value associated -- with `ltl`. -- We prove that the LHS, which is a fold over a `list ℕ` is equal to the RHS, which is that -- the `val : ℕ` that `nat.of_digits` produces when supplied a `list ℕ that has been produced -- via mapping a `list char` using `char.to_nat`. Specifically, that `list char` are the -- characters in the `cb : char_buffer`, from position `n` to position `n'` (excluding `n'`), -- in reverse. rcases hdm with rfl|hdm, { -- Case that `ltl = []`. simp only [many1_eq_done, many_eq_done_nil, exists_and_distrib_right] at hp, -- This means we must have failed parsing with `parser.digit` at some other position, -- which we prove must be `n + 1` via the `step` property. obtain ⟨_, hp, rfl, hp'⟩ := hp, have := step.of_done hp, subst this, -- Now we rely on the simplifier, which simplfies the LHS, which is a fold over a singleton -- list. On the RHS, `list.take (n + 1 - n)` also produces a singleton list, which, when -- reversed, is the same list. `nat.of_digits` of a singleton list is precisely the value in -- the list. And we already have that `chd.to_nat - '0'.to_nat = lhd`. simp [chdh] }, -- We now have to deal with the case where we parsed in more than one digit, and thus -- `n + 1 < n'`, which means `ctl` has one or more elements. Similarly, `ltl` has one or more -- elements. -- We finish ridding ourselves of references to `cb : char_buffer`, by relying on the fact that -- our `ctl : list char` must be the appropriate portion of `cb` once enough elements have been -- dropped and taken. have rearr : list.take (n + (k + 1) - (n + 1)) (list.drop (n + 1) (buffer.to_list cb)) = ctl.take k, { simp [←list.tail_drop, hx, nat.sub_succ, hk] }, -- We have to prove that the number of digits produced (given by `ltl`) is equal to the number -- of characters parsed in, as given by `ctl.take k`, and that this is precisely `k`. We phrase it -- in the statement using `min`, because lemmas about `list.length (list.take ...)` simplify to -- a statement that uses `min`. The `list.length` term appears from the reduction of the folding -- function, as proven above. have ltll : min k ctl.length = ltl.length, { -- Here is an example of how statements about the `list.length` of `list.take` simplify. have : (ctl.take k).length = min k ctl.length := by simp, -- We bring back the underlying definition of `ctl` as the result of a sequence of `list.take` -- and `list.drop`, so that lemmas about `list.length` of those can fire. rw [←this, ←rearr, many1_length_of_done hdm], -- Likewise, we rid ourselves of the `k` we generated earlier. have : k = n' - n - 1, { simp [hk, add_assoc] }, subst this, simp only [nat.sub_succ, add_comm, ←nat.pred_sub, buffer.length_to_list, nat.pred_one_add, min_eq_left_iff, list.length_drop, nat.add_sub_cancel_left, list.length_take, nat.sub_zero], -- We now have a goal of proving an inequality dealing with `nat` subtraction and `nat.pred`, -- both of which require special care to provide positivity hypotheses. rw [nat.sub_le_sub_right_iff, nat.pred_le_iff], { -- We know that `n' ≤ cb.size` because of the `bounded` property, that a parser will not -- produce a `done` result at a position farther than the size of the underlying -- `char_buffer`. convert many1_bounded_of_done hp, -- What is now left to prove is that `0 < cb.size`, which can be rephrased -- as proving that it is nonempty. cases hc : cb.size, { -- Proof by contradiction. Let's say that `cb.size = 0`. But we know that we succeeded -- parsing in at position `n` using a `bounded` parser, so we must have that -- `n < cb.size`. have := bounded.of_done hp, rw hc at this, -- But then `n < 0`, a contradiction. exact absurd n.zero_le this.not_le }, { simp } }, { -- Here, we use the same result as above, that `n < cb.size`, and relate it to -- `n ≤ cb.size.pred`. exact nat.le_pred_of_lt (bounded.of_done hp) } }, -- Finally, we simplify. On the LHS, we have a fold over `lhd :: ltl`, which simplifies to -- the operation of the summing folding function on `lhd` and the fold over `ltl`. To that we can -- apply the induction hypothesis, because we know that our parser would have succeeded had we -- started at position `n + 1`. We replace mentions of `cb : char_buffer` with the appropriate -- `chd :: ctl`, replace `lhd` with the appropriate statement of how it is calculated from `chd`, -- and use the lemmas describing the length of `ltl` and how it is associated with `k`. We also -- remove mentions of `n'` and replace with an expression using solely `n + k + 1`. -- We use the lemma we proved above about how the folding function produces the -- `prod.snd` value, which is `10` to the power of the length of the list provided to the fold. -- Finally, we rely on `nat.of_digits_append` for the related statement of how digits given -- are used in the `nat.of_digits` calculation, which also involves `10 ^ list.length ...`. -- The `list.append` operation appears due to the `list.reverse (chd :: ctl)`. -- We include some addition and multiplication lemmas to help the simplifier rearrange terms. simp [IH _ hdm, hx, hk, rearr, ←chdh, ←ltll, hpow, add_assoc, nat.of_digits_append, mul_comm] end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for all `k : ℕ`, `n ≤ k`, `k < n'`, the character at the `k`th position in `cb : char_buffer` is "numeric", that is, is between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_as_digit {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' ≤ cb.size) k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn⟩ ∧ cb.read ⟨k, hk.trans_le hn⟩ ≤ '9' := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: we prove that the `parser.digit.many1` produced a valid `(hd :: tl) : list ℕ`, -- by showing that is the case for the character at position `n`, which gave `hd`, and use the -- induction hypothesis on the remaining `tl`. -- We break apart a `many1` success into a success of the underlying `parser.digit` to give `hd` -- and a `parser.digit.many` which gives `tl`. We first deal with the `hd`. rw many1_eq_done at h, -- Right away, we can throw away the information about the "new" position that `parser.digit` -- ended on because we will soon prove that it must have been `n + 1`. obtain ⟨_, hp, h⟩ := h, -- The main lemma here is `digit_eq_done`, which already proves the necessary conditions about -- the character at hand. What is left to do is properly unpack the information. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left, exists_and_distrib_left] at hp, obtain ⟨rfl, -, hn, ge0, le9, rfl⟩ := hp, -- Let's now consider a position `k` between `n` and `n'`, excluding `n'`. intros hn k hk hk', -- What if we are at `n`? What if we are past `n`? We case on the `n ≤ k`. rcases hk'.eq_or_lt with rfl|hk', { -- The `n = k` case. But this is exactly what we know already, so we provide the -- relevant hypotheses. exact ⟨ge0, le9⟩ }, -- The `n < k` case. First, we check if there would have even been digits parsed in. So, we -- case on `tl : list ℕ` cases tl, { -- Case where `tl = []`. But that means `many` gave us a `[]` so either the character at -- position `k` was not "numeric" or we are out of bounds. More importantly, when `many` -- successfully produces a `[]`, it does not progress the parser head, so we have that -- `n + 1 = n'`. This will lead to a contradiction because now we have `n < k` and `k < n + 1`. simp only [many_eq_done_nil, exists_and_distrib_right] at h, -- Extract out just the `n + 1 = n'`. obtain ⟨rfl, -⟩ := h, -- Form the contradictory hypothesis, and discharge the goal. have : k < k := hk.trans_le (nat.succ_le_of_lt hk'), exact absurd this (lt_irrefl _) }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw ←many1_eq_done_iff_many_eq_done at h, apply hl h, -- All that is left to prove is that our `k` is at least our new "lower bound" `n + 1`, which -- we have from our original split of the `n ≤ k`, since we are now on the `n < k` case. exact nat.succ_le_of_lt hk' } end /-- If we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`, then it must be the case that for the ending position `n'`, either it is beyond the end of the `cb : char_buffer`, or the character at that position is not "numeric", that is, between `'0'` and `'9'` inclusive. This is a necessary part of proving one of the directions of `nat_eq_done`. -/ lemma nat_of_done_bounded {val : ℕ} (h : nat cb n = done n' val) : ∀ (hn : n' < cb.size), '0' ≤ cb.read ⟨n', hn⟩ → '9' < cb.read ⟨n', hn⟩ := begin -- The properties to be shown for the characters involved rely solely on the success of -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced. -- We break done the success of `parser.nat` into the `parser.digit` success and throw away -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by -- `parser.digit.many1`. -- We deal with the case of `n'` is "out-of-bounds" right away by requiring that -- `∀ (hn : n' < cb.size)`. Thus we only have to prove the lemma for the cases where `n'` is still -- "in-bounds". simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨xs, h, -⟩ := h, -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we -- induct on the `xs : list ℕ` that `parser.digit.many1` produced. induction xs with hd tl hl generalizing n n', { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a -- nonempty list, as proven by `many1_ne_done_nil`. simpa using h }, -- Inductive case: at least one character has been parsed in, starting at position `n`. -- We know that the size of `cb : char_buffer` must be at least `n + 1` because -- `parser.digit.many1` is `bounded` (`n < cb.size`). -- We show that either we parsed in just that one character, or we use the inductive hypothesis. obtain ⟨k, hk⟩ : ∃ k, cb.size = n + k + 1 := nat.exists_eq_add_of_lt (bounded.of_done h), cases tl, { -- Case where `tl = []`, so we parsed in only `hd`. That must mean that `parser.digit` failed -- at `n + 1`. simp only [many1_eq_done, many_eq_done_nil, and.left_comm, exists_and_distrib_right, exists_eq_left] at h, -- We throw away the success information of what happened at position `n`, and we do not need -- the "error" value that the failure produced. obtain ⟨-, _, h⟩ := h, -- If `parser.digit` failed at `n + 1`, then either we hit a non-numeric character, or -- we are out of bounds. `digit_eq_fail` provides us with those two cases. simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left, eq_self_iff_true, exists_and_distrib_left] at h, obtain (⟨rfl, h⟩ | ⟨h, -⟩) := h, { -- First case: we are still in bounds, but the character is not numeric. We must prove -- that we are still in bounds. But we know that from our initial requirement. intro hn, simpa using h hn }, { -- Second case: we are out of bounds, and somehow the fold that `many1` relied on failed. -- But we know that `parser.digit` is mono, that is, it never goes backward in position, -- in neither success nor in failure. We also have that `foldr_core` respects `mono`. -- But in this case, `foldr_core` is starting at position `n' + 1` but failing at -- position `n'`, which is a contradiction, because otherwise we would have `n' + 1 ≤ n'`. simpa using mono.of_fail h } }, { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so -- `many1` would have successfully parsed at this position too. We use this statement to -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it. rw many1_eq_done at h, obtain ⟨_, -, h⟩ := h, rw ←many1_eq_done_iff_many_eq_done at h, exact hl h } end /-- The `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value represented by the string of decimal digits (possibly padded with 0s on the left) starting from the parsing position `n` and ending at position `n'`, where `n < n'`. The number of characters parsed in is necessarily `n' - n`. Additionally, all of the characters in the `cb` starting at position `n` (inclusive) up to position `n'` (exclusive) are "numeric", in that they are between `'0'` and `'9'` inclusive. Such a `char_buffer` would produce the `ℕ` value encoded by its decimal characters. -/ lemma nat_eq_done {val : ℕ} : nat cb n = done n' val ↔ ∃ (hn : n < n'), val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map (λ c, c.to_nat - '0'.to_nat)))) ∧ (∀ (hn' : n' < cb.size), ('0' ≤ cb.read ⟨n', hn'⟩ → '9' < cb.read ⟨n', hn'⟩)) ∧ ∃ (hn'' : n' ≤ cb.size), (∀ k (hk : k < n'), n ≤ k → '0' ≤ cb.read ⟨k, hk.trans_le hn''⟩ ∧ cb.read ⟨k, hk.trans_le hn''⟩ ≤ '9') := begin -- To prove this iff, we have most of the way in the forward direction, using the lemmas proven -- above. First, we must use that `parser.nat` is `prog`, which means that on success, it must -- move forward. We also have to prove the statement that a success means the parsed in -- characters were properly "numeric". It involves first generating ane existential witness -- that the parse was completely "in-bounds". -- For the reverse direction, we first discharge the goals that deal with proving that our parser -- succeeded because it encountered characters with the proper "numeric" properties, was -- "in-bounds" and hit a nonnumeric character. The more difficult portion is proving that the -- list of characters from positions `n` to `n'`, when folded over by the function defined inside -- `parser.nat` gives exactly the same value as `nat.of_digits` when supplied with the same -- (modulo rearrangement) list. To reach this goal, we try to remove any reliance on the -- underlying `cb : char_buffer` or parsers as soon as possible, via a cased-induction. refine ⟨λ h, ⟨prog.of_done h, nat_of_done h, nat_of_done_bounded h, _⟩, _⟩, { -- To provide the existential witness that `n'` is within the bounds of the `cb : char_buffer`, -- we rely on the fact that `parser.nat` is primarily a `parser.digit.many1`, and that `many1`, -- must finish with the bounds of the `cb`, as long as the underlying parser is `step` and -- `bounded`, which `digit` is. We do not prove this as a separate lemma about `parser.nat` -- because it would almost always be only relevant in this larger theorem. -- We clone the success hypothesis `h` so that we can supply it back later. have H := h, -- We unwrap the `parser.nat` success down to the `many1` success, throwing away other info. rw [nat] at h, simp only [decorate_error_eq_done, bind_eq_done, pure_eq_done, and.left_comm, exists_eq_left, exists_and_distrib_left] at h, obtain ⟨_, h, -⟩ := h, -- Now we get our existential witness that `n' ≤ cb.size`. replace h := many1_bounded_of_done h, -- With that, we can use the lemma proved above that our characters are "numeric" exact ⟨h, nat_of_done_as_digit H h⟩ }, -- We now prove that given the `cb : char_buffer` with characters within the `n ≤ k < n'` interval -- properly "numeric" and such that their `nat.of_digits` generates the `val : ℕ`, `parser.nat` -- of that `cb`, when starting at `n`, will finish at `n'` and produce the same `val`. -- We first introduce the relevant hypotheses, including the fact that we have a valid interval -- where `n < n'` and that characters at `n'` and beyond are no longer numeric. rintro ⟨hn, hv, hb, hn', ho⟩, -- We first unwrap the `parser.nat` definition to the underlying `parser.digit.many1` success -- and the fold function of the digits. rw nat, simp only [and.left_comm, pure_eq_done, hv, decorate_error_eq_done, list.map_reverse, bind_eq_done, exists_eq_left, exists_and_distrib_left], -- We won't actually need the `val : ℕ` itself, since it is entirely characterized by the -- underlying characters. Instead, we will induct over the `list char` of characters from -- position `n` onwards, showing that if we could have provided a list at `n`, we could have -- provided a valid list of characters at `n + 1` too. clear hv val, /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined in core, we have to work with how it is defined instead of changing its definition. In its definition, the function that folds over the parsed in digits is defined internally, as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term when rewriting the definition of `parser.nat` away. Since we know exactly what the function is, we have a `rfl`-like lemma here to rewrite it back into a readable form. -/ have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩), { ext1, ext1 ⟨⟩, refl }, -- We induct over the characters available at position `n` and onwards. Because `cb` is used -- in other expressions, we utilize the `induction H : ...` tactic to induct separately from -- destructing `cb` itself. induction H : (cb.to_list.drop n) with hd tl IH generalizing n, { -- Base case: there are no characters at position `n` or onwards, which means that -- `cb.size ≤ n`. But this is a contradiction, since we have `n < n' ≤ cb.size`. rw list.drop_eq_nil_iff_le at H, refine absurd ((lt_of_le_of_lt H hn).trans_le hn') _, simp }, { -- Inductive case: we prove that if we could have parsed from `n + 1`, we could have also parsed -- from `n`, if there was a valid numerical character at `n`. Most of the body -- of this inductive case is generating the appropriate conditions for use of the inductive -- hypothesis. specialize @IH (n + 1), -- We have, by the inductive case, that there is at least one character `hd` at position `n`, -- with the rest at `tl`. We rearrange our inductive case to make `tl` be expressed as -- list.drop (n + 1), which fits out induction hypothesis conditions better. To use the -- rearranging lemma, we must prove that we are "dropping" in bounds, which we supply on-the-fly simp only [←list.cons_nth_le_drop_succ (show n < cb.to_list.length, by simpa using hn.trans_le hn')] at H, -- We prove that parsing our `n`th character, `hd`, would have resulted in a success from -- `parser.digit`, with the appropriate `ℕ` success value. We use this later to simplify the -- unwrapped fold, since `hd` is our head character. have hdigit : digit cb n = done (n + 1) (hd.to_nat - '0'.to_nat), { -- By our necessary condition, we know that `n` is in bounds, and that the `n`th character -- has the necessary "numeric" properties. specialize ho n hn (le_refl _), -- We prove an additional result that the conversion of `hd : char` to a `ℕ` would give a -- value `x ≤ 9`, since that is part of the iff statement in the `digit_eq_done` lemma. have : (buffer.read cb ⟨n, hn.trans_le hn'⟩).to_nat - '0'.to_nat ≤ 9, { -- We rewrite the statement to be a statement about characters instead, and split the -- inequality into the case that our hypotheses prove, and that `'0' ≤ '9'`, which -- is true by computation, handled by `dec_trivial`. rw [show 9 = '9'.to_nat - '0'.to_nat, from dec_trivial, nat.sub_le_sub_right_iff], { exact ho.right }, { dec_trivial } }, -- We rely on the simplifier, mostly powered by `digit_eq_done`, and supply all the -- necessary conditions of bounds and identities about `hd`. simp [digit_eq_done, this, ←H.left, buffer.nth_le_to_list, hn.trans_le hn', ho] }, -- We now case on whether we've moved to the end of our parse or not. We phrase this as -- casing on either `n + 1 < n` or `n ≤ n + 1`. The more difficult goal comes first. cases lt_or_ge (n + 1) n' with hn'' hn'', { -- Case `n + 1 < n'`. We can directly supply this to our induction hypothesis. -- We now have to prove, for the induction hypothesis, that the characters at positions `k`, -- `n + 1 ≤ k < n'` are "numeric". We already had this for `n ≤ k < n`, so we just rearrange -- the hypotheses we already have. specialize IH hn'' _ H.right, { intros k hk hk', apply ho, exact nat.le_of_succ_le hk' }, -- With the induction hypothesis conditions satisfier, we can extract out a list that -- `parser.digit.many1` would have generated from position `n + 1`, as well as the associated -- property of the list, that it folds into what `nat.of_digits` generates from the -- characters in `cb : char_buffer`, now known as `hd :: tl`. obtain ⟨l, hdl, hvl⟩ := IH, -- Of course, the parsed in list from position `n` would be `l` prepended with the result -- of parsing in `hd`, which is provided explicitly. use (hd.to_nat - '0'.to_nat) :: l, -- We case on `l : list ℕ` so that we can make statements about the fold on `l` cases l with lhd ltl, { -- As before, if `l = []` then `many1` produced a `[]` success, which is a contradiction. simpa using hdl }, -- Case `l = lhd :: ltl`. We can rewrite the fold of the function inside `parser.nat` on -- `lhd :: ltl`, which will be used to rewrite in the goal. simp only [natm, list.foldr] at hvl, -- We also expand the fold in the goal, using the expanded fold from our hypothesis, powered -- by `many1_eq_done` to proceed in the parsing. We know exactly what the next `many` will -- produce from `many1_eq_done_iff_many_eq_done.mp` of our `hdl` hypothesis. Finally, -- we also use `hdigit` to express what the single `parser.digit` result would be at `n`. simp only [natm, hvl, many1_eq_done, hdigit, many1_eq_done_iff_many_eq_done.mp hdl, true_and, and_true, eq_self_iff_true, list.foldr, exists_eq_left'], -- Now our goal is solely about the equality of two different folding functions, one from the -- function defined inside `parser.nat` and the other as `nat.of_digits`, when applied to -- similar list inputs. -- First, we rid ourselves of `n'` by replacing with `n + m + 1`, which allows us to -- simplify the term of how many elements we are keeping using a `list.take`. obtain ⟨m, rfl⟩ : ∃ m, n' = n + m + 1 := nat.exists_eq_add_of_lt hn, -- The following rearrangement lemma is to simplify the `list.take (n' - n)` expression we had have : n + m + 1 - n = m + 1, { rw [add_assoc, nat.sub_eq_iff_eq_add, add_comm], exact nat.le_add_right _ _ }, -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` -- with the function above. We use this lemma to finish our inductive case. have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length, { intro l, induction l with hd tl hl, { simp }, { simp [hl, pow_succ, mul_comm] } }, -- We prove that the parsed list of digits `(lhd :: ltl) : list ℕ` must be of length `m` -- which is used later when the `parser.nat` fold places `ltl.length` in the exponent. have hml : ltl.length + 1 = m := by simpa using many1_length_of_done hdl, -- A simplified `list.length (list.take ...)` expression refers to the minimum of the -- underlying length and the amount of elements taken. We know that `m ≤ tl.length`, so -- we provide this auxiliary lemma so that the simplified "take-length" can simplify further have ltll : min m tl.length = m, { -- On the way to proving this, we have to actually show that `m ≤ tl.length`, by showing -- that since `tl` was a subsequence in `cb`, and was retrieved from `n + 1` to `n + m + 1`, -- then since `n + m + 1 ≤ cb.size`, we have that `tl` must be at least `m` in length. simpa [←H.right, ←nat.add_le_to_le_sub _ (hn''.trans_le hn').le, add_comm, add_assoc, add_left_comm] using hn' }, -- Finally, we rely on the simplifier. We already expressions of `nat.of_digits` on both -- the LHS and RHS. All that is left to do is to prove that the summand on the LHS is produced -- by the fold of `nat.of_digits` on the RHS of `hd :: tl`. The `nat.of_digits_append` is used -- because of the append that forms from the included `list.reverse`. The lengths of the lists -- are placed in the exponents with `10` as a base, and are combined using `←pow_succ 10`. -- Any complicated expression about list lengths is further simplified by the auxiliary -- lemmas we just proved. Finally, we assist the simplifier by rearranging terms with our -- `n + m + 1 - n = m + 1` proof and `mul_comm`. simp [this, hpow, nat.of_digits_append, mul_comm, ←pow_succ 10, hml, ltll] }, { -- Consider the case that `n' ≤ n + 1`. But then since `n < n' ≤ n + 1`, `n' = n + 1`. have : n' = n + 1 := le_antisymm hn'' (nat.succ_le_of_lt hn), subst this, -- This means we have only parsed in a single character, so the resulting parsed in list -- is explicitly formed from an expression we can construct from `hd`. use [[hd.to_nat - '0'.to_nat]], -- Our list expression simplifies nicely because it is a fold over a singleton, so we -- do not have to supply any auxiliary lemmas for it, other than what we already know about -- `hd` and the function defined in `parser.nat`. However, we will have to prove that our -- parse ended because of a good reason: either we are out of bounds or we hit a nonnumeric -- character. simp only [many1_eq_done, many_eq_done_nil, digit_eq_fail, natm, and.comm, and.left_comm, hdigit, true_and, mul_one, nat.of_digits_singleton, list.take, exists_eq_left, exists_and_distrib_right, nat.add_sub_cancel_left, eq_self_iff_true, list.reverse_singleton, zero_add, list.foldr, list.map], -- We take the route of proving that we hit a nonnumeric character, since we already have -- a hypothesis that says that characters at `n'` and past it are nonnumeric. (Note, by now -- we have substituted `n + 1` for `n'. -- We are also asked to provide the error value that our failed parse would report. But -- `digit_eq_fail` already knows what it is, so we can discharge that with an inline `rfl`. refine ⟨_, or.inl ⟨rfl, _⟩⟩, -- The nonnumeric condition looks almost exactly like the hypothesis we already have, so -- we let the simplifier align them for us simpa using hb } } end end nat end parser
2c4f1b1278018debf0a27dcec72a4f48ced0c104
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/coeIssues4.lean
b1d1866e73899d882b866fec1f72714b9cb48dbd
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
546
lean
new_frontend def f : List Int → Bool := fun _ => true def ex3 : IO Bool := do let xs ← pure [1, 2, 3]; pure $ f xs -- Works inductive Expr | val : Nat → Expr | app : Expr → Expr → Expr instance : Coe Nat Expr := ⟨Expr.val⟩ def foo : Expr → Expr := fun e => e def ex1 : Bool := f [1, 2, 3] -- Works def ex2 : Bool := let xs := [1, 2, 3]; f xs -- Works def ex4 := [1, 2, 3].map $ fun x => x+1 def ex5 (xs : List String) := xs.foldl (fun r x => r.push x) Array.empty set_option pp.all true #check foo 1 def ex6 := foo 1
f1f53af8bd427e92c4b19137eb19c8401fd34468
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/core.lean
0951e7c801f303c20d730943179c876cd48e3215
[ "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
18,662
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude notation `Prop` := Sort 0 notation f ` $ `:1 a:0 := f a /- Reserving notation. We do this sot that the precedence of all of the operators can be seen in one place and to prevent core notation being accidentally overloaded later. -/ /- Notation for logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 -- not used reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 -- eq reserve infix ` == `:50 -- heq reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 -- has_equiv.equiv reserve infix ` ~ `:50 -- used as local notation for relations reserve infix ` ≡ `:50 -- not used reserve infixl ` ⬝ `:75 -- not used reserve infixr ` ▸ `:75 -- eq.subst reserve infixr ` ▹ `:75 -- not used /- types and type constructors -/ reserve infixr ` ⊕ `:30 -- sum (defined in init/data/sum/basic.lean) reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:100 reserve infixr ` ^ `:80 reserve infixr ` ∘ `:90 -- function composition 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 reserve infix ` ⊂ `:50 reserve infix ` ⊃ `:50 reserve infix ` \ `:70 -- symmetric difference /- other symbols -/ reserve infix ` ∣ `:50 -- has_dvd.dvd. Note this is different to `|`. reserve infixl ` ++ `:65 -- has_append.append reserve infixr ` :: `:67 -- list.cons reserve infixl `; `:1 -- has_andthen.andthen universes u v w /-- The kernel definitional equality test (t =?= s) has special support for id_delta applications. It implements the following rules 1) (id_delta t) =?= t 2) t =?= (id_delta t) 3) (id_delta t) =?= s IF (unfold_of t) =?= s 4) t =?= id_delta s IF t =?= (unfold_of s) This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel. We use id_delta applications to address performance problems when type checking lemmas generated by the equation compiler. -/ @[inline] def id_delta {α : Sort u} (a : α) : α := a /-- Gadget for optional parameter support. -/ @[reducible] def opt_param (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def out_param (α : Sort u) : Sort u := α /- id_rhs is an auxiliary declaration used in the equation compiler to address performance issues when proving equational lemmas. The equation compiler uses it as a marker. -/ abbreviation id_rhs (α : Sort u) (a : α) : α := a inductive punit : Sort u | star : punit /-- An abbreviation for `punit.{0}`, its most common instantiation. This type should be preferred over `punit` where possible to avoid unnecessary universe parameters. -/ abbreviation unit : Type := punit @[pattern] abbreviation unit.star : unit := punit.star /-- Gadget for defining thunks, thunk parameters have special treatment. Example: given def f (s : string) (t : thunk nat) : nat an application f "hello" 10 is converted into f "hello" (λ _, 10) -/ @[reducible] def thunk (α : Type u) : Type u := unit → α inductive true : Prop | intro : true inductive false : Prop inductive empty : Type def not (a : Prop) := a → false prefix `¬` := not inductive eq {α : Sort u} (a : α) : α → Prop | refl : eq a /- Initialize the quotient module, which effectively adds the following definitions: constant quot {α : Sort u} (r : α → α → Prop) : Sort u constant quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : quot r constant quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → eq (f a) (f b)) → quot r → β constant quot.ind {α : Sort u} {r : α → α → Prop} {β : quot r → Prop} : (∀ a : α, β (quot.mk r a)) → ∀ q : quot r, β q Also the reduction rule: quot.lift f _ (quot.mk a) ~~> f a -/ init_quotient /-- Heterogeneous equality. It's purpose is to write down equalities between terms whose types are not definitionally equal. For example, given `x : vector α n` and `y : vector α (0+n)`, `x = y` doesn't typecheck but `x == y` does. -/ inductive heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop | refl : heq a structure prod (α : Type u) (β : Type v) := (fst : α) (snd : β) /-- Similar to `prod`, but α and β can be propositions. We use this type internally to automatically generate the brec_on recursor. -/ structure pprod (α : Sort u) (β : Sort v) := (fst : α) (snd : β) structure and (a b : Prop) : Prop := intro :: (left : a) (right : b) def and.elim_left {a b : Prop} (h : and a b) : a := h.1 def and.elim_right {a b : Prop} (h : and a b) : b := h.2 /- eq basic support -/ infix = := eq attribute [refl] eq.refl @[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a @[elab_as_eliminator, subst] lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b := eq.rec h₂ h₁ notation h1 ▸ h2 := eq.subst h1 h2 @[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ @[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a := h ▸ rfl infix == := heq @[pattern] def heq.rfl {α : Sort u} {a : α} : a == a := heq.refl a lemma eq_of_heq {α : Sort u} {a a' : α} (h : a == a') : a = a' := have ∀ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from λ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl), show (eq.rec_on (eq.refl α) a : α) = a', from this α a' h (eq.refl α) /- The following four lemmas could not be automatically generated when the structures were declared, so we prove them manually here. -/ lemma prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → and (x₁ = x₂) (y₁ = y₂) := λ h, prod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩) lemma prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P := λ h₁ _ h₂, prod.no_confusion h₁ h₂ lemma pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : pprod.mk x₁ y₁ = pprod.mk x₂ y₂ → and (x₁ = x₂) (y₁ = y₂) := λ h, pprod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩) lemma pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P := λ h₁ _ h₂, prod.no_confusion h₁ h₂ inductive sum (α : Type u) (β : Type v) | inl {} (val : α) : sum | inr {} (val : β) : sum inductive psum (α : Sort u) (β : Sort v) | inl {} (val : α) : psum | inr {} (val : β) : psum inductive or (a b : Prop) : Prop | inl {} (h : a) : or | inr {} (h : b) : or def or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b := or.inl ha def or.intro_right (a : Prop) {b : Prop} (hb : b) : or a b := or.inr hb structure sigma {α : Type u} (β : α → Type v) := mk :: (fst : α) (snd : β fst) structure psigma {α : Sort u} (β : α → Sort v) := mk :: (fst : α) (snd : β fst) inductive bool : Type | ff : bool | tt : bool /- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/ structure subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) attribute [pp_using_anonymous_constructor] sigma psigma subtype pprod and class inductive decidable (p : Prop) | is_false (h : ¬p) : decidable | is_true (h : p) : decidable @[reducible] def decidable_pred {α : Sort u} (r : α → Prop) := Π (a : α), decidable (r a) @[reducible] def decidable_rel {α : Sort u} (r : α → α → Prop) := Π (a b : α), decidable (r a b) @[reducible] def decidable_eq (α : Sort u) := decidable_rel (@eq α) inductive option (α : Type u) | none {} : option | some (val : α) : option export option (none some) export bool (ff tt) inductive list (T : Type u) | nil {} : list | cons (hd : T) (tl : list) : list notation h :: t := list.cons h t notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l inductive nat | zero : nat | succ (n : nat) : nat structure unification_constraint := {α : Type u} (lhs : α) (rhs : α) infix ` ≟ `:50 := unification_constraint.mk infix ` =?= `:50 := unification_constraint.mk structure unification_hint := (pattern : unification_constraint) (constraints : list unification_constraint) /- Declare builtin and reserved notation -/ class has_zero (α : Type u) := (zero : α) class has_one (α : Type u) := (one : α) class has_add (α : Type u) := (add : α → α → α) class has_mul (α : Type u) := (mul : α → α → α) class has_inv (α : Type u) := (inv : α → α) class has_neg (α : Type u) := (neg : α → α) class has_sub (α : Type u) := (sub : α → α → α) class has_div (α : Type u) := (div : α → α → α) class has_dvd (α : Type u) := (dvd : α → α → Prop) class has_mod (α : Type u) := (mod : α → α → α) class has_le (α : Type u) := (le : α → α → Prop) class has_lt (α : Type u) := (lt : α → α → Prop) class has_append (α : Type u) := (append : α → α → α) class has_andthen (α : Type u) (β : Type v) (σ : out_param $ Type w) := (andthen : α → β → σ) class has_union (α : Type u) := (union : α → α → α) class has_inter (α : Type u) := (inter : α → α → α) class has_sdiff (α : Type u) := (sdiff : α → α → α) class has_equiv (α : Sort u) := (equiv : α → α → Prop) class has_subset (α : Type u) := (subset : α → α → Prop) class has_ssubset (α : Type u) := (ssubset : α → α → Prop) /- Type classes has_emptyc and has_insert are used to implement polymorphic notation for collections. Example: {a, b, c}. -/ class has_emptyc (α : Type u) := (emptyc : α) class has_insert (α : out_param $ Type u) (γ : Type v) := (insert : α → γ → γ) /- Type class used to implement the notation { a ∈ c | p a } -/ class has_sep (α : out_param $ Type u) (γ : Type v) := (sep : (α → Prop) → γ → γ) /- Type class for set-like membership -/ class has_mem (α : out_param $ Type u) (γ : Type v) := (mem : α → γ → Prop) class has_pow (α : Type u) (β : Type v) := (pow : α → β → α) export has_andthen (andthen) export has_pow (pow) infix ∈ := has_mem.mem notation a ∉ s := ¬ has_mem.mem a s infix + := has_add.add infix * := has_mul.mul infix - := has_sub.sub infix / := has_div.div infix ∣ := has_dvd.dvd infix % := has_mod.mod prefix - := has_neg.neg infix <= := has_le.le infix ≤ := has_le.le infix < := has_lt.lt infix ++ := has_append.append infix ; := andthen notation `∅` := has_emptyc.emptyc _ infix ∪ := has_union.union infix ∩ := has_inter.inter infix ⊆ := has_subset.subset infix ⊂ := has_ssubset.ssubset infix \ := has_sdiff.sdiff infix ≈ := has_equiv.equiv infixr ^ := has_pow.pow export has_append (append) @[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := has_le.le b a @[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := has_lt.lt b a infix >= := ge infix ≥ := ge infix > := gt @[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := has_subset.subset b a @[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := has_ssubset.ssubset b a infix ⊇ := superset infix ⊃ := ssuperset def bit0 {α : Type u} [s : has_add α] (a : α) : α := a + a def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := (bit0 a) + 1 attribute [pattern] has_zero.zero has_one.one bit0 bit1 has_add.add has_neg.neg def insert {α : Type u} {γ : Type v} [has_insert α γ] : α → γ → γ := has_insert.insert /-- The singleton collection -/ def singleton {α : Type u} {γ : Type v} [has_emptyc γ] [has_insert α γ] (a : α) : γ := has_insert.insert a ∅ /- nat basic instances -/ namespace nat protected def add : nat → nat → nat | a zero := a | a (succ b) := succ (add a b) /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation compiler. -/ attribute [pattern] nat.add nat.add._main end nat instance : has_zero nat := ⟨nat.zero⟩ instance : has_one nat := ⟨nat.succ (nat.zero)⟩ instance : has_add nat := ⟨nat.add⟩ def std.priority.default : nat := 1000 def std.priority.max : nat := 0xFFFFFFFF namespace nat protected def prio := std.priority.default + 100 end nat /- 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. -/ def std.prec.max : nat := 1024 -- the strength of application, identifiers, (, [, etc. def std.prec.arrow : nat := 25 /- The next def is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ def std.prec.max_plus : nat := std.prec.max + 10 reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv postfix ⁻¹ := has_inv.inv notation α × β := prod α β -- notation for n-ary tuples /- sizeof -/ class has_sizeof (α : Sort u) := (sizeof : α → nat) def sizeof {α : Sort u} [s : has_sizeof α] : α → nat := has_sizeof.sizeof /- Declare sizeof instances and lemmas for types declared before has_sizeof. From now on, the inductive compiler will automatically generate sizeof instances and lemmas. -/ /- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/ protected def default.sizeof (α : Sort u) : α → nat | a := 0 instance default_has_sizeof (α : Sort u) : has_sizeof α := ⟨default.sizeof α⟩ protected def nat.sizeof : nat → nat | n := n instance : has_sizeof nat := ⟨nat.sizeof⟩ protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) := ⟨prod.sizeof⟩ protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat | (sum.inl a) := 1 + sizeof a | (sum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) := ⟨sum.sizeof⟩ protected def psum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (psum α β) → nat | (psum.inl a) := 1 + sizeof a | (psum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) := ⟨psum.sizeof⟩ protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) := ⟨sigma.sizeof⟩ protected def psigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : psigma β → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (psigma β) := ⟨psigma.sizeof⟩ protected def punit.sizeof : punit → nat | u := 1 instance : has_sizeof punit := ⟨punit.sizeof⟩ protected def bool.sizeof : bool → nat | b := 1 instance : has_sizeof bool := ⟨bool.sizeof⟩ protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat | none := 1 | (some a) := 1 + sizeof a instance (α : Type u) [has_sizeof α] : has_sizeof (option α) := ⟨option.sizeof⟩ protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat | list.nil := 1 | (list.cons a l) := 1 + sizeof a + list.sizeof l instance (α : Type u) [has_sizeof α] : has_sizeof (list α) := ⟨list.sizeof⟩ protected def subtype.sizeof {α : Type u} [has_sizeof α] {p : α → Prop} : subtype p → nat | ⟨a, _⟩ := sizeof a instance {α : Type u} [has_sizeof α] (p : α → Prop) : has_sizeof (subtype p) := ⟨subtype.sizeof⟩ lemma nat_add_zero (n : nat) : n + 0 = n := rfl /- Combinator calculus -/ namespace combinator universes u₁ u₂ u₃ def I {α : Type u₁} (a : α) := a def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z) end combinator /-- Auxiliary datatype for #[ ... ] notation. #[1, 2, 3, 4] is notation for bin_tree.node (bin_tree.node (bin_tree.leaf 1) (bin_tree.leaf 2)) (bin_tree.node (bin_tree.leaf 3) (bin_tree.leaf 4)) We use this notation to input long sequences without exhausting the system stack space. Later, we define a coercion from `bin_tree` into `list`. -/ inductive bin_tree (α : Type u) | empty {} : bin_tree | leaf (val : α) : bin_tree | node (left right : bin_tree) : bin_tree attribute [elab_simple] bin_tree.node bin_tree.leaf /- Basic unification hints -/ @[unify] def add_succ_defeq_succ_add_hint (x y z : nat) : unification_hint := { pattern := x + nat.succ y ≟ nat.succ z, constraints := [z ≟ x + y] } /-- Like `by apply_instance`, but not dependent on the tactic framework. -/ @[reducible] def infer_instance {α : Type u} [i : α] : α := i
b071266e9fb5080aea27780a2222bc0cd1a6a43f
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/introduction/unnamed_200.lean
ce119efea13066c2b3504c6191b2c0c805c4d124
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
336
lean
import data.nat.parity tactic open nat example : ∀ m n : nat, even n → even (m * n) := begin -- say m and n are natural numbers, and assume n=2*k rintros m n ⟨k, hk⟩, -- We need to prove m*n is twice a natural. Let's show it's twice m*k. use m * k, -- substitute in for n rw hk, -- and now it's obvious ring end
3a9b09b208ba9e63f25ae9d970b74297a5d38fb4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/linear_algebra/linear_independent.lean
e6a10f117a5d0bbd52e8393b9fc42a24dcfdaeac
[ "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
41,543
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp, Anne Baanen -/ import linear_algebra.finsupp import order.zorn import data.finset.order import data.equiv.fin /-! # Linear independence This file defines linear independence in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define `linear_independent R v` as `ker (finsupp.total ι M R v) = ⊥`. Here `finsupp.total` is the linear map sending a function `f : ι →₀ R` with finite support to the linear combination of vectors from `v` with these coefficients. Then we prove that several other statements are equivalent to this one, including injectivity of `finsupp.total ι M R v` and some versions with explicitly written linear combinations. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. ## Main statements We prove several specialized tests for linear independence of families of vectors and of sets of vectors. * `fintype.linear_independent_iff`: if `ι` is a finite type, then any function `f : ι → R` has finite support, so we can reformulate the statement using `∑ i : ι, f i • v i` instead of a sum over an auxiliary `s : finset ι`; * `linear_independent_empty_type`: a family indexed by an empty type is linearly independent; * `linear_independent_unique_iff`: if `ι` is a singleton, then `linear_independent K v` is equivalent to `v (default ι) ≠ 0`; * linear_independent_option`, `linear_independent_sum`, `linear_independent_fin_cons`, `linear_independent_fin_succ`: type-specific tests for linear independence of families of vector fields; * `linear_independent_insert`, `linear_independent_union`, `linear_independent_pair`, `linear_independent_singleton`: linear independence tests for set operations. In many cases we additionally provide dot-style operations (e.g., `linear_independent.union`) to make the linear independence tests usable as `hv.insert ha` etc. We also prove that any family of vectors includes a linear independent subfamily spanning the same submodule. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence -/ noncomputable theory open function set submodule open_locale classical big_operators universe u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} variables (R) (v) /-- `linear_independent R v` states the family of vectors `v` is linearly independent over `R`. -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff_injective_total : linear_independent R v ↔ function.injective (finsupp.total ι M R v) := linear_independent_iff.trans (finsupp.total ι M R v).to_add_monoid_hom.injective_iff.symm alias linear_independent_iff_injective_total ↔ linear_independent.injective_total _ theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, (∑ i in s, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, not_forall], end theorem fintype.linear_independent_iff [fintype ι] : linear_independent R v ↔ ∀ g : ι → R, ∑ i, g i • v i = 0 → ∀ i, g i = 0 := begin refine ⟨λ H g, by simpa using linear_independent_iff'.1 H finset.univ g, λ H, linear_independent_iff''.2 $ λ s g hg hs i, H _ _ _⟩, rw ← hs, refine (finset.sum_subset (finset.subset_univ _) (λ i _ hi, _)).symm, rw [hg i hi, zero_smul] end lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (h ⟨i⟩) end lemma linear_independent.ne_zero [nontrivial R] {i : ι} (hv : linear_independent R v) : v i ≠ 0 := λ h, @zero_ne_one R _ _ $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end /-- A subfamily of a linearly independent family (i.e., a composition with an injective map) is a linearly independent family. -/ lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext x, convert h_map_domain x, rw [finsupp.map_domain_apply hf] end /-- If `v` is a linearly independent family of vectors and the kernel of a linear map `f` is disjoint with the sumodule spaned by the vectors of `v`, then `f ∘ v` is a linearly independent family of vectors. See also `linear_independent.map'` for a special case assuming `ker f = ⊥`. -/ lemma linear_independent.map (hv : linear_independent R v) {f : M →ₗ[R] M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv ⊢, rw [hv, le_bot_iff] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [finsupp.total_comp, @finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, linear_map.ker_comp, hf_inj], exact λ _, rfl, end /-- An injective linear map sends linearly independent families of vectors to linearly independent families of vectors. See also `linear_independent.map` for a more general statement. -/ lemma linear_independent.map' (hv : linear_independent R v) (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) := hv.map $ by simp [hf_inj] /-- If the image of a family of vectors under a linear map is linearly independent, then so is the original family. -/ lemma linear_independent.of_comp (f : M →ₗ[R] M') (hfv : linear_independent R (f ∘ v)) : linear_independent R v := linear_independent_iff'.2 $ λ s g hg i his, have ∑ (i : ι) in s, g i • f (v i) = 0, by simp_rw [← f.map_smul, ← f.map_sum, hg, f.map_zero], linear_independent_iff'.1 hfv s g this i his /-- If `f` is an injective linear map, then the family `f ∘ v` is linearly independent if and only if the family `v` is linearly independent. -/ protected lemma linear_map.linear_independent_iff (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) ↔ linear_independent R v := ⟨λ h, h.of_comp f, λ h, h.map $ by simp only [hf_inj, disjoint_bot_right]⟩ @[nontriviality] lemma linear_independent_of_subsingleton [subsingleton R] : linear_independent R v := linear_independent_iff.2 (λ l hl, subsingleton.elim _ _) lemma linear_independent.injective [nontrivial R] (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [hij] }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, simpa [finsupp.single_eq_single_iff] using h_single_eq end theorem linear_independent_equiv (e : ι ≃ ι') {f : ι' → M} : linear_independent R (f ∘ e) ↔ linear_independent R f := ⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, λ h, h.comp _ e.injective⟩ theorem linear_independent_equiv' (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ e = g) : linear_independent R g ↔ linear_independent R f := h ▸ linear_independent_equiv e theorem linear_independent_subtype_range {ι} {f : ι → M} (hf : injective f) : linear_independent R (coe : range f → M) ↔ linear_independent R f := iff.symm $ linear_independent_equiv' (equiv.set.range f hf) rfl alias linear_independent_subtype_range ↔ linear_independent.of_subtype_range _ theorem linear_independent.to_subtype_range {ι} {f : ι → M} (hf : linear_independent R f) : linear_independent R (coe : range f → M) := begin nontriviality R, exact (linear_independent_subtype_range hf.injective).2 hf end theorem linear_independent.to_subtype_range' {ι} {f : ι → M} (hf : linear_independent R f) {t} (ht : range f = t) : linear_independent R (coe : t → M) := ht ▸ hf.to_subtype_range theorem linear_independent_image {ι} {s : set ι} {f : ι → M} (hf : set.inj_on f s) : linear_independent R (λ x : s, f x) ↔ linear_independent R (λ x : f '' s, (x : M)) := linear_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl theorem linear_independent.image {ι} {s : set ι} {f : ι → M} (hs : linear_independent R (λ x : s, f x)) : linear_independent R (λ x : f '' s, (x : M)) := (linear_independent_equiv' (equiv.set.of_eq $ by rw [range_comp, subtype.range_coe]) rfl).1 hs.to_subtype_range lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := linear_independent.of_comp (span R (range v)).subtype hs section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin simp only [linear_independent_iff, (∘), finsupp.mem_supported, finsupp.total_apply, set.subset_def, finset.mem_coe], split, { intros h l hl₁ hl₂, have := h (l.subtype_domain s) ((finsupp.sum_subtype_domain_index hl₁).trans hl₂), exact (finsupp.subtype_domain_eq_zero_iff hl₁).1 this }, { intros h l hl, refine finsupp.emb_domain_eq_zero.1 (h (l.emb_domain $ function.embedding.subtype s) _ _), { suffices : ∀ i hi, ¬l ⟨i, hi⟩ = 0 → i ∈ s, by simpa, intros, assumption }, { rwa [finsupp.emb_domain_eq_map_domain, finsupp.sum_map_domain_index], exacts [λ _, zero_smul _ _, λ _ _ _, add_smul _ _ _] } } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := hs variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent.disjoint_span_image (hv : linear_independent R v) {s t : set ι} (hs : disjoint s t) : disjoint (submodule.span R $ v '' s) (submodule.span R $ v '' t) := begin simp only [disjoint_def, finsupp.mem_span_iff_total], rintros _ ⟨l₁, hl₁, rfl⟩ ⟨l₂, hl₂, H⟩, rw [hv.injective_total.eq_iff] at H, subst l₂, have : l₁ = 0 := finsupp.disjoint_supported_supported hs (submodule.mem_inf.2 ⟨hl₁, hl₂⟩), simp [this] end lemma linear_independent_sum {v : ι ⊕ ι' → M} : linear_independent R v ↔ linear_independent R (v ∘ sum.inl) ∧ linear_independent R (v ∘ sum.inr) ∧ disjoint (submodule.span R (range (v ∘ sum.inl))) (submodule.span R (range (v ∘ sum.inr))) := begin rw [range_comp v, range_comp v], refine ⟨λ h, ⟨h.comp _ sum.injective_inl, h.comp _ sum.injective_inr, h.disjoint_span_image is_compl_range_inl_range_inr.1⟩, _⟩, rintro ⟨hl, hr, hlr⟩, rw [linear_independent_iff'] at *, intros s g hg i hi, have : ∑ i in s.preimage sum.inl (sum.injective_inl.inj_on _), (λ x, g x • v x) (sum.inl i) + ∑ i in s.preimage sum.inr (sum.injective_inr.inj_on _), (λ x, g x • v x) (sum.inr i) = 0, { rw [finset.sum_preimage', finset.sum_preimage', ← finset.sum_union, ← finset.filter_or], { simpa only [← mem_union, range_inl_union_range_inr, mem_univ, finset.filter_true] }, { exact finset.disjoint_filter.2 (λ x hx, disjoint_left.1 is_compl_range_inl_range_inr.1) } }, { rw ← eq_neg_iff_add_eq_zero at this, rw [disjoint_def'] at hlr, have A := hlr _ (sum_mem _ $ λ i hi, _) _ (neg_mem _ $ sum_mem _ $ λ i hi, _) this, { cases i with i i, { exact hl _ _ A i (finset.mem_preimage.2 hi) }, { rw [this, neg_eq_zero] at A, exact hr _ _ A i (finset.mem_preimage.2 hi) } }, { exact smul_mem _ _ (subset_span ⟨sum.inl i, mem_range_self _, rfl⟩) }, { exact smul_mem _ _ (subset_span ⟨sum.inr i, mem_range_self _, rfl⟩) } } end lemma linear_independent.sum_type {v' : ι' → M} (hv : linear_independent R v) (hv' : linear_independent R v') (h : disjoint (submodule.span R (range v)) (submodule.span R (range v'))) : linear_independent R (sum.elim v v') := linear_independent_sum.2 ⟨hv, hv', h⟩ lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := (hs.sum_type ht $ by simpa).to_subtype_range' $ by simp lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { resetI, refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros i s his ih, rw [finset.sup_insert], refine (hl _).union ih _, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros i, exact ⟨i, le_refl _⟩ }, { exact s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin nontriviality R, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) : surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype [nontrivial R] {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [← @subtype.range_coe _ s] at hf_inj, refine (hs.map hf_inj).to_subtype_range' _, simp [set.range_comp f] end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := (hv.map' (inl R M M') ker_inl).sum_type (hv'.map' (inr R M M') ker_inr) $ begin refine is_compl_range_inl_inr.disjoint.mono _ _; simp only [span_le, range_coe, range_comp_subset_range], end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : finset.sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [finset.sum_apply, finset.sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span hl hsu htu, span_mono⟩ end module section vector_space variables [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] variables {v : ι → V} {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique_iff [unique ι] : linear_independent K v ↔ v (default ι) ≠ 0 := begin simp only [linear_independent_iff, finsupp.total_unique, smul_eq_zero], refine ⟨λ h hv, _, λ hv l hl, finsupp.unique_ext $ hl.resolve_right hv⟩, have := h (finsupp.single (default ι) 1) (or.inr hv), exact one_ne_zero (finsupp.single_eq_zero.1 this) end alias linear_independent_unique_iff ↔ _ linear_independent_unique lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := @linear_independent_unique _ _ _ _ _ _ _ (set.unique_singleton _) ‹_› lemma linear_independent_option' : linear_independent K (λ o, option.cases_on' o x v : option ι → V) ↔ linear_independent K v ∧ (x ∉ submodule.span K (range v)) := begin rw [← linear_independent_equiv (equiv.option_equiv_sum_punit ι).symm, linear_independent_sum, @range_unique _ punit, @linear_independent_unique_iff punit, disjoint_span_singleton], dsimp [(∘)], refine ⟨λ h, ⟨h.1, λ hx, h.2.1 $ h.2.2 hx⟩, λ h, ⟨h.1, _, λ hx, (h.2 hx).elim⟩⟩, rintro rfl, exact h.2 (zero_mem _) end lemma linear_independent.option (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (λ o, option.cases_on' o x v : option ι → V) := linear_independent_option'.2 ⟨hv, hx⟩ lemma linear_independent_option {v : option ι → V} : linear_independent K v ↔ linear_independent K (v ∘ coe : ι → V) ∧ v none ∉ submodule.span K (range (v ∘ coe : ι → V)) := by simp only [← linear_independent_option', option.cases_on'_none_coe] lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton' x0] end theorem linear_independent_insert' {ι} {s : set ι} {a : ι} {f : ι → V} (has : a ∉ s) : linear_independent K (λ x : insert a s, f x) ↔ linear_independent K (λ x : s, f x) ∧ f a ∉ submodule.span K (f '' s) := by { rw [← linear_independent_equiv ((equiv.option_equiv_sum_punit _).trans (equiv.set.insert has).symm), linear_independent_option], simp [(∘), range_comp f] } theorem linear_independent_insert (hxs : x ∉ s) : linear_independent K (λ b : insert x s, (b : V)) ↔ linear_independent K (λ b : s, (b : V)) ∧ x ∉ submodule.span K s := (@linear_independent_insert' _ _ _ _ _ _ _ _ id hxs).trans $ by simp lemma linear_independent_pair {x y : V} (hx : x ≠ 0) (hy : ∀ a : K, a • x ≠ y) : linear_independent K (coe : ({x, y} : set V) → V) := pair_comm y x ▸ (linear_independent_singleton hx).insert $ mt mem_span_singleton.1 (not_exists.2 hy) lemma linear_independent_fin_cons {n} {v : fin n → V} : linear_independent K (fin.cons x v : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := begin rw [← linear_independent_equiv (fin_succ_equiv n).symm, linear_independent_option], simp [(∘), fin_succ_equiv, option.coe_def, fin.cons_succ, *] end lemma linear_independent.fin_cons {n} {v : fin n → V} (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (fin.cons x v : fin (n + 1) → V) := linear_independent_fin_cons.2 ⟨hv, hx⟩ lemma linear_independent_fin_succ {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.tail v) ∧ v 0 ∉ submodule.span K (range $ fin.tail v) := by rw [← linear_independent_fin_cons, fin.cons_self_tail] lemma linear_independent_fin2 {f : fin 2 → V} : linear_independent K f ↔ f 1 ≠ 0 ∧ ∀ a : K, a • f 1 ≠ f 0 := by rw [linear_independent_fin_succ, linear_independent_unique_iff, range_unique, mem_span_singleton, not_exists]; refl lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ end vector_space
d2c73190e3a367c1daa2a8ca8234e90f105c6271
57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5
/algebra/ring.lean
8bf4fec5129c1a76b7f776d6653af12b274eb8f5
[ "Apache-2.0" ]
permissive
louisanu/mathlib
11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe
2bd5e2159d20a8f20d04fc4d382e65eea775ed39
refs/heads/master
1,617,706,993,439
1,523,163,654,000
1,523,163,654,000
124,519,997
0
0
Apache-2.0
1,520,588,283,000
1,520,588,283,000
null
UTF-8
Lean
false
false
5,406
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn -/ import algebra.group tactic data.set.basic universes u v variable {α : Type u} section variable [semiring α] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm end section variables [ring α] (a b c d e : α) lemma mul_neg_one (a : α) : a * -1 = -a := by simp lemma neg_one_mul (a : α) : -1 * a = -a := by simp theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h, begin simp [h.symm] end) ... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg α, @right_distrib α] end theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg α, @right_distrib α] end ... = d : begin rewrite h, simp [@add_sub_cancel α] end theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : α} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, { intro ha, apply h, simp [ha] }, { intro hb, apply h, simp [hb] } end end section comm_ring variable [comm_ring α] @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ end comm_ring def nonunits (α : Type u) [comm_ring α] : set α := { x | ¬∃ y, y * x = 1 } class is_ring_hom {α : Type u} {β : Type v} [comm_ring α] [comm_ring β] (f : α → β) : Prop := (map_add : ∀ {x y}, f (x + y) = f x + f y) (map_mul : ∀ {x y}, f (x * y) = f x * f y) (map_one : f 1 = 1) namespace is_ring_hom variables {β : Type v} [comm_ring α] [comm_ring β] variables (f : α → β) [is_ring_hom f] {x y : α} lemma map_zero : f 0 = 0 := calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp ... = 0 : by simp lemma map_neg : f (-x) = -f x := calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp ... = -f x : by simp [map_zero f] lemma map_sub : f (x - y) = f x - f y := by simp [map_add f, map_neg f] end is_ring_hom set_option old_structure_cmd true /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ class domain (α : Type u) extends ring α, no_zero_divisors α, zero_ne_one_class α section domain variable [domain α] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂ theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁); rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂] theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁); rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂] theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h) end domain /- integral domains -/ section variables [s : integral_domain α] (a b c d e : α) include s instance integral_domain.to_domain : domain α := {..s} theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rewrite [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rewrite [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this theorem mul_dvd_mul_iff_left {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, domain.mul_left_inj ha] theorem mul_dvd_mul_iff_right {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, domain.mul_right_inj hc] end
98e41fa0b60ee06f0105b75e742f4ecf2b0bf8e2
ce89339993655da64b6ccb555c837ce6c10f9ef4
/na4zagin3/top-10.lean
8bac50e668d3ae1b23eab550dc2df587579a1880
[]
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
2,212
lean
-- LEAN (* definition prefix_sum : ℕ → list ℕ → list ℕ | sum [] := [sum] | sum (head :: tail) := sum :: (prefix_sum (sum + head) tail). definition plus_list : list ℕ → list ℕ → list ℕ | [] _ := [] | _ [] := [] | (h1 :: t1) (h2 :: t2) := (h1 + h2) :: plus_list t1 t2. example : ∀ l1 l2 : list ℕ, prefix_sum 0 (plus_list l1 l2) = plus_list (prefix_sum 0 l1) (prefix_sum 0 l2) := begin have plus_list_nil_l : ∀ l : list ℕ, plus_list [] l = [] := begin intros l, cases l, unfold plus_list, unfold plus_list, end, have plus_list_nil_r : ∀ l : list ℕ, plus_list l [] = [] := begin intros l, cases l, unfold plus_list, unfold plus_list, end, have generic_lemma : ∀ l1 l2 : list ℕ, ∀ n m, prefix_sum (n + m) (plus_list l1 l2) = plus_list (prefix_sum n l1) (prefix_sum m l2) := begin intros l1, induction l1; intros l2, unfold prefix_sum, rewrite plus_list_nil_l, unfold prefix_sum, cases l2; intros n m, unfold prefix_sum, by unfold plus_list, unfold prefix_sum, unfold plus_list, by rewrite plus_list_nil_l, intros n m, unfold prefix_sum, cases l2, unfold prefix_sum, unfold plus_list, unfold prefix_sum, by rewrite plus_list_nil_r, unfold plus_list, unfold prefix_sum, unfold plus_list, simp, rw [←l1_ih l2_tl (l1_hd + n) (m + l2_hd)], by rw [add_assoc], end, intros l1 l2, by rewrite [←generic_lemma], end. /- Coq *) unfold task. assert (plus_list_nil_r : forall l, plus_list l nil = nil). { intro l; case l; reflexivity. } assert (generic : forall l1 l2, forall n m, prefix_sum (n + m) (plus_list l1 l2) = plus_list (prefix_sum n l1) (prefix_sum m l2)). { intro l1. induction l1. intro l2. induction l2; intros n m; reflexivity. intro l2. case l2. intros n m. simpl. rewrite plus_list_nil_r. reflexivity. intros x l2' n m. simpl. rewrite <- IHl1. rewrite PeanoNat.Nat.add_shuffle1. reflexivity. } intros l1 l2. rewrite <- generic. reflexivity. (* -/ -- *)
46782fced1835e886e106fa6c0909e5729b1910b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/change1.lean
db2d87a9d448e5713be8c7603c72cbf1310ec751
[ "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
542
lean
open tactic nat expr option attribute [simp] lemma succ_eq_add (n : nat) : succ n = n + 1 := rfl example (a b : nat) : a = b → succ (succ a) = succ (b + 1) := by do intro `Heq, trace_state, s ← simp_lemmas.mk_default, t' ← target >>= s^.dsimplify, change t', trace "---- after change ----", trace_state, get_local `a >>= subst, t ← target, match (is_eq t) with | (some (lhs, rhs)) := do pr ← mk_app `eq.refl [lhs], exact pr | none := failed end
f5d26c3df9dcdfcae027bd6f5780a6ce3834a8da
90edd5cdcf93124fe15627f7304069fdce3442dd
/src/Lean/Aesop/Tracing.lean
31e19940633b133556fc550348152e064e2d01c3
[ "Apache-2.0" ]
permissive
JLimperg/lean4-aesop
8a9d9cd3ee484a8e67fda2dd9822d76708098712
5c4b9a3e05c32f69a4357c3047c274f4b94f9c71
refs/heads/master
1,689,415,944,104
1,627,383,284,000
1,627,383,284,000
377,536,770
0
0
null
null
null
null
UTF-8
Lean
false
false
2,173
lean
/- Copyright (c) 2021 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ -- TODO Instead of tracing, I think we want to construct a couple of big -- messages at the end: one with the ruleset, one with the final search tree, -- one with the steps taken (displayed in a nice structured manner and hopefully -- inspectable). import Lean.Util.Trace open Lean builtin_initialize registerTraceClass `Aesop.RuleSet registerTraceClass `Aesop.Steps registerTraceClass `Aesop.Steps.Goals registerTraceClass `Aesop.Steps.UnsafeQueues registerTraceClass `Aesop.Steps.FailedRuleApplications registerTraceClass `Aesop.Steps.RuleSelection registerTraceClass `Aesop.Steps.FinalProof registerTraceClass `Aesop.Steps.Normalization registerTraceClass `Aesop.Tree registerTraceClass `Aesop.Tree.Goals registerTraceClass `Aesop.Tree.UnsafeQueues registerTraceClass `Aesop.Tree.FailedRuleApplications namespace Lean.Aesop inductive TraceContext | steps | tree namespace TraceContext @[inlineIfReduce] protected def toTraceOptionPrefix : TraceContext → Name | steps => `trace.Aesop.Steps | tree => `trace.Aesop.Tree end TraceContext inductive TraceOption : TraceContext → Type | showGoals : TraceOption c | showUnsafeQueues : TraceOption c | showFailedRapps : TraceOption c | showRuleSelection : TraceOption TraceContext.steps | showFinalProof : TraceOption TraceContext.steps | showNormalizationSteps : TraceOption TraceContext.steps namespace TraceOption @[inlineIfReduce] protected def toTraceOptionSuffix {c} : TraceOption c → Name | showGoals => `Goals | showUnsafeQueues => `UnsafeQueues | showFailedRapps => `FailedRuleApplications | showRuleSelection => `RuleSelection | showFinalProof => `FinalProof | showNormalizationSteps => `Normalization @[inline] protected def default {c} : TraceOption c → Bool := λ _ => true @[inline] def get [Monad m] [MonadOptions m] (c : TraceContext) (o : TraceOption c) : m Bool := getBoolOption (c.toTraceOptionPrefix ++ o.toTraceOptionSuffix) o.default end TraceOption end Lean.Aesop
063d0df51efc5d9e57f071f87b54cbd1bc271a2c
26ac254ecb57ffcb886ff709cf018390161a9225
/src/linear_algebra/basis.lean
5bede4294c0acfa11d3ac7174524733f5c538d09
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
55,051
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp -/ import linear_algebra.finsupp import linear_algebra.projection import order.zorn import data.fintype.card /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function set submodule open_locale classical big_operators universe u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] variables [module R M] [module R M'] variables {a b : R} {x y : M} variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, s.sum (λ i, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, classical.not_forall], end lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma linear_independent.ne_zero {i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on coe (coe ⁻¹' ↑l.support : set s) ↑l.support, { apply bij_on.mk, { apply maps_to_preimage }, { apply subtype.coe_injective.inj_on }, intros i hi, rw [image_preimage_eq_inter_range, subtype.range_coe], exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (coe : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], exact subtype.coe_injective, rw subtype.range_coe, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨coe, subtype.coe_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' ↑l.support) ↑l.support, { apply bij_on.mk, { apply maps_to_preimage }, { apply (linear_independent.injective zero_eq_one hv).inj_on }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l h_bij, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage_of_bij v l.support h_bij (λ (x : M), l x • x)], rwa [finsupp.total_apply, finsupp.sum] at hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.map_domain_injective hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := begin have h_restrict : restrict v s = v ∘ coe := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain coe = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R coe l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.coe_image_subset _ _ this }, apply @finsupp.map_domain_injective _ (subtype s) ι, { apply subtype.coe_injective }, { simpa }, end variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], refine (hl _).union ih _, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' ↑s), exact s.finite_to_set.preimage (assume i j _ _, plift.up.inj) } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero zero_eq_one h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)): surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1) (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact prod.inl_injective.comp inj_v }, { exact prod.inr_injective.comp inj_v' }, { intros, simp [hv.ne_zero zero_eq_one] } }, { rw sum.elim_range, refine (hv.image _).to_subtype_range.union (hv'.image _).to_subtype_range _; [simp, simp, skip], apply disjoint_inl_inr.mono _ _; simp only [set.range_comp, span_image, linear_map.map_le_range] } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : pi.finset_sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [pi.finset_sum_apply, pi.finset_sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h lemma is_basis.range (hv : is_basis R v) : is_basis R (λ x, x : range v → M) := ⟨hv.1.to_subtype_range, by { convert hv.2, ext i, exact ⟨λ ⟨p, hp⟩, hp ▸ p.2, λ hi, ⟨⟨i, hi⟩, rfl⟩⟩ }⟩ /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ left_inverse.injective hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end @[simp] lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ λ b, by simp lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ λ b, by simp lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm @[simp] theorem module_equiv_finsupp_apply_basis (hv : is_basis R v) (i : ι) : module_equiv_finsupp hv (v i) = finsupp.single i 1 := (linear_equiv.symm_apply_eq _).2 $ by simp [linear_independent.total_equiv] /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the indexing sets of the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') (e : ι ≃ ι') : M ≃ₗ[R] M' := { inv_fun := hv'.constr (v ∘ e.symm), left_inv := have (hv'.constr (v ∘ e.symm)).comp (hv.constr (v' ∘ e)) = linear_map.id, from hv.ext $ by simp, λ x, congr_arg (λ h : M →ₗ[R] M, h x) this, right_inv := have (hv.constr (v' ∘ e)).comp (hv'.constr (v ∘ e.symm)) = linear_map.id, from hv'.ext $ by simp, λ y, congr_arg (λ h : M' →ₗ[R] M', h y) this, ..hv.constr (v' ∘ e) } /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def equiv_of_is_basis' {v : ι → M} {v' : ι' → M'} (f : M → M') (g : M' → M) (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp only [mem_span_singleton, range_const, mul_one, exists_eq, smul_eq_mul] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.ext_iff, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext_iff_val.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def equiv_fun_basis : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, map_add' := λ x y, by ext; exact finsupp.add_apply, map_smul' := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ (equiv_fun_basis h).to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma equiv_fun_basis_symm_apply (x : ι → R) : (equiv_fun_basis h).symm x = ∑ i, x i • v i := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = ∑ i, x i • v i, dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0, { simp [H] }, { simp [H], refl } end end module section vector_space variables {v : ι → V} [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (coe : b → V) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ lemma exists_sum_is_basis (hs : linear_independent K v) : ∃ (ι' : Type u) (v' : ι' → V), is_basis K (sum.elim v v') := begin -- This is a hack: we jump through hoops to reuse `exists_subset_is_basis`. let s := set.range v, let e : ι ≃ s := equiv.set.range v (hs.injective zero_ne_one), have : (λ x, x : s → V) = v ∘ e.symm := by { funext, dsimp, rw [equiv.set.apply_range_symm v], }, have : linear_independent K (λ x, x : s → V), { rw this, exact linear_independent.comp hs _ (e.symm.injective), }, obtain ⟨b, ss, is⟩ := exists_subset_is_basis this, let e' : ι ⊕ (b \ s : set V) ≃ b := calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : equiv.set.sum_diff_subset ss, refine ⟨(b \ s : set V), λ x, x.1, _⟩, convert is_basis.comp is e' _, { funext x, cases x; simp; refl, }, { exact e'.bijective, }, end variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i, i : b → V) := let ⟨b, _, hb⟩ := exists_subset_is_basis (linear_independent_empty K V : _) in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype zero_ne_one hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), rwa subtype.range_coe at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hB.ext (λ b, _), rw image_subset_iff at BC, have : f b = (⟨f b, BC b.2⟩ : C) := rfl, dsimp, rw [this, constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hC.ext (λ c, _), simp [constr_basis hC, right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) open fintype variables (K) (V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := exists.elim (exists_is_basis K V) $ λ b hb, ⟨card b, module.card_fintype hb⟩ end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variable [fintype η] lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R η) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), unit), (std_basis R (λ (i : η), R) (ji.fst)) 1) := @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _) lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply (is_basis_fun₀ R η).comp (λ i, ⟨i, punit.star⟩), apply bijective_iff_has_inverse.2, use sigma.fst, simp [function.left_inverse, function.right_inverse] end end end module end pi
badd9615e6903e50d21c1128f62c41cd0971aac2
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/category_theory/discrete_category.lean
151bd774a5e0530b800b4678bb59e0eb3bb624a0
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
3,191
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Floris van Doorn -/ import data.ulift import data.fintype import category_theory.opposites category_theory.equivalence namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation def discrete (α : Type u₁) := α instance discrete_category (α : Type u₁) : small_category (discrete α) := { hom := λ X Y, ulift (plift (X = Y)), id := λ X, ulift.up (plift.up rfl), comp := λ X Y Z g f, by { rcases f with ⟨⟨rfl⟩⟩, exact g } } namespace discrete variables {α : Type u₁} instance [inhabited α] : inhabited (discrete α) := by unfold discrete; apply_instance instance [fintype α] : fintype (discrete α) := by { dsimp [discrete], apply_instance } instance fintype_fun [decidable_eq α] (X Y : discrete α) : fintype (X ⟶ Y) := by { apply ulift.fintype } @[simp] lemma id_def (X : discrete α) : ulift.up (plift.up (eq.refl X)) = 𝟙 X := rfl end discrete variables {C : Type u₂} [𝒞 : category.{v₂} C] include 𝒞 namespace functor def of_function {I : Type u₁} (F : I → C) : (discrete I) ⥤ C := { obj := F, map := λ X Y f, begin cases f, cases f, cases f, exact 𝟙 (F X) end } @[simp] lemma of_function_obj {I : Type u₁} (F : I → C) (i : I) : (of_function F).obj i = F i := rfl lemma of_function_map {I : Type u₁} (F : I → C) {i : discrete I} (f : i ⟶ i) : (of_function F).map f = 𝟙 (F i) := by { cases f, cases f, cases f, refl } end functor namespace nat_trans def of_homs {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) : F ⟶ G := { app := f } @[simp] lemma of_homs_app {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ⟶ G.obj i) (i) : (of_homs f).app i = f i := rfl def of_function {I : Type u₁} {F G : I → C} (f : Π i : I, F i ⟶ G i) : (functor.of_function F) ⟶ (functor.of_function G) := of_homs f @[simp] lemma of_function_app {I : Type u₁} {F G : I → C} (f : Π i : I, F i ⟶ G i) (i : I) : (of_function f).app i = f i := rfl end nat_trans namespace nat_iso def of_isos {I : Type u₁} {F G : discrete I ⥤ C} (f : Π i : discrete I, F.obj i ≅ G.obj i) : F ≅ G := of_components f (by tidy) end nat_iso namespace discrete variables {J : Type v₁} omit 𝒞 def lift {α : Type u₁} {β : Type u₂} (f : α → β) : (discrete α) ⥤ (discrete β) := functor.of_function f open opposite protected def opposite (α : Type u₁) : (discrete α)ᵒᵖ ≌ discrete α := let F : discrete α ⥤ (discrete α)ᵒᵖ := functor.of_function (λ x, op x) in begin refine equivalence.mk (functor.left_op F) F _ (nat_iso.of_isos $ λ X, by simp [F]), refine nat_iso.of_components (λ X, by simp [F]) _, tidy end include 𝒞 @[simp] lemma functor_map_id (F : discrete J ⥤ C) {j : discrete J} (f : j ⟶ j) : F.map f = 𝟙 (F.obj j) := begin have h : f = 𝟙 j, { cases f, cases f, ext, }, rw h, simp, end end discrete end category_theory
4addb62692a853cecba6d62b97bf5ae1206b14e9
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Data/Array/QSort.lean
c7a2c4ae18f67bfc7a0eeafec7eb489a6e11c9df
[ "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
1,657
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Array.Basic namespace Array -- TODO: remove the [Inhabited α] parameters as soon as we have the tactic framework for automating proof generation and using Array.fget -- TODO: remove `partial` using well-founded recursion @[inline] partial def qpartition {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) (lo hi : Nat) : Nat × Array α := let mid := (lo + hi) / 2; let as := if lt (as.get! mid) (as.get! lo) then as.swap! lo mid else as let as := if lt (as.get! hi) (as.get! lo) then as.swap! lo hi else as let as := if lt (as.get! mid) (as.get! hi) then as.swap! mid hi else as let pivot := as.get! hi let rec loop (as : Array α) (i j : Nat) := if j < hi then if lt (as.get! j) pivot then let as := as.swap! i j; loop as (i+1) (j+1) else loop as i (j+1) else let as := as.swap! i hi; (i, as) loop as lo lo @[inline] partial def qsort {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) (low := 0) (high := as.size - 1) : Array α := let rec @[specialize] sort (as : Array α) (low high : Nat) := if low < high then let p := qpartition as lt low high; -- TODO: fix `partial` support in the equation compiler, it breaks if we use `let (mid, as) := partition as lt low high` let mid := p.1; let as := p.2; if mid >= high then as else let as := sort as low mid; sort as (mid+1) high else as sort as low high end Array
a571525991343310186bc02fcab30485a992408a
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world08/level08.lean
5803b8288c26a614893b905fbda15c2c13c74534
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
140
lean
lemma eq_zero_of_add_right_eq_self {a b : mynat} : a + b = a → b = 0 := begin intro h, apply add_left_cancel a, rw add_zero, exact h, end
28c68a08c5bfbc4ca8a1c405340dab412088a927
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/Server/FileWorker/RequestHandling.lean
1a044207f8fc1d569b9926685e442d06b5c14e3a
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,031
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.DeclarationRange import Lean.Data.Json import Lean.Data.Lsp import Lean.Server.FileWorker.Utils import Lean.Server.Requests import Lean.Server.Completion import Lean.Widget.InteractiveGoal namespace Lean.Server.FileWorker open Lsp open RequestM open Snapshots partial def handleCompletion (p : CompletionParams) : RequestM (RequestTask CompletionList) := do let doc ← readDoc 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) : RequestM (RequestTask (Option Hover)) := do let doc ← readDoc 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 inductive GoToKind | declaration | definition | type deriving DecidableEq open Elab GoToKind in partial def handleDefinition (kind : GoToKind) (p : TextDocumentPositionParams) : RequestM (RequestTask (Array LocationLink)) := do let rc ← read let doc ← readDoc let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position let locationLinksFromDecl (i : Elab.Info) (n : Name) := do let mod? ← findModuleOf? n let modUri? ← match mod? with | some modName => let modFname? ← rc.srcSearchPath.findWithExt "lean" modName pure <| modFname?.map toFileUri | none => pure <| some doc.meta.uri let ranges? ← 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? := (·.toLspRange text) <$> i.range? targetUri := modUri targetRange := declRangeToLspRange ranges.range targetSelectionRange := declRangeToLspRange ranges.selectionRange } return #[ll] return #[] let locationLinksFromBinder (t : InfoTree) (i : Elab.Info) (id : FVarId) := do if let some i' := t.findInfo? fun | Info.ofTermInfo { isBinder := true, expr := Expr.fvar id' .., .. } => id' == id | _ => false then if let some r := i'.range? then let r := r.toLspRange text let ll : LocationLink := { originSelectionRange? := (·.toLspRange text) <$> i.range? targetUri := p.textDocument.uri targetRange := r targetSelectionRange := r } return #[ll] return #[] withWaitFindSnap doc (fun s => s.endPos > hoverPos) (notFoundX := pure #[]) fun snap => do for t in snap.cmdState.infoState.trees do if let some (ci, i) := t.hoverableInfoAt? hoverPos then if let Info.ofTermInfo ti := i then let mut expr := ti.expr if kind = type then expr ← ci.runMetaM i.lctx do Expr.getAppFn (← Meta.instantiateMVars (← Meta.inferType expr)) match expr with | Expr.const n .. => return ← ci.runMetaM i.lctx <| locationLinksFromDecl i n | Expr.fvar id .. => return ← ci.runMetaM i.lctx <| locationLinksFromBinder t i id | _ => pure () if let Info.ofFieldInfo fi := i then if kind = type then let expr ← ci.runMetaM i.lctx do Meta.instantiateMVars (← Meta.inferType fi.val) if let some n := expr.getAppFn.constName? then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i n else return ← ci.runMetaM i.lctx <| locationLinksFromDecl i fi.projName -- If other go-tos fail, we try to show the elaborator or parser if let some ei := i.toElabInfo? then if kind = declaration ∧ ci.env.contains ei.stx.getKind then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i ei.stx.getKind if kind = definition ∧ ci.env.contains ei.elaborator then return ← ci.runMetaM i.lctx <| locationLinksFromDecl i ei.elaborator return #[] open RequestM in def getInteractiveGoals (p : Lsp.PlainGoalParams) : RequestM (RequestTask (Option Widget.InteractiveGoals)) := do let doc ← readDoc 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 (Widget.goalToInteractive g)) return some { goals := goals.toArray } return none open Elab in partial def handlePlainGoal (p : PlainGoalParams) : RequestM (RequestTask (Option PlainGoal)) := do let t ← getInteractiveGoals p t.map <| Except.map <| Option.map <| fun ⟨goals⟩ => if goals.isEmpty then { goals := #[], rendered := "no goals" } else let goalStrs := goals.map (toString ·.pretty) let goalBlocks := goalStrs.map fun goal => s!"```lean {goal} ```" let md := String.intercalate "\n---\n" goalBlocks.toList { goals := goalStrs, rendered := md } partial def getInteractiveTermGoal (p : Lsp.PlainTermGoalParams) : RequestM (RequestTask (Option Widget.InteractiveTermGoal)) := do let doc ← readDoc 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, i@(Elab.Info.ofTermInfo ti)) := t.termGoalAt? hoverPos then let ty ← ci.runMetaM i.lctx do Meta.instantiateMVars <| ti.expectedType?.getD (← Meta.inferType ti.expr) -- for binders, hide the last hypothesis (the binder itself) let lctx' := if ti.isBinder then i.lctx.pop else i.lctx let goal ← ci.runMetaM lctx' do Meta.withPPInaccessibleNames <| Widget.goalToInteractive (← Meta.mkFreshExprMVar ty).mvarId! let range := if let some r := i.range? then r.toLspRange text else ⟨p.position, p.position⟩ return some { goal with range } return none def handlePlainTermGoal (p : PlainTermGoalParams) : RequestM (RequestTask (Option PlainTermGoal)) := do let t ← getInteractiveTermGoal p t.map <| Except.map <| Option.map fun goal => { goal := toString goal.toInteractiveGoal.pretty range := goal.range } partial def handleDocumentHighlight (p : DocumentHighlightParams) : RequestM (RequestTask (Array DocumentHighlight)) := do let doc ← readDoc 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) => do if let some range := i.getRange? then if range.contains pos then return some { range := doRange?.getD (range.toLspRange text), kind? := DocumentHighlightKind.text } highlightReturn? doRange? e | `(do%$i $elems) => highlightReturn? (i.getRange?.get!.toLspRange text) 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 #[] section -- TODO https://github.com/leanprover/lean4/issues/529 open Parser.Command partial def handleDocumentSymbol (p : DocumentSymbolParams) : RequestM (RequestTask DocumentSymbolResult) := do let doc ← readDoc asTask do let ⟨cmdSnaps, e?⟩ ← doc.cmdSnaps.updateFinishedPrefix let mut stxs := cmdSnaps.finishedPrefix.map (·.stx) match e? with | some ElabTaskError.aborted => throw RequestError.fileChanged | some (ElabTaskError.ioError e) => throwThe IO.Error e | _ => () let lastSnap := cmdSnaps.finishedPrefix.getLastD doc.headerSnap stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList let (syms, _) := toDocumentSymbols doc.meta.text stxs return { 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) | _ => do let (syms, stxs') := toDocumentSymbols text stxs unless stx.isOfKind ``Lean.Parser.Command.declaration do return (syms, stxs') if let some stxRange := stx.getRange? 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 let some selRange := selection.getRange? then return (DocumentSymbol.mk { name := name kind := SymbolKind.method range := stxRange.toLspRange text selectionRange := selRange.toLspRange text } :: syms, stxs') return (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 := (mkNullNode #[stx, endStx]).getRange?.get!.toLspRange text (DocumentSymbol.mk { name kind range selectionRange := selection.getRange? |>.map (·.toLspRange text) |>.getD range children? := syms.toArray } :: syms', stxs'') end 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) : RequestM (RequestTask SemanticTokens) := do let doc ← readDoc let text := doc.meta.text let t ← doc.cmdSnaps.waitAll (·.beginPos < endPos) mapTask 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 { 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 RequestM) _ := do if let some range := stx.getRange? 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 range.contains ipos then some ti else none | _ => none | _, _, _ => none) do match ti.expr with | Expr.fvar .. => addToken ti.stx SemanticTokenType.variable | _ => if ti.stx.getPos?.get! > range.start 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) : RequestM (RequestTask SemanticTokens) := do handleSemanticTokens 0 (1 <<< 16) def handleSemanticTokensRange (p : SemanticTokensRangeParams) : RequestM (RequestTask SemanticTokens) := do let doc ← readDoc 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) : RequestM (RequestTask WaitForDiagnostics) := do let rec waitLoop : RequestM EditableDocument := do let doc ← readDoc if p.version ≤ doc.meta.version then return doc else IO.sleep 50 waitLoop let t ← RequestM.asTask waitLoop RequestM.bindTask t fun doc? => do let doc ← doc? let t₁ ← doc.cmdSnaps.waitAll return t₁.map fun _ => pure WaitForDiagnostics.mk builtin_initialize registerLspRequestHandler "textDocument/waitForDiagnostics" WaitForDiagnosticsParams WaitForDiagnostics handleWaitForDiagnostics registerLspRequestHandler "textDocument/completion" CompletionParams CompletionList handleCompletion registerLspRequestHandler "textDocument/hover" HoverParams (Option Hover) handleHover registerLspRequestHandler "textDocument/declaration" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.declaration) registerLspRequestHandler "textDocument/definition" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.definition) registerLspRequestHandler "textDocument/typeDefinition" TextDocumentPositionParams (Array LocationLink) (handleDefinition GoToKind.type) registerLspRequestHandler "textDocument/documentHighlight" DocumentHighlightParams DocumentHighlightResult handleDocumentHighlight registerLspRequestHandler "textDocument/documentSymbol" DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol registerLspRequestHandler "textDocument/semanticTokens/full" SemanticTokensParams SemanticTokens handleSemanticTokensFull registerLspRequestHandler "textDocument/semanticTokens/range" SemanticTokensRangeParams SemanticTokens handleSemanticTokensRange registerLspRequestHandler "$/lean/plainGoal" PlainGoalParams (Option PlainGoal) handlePlainGoal registerLspRequestHandler "$/lean/plainTermGoal" PlainTermGoalParams (Option PlainTermGoal) handlePlainTermGoal end Lean.Server.FileWorker
6e8992f4d3e3c2640ca344671299b7e238648e97
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Meta/Match/Match.lean
f188f92f35710e0928295e6edcc411050e7ae532
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,216
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectLevelParams import Lean.Util.Recognizers import Lean.Compiler.ExternAttr import Lean.Meta.Check import Lean.Meta.Closure import Lean.Meta.Tactic.Cases import Lean.Meta.GeneralizeTelescope import Lean.Meta.Match.Basic import Lean.Meta.Match.MVarRenaming import Lean.Meta.Match.CaseValues namespace Lean.Meta.Match /- The number of patterns in each AltLHS must be equal to majors.length -/ private def checkNumPatterns (majors : Array Expr) (lhss : List AltLHS) : MetaM Unit := do let num := majors.size if lhss.any fun lhs => lhs.patterns.length != num then throwError "incorrect number of patterns" /- Given a list of `AltLHS`, create a minor premise for each one, convert them into `Alt`, and then execute `k` -/ private def withAlts {α} (motive : Expr) (lhss : List AltLHS) (k : List Alt → Array (Expr × Nat) → MetaM α) : MetaM α := loop lhss [] #[] where mkMinorType (xs : Array Expr) (lhs : AltLHS) : MetaM Expr := withExistingLocalDecls lhs.fvarDecls do let args ← lhs.patterns.toArray.mapM (Pattern.toExpr · (annotate := true)) let minorType := mkAppN motive args mkForallFVars xs minorType loop (lhss : List AltLHS) (alts : List Alt) (minors : Array (Expr × Nat)) : MetaM α := do match lhss with | [] => k alts.reverse minors | lhs::lhss => let xs := lhs.fvarDecls.toArray.map LocalDecl.toExpr let minorType ← mkMinorType xs lhs let (minorType, minorNumParams) := if !xs.isEmpty then (minorType, xs.size) else (mkSimpleThunkType minorType, 1) let idx := alts.length let minorName := (`h).appendIndexAfter (idx+1) trace[Meta.Match.debug]! "minor premise {minorName} : {minorType}" withLocalDeclD minorName minorType fun minor => do let rhs := if xs.isEmpty then mkApp minor (mkConst `Unit.unit) else mkAppN minor xs let minors := minors.push (minor, minorNumParams) let fvarDecls ← lhs.fvarDecls.mapM instantiateLocalDeclMVars let alts := { ref := lhs.ref, idx := idx, rhs := rhs, fvarDecls := fvarDecls, patterns := lhs.patterns : Alt } :: alts loop lhss alts minors def assignGoalOf (p : Problem) (e : Expr) : MetaM Unit := withGoalOf p (assignExprMVar p.mvarId e) structure State where used : Std.HashSet Nat := {} -- used alternatives counterExamples : List (List Example) := [] /-- Return true if the given (sub-)problem has been solved. -/ private def isDone (p : Problem) : Bool := p.vars.isEmpty /-- Return true if the next element on the `p.vars` list is a variable. -/ private def isNextVar (p : Problem) : Bool := match p.vars with | Expr.fvar _ _ :: _ => true | _ => false private def hasAsPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.as _ _ :: _ => true | _ => false private def hasCtorPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.ctor _ _ _ _ :: _ => true | _ => false private def hasValPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.val _ :: _ => true | _ => false private def hasNatValPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.val v :: _ => v.isNatLit | _ => false private def hasVarPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.var _ :: _ => true | _ => false private def hasArrayLitPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | Pattern.arrayLit _ _ :: _ => true | _ => false private def isVariableTransition (p : Problem) : Bool := p.alts.all fun alt => match alt.patterns with | Pattern.inaccessible _ :: _ => true | Pattern.var _ :: _ => true | _ => false private def isConstructorTransition (p : Problem) : Bool := (hasCtorPattern p || p.alts.isEmpty) && p.alts.all fun alt => match alt.patterns with | Pattern.ctor _ _ _ _ :: _ => true | Pattern.var _ :: _ => true | Pattern.inaccessible _ :: _ => true | _ => false private def isValueTransition (p : Problem) : Bool := hasVarPattern p && hasValPattern p && p.alts.all fun alt => match alt.patterns with | Pattern.val _ :: _ => true | Pattern.var _ :: _ => true | _ => false private def isArrayLitTransition (p : Problem) : Bool := hasArrayLitPattern p && hasVarPattern p && p.alts.all fun alt => match alt.patterns with | Pattern.arrayLit _ _ :: _ => true | Pattern.var _ :: _ => true | _ => false private def isNatValueTransition (p : Problem) : Bool := hasNatValPattern p && (!isNextVar p || p.alts.any fun alt => match alt.patterns with | Pattern.ctor _ _ _ _ :: _ => true | Pattern.inaccessible _ :: _ => true | _ => false) private def processSkipInaccessible (p : Problem) : Problem := match p.vars with | [] => unreachable! | x :: xs => do let alts := p.alts.map fun alt => match alt.patterns with | Pattern.inaccessible _ :: ps => { alt with patterns := ps } | _ => unreachable! { p with alts := alts, vars := xs } private def processLeaf (p : Problem) : StateRefT State MetaM Unit := match p.alts with | [] => do liftM $ admit p.mvarId modify fun s => { s with counterExamples := p.examples :: s.counterExamples } | alt :: _ => do -- TODO: check whether we have unassigned metavars in rhs liftM $ assignGoalOf p alt.rhs modify fun s => { s with used := s.used.insert alt.idx } private def processAsPattern (p : Problem) : MetaM Problem := match p.vars with | [] => unreachable! | x :: xs => withGoalOf p do let alts ← p.alts.mapM fun alt => match alt.patterns with | Pattern.as fvarId p :: ps => { alt with patterns := p :: ps }.checkAndReplaceFVarId fvarId x | _ => pure alt pure { p with alts := alts } private def processVariable (p : Problem) : MetaM Problem := match p.vars with | [] => unreachable! | x :: xs => withGoalOf p do let alts ← p.alts.mapM fun alt => match alt.patterns with | Pattern.inaccessible _ :: ps => pure { alt with patterns := ps } | Pattern.var fvarId :: ps => { alt with patterns := ps }.checkAndReplaceFVarId fvarId x | _ => unreachable! pure { p with alts := alts, vars := xs } private def throwInductiveTypeExpected {α} (e : Expr) : MetaM α := do let t ← inferType e throwError! "failed to compile pattern matching, inductive type expected{indentExpr e}\nhas type{indentExpr t}" private def inLocalDecls (localDecls : List LocalDecl) (fvarId : FVarId) : Bool := localDecls.any fun d => d.fvarId == fvarId namespace Unify structure Context where altFVarDecls : List LocalDecl structure State where fvarSubst : FVarSubst := {} abbrev M := ReaderT Context $ StateRefT State MetaM def isAltVar (fvarId : FVarId) : M Bool := do return inLocalDecls (← read).altFVarDecls fvarId def expandIfVar (e : Expr) : M Expr := do match e with | Expr.fvar _ _ => return (← get).fvarSubst.apply e | _ => return e def occurs (fvarId : FVarId) (v : Expr) : Bool := Option.isSome $ v.find? fun e => match e with | Expr.fvar fvarId' _ => fvarId == fvarId' | _=> false def assign (fvarId : FVarId) (v : Expr) : M Bool := do if occurs fvarId v then trace[Meta.Match.unify]! "assign occurs check failed, {mkFVar fvarId} := {v}" pure false else let ctx ← read if (← isAltVar fvarId) then trace[Meta.Match.unify]! "{mkFVar fvarId} := {v}" modify fun s => { s with fvarSubst := s.fvarSubst.insert fvarId v } pure true else trace[Meta.Match.unify]! "assign failed variable is not local, {mkFVar fvarId} := {v}" pure false partial def unify (a : Expr) (b : Expr) : M Bool := do trace[Meta.Match.unify]! "{a} =?= {b}" if (← isDefEq a b) then pure true else let a' ← expandIfVar a let b' ← expandIfVar b if a != a' || b != b' then unify a' b' else match a, b with | Expr.mdata _ a _, b => unify a b | a, Expr.mdata _ b _ => unify a b | Expr.fvar aFvarId _, Expr.fvar bFVarId _ => assign aFvarId b <||> assign bFVarId a | Expr.fvar aFvarId _, b => assign aFvarId b | a, Expr.fvar bFVarId _ => assign bFVarId a | Expr.app aFn aArg _, Expr.app bFn bArg _ => unify aFn bFn <&&> unify aArg bArg | _, _ => pure false end Unify private def unify? (altFVarDecls : List LocalDecl) (a b : Expr) : MetaM (Option FVarSubst) := do let a ← instantiateMVars a let b ← instantiateMVars b let (b, s) ← Unify.unify a b { altFVarDecls := altFVarDecls} |>.run {} if b then pure s.fvarSubst else pure none private def expandVarIntoCtor? (alt : Alt) (fvarId : FVarId) (ctorName : Name) : MetaM (Option Alt) := withExistingLocalDecls alt.fvarDecls do let env ← getEnv let ldecl ← getLocalDecl fvarId let expectedType ← inferType (mkFVar fvarId) let expectedType ← whnfD expectedType let (ctorLevels, ctorParams) ← getInductiveUniverseAndParams expectedType let ctor := mkAppN (mkConst ctorName ctorLevels) ctorParams let ctorType ← inferType ctor forallTelescopeReducing ctorType fun ctorFields resultType => do let ctor := mkAppN ctor ctorFields let alt := alt.replaceFVarId fvarId ctor let ctorFieldDecls ← ctorFields.mapM fun ctorField => getLocalDecl ctorField.fvarId! let newAltDecls := ctorFieldDecls.toList ++ alt.fvarDecls let subst? ← unify? newAltDecls resultType expectedType match subst? with | none => pure none | some subst => let newAltDecls := newAltDecls.filter fun d => !subst.contains d.fvarId -- remove declarations that were assigned let newAltDecls := newAltDecls.map fun d => d.applyFVarSubst subst -- apply substitution to remaining declaration types let patterns := alt.patterns.map fun p => p.applyFVarSubst subst let rhs := subst.apply alt.rhs let ctorFieldPatterns := ctorFields.toList.map fun ctorField => match subst.get ctorField.fvarId! with | e@(Expr.fvar fvarId _) => if inLocalDecls newAltDecls fvarId then Pattern.var fvarId else Pattern.inaccessible e | e => Pattern.inaccessible e pure $ some { alt with fvarDecls := newAltDecls, rhs := rhs, patterns := ctorFieldPatterns ++ patterns } private def getInductiveVal? (x : Expr) : MetaM (Option InductiveVal) := do let xType ← inferType x let xType ← whnfD xType match xType.getAppFn with | Expr.const constName _ _ => let cinfo ← getConstInfo constName match cinfo with | ConstantInfo.inductInfo val => pure (some val) | _ => pure none | _ => pure none private def hasRecursiveType (x : Expr) : MetaM Bool := do match (← getInductiveVal? x) with | some val => pure val.isRec | _ => pure false /- Given `alt` s.t. the next pattern is an inaccessible pattern `e`, try to normalize `e` into a constructor application. If it is not a constructor, throw an error. Otherwise, if it is a constructor application of `ctorName`, update the next patterns with the fields of the constructor. Otherwise, return none. -/ def processInaccessibleAsCtor (alt : Alt) (ctorName : Name) : MetaM (Option Alt) := do let env ← getEnv match alt.patterns with | p@(Pattern.inaccessible e) :: ps => trace[Meta.Match.match]! "inaccessible in ctor step {e}" withExistingLocalDecls alt.fvarDecls do -- Try to push inaccessible annotations. let e ← whnfD e match e.constructorApp? env with | some (ctorVal, ctorArgs) => if ctorVal.name == ctorName then let fields := ctorArgs.extract ctorVal.numParams ctorArgs.size let fields := fields.toList.map Pattern.inaccessible pure $ some { alt with patterns := fields ++ ps } else pure none | _ => throwErrorAt! alt.ref "dependent match elimination failed, inaccessible pattern found{indentD p.toMessageData}\nconstructor expected" | _ => unreachable! private def processConstructor (p : Problem) : MetaM (Array Problem) := do trace[Meta.Match.match]! "constructor step" let env ← getEnv match p.vars with | [] => unreachable! | x :: xs => do let subgoals? ← commitWhenSome? do let subgoals ← cases p.mvarId x.fvarId! if subgoals.isEmpty then /- Easy case: we have solved problem `p` since there are no subgoals -/ pure (some #[]) else if !p.alts.isEmpty then pure (some subgoals) else do let isRec ← withGoalOf p $ hasRecursiveType x /- If there are no alternatives and the type of the current variable is recursive, we do NOT consider a constructor-transition to avoid nontermination. TODO: implement a more general approach if this is not sufficient in practice -/ if isRec then pure none else pure (some subgoals) match subgoals? with | none => pure #[{ p with vars := xs }] | some subgoals => subgoals.mapM fun subgoal => withMVarContext subgoal.mvarId do let subst := subgoal.subst let fields := subgoal.fields.toList let newVars := fields ++ xs let newVars := newVars.map fun x => x.applyFVarSubst subst let subex := Example.ctor subgoal.ctorName $ fields.map fun field => match field with | Expr.fvar fvarId _ => Example.var fvarId | _ => Example.underscore -- This case can happen due to dependent elimination let examples := p.examples.map $ Example.replaceFVarId x.fvarId! subex let examples := examples.map $ Example.applyFVarSubst subst let newAlts := p.alts.filter fun alt => match alt.patterns with | Pattern.ctor n _ _ _ :: _ => n == subgoal.ctorName | Pattern.var _ :: _ => true | Pattern.inaccessible _ :: _ => true | _ => false let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst let newAlts ← newAlts.filterMapM fun alt => match alt.patterns with | Pattern.ctor _ _ _ fields :: ps => pure $ some { alt with patterns := fields ++ ps } | Pattern.var fvarId :: ps => expandVarIntoCtor? { alt with patterns := ps } fvarId subgoal.ctorName | Pattern.inaccessible _ :: _ => processInaccessibleAsCtor alt subgoal.ctorName | _ => unreachable! pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } private def processNonVariable (p : Problem) : MetaM Problem := match p.vars with | [] => unreachable! | x :: xs => withGoalOf p do let x ← whnfD x let env ← getEnv match x.constructorApp? env with | some (ctorVal, xArgs) => let alts ← p.alts.filterMapM fun alt => match alt.patterns with | Pattern.ctor n _ _ fields :: ps => if n != ctorVal.name then pure none else pure $ some { alt with patterns := fields ++ ps } | Pattern.inaccessible _ :: _ => processInaccessibleAsCtor alt ctorVal.name | p :: _ => throwError! "failed to compile pattern matching, inaccessible pattern or constructor expected{indentD p.toMessageData}" | _ => unreachable! let xFields := xArgs.extract ctorVal.numParams xArgs.size pure { p with alts := alts, vars := xFields.toList ++ xs } | none => let alts ← p.alts.filterMapM fun alt => match alt.patterns with | Pattern.inaccessible e :: ps => do if (← isDefEq x e) then pure $ some { alt with patterns := ps } else pure none | p :: _ => throwError! "failed to compile pattern matching, unexpected pattern{indentD p.toMessageData}\ndiscriminant{indentExpr x}" | _ => unreachable! pure { p with alts := alts, vars := xs } private def collectValues (p : Problem) : Array Expr := p.alts.foldl (init := #[]) fun values alt => match alt.patterns with | Pattern.val v :: _ => if values.contains v then values else values.push v | _ => values private def isFirstPatternVar (alt : Alt) : Bool := match alt.patterns with | Pattern.var _ :: _ => true | _ => false private def processValue (p : Problem) : MetaM (Array Problem) := do trace[Meta.Match.match]! "value step" match p.vars with | [] => unreachable! | x :: xs => do let values := collectValues p let subgoals ← caseValues p.mvarId x.fvarId! values subgoals.mapIdxM fun i subgoal => do if h : i.val < values.size then let value := values.get ⟨i, h⟩ -- (x = value) branch let subst := subgoal.subst let examples := p.examples.map $ Example.replaceFVarId x.fvarId! (Example.val value) let examples := examples.map $ Example.applyFVarSubst subst let newAlts := p.alts.filter fun alt => match alt.patterns with | Pattern.val v :: _ => v == value | Pattern.var _ :: _ => true | _ => false let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst let newAlts := newAlts.map fun alt => match alt.patterns with | Pattern.val _ :: ps => { alt with patterns := ps } | Pattern.var fvarId :: ps => let alt := { alt with patterns := ps } alt.replaceFVarId fvarId value | _ => unreachable! let newVars := xs.map fun x => x.applyFVarSubst subst pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } else -- else branch for value let newAlts := p.alts.filter isFirstPatternVar pure { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs } private def collectArraySizes (p : Problem) : Array Nat := p.alts.foldl (init := #[]) fun sizes alt => match alt.patterns with | Pattern.arrayLit _ ps :: _ => let sz := ps.length; if sizes.contains sz then sizes else sizes.push sz | _ => sizes private def expandVarIntoArrayLit (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (arraySize : Nat) : MetaM Alt := withExistingLocalDecls alt.fvarDecls do let fvarDecl ← getLocalDecl fvarId let varNamePrefix := fvarDecl.userName let rec loop | n+1, newVars => withLocalDeclD (varNamePrefix.appendIndexAfter (n+1)) arrayElemType fun x => loop n (newVars.push x) | 0, newVars => do let arrayLit ← mkArrayLit arrayElemType newVars.toList let alt := alt.replaceFVarId fvarId arrayLit let newDecls ← newVars.toList.mapM fun newVar => getLocalDecl newVar.fvarId! let newPatterns := newVars.toList.map fun newVar => Pattern.var newVar.fvarId! pure { alt with fvarDecls := newDecls ++ alt.fvarDecls, patterns := newPatterns ++ alt.patterns } loop arraySize #[] private def processArrayLit (p : Problem) : MetaM (Array Problem) := do trace[Meta.Match.match]! "array literal step" match p.vars with | [] => unreachable! | x :: xs => do let sizes := collectArraySizes p let subgoals ← caseArraySizes p.mvarId x.fvarId! sizes subgoals.mapIdxM fun i subgoal => do if h : i.val < sizes.size then let size := sizes.get! i let subst := subgoal.subst let elems := subgoal.elems.toList let newVars := elems.map mkFVar ++ xs let newVars := newVars.map fun x => x.applyFVarSubst subst let subex := Example.arrayLit <| elems.map Example.var let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex let examples := examples.map <| Example.applyFVarSubst subst let newAlts := p.alts.filter fun alt => match alt.patterns with | Pattern.arrayLit _ ps :: _ => ps.length == size | Pattern.var _ :: _ => true | _ => false let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst let newAlts ← newAlts.mapM fun alt => match alt.patterns with | Pattern.arrayLit _ pats :: ps => pure { alt with patterns := pats ++ ps } | Pattern.var fvarId :: ps => do let α ← getArrayArgType <| subst.apply x expandVarIntoArrayLit { alt with patterns := ps } fvarId α size | _ => unreachable! pure { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } else do -- else branch let newAlts := p.alts.filter isFirstPatternVar pure { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs } private def expandNatValuePattern (p : Problem) : Problem := do let alts := p.alts.map fun alt => match alt.patterns with | Pattern.val (Expr.lit (Literal.natVal 0) _) :: ps => { alt with patterns := Pattern.ctor `Nat.zero [] [] [] :: ps } | Pattern.val (Expr.lit (Literal.natVal (n+1)) _) :: ps => { alt with patterns := Pattern.ctor `Nat.succ [] [] [Pattern.val (mkNatLit n)] :: ps } | _ => alt { p with alts := alts } private def traceStep (msg : String) : StateRefT State MetaM Unit := trace[Meta.Match.match]! "{msg} step" private def traceState (p : Problem) : MetaM Unit := withGoalOf p (traceM `Meta.Match.match p.toMessageData) private def throwNonSupported (p : Problem) : MetaM Unit := withGoalOf p do let msg ← p.toMessageData throwError! "failed to compile pattern matching, stuck at{indentD msg}" def isCurrVarInductive (p : Problem) : MetaM Bool := do match p.vars with | [] => pure false | x::_ => withGoalOf p do let val? ← getInductiveVal? x pure val?.isSome private def checkNextPatternTypes (p : Problem) : MetaM Unit := do match p.vars with | [] => return () | x::_ => withGoalOf p do for alt in p.alts do withRef alt.ref do match alt.patterns with | [] => pure () | p::_ => let e ← p.toExpr let xType ← inferType x let eType ← inferType e unless (← isDefEq xType eType) do throwError! "pattern{indentExpr e}\n{← mkHasTypeButIsExpectedMsg eType xType}" private partial def process (p : Problem) : StateRefT State MetaM Unit := withIncRecDepth do traceState p let isInductive ← liftM $ isCurrVarInductive p if isDone p then processLeaf p else if hasAsPattern p then traceStep ("as-pattern") let p ← processAsPattern p process p else if isNatValueTransition p then traceStep ("nat value to constructor") process (expandNatValuePattern p) else if !isNextVar p then traceStep ("non variable") let p ← processNonVariable p process p else if isInductive && isConstructorTransition p then let ps ← processConstructor p ps.forM process else if isVariableTransition p then traceStep ("variable") let p ← processVariable p process p else if isValueTransition p then let ps ← processValue p ps.forM process else if isArrayLitTransition p then let ps ← processArrayLit p ps.forM process else if hasNatValPattern p then -- This branch is reachable when `p`, for example, is just values without an else-alternative. -- We added it just to get better error messages. traceStep ("nat value to constructor") process (expandNatValuePattern p) else checkNextPatternTypes p throwNonSupported p private def getUElimPos? (matcherLevels : List Level) (uElim : Level) : MetaM (Option Nat) := if uElim == levelZero then pure none else match matcherLevels.toArray.indexOf? uElim with | none => throwError "dependent match elimination failed, universe level not found" | some pos => pure $ some pos.val /- See comment at `mkMatcher` before `mkAuxDefinition` -/ register_builtin_option bootstrap.genMatcherCode : Bool := { defValue := true group := "bootstrap" descr := "disable code generation for auxiliary matcher function" } /- Create a dependent matcher for `matchType` where `matchType` is of the form `(a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> B[a_1, ..., a_n]` where `n = numDiscrs`, and the `lhss` are the left-hand-sides of the `match`-expression alternatives. Each `AltLHS` has a list of local declarations and a list of patterns. The number of patterns must be the same in each `AltLHS`. The generated matcher has the structure described at `MatcherInfo`. The motive argument is of the form `(motive : (a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> Sort v)` where `v` is a universe parameter or 0 if `B[a_1, ..., a_n]` is a proposition. -/ def mkMatcher (matcherName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : MetaM MatcherResult := forallBoundedTelescope matchType numDiscrs fun majors matchTypeBody => do checkNumPatterns majors lhss /- We generate an matcher that can eliminate using different motives with different universe levels. `uElim` is the universe level the caller wants to eliminate to. If it is not levelZero, we create a matcher that can eliminate in any universe level. This is useful for implementing `MatcherApp.addArg` because it may have to change the universe level. -/ let uElim ← getLevel matchTypeBody let uElimGen ← if uElim == levelZero then pure levelZero else mkFreshLevelMVar let motiveType ← mkForallFVars majors (mkSort uElimGen) withLocalDeclD `motive motiveType fun motive => do trace[Meta.Match.debug]! "motiveType: {motiveType}" let mvarType := mkAppN motive majors trace[Meta.Match.debug]! "target: {mvarType}" withAlts motive lhss fun alts minors => do let mvar ← mkFreshExprMVar mvarType let examples := majors.toList.map fun major => Example.var major.fvarId! let (_, s) ← (process { mvarId := mvar.mvarId!, vars := majors.toList, alts := alts, examples := examples }).run {} let args := #[motive] ++ majors ++ minors.map Prod.fst let type ← mkForallFVars args mvarType let val ← mkLambdaFVars args mvar trace[Meta.Match.debug]! "matcher value: {val}\ntype: {type}" /- The option `bootstrap.gen_matcher_code` is a helper hack. It is useful, for example, for compiling `src/Init/Data/Int`. It is needed because the compiler uses `Int.decLt` for generating code for `Int.casesOn` applications, but `Int.casesOn` is used to give the reference implementation for ``` @[extern "lean_int_neg"] def neg (n : @& Int) : Int := match n with | ofNat n => negOfNat n | negSucc n => succ n ``` which is defined **before** `Int.decLt` -/ let matcher ← mkAuxDefinition matcherName type val (compile := bootstrap.genMatcherCode.get (← getOptions)) trace[Meta.Match.debug]! "matcher levels: {matcher.getAppFn.constLevels!}, uElim: {uElimGen}" let uElimPos? ← getUElimPos? matcher.getAppFn.constLevels! uElimGen discard <| isLevelDefEq uElimGen uElim addMatcherInfo matcherName { numParams := matcher.getAppNumArgs, numDiscrs := numDiscrs, altNumParams := minors.map Prod.snd, uElimPos? := uElimPos? } setInlineAttribute matcherName trace[Meta.Match.debug]! "matcher: {matcher}" let unusedAltIdxs := lhss.length.fold (init := []) fun i r => if s.used.contains i then r else i::r pure { matcher := matcher, counterExamples := s.counterExamples, unusedAltIdxs := unusedAltIdxs.reverse } end Match /- Auxiliary function for MatcherApp.addArg -/ private partial def updateAlts (typeNew : Expr) (altNumParams : Array Nat) (alts : Array Expr) (i : Nat) : MetaM (Array Nat × Array Expr) := do if h : i < alts.size then let alt := alts.get ⟨i, h⟩ let numParams := altNumParams[i] let typeNew ← whnfD typeNew match typeNew with | Expr.forallE n d b _ => let alt ← forallBoundedTelescope d (some numParams) fun xs d => do let alt ← try instantiateLambda alt xs catch _ => throwError "unexpected matcher application, insufficient number of parameters in alternative" forallBoundedTelescope d (some 1) fun x d => do let alt ← mkLambdaFVars x alt -- x is the new argument we are adding to the alternative let alt ← mkLambdaFVars xs alt pure alt updateAlts (b.instantiate1 alt) (altNumParams.set! i (numParams+1)) (alts.set ⟨i, h⟩ alt) (i+1) | _ => throwError "unexpected type at MatcherApp.addArg" else pure (altNumParams, alts) /- Given - matcherApp `match_i As (fun xs => motive[xs]) discrs (fun ys_1 => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n => (alt_n : motive (C_n[ys_n]) remaining`, and - expression `e : B[discrs]`, Construct the term `match_i As (fun xs => B[xs] -> motive[xs]) discrs (fun ys_1 (y : B[C_1[ys_1]]) => alt_1) ... (fun ys_n (y : B[C_n[ys_n]]) => alt_n) e remaining`, and We use `kabstract` to abstract the discriminants from `B[discrs]`. This method assumes - the `matcherApp.motive` is a lambda abstraction where `xs.size == discrs.size` - each alternative is a lambda abstraction where `ys_i.size == matcherApp.altNumParams[i]` -/ def MatcherApp.addArg (matcherApp : MatcherApp) (e : Expr) : MetaM MatcherApp := lambdaTelescope matcherApp.motive fun motiveArgs motiveBody => do unless motiveArgs.size == matcherApp.discrs.size do -- This error can only happen if someone implemented a transformation that rewrites the motive created by `mkMatcher`. throwError! "unexpected matcher application, motive must be lambda expression with #{matcherApp.discrs.size} arguments" let eType ← inferType e let eTypeAbst ← matcherApp.discrs.size.foldRevM (init := eType) fun i eTypeAbst => do let motiveArg := motiveArgs[i] let discr := matcherApp.discrs[i] let eTypeAbst ← kabstract eTypeAbst discr pure $ eTypeAbst.instantiate1 motiveArg let motiveBody ← mkArrow eTypeAbst motiveBody let matcherLevels ← match matcherApp.uElimPos? with | none => pure matcherApp.matcherLevels | some pos => let uElim ← getLevel motiveBody pure $ matcherApp.matcherLevels.set! pos uElim let motive ← mkLambdaFVars motiveArgs motiveBody -- Construct `aux` `match_i As (fun xs => B[xs] → motive[xs]) discrs`, and infer its type `auxType`. -- We use `auxType` to infer the type `B[C_i[ys_i]]` of the new argument in each alternative. let aux := mkAppN (mkConst matcherApp.matcherName matcherLevels.toList) matcherApp.params let aux := mkApp aux motive let aux := mkAppN aux matcherApp.discrs trace! `Meta.debug aux check aux unless (← isTypeCorrect aux) do throwError "failed to add argument to matcher application, type error when constructing the new motive" let auxType ← inferType aux let (altNumParams, alts) ← updateAlts auxType matcherApp.altNumParams matcherApp.alts 0 pure { matcherApp with matcherLevels := matcherLevels, motive := motive, alts := alts, altNumParams := altNumParams, remaining := #[e] ++ matcherApp.remaining } builtin_initialize registerTraceClass `Meta.Match.match registerTraceClass `Meta.Match.debug registerTraceClass `Meta.Match.unify end Lean.Meta
eeba1672fd7750932484407d71e841383ee1dbb3
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/inner_product_space/projection.lean
57143ef100655fe9340b66d94cf3f684558b17b3
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
56,228
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Frédéric Dupuis, Heather Macbeth -/ import analysis.convex.basic import analysis.inner_product_space.basic import analysis.normed_space.is_R_or_C /-! # The orthogonal projection Given a nonempty complete subspace `K` of an inner product space `E`, this file constructs `orthogonal_projection K : E →L[𝕜] K`, the orthogonal projection of `E` onto `K`. This map satisfies: for any point `u` in `E`, the point `v = orthogonal_projection K u` in `K` minimizes the distance `∥u - v∥` to `u`. Also a linear isometry equivalence `reflection K : E ≃ₗᵢ[𝕜] E` is constructed, by choosing, for each `u : E`, the point `reflection K u` to satisfy `u + (reflection K u) = 2 • orthogonal_projection K u`. Basic API for `orthogonal_projection` and `reflection` is developed. Next, the orthogonal projection is used to prove a series of more subtle lemmas about the the orthogonal complement of complete subspaces of `E` (the orthogonal complement itself was defined in `analysis.inner_product_space.basic`); the lemma `submodule.sup_orthogonal_of_is_complete`, stating that for a complete subspace `K` of `E` we have `K ⊔ Kᗮ = ⊤`, is a typical example. ## References The orthogonal projection construction is adapted from * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators topological_space variables {𝕜 E F : Type*} [is_R_or_C 𝕜] variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local notation `absR` := has_abs.abs /-! ### Orthogonal projection in inner product spaces -/ /-- Existence of minimizers Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex ℝ K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos le_rfl nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ), { have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):F), let wq := ((w q):F), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw _root_.abs_of_nonneg, exact zero_le_two } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by simp [norm_smul] ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, from (sub_sub_sub_cancel_left _ _ _).symm, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm _ _, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_sq_le_sq, { exact sqrt_nonneg _ }, rw mul_self_sqrt, calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers for the projection on a convex set in a real inner product space. -/ theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex ℝ K) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [sq], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_sq, inner_smul_right, norm_smul], simp only [sq], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), by abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_right this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact sq_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (sq_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_sq_le_sq (norm_nonneg _), have := h w w.2, calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 : by { rw sq, refine le_add_of_nonneg_right _, exact sq_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_sq.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, sq] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end variables (K : submodule 𝕜 E) /-- Existence of projections on complete subspaces. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E, let K' : submodule ℝ E := submodule.restrict_scalars ℝ K, exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex end /-- Characterization of minimizers in the projection on a subspace, in the real case. Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`). This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over any `is_R_or_C` field. -/ theorem norm_eq_infi_iff_real_inner_eq_zero (K : submodule ℝ F) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, { rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : ⟪u - v, w⟫_ℝ ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : ⟪u - v, w⟫_ℝ ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_real_inner_le_zero, exacts [submodule.convex _, hv] end /-- Characterization of minimizers in the projection on a subspace. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero {u : E} {v : E} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E, let K' : submodule ℝ E := K.restrict_scalars ℝ, split, { assume H, have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H, assume w hw, apply ext, { simp [A w hw] }, { symmetry, calc im (0 : 𝕜) = 0 : im.map_zero ... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm ... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right ... = im ⟪u - v, w⟫ : by simp } }, { assume H, have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0, { assume w hw, rw [real_inner_eq_re_inner, H w hw], exact zero_re' }, exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this } end section orthogonal_projection variables [complete_space K] /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (v : E) := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some variables {K} /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem (v : E) : orthogonal_projection_fn K v ∈ K := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn K v, w⟫ = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem v), exact (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : orthogonal_projection_fn K u = v := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : orthogonal_projection_fn K u - v ∈ K := submodule.sub_mem K (orthogonal_projection_fn_mem u) hvm, have huo : ⟪u - orthogonal_projection_fn K u, orthogonal_projection_fn K u - v⟫ = 0 := orthogonal_projection_fn_inner_eq_zero u _ hvs, have huv : ⟪u - v, orthogonal_projection_fn K u - v⟫ = 0 := hvo _ hvs, have houv : ⟪(u - v) - (u - orthogonal_projection_fn K u), orthogonal_projection_fn K u - v⟫ = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end variables (K) lemma orthogonal_projection_fn_norm_sq (v : E) : ∥v∥ * ∥v∥ = ∥v - (orthogonal_projection_fn K v)∥ * ∥v - (orthogonal_projection_fn K v)∥ + ∥orthogonal_projection_fn K v∥ * ∥orthogonal_projection_fn K v∥ := begin set p := orthogonal_projection_fn K v, have h' : ⟪v - p, p⟫ = 0, { exact orthogonal_projection_fn_inner_eq_zero _ _ (orthogonal_projection_fn_mem v) }, convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (v - p) p h' using 2; simp, end /-- The orthogonal projection onto a complete subspace. -/ def orthogonal_projection : E →L[𝕜] K := linear_map.mk_continuous { to_fun := λ v, ⟨orthogonal_projection_fn K v, orthogonal_projection_fn_mem v⟩, map_add' := λ x y, begin have hm : orthogonal_projection_fn K x + orthogonal_projection_fn K y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem x) (orthogonal_projection_fn_mem y), have ho : ∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn K x + orthogonal_projection_fn K y), w⟫ = 0, { intros w hw, rw [add_sub_add_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero _ w hw, orthogonal_projection_fn_inner_eq_zero _ w hw, add_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn K x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem x), have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn K x, w⟫ = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero _ w hw, mul_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end } 1 (λ x, begin simp only [one_mul, linear_map.coe_mk], refine le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _, change ∥orthogonal_projection_fn K x∥ ^ 2 ≤ ∥x∥ ^ 2, nlinarith [orthogonal_projection_fn_norm_sq K x] end) variables {K} @[simp] lemma orthogonal_projection_fn_eq (v : E) : orthogonal_projection_fn K v = (orthogonal_projection K v : E) := rfl /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 := orthogonal_projection_fn_inner_eq_zero v /-- The difference of `v` from its orthogonal projection onto `K` is in `Kᗮ`. -/ @[simp] lemma sub_orthogonal_projection_mem_orthogonal (v : E) : v - orthogonal_projection K v ∈ Kᗮ := begin intros w hw, rw inner_eq_zero_sym, exact orthogonal_projection_inner_eq_zero _ _ hw end /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hvm hvo /-- The orthogonal projection of `y` on `U` minimizes the distance `∥y - x∥` for `x ∈ U`. -/ lemma orthogonal_projection_minimal {U : submodule 𝕜 E} [complete_space U] (y : E) : ∥y - orthogonal_projection U y∥ = ⨅ x : U, ∥y - x∥ := begin rw norm_eq_infi_iff_inner_eq_zero _ (submodule.coe_mem _), exact orthogonal_projection_inner_eq_zero _ end /-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/ lemma eq_orthogonal_projection_of_eq_submodule {K' : submodule 𝕜 E} [complete_space K'] (h : K = K') (u : E) : (orthogonal_projection K u : E) = (orthogonal_projection K' u : E) := begin change orthogonal_projection_fn K u = orthogonal_projection_fn K' u, congr, exact h end /-- The orthogonal projection sends elements of `K` to themselves. -/ @[simp] lemma orthogonal_projection_mem_subspace_eq_self (v : K) : orthogonal_projection K v = v := by { ext, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero; simp } /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {v : E} : (orthogonal_projection K v : E) = v ↔ v ∈ K := begin refine ⟨λ h, _, λ h, eq_orthogonal_projection_of_mem_of_inner_eq_zero h _⟩, { rw ← h, simp }, { simp } end lemma linear_isometry.map_orthogonal_projection {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E →ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p] (x : E) : f (orthogonal_projection p x) = orthogonal_projection (p.map f.to_linear_map) (f x) := begin refine (eq_orthogonal_projection_of_mem_of_inner_eq_zero (submodule.apply_coe_mem_map _ _) $ λ y hy, _).symm, rcases hy with ⟨x', hx', rfl : f x' = y⟩, rw [f.coe_to_linear_map, ← f.map_sub, f.inner_map_map, orthogonal_projection_inner_eq_zero x x' hx'] end /-- Orthogonal projection onto the `submodule.map` of a subspace. -/ lemma orthogonal_projection_map_apply {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p] (x : E') : (orthogonal_projection (p.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x : E') = f (orthogonal_projection p (f.symm x)) := by simpa only [f.coe_to_linear_isometry, f.apply_symm_apply] using (f.to_linear_isometry.map_orthogonal_projection p (f.symm x)).symm /-- The orthogonal projection onto the trivial submodule is the zero map. -/ @[simp] lemma orthogonal_projection_bot : orthogonal_projection (⊥ : submodule 𝕜 E) = 0 := by ext variables (K) /-- The orthogonal projection has norm `≤ 1`. -/ lemma orthogonal_projection_norm_le : ∥orthogonal_projection K∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (by norm_num) _ variables (𝕜) lemma smul_orthogonal_projection_singleton {v : E} (w : E) : (∥v∥ ^ 2 : 𝕜) • (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := begin suffices : ↑(orthogonal_projection (𝕜 ∙ v) ((∥v∥ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v, { simpa using this }, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { rw submodule.mem_span_singleton, use ⟪v, w⟫ }, { intros x hx, obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx, have hv : ↑∥v∥ ^ 2 = ⟪v, v⟫ := by { norm_cast, simp [norm_sq_eq_inner] }, simp [inner_sub_left, inner_smul_left, inner_smul_right, map_div₀, mul_comm, hv, inner_product_space.conj_sym, hv] } end /-- Formula for orthogonal projection onto a single vector. -/ lemma orthogonal_projection_singleton {v : E} (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ∥v∥ ^ 2) • v := begin by_cases hv : v = 0, { rw [hv, eq_orthogonal_projection_of_eq_submodule (submodule.span_zero_singleton 𝕜)], { simp }, { apply_instance } }, have hv' : ∥v∥ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv), have key : ((∥v∥ ^ 2 : 𝕜)⁻¹ * ∥v∥ ^ 2) • ↑(orthogonal_projection (𝕜 ∙ v) w) = ((∥v∥ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v, { simp [mul_smul, smul_orthogonal_projection_singleton 𝕜 w] }, convert key; field_simp [hv'] end /-- Formula for orthogonal projection onto a single unit vector. -/ lemma orthogonal_projection_unit_singleton {v : E} (hv : ∥v∥ = 1) (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := by { rw ← smul_orthogonal_projection_singleton 𝕜 w, simp [hv] } end orthogonal_projection section reflection variables {𝕜} (K) [complete_space K] /-- Auxiliary definition for `reflection`: the reflection as a linear equivalence. -/ def reflection_linear_equiv : E ≃ₗ[𝕜] E := linear_equiv.of_involutive (bit0 (K.subtype.comp (orthogonal_projection K).to_linear_map) - linear_map.id) (λ x, by simp [bit0]) /-- Reflection in a complete subspace of an inner product space. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in a subspace, is a more general sense of the word that includes both those common cases. -/ def reflection : E ≃ₗᵢ[𝕜] E := { norm_map' := begin intros x, let w : K := orthogonal_projection K x, let v := x - w, have : ⟪v, w⟫ = 0 := orthogonal_projection_inner_eq_zero x w w.2, convert norm_sub_eq_norm_add this using 2, { rw [linear_equiv.coe_mk, reflection_linear_equiv, linear_equiv.to_fun_eq_coe, linear_equiv.coe_of_involutive, linear_map.sub_apply, linear_map.id_apply, bit0, linear_map.add_apply, linear_map.comp_apply, submodule.subtype_apply, continuous_linear_map.to_linear_map_eq_coe, continuous_linear_map.coe_coe], dsimp [w, v], abel, }, { simp only [add_sub_cancel'_right, eq_self_iff_true], } end, ..reflection_linear_equiv K } variables {K} /-- The result of reflecting. -/ lemma reflection_apply (p : E) : reflection K p = bit0 ↑(orthogonal_projection K p) - p := rfl /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm : (reflection K).symm = reflection K := rfl /-- Reflection is its own inverse. -/ @[simp] lemma reflection_inv : (reflection K)⁻¹ = reflection K := rfl variables (K) /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (p : E) : reflection K (reflection K p) = p := (reflection K).left_inv p /-- Reflection is involutive. -/ lemma reflection_involutive : function.involutive (reflection K) := reflection_reflection K /-- Reflection is involutive. -/ @[simp] lemma reflection_trans_reflection : (reflection K).trans (reflection K) = linear_isometry_equiv.refl 𝕜 E := linear_isometry_equiv.ext $ reflection_involutive K /-- Reflection is involutive. -/ @[simp] lemma reflection_mul_reflection : reflection K * reflection K = 1 := reflection_trans_reflection _ variables {K} /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff (x : E) : reflection K x = x ↔ x ∈ K := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply, sub_eq_iff_eq_add', ← two_smul 𝕜, ← two_smul' 𝕜], refine (smul_right_injective E _).eq_iff, exact two_ne_zero end lemma reflection_mem_subspace_eq_self {x : E} (hx : x ∈ K) : reflection K x = x := (reflection_eq_self_iff x).mpr hx /-- Reflection in the `submodule.map` of a subspace. -/ lemma reflection_map_apply {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [complete_space K] (x : E') : reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x = f (reflection K (f.symm x)) := by simp [bit0, reflection_apply, orthogonal_projection_map_apply f K x] /-- Reflection in the `submodule.map` of a subspace. -/ lemma reflection_map {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [complete_space K] : reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) = f.symm.trans ((reflection K).trans f) := linear_isometry_equiv.ext $ reflection_map_apply f K /-- Reflection through the trivial subspace {0} is just negation. -/ @[simp] lemma reflection_bot : reflection (⊥ : submodule 𝕜 E) = linear_isometry_equiv.neg 𝕜 := by ext; simp [reflection_apply] end reflection section orthogonal /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_complete_space {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) [complete_space K₁] : K₁ ⊔ (K₁ᗮ ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, let v : K₁ := orthogonal_projection K₁ x, have hvm : x - v ∈ K₁ᗮ := sub_orthogonal_projection_mem_orthogonal x, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, v.prop, x - v, ⟨hvm, K₂.sub_mem hx (h v.prop)⟩, add_sub_cancel'_right _ _⟩ } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/ lemma submodule.sup_orthogonal_of_complete_space [complete_space K] : K ⊔ Kᗮ = ⊤ := begin convert submodule.sup_orthogonal_inf_of_complete_space (le_top : K ≤ ⊤), simp end variables (K) /-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/ lemma submodule.exists_sum_mem_mem_orthogonal [complete_space K] (v : E) : ∃ (y ∈ K) (z ∈ Kᗮ), v = y + z := begin have h_mem : v ∈ K ⊔ Kᗮ := by simp [submodule.sup_orthogonal_of_complete_space], obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem, exact ⟨y, hy, z, hz, hyz.symm⟩ end /-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/ @[simp] lemma submodule.orthogonal_orthogonal [complete_space K] : Kᗮᗮ = K := begin ext v, split, { obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v, intros hv, have hz' : z = 0, { have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_sym], simpa [inner_add_right, hyz] using hv z hz }, simp [hy, hz'] }, { intros hv w hw, rw inner_eq_zero_sym, exact hw v hv } end lemma submodule.orthogonal_orthogonal_eq_closure [complete_space E] : Kᗮᗮ = K.topological_closure := begin refine le_antisymm _ _, { convert submodule.orthogonal_orthogonal_monotone K.submodule_topological_closure, haveI : complete_space K.topological_closure := K.is_closed_topological_closure.complete_space_coe, rw K.topological_closure.orthogonal_orthogonal }, { exact K.topological_closure_minimal K.le_orthogonal_orthogonal Kᗮ.is_closed_orthogonal } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_complete_space [complete_space K] : is_compl K Kᗮ := ⟨K.orthogonal_disjoint, le_of_eq submodule.sup_orthogonal_of_complete_space.symm⟩ @[simp] lemma submodule.orthogonal_eq_bot_iff [complete_space (K : set E)] : Kᗮ = ⊥ ↔ K = ⊤ := begin refine ⟨_, λ h, by rw [h, submodule.top_orthogonal_eq_bot] ⟩, intro h, have : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_complete_space, rwa [h, sup_comm, bot_sup_eq] at this, end /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal [complete_space K] {u v : E} (hv : v ∈ K) (hvo : u - v ∈ Kᗮ) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hv (λ w, inner_eq_zero_sym.mp ∘ (hvo w)) /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal' [complete_space K] {u v z : E} (hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_of_mem_orthogonal hv (by simpa [hu]) /-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero [complete_space K] {v : E} (hv : v ∈ Kᗮ) : orthogonal_projection K v = 0 := by { ext, convert eq_orthogonal_projection_of_mem_orthogonal _ _; simp [hv] } /-- The reflection in `K` of an element of `Kᗮ` is its negation. -/ lemma reflection_mem_subspace_orthogonal_complement_eq_neg [complete_space K] {v : E} (hv : v ∈ Kᗮ) : reflection K v = - v := by simp [reflection_apply, orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero hv] /-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero [complete_space E] {v : E} (hv : v ∈ K) : orthogonal_projection Kᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv) /-- If `U ≤ V`, then projecting on `V` and then on `U` is the same as projecting on `U`. -/ lemma orthogonal_projection_orthogonal_projection_of_le {U V : submodule 𝕜 E} [complete_space U] [complete_space V] (h : U ≤ V) (x : E) : orthogonal_projection U (orthogonal_projection V x) = orthogonal_projection U x := eq.symm $ by simpa only [sub_eq_zero, map_sub] using orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (submodule.orthogonal_le h (sub_orthogonal_projection_mem_orthogonal x)) /-- Given a monotone family `U` of complete submodules of `E` and a fixed `x : E`, the orthogonal projection of `x` on `U i` tends to the orthogonal projection of `x` on `(⨆ i, U i).topological_closure` along `at_top`. -/ lemma orthogonal_projection_tendsto_closure_supr [complete_space E] {ι : Type*} [semilattice_sup ι] (U : ι → submodule 𝕜 E) [∀ i, complete_space (U i)] (hU : monotone U) (x : E) : filter.tendsto (λ i, (orthogonal_projection (U i) x : E)) at_top (𝓝 (orthogonal_projection (⨆ i, U i).topological_closure x : E)) := begin casesI is_empty_or_nonempty ι, { rw filter_eq_bot_of_is_empty (at_top : filter ι), exact tendsto_bot }, let y := (orthogonal_projection (⨆ i, U i).topological_closure x : E), have proj_x : ∀ i, orthogonal_projection (U i) x = orthogonal_projection (U i) y := λ i, (orthogonal_projection_orthogonal_projection_of_le ((le_supr U i).trans (supr U).submodule_topological_closure) _).symm, suffices : ∀ ε > 0, ∃ I, ∀ i ≥ I, ∥(orthogonal_projection (U i) y : E) - y∥ < ε, { simpa only [proj_x, normed_add_comm_group.tendsto_at_top] using this }, intros ε hε, obtain ⟨a, ha, hay⟩ : ∃ a ∈ ⨆ i, U i, dist y a < ε, { have y_mem : y ∈ (⨆ i, U i).topological_closure := submodule.coe_mem _, rw [← set_like.mem_coe, submodule.topological_closure_coe, metric.mem_closure_iff] at y_mem, exact y_mem ε hε }, rw dist_eq_norm at hay, obtain ⟨I, hI⟩ : ∃ I, a ∈ U I, { rwa [submodule.mem_supr_of_directed _ (hU.directed_le)] at ha }, refine ⟨I, λ i (hi : I ≤ i), _⟩, rw [norm_sub_rev, orthogonal_projection_minimal], refine lt_of_le_of_lt _ hay, change _ ≤ ∥y - (⟨a, hU hi hI⟩ : U i)∥, exact cinfi_le ⟨0, set.forall_range_iff.mpr $ λ _, norm_nonneg _⟩ _, end /-- Given a monotone family `U` of complete submodules of `E` with dense span supremum, and a fixed `x : E`, the orthogonal projection of `x` on `U i` tends to `x` along `at_top`. -/ lemma orthogonal_projection_tendsto_self [complete_space E] {ι : Type*} [semilattice_sup ι] (U : ι → submodule 𝕜 E) [∀ t, complete_space (U t)] (hU : monotone U) (x : E) (hU' : ⊤ ≤ (⨆ t, U t).topological_closure) : filter.tendsto (λ t, (orthogonal_projection (U t) x : E)) at_top (𝓝 x) := begin rw ← eq_top_iff at hU', convert orthogonal_projection_tendsto_closure_supr U hU x, rw orthogonal_projection_eq_self_iff.mpr _, rw hU', trivial end /-- The orthogonal complement satisfies `Kᗮᗮᗮ = Kᗮ`. -/ lemma submodule.triorthogonal_eq_orthogonal [complete_space E] : Kᗮᗮᗮ = Kᗮ := begin rw Kᗮ.orthogonal_orthogonal_eq_closure, exact K.is_closed_orthogonal.submodule_topological_closure_eq, end /-- The closure of `K` is the full space iff `Kᗮ` is trivial. -/ lemma submodule.topological_closure_eq_top_iff [complete_space E] : K.topological_closure = ⊤ ↔ Kᗮ = ⊥ := begin rw ←submodule.orthogonal_orthogonal_eq_closure, split; intro h, { rw [←submodule.triorthogonal_eq_orthogonal, h, submodule.top_orthogonal_eq_bot] }, { rw [h, submodule.bot_orthogonal_eq_top] } end /-- The reflection in `Kᗮ` of an element of `K` is its negation. -/ lemma reflection_mem_subspace_orthogonal_precomplement_eq_neg [complete_space E] {v : E} (hv : v ∈ K) : reflection Kᗮ v = -v := reflection_mem_subspace_orthogonal_complement_eq_neg (K.le_orthogonal_orthogonal hv) /-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/ lemma orthogonal_projection_orthogonal_complement_singleton_eq_zero [complete_space E] (v : E) : orthogonal_projection (𝕜 ∙ v)ᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero (submodule.mem_span_singleton_self v) /-- The reflection in `(𝕜 ∙ v)ᗮ` of `v` is `-v`. -/ lemma reflection_orthogonal_complement_singleton_eq_neg [complete_space E] (v : E) : reflection (𝕜 ∙ v)ᗮ v = -v := reflection_mem_subspace_orthogonal_precomplement_eq_neg (submodule.mem_span_singleton_self v) lemma reflection_sub [complete_space F] {v w : F} (h : ∥v∥ = ∥w∥) : reflection (ℝ ∙ (v - w))ᗮ v = w := begin set R : F ≃ₗᵢ[ℝ] F := reflection (ℝ ∙ (v - w))ᗮ, suffices : R v + R v = w + w, { apply smul_right_injective F (by norm_num : (2:ℝ) ≠ 0), simpa [two_smul] using this }, have h₁ : R (v - w) = -(v - w) := reflection_orthogonal_complement_singleton_eq_neg (v - w), have h₂ : R (v + w) = v + w, { apply reflection_mem_subspace_eq_self, apply mem_orthogonal_singleton_of_inner_left, rw real_inner_add_sub_eq_zero_iff, exact h }, convert congr_arg2 (+) h₂ h₁ using 1, { simp }, { abel } end variables (K) /-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a complete submodule `K` and onto the orthogonal complement of `K`.-/ lemma eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] (w : E) : w = (orthogonal_projection K w : E) + (orthogonal_projection Kᗮ w : E) := begin obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w, convert hwyz, { exact eq_orthogonal_projection_of_mem_orthogonal' hy hz hwyz }, { rw add_comm at hwyz, refine eq_orthogonal_projection_of_mem_orthogonal' hz _ hwyz, simp [hy] } end /-- The Pythagorean theorem, for an orthogonal projection.-/ lemma norm_sq_eq_add_norm_sq_projection (x : E) (S : submodule 𝕜 E) [complete_space E] [complete_space S] : ∥x∥^2 = ∥orthogonal_projection S x∥^2 + ∥orthogonal_projection Sᗮ x∥^2 := begin let p1 := orthogonal_projection S, let p2 := orthogonal_projection Sᗮ, have x_decomp : x = p1 x + p2 x := eq_sum_orthogonal_projection_self_orthogonal_complement S x, have x_orth : ⟪ p1 x, p2 x ⟫ = 0 := submodule.inner_right_of_mem_orthogonal (set_like.coe_mem (p1 x)) (set_like.coe_mem (p2 x)), nth_rewrite 0 [x_decomp], simp only [sq, norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero ((p1 x) : E) (p2 x) x_orth, add_left_inj, mul_eq_mul_left_iff, norm_eq_zero, true_or, eq_self_iff_true, submodule.coe_norm, submodule.coe_eq_zero] end /-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal complement sum to the identity. -/ lemma id_eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] : continuous_linear_map.id 𝕜 E = K.subtypeL.comp (orthogonal_projection K) + Kᗮ.subtypeL.comp (orthogonal_projection Kᗮ) := by { ext w, exact eq_sum_orthogonal_projection_self_orthogonal_complement K w } /-- The orthogonal projection is self-adjoint. -/ lemma inner_orthogonal_projection_left_eq_right [complete_space E] [complete_space K] (u v : E) : ⟪↑(orthogonal_projection K u), v⟫ = ⟪u, orthogonal_projection K v⟫ := begin nth_rewrite 0 eq_sum_orthogonal_projection_self_orthogonal_complement K v, nth_rewrite 1 eq_sum_orthogonal_projection_self_orthogonal_complement K u, rw [inner_add_left, inner_add_right, submodule.inner_right_of_mem_orthogonal (submodule.coe_mem (orthogonal_projection K u)) (submodule.coe_mem (orthogonal_projection Kᗮ v)), submodule.inner_left_of_mem_orthogonal (submodule.coe_mem (orthogonal_projection K v)) (submodule.coe_mem (orthogonal_projection Kᗮ u))], end open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.finrank_add_inf_finrank_orthogonal {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) : finrank 𝕜 K₁ + finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = finrank 𝕜 K₂ := begin haveI := submodule.finite_dimensional_of_le h, haveI := proper_is_R_or_C 𝕜 K₁, have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁ᗮ ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, finrank_bot, submodule.sup_orthogonal_inf_of_complete_space h] at hd, rw add_zero at hd, exact hd.symm end /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.finrank_add_inf_finrank_orthogonal' {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : finrank 𝕜 K₁ + n = finrank 𝕜 K₂) : finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = n := by { rw ← add_right_inj (finrank 𝕜 K₁), simp [submodule.finrank_add_inf_finrank_orthogonal h, h_dim] } /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.finrank_add_finrank_orthogonal [finite_dimensional 𝕜 E] (K : submodule 𝕜 E) : finrank 𝕜 K + finrank 𝕜 Kᗮ = finrank 𝕜 E := begin convert submodule.finrank_add_inf_finrank_orthogonal (le_top : K ≤ ⊤) using 1, { rw inf_top_eq }, { simp } end /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.finrank_add_finrank_orthogonal' [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} {n : ℕ} (h_dim : finrank 𝕜 K + n = finrank 𝕜 E) : finrank 𝕜 Kᗮ = n := by { rw ← add_right_inj (finrank 𝕜 K), simp [submodule.finrank_add_finrank_orthogonal, h_dim] } local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ /-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the span of a nonzero vector is one less than the dimension of the space. -/ lemma finrank_orthogonal_span_singleton {n : ℕ} [_i : fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : finrank 𝕜 (𝕜 ∙ v)ᗮ = n := submodule.finrank_add_finrank_orthogonal' $ by simp [finrank_span_singleton hv, _i.elim, add_comm] /-- An element `φ` of the orthogonal group of `F` can be factored as a product of reflections, and specifically at most as many reflections as the dimension of the complement of the fixed subspace of `φ`. -/ lemma linear_isometry_equiv.reflections_generate_dim_aux [finite_dimensional ℝ F] {n : ℕ} (φ : F ≃ₗᵢ[ℝ] F) (hn : finrank ℝ (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).kerᗮ ≤ n) : ∃ l : list F, l.length ≤ n ∧ φ = (l.map (λ v, reflection (ℝ ∙ v)ᗮ)).prod := begin -- We prove this by strong induction on `n`, the dimension of the orthogonal complement of the -- fixed subspace of the endomorphism `φ` induction n with n IH generalizing φ, { -- Base case: `n = 0`, the fixed subspace is the whole space, so `φ = id` refine ⟨[], rfl.le, show φ = 1, from _⟩, have : (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).ker = ⊤, { rwa [nat.le_zero_iff, finrank_eq_zero, submodule.orthogonal_eq_bot_iff] at hn }, symmetry, ext x, have := linear_map.congr_fun (linear_map.ker_eq_top.mp this) x, rwa [continuous_linear_map.coe_sub, linear_map.zero_apply, linear_map.sub_apply, sub_eq_zero] at this }, { -- Inductive step. Let `W` be the fixed subspace of `φ`. We suppose its complement to have -- dimension at most n + 1. let W := (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).ker, have hW : ∀ w ∈ W, φ w = w := λ w hw, (sub_eq_zero.mp hw).symm, by_cases hn' : finrank ℝ Wᗮ ≤ n, { obtain ⟨V, hV₁, hV₂⟩ := IH φ hn', exact ⟨V, hV₁.trans n.le_succ, hV₂⟩ }, -- Take a nonzero element `v` of the orthogonal complement of `W`. haveI : nontrivial Wᗮ := nontrivial_of_finrank_pos (by linarith [zero_le n] : 0 < finrank ℝ Wᗮ), obtain ⟨v, hv⟩ := exists_ne (0 : Wᗮ), have hφv : φ v ∈ Wᗮ, { intros w hw, rw [← hW w hw, linear_isometry_equiv.inner_map_map], exact v.prop w hw }, have hv' : (v:F) ∉ W, { intros h, exact hv ((submodule.mem_left_iff_eq_zero_of_disjoint W.orthogonal_disjoint).mp h) }, -- Let `ρ` be the reflection in `v - φ v`; this is designed to swap `v` and `φ v` let x : F := v - φ v, let ρ := reflection (ℝ ∙ x)ᗮ, -- Notation: Let `V` be the fixed subspace of `φ.trans ρ` let V := (continuous_linear_map.id ℝ F - (φ.trans ρ).to_continuous_linear_equiv).ker, have hV : ∀ w, ρ (φ w) = w → w ∈ V, { intros w hw, change w - ρ (φ w) = 0, rw [sub_eq_zero, hw] }, -- Everything fixed by `φ` is fixed by `φ.trans ρ` have H₂V : W ≤ V, { intros w hw, apply hV, rw hW w hw, refine reflection_mem_subspace_eq_self _, apply mem_orthogonal_singleton_of_inner_left, exact submodule.sub_mem _ v.prop hφv _ hw }, -- `v` is also fixed by `φ.trans ρ` have H₁V : (v : F) ∈ V, { apply hV, have : ρ v = φ v := reflection_sub (φ.norm_map v).symm, rw ←this, exact reflection_reflection _ _, }, -- By dimension-counting, the complement of the fixed subspace of `φ.trans ρ` has dimension at -- most `n` have : finrank ℝ Vᗮ ≤ n, { change finrank ℝ Wᗮ ≤ n + 1 at hn, have : finrank ℝ W + 1 ≤ finrank ℝ V := submodule.finrank_lt_finrank_of_lt (set_like.lt_iff_le_and_exists.2 ⟨H₂V, v, H₁V, hv'⟩), have : finrank ℝ V + finrank ℝ Vᗮ = finrank ℝ F := V.finrank_add_finrank_orthogonal, have : finrank ℝ W + finrank ℝ Wᗮ = finrank ℝ F := W.finrank_add_finrank_orthogonal, linarith }, -- So apply the inductive hypothesis to `φ.trans ρ` obtain ⟨l, hl, hφl⟩ := IH (ρ * φ) this, -- Prepend `ρ` to the factorization into reflections obtained for `φ.trans ρ`; this gives a -- factorization into reflections for `φ`. refine ⟨x :: l, nat.succ_le_succ hl, _⟩, rw [list.map_cons, list.prod_cons], have := congr_arg ((*) ρ) hφl, rwa [←mul_assoc, reflection_mul_reflection, one_mul] at this, } end /-- The orthogonal group of `F` is generated by reflections; specifically each element `φ` of the orthogonal group is a product of at most as many reflections as the dimension of `F`. Special case of the **Cartan–Dieudonné theorem**. -/ lemma linear_isometry_equiv.reflections_generate_dim [finite_dimensional ℝ F] (φ : F ≃ₗᵢ[ℝ] F) : ∃ l : list F, l.length ≤ finrank ℝ F ∧ φ = (l.map (λ v, reflection (ℝ ∙ v)ᗮ)).prod := let ⟨l, hl₁, hl₂⟩ := φ.reflections_generate_dim_aux le_rfl in ⟨l, hl₁.trans (submodule.finrank_le _), hl₂⟩ /-- The orthogonal group of `F` is generated by reflections. -/ lemma linear_isometry_equiv.reflections_generate [finite_dimensional ℝ F] : subgroup.closure (set.range (λ v : F, reflection (ℝ ∙ v)ᗮ)) = ⊤ := begin rw subgroup.eq_top_iff', intros φ, rcases φ.reflections_generate_dim with ⟨l, _, rfl⟩, apply (subgroup.closure _).list_prod_mem, intros x hx, rcases list.mem_map.mp hx with ⟨a, _, hax⟩, exact subgroup.subset_closure ⟨a, hax⟩, end end orthogonal section orthogonal_family variables {ι : Type*} /-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is, they provide an internal direct sum decomposition of `E`) if and only if their span has trivial orthogonal complement. -/ lemma orthogonal_family.is_internal_iff_of_is_complete [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) (hc : is_complete (↑(supr V) : set E)) : direct_sum.is_internal V ↔ (supr V)ᗮ = ⊥ := begin haveI : complete_space ↥(supr V) := hc.complete_space_coe, simp only [direct_sum.is_internal_submodule_iff_independent_and_supr_eq_top, hV.independent, true_and, submodule.orthogonal_eq_bot_iff] end /-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is, they provide an internal direct sum decomposition of `E`) if and only if their span has trivial orthogonal complement. -/ lemma orthogonal_family.is_internal_iff [decidable_eq ι] [finite_dimensional 𝕜 E] {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) : direct_sum.is_internal V ↔ (supr V)ᗮ = ⊥ := begin haveI h := finite_dimensional.proper_is_R_or_C 𝕜 ↥(supr V), exact hV.is_internal_iff_of_is_complete (complete_space_coe_iff_is_complete.mp infer_instance) end end orthogonal_family section orthonormal_basis variables {𝕜 E} {v : set E} open finite_dimensional submodule set /-- An orthonormal set in an `inner_product_space` is maximal, if and only if the orthogonal complement of its span is empty. -/ lemma maximal_orthonormal_iff_orthogonal_complement_eq_bot (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v)ᗮ = ⊥ := begin rw submodule.eq_bot_iff, split, { contrapose!, -- ** direction 1: nonempty orthogonal complement implies nonmaximal rintros ⟨x, hx', hx⟩, -- take a nonzero vector and normalize it let e := (∥x∥⁻¹ : 𝕜) • x, have he : ∥e∥ = 1 := by simp [e, norm_smul_inv_norm hx], have he' : e ∈ (span 𝕜 v)ᗮ := smul_mem' _ _ hx', have he'' : e ∉ v, { intros hev, have : e = 0, { have : e ∈ (span 𝕜 v) ⊓ (span 𝕜 v)ᗮ := ⟨subset_span hev, he'⟩, simpa [(span 𝕜 v).inf_orthogonal_eq_bot] using this }, have : e ≠ 0 := hv.ne_zero ⟨e, hev⟩, contradiction }, -- put this together with `v` to provide a candidate orthonormal basis for the whole space refine ⟨insert e v, v.subset_insert e, ⟨_, _⟩, (v.ne_insert_of_not_mem he'').symm⟩, { -- show that the elements of `insert e v` have unit length rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { simp [ha, he] }, { exact hv.1 ⟨a, ha⟩ } }, { -- show that the elements of `insert e v` are orthogonal have h_end : ∀ a ∈ v, ⟪a, e⟫ = 0, { intros a ha, exact he' a (submodule.subset_span ha) }, rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { rintros ⟨b, hb'⟩ hab', have hb : b ∈ v, { refine mem_of_mem_insert_of_ne hb' _, intros hbe', apply hab', simp [ha, hbe'] }, rw inner_eq_zero_sym, simpa [ha] using h_end b hb }, rintros ⟨b, hb'⟩ hab', cases eq_or_mem_of_mem_insert hb' with hb hb, { simpa [hb] using h_end a ha }, have : (⟨a, ha⟩ : v) ≠ ⟨b, hb⟩, { intros hab'', apply hab', simpa using hab'' }, exact hv.2 this } }, { -- ** direction 2: empty orthogonal complement implies maximal simp only [subset.antisymm_iff], rintros h u (huv : v ⊆ u) hu, refine ⟨_, huv⟩, intros x hxu, refine ((mt (h x)) (hu.ne_zero ⟨x, hxu⟩)).imp_symm _, intros hxv y hy, have hxv' : (⟨x, hxu⟩ : u) ∉ (coe ⁻¹' v : set u) := by simp [huv, hxv], obtain ⟨l, hl, rfl⟩ : ∃ l ∈ finsupp.supported 𝕜 𝕜 (coe ⁻¹' v : set u), (finsupp.total ↥u E 𝕜 coe) l = y, { rw ← finsupp.mem_span_image_iff_total, simp [huv, inter_eq_self_of_subset_left, hy] }, exact hu.inner_finsupp_eq_zero hxv' hl } end variables [finite_dimensional 𝕜 E] /-- An orthonormal set in a finite-dimensional `inner_product_space` is maximal, if and only if it is a basis. -/ lemma maximal_orthonormal_iff_basis_of_finite_dimensional (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ ∃ b : basis v 𝕜 E, ⇑b = coe := begin haveI := proper_is_R_or_C 𝕜 (span 𝕜 v), rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hv, have hv_compl : is_complete (span 𝕜 v : set E) := (span 𝕜 v).complete_of_finite_dimensional, rw submodule.orthogonal_eq_bot_iff, have hv_coe : range (coe : v → E) = v := by simp, split, { refine λ h, ⟨basis.mk hv.linear_independent _, basis.coe_mk _ _⟩, convert h.ge }, { rintros ⟨h, coe_h⟩, rw [← h.span_eq, coe_h, hv_coe] } end end orthonormal_basis
5b551bd8ebb2c67bf59896bf4969f0d3f6b032f6
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/equiv/ring.lean
80c9da149066cc0fcca9776dd89dd6d90ae59ca1
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
10,304
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, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add import algebra.field import algebra.opposites /-! # (Semi)ring equivs In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the corresponding group of automorphisms `ring_aut`. ## Notations The extended equiv have coercions to functions, and the coercion is the canonical notation when treating the isomorphism as maps. ## Implementation notes The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut -/ variables {R : Type*} {S : Type*} {S' : Type*} set_option old_structure_cmd true /- (semi)ring equivalence. -/ structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S] extends R ≃ S, R ≃* S, R ≃+ S infix ` ≃+* `:25 := ring_equiv namespace ring_equiv section basic variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S'] instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe_fun (f : R ≃+* S) : f.to_fun = f := rfl instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩ instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩ @[norm_cast] lemma coe_mul_equiv (f : R ≃+* S) (a : R) : (f : R ≃* S) a = f a := rfl @[norm_cast] lemma coe_add_equiv (f : R ≃+* S) (a : R) : (f : R ≃+ S) a = f a := rfl variable (R) /-- The identity map is a ring isomorphism. -/ @[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R } @[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl @[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl @[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl variables {R} /-- The inverse of a ring isomorphism is a ring isomorphism. -/ @[symm] protected def symm (e : R ≃+* S) : S ≃+* R := { .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm } /-- Transitivity of `ring_equiv`. -/ @[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' := { .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) } protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective @[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end basic section comm_semiring open opposite variables (R) [comm_semiring R] /-- A commutative ring is isomorphic to its opposite. -/ def to_opposite : R ≃+* Rᵒᵖ := { map_add' := λ x y, rfl, map_mul' := λ x y, mul_comm (op y) (op x), ..equiv_to_opposite } @[simp] lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl @[simp] lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl end comm_semiring section semiring variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism preserves multiplication. -/ @[simp] lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y /-- A ring isomorphism sends one to one. -/ @[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one /-- A ring isomorphism preserves addition. -/ @[simp] lemma map_add : f (x + y) = f x + f y := f.map_add' x y /-- A ring isomorphism sends zero to zero. -/ @[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero variable {x} @[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff @[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff /-- Produce a ring isomorphism from a bijective ring homomorphism. -/ noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S := { .. equiv.of_bijective f hf, .. f } end semiring section variables [ring R] [ring S] (f : R ≃+* S) (x y : R) @[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x @[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y @[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1 end section semiring_hom variables [semiring R] [semiring S] [semiring S'] /-- Reinterpret a ring equivalence as a ring homomorphism. -/ def to_ring_hom (e : R ≃+* S) : R →+* S := { .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom } instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩ @[norm_cast] lemma coe_ring_hom (f : R ≃+* S) (a : R) : (f : R →+* S) a = f a := rfl /-- Reinterpret a ring equivalence as a monoid homomorphism. -/ abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom /-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/ abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom @[simp] lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl @[simp] lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl @[simp] lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl @[simp] lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) : ∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y := e.to_equiv.apply_symm_apply @[simp] lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) : ∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x := equiv.symm_apply_apply (e.to_equiv) @[simp] lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : (e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl end semiring_hom end ring_equiv namespace mul_equiv /-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/ def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S] (h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S := {..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H } end mul_equiv namespace ring_equiv variables [has_add R] [has_add S] [has_mul R] [has_mul S] /-- Two ring isomorphisms agree if they are defined by the same underlying function. -/ @[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end @[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3 @[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4 /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B] (hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A := { mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa, eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy, have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero], (hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx) (λ hy, by simpa using congr_arg e.symm hy), exists_pair_ne := ⟨e.symm 0, e.symm 1, by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ } /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B] (e : A ≃+* B) : integral_domain A := { .. (‹_› : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) } end ring_equiv /-- The group of ring automorphisms. -/ @[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R namespace ring_aut variables (R) [has_mul R] [has_add R] /-- The group operation on automorphisms of a ring is defined by λ g h, ring_equiv.trans h g. This means that multiplication agrees with composition, (g*h)(x) = g (h x) . -/ instance : group (ring_aut R) := by refine_struct { mul := λ g h, ring_equiv.trans h g, one := ring_equiv.refl R, inv := ring_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (ring_aut R) := ⟨1⟩ /-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/ def to_add_aut : ring_aut R →* add_aut R := by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/ def to_mul_aut : ring_aut R →* mul_aut R := by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to permutations. -/ def to_perm : ring_aut R →* equiv.perm R := by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl end ring_aut namespace equiv variables (K : Type*) [division_ring K] def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} := ⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ variable {K} @[simp] lemma coe_units_equiv_ne_zero (a : units K) : ((units_equiv_ne_zero K a) : K) = a := rfl end equiv
062aa6a9014e63a19b649d1e1759076e24cd3c04
626e312b5c1cb2d88fca108f5933076012633192
/src/group_theory/quotient_group.lean
0a7257e2573d7ecd69b8d0766b9c55699b0fb218
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,401
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`. * `quotient_group.quotient_quotient_equiv_quotient`: Noether's third isomorphism theorem, the canonical isomorphism between `(G / M) / (M / N)` and `G / N`, where `N ≤ M`. ## Tags isomorphism theorems, quotient groups -/ 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) @[to_additive, simp] lemma coe_mk' : (mk' N : G → quotient N) = coe := rfl @[to_additive, simp] lemma mk'_apply (x : G) : mk' N x = x := rfl /-- Two `monoid_hom`s from a quotient group are equal if their compositions with `quotient_group.mk'` are equal. See note [partially-applied ext lemmas]. -/ @[to_additive /-" Two `add_monoid_hom`s from an additive quotient group are equal if their compositions with `add_quotient_group.mk'` are equal. See note [partially-applied ext lemmas]. "-/, ext] lemma monoid_hom_ext ⦃f g : quotient N →* H⦄ (h : f.comp (mk' N) = g.comp (mk' N)) : f = g := monoid_hom.ext $ λ x, quotient_group.induction_on x $ (monoid_hom.congr_fun h : _) attribute [ext] quotient_add_group.add_monoid_hom_ext @[simp, to_additive quotient_add_group.eq_zero_iff] lemma eq_one_iff {N : subgroup G} [nN : N.normal] (x : G) : (x : quotient N) = 1 ↔ x ∈ N := begin refine quotient_group.eq.trans _, rw [mul_one, subgroup.inv_mem_iff], end @[simp, to_additive quotient_add_group.ker_mk] lemma ker_mk : monoid_hom.ker (quotient_group.mk' N : G →* quotient_group.quotient N) = N := subgroup.ext eq_one_iff @[to_additive quotient_add_group.eq_iff_sub_mem] lemma eq_iff_div_mem {N : subgroup G} [nN : N.normal] {x y : G} : (x : quotient N) = y ↔ x / y ∈ N := begin refine eq_comm.trans (quotient_group.eq.trans _), rw [nN.mem_comm_iff, div_eq_mul_inv] 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)) : (φ.map_mul a (a⁻¹ * b)).symm ... = φ b : by rw mul_inv_cancel_left)) (λ q r, quotient.induction_on₂' q r $ φ.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 @[simp, to_additive quotient_add_group.map_coe] lemma map_coe (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) (x : G) : map N M f h ↑x = ↑(f x) := lift_mk' _ _ x @[to_additive quotient_add_group.map_mk'] lemma map_mk' (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) (x : G) : map N M f h (mk' _ x) = ↑(f x) := quotient_group.lift_mk' _ _ x 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, φ.map_mul, ← h, φ.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 /-- **Noether's 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 homomorphism `φ : G →* H` with a right inverse `ψ : H → G`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_right_inverse "The canonical isomorphism `G/(ker φ) ≃+ H` induced by a homomorphism `φ : G →+ H` with a right inverse `ψ : H → G`.", simps] def quotient_ker_equiv_of_right_inverse (ψ : H → G) (hφ : function.right_inverse ψ φ) : quotient (ker φ) ≃* H := { to_fun := ker_lift φ, inv_fun := mk ∘ ψ, left_inv := λ x, ker_lift_injective φ (by rw [function.comp_app, ker_lift_mk', hφ]), right_inv := hφ, .. ker_lift φ } /-- The canonical isomorphism `G/(ker φ) ≃* H` induced by a surjection `φ : G →* H`. For a `computable` version, see `quotient_group.quotient_ker_equiv_of_right_inverse`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_surjective "The canonical isomorphism `G/(ker φ) ≃+ H` induced by a surjection `φ : G →+ H`. For a `computable` version, see `quotient_add_group.quotient_ker_equiv_of_right_inverse`."] noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) : quotient (ker φ) ≃* H := quotient_ker_equiv_of_right_inverse φ _ hφ.has_right_inverse.some_spec /-- 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 } @[simp, to_additive] lemma equiv_quotient_of_eq_mk {M N : subgroup G} [M.normal] [N.normal] (h : M = N) (x : G) : quotient_group.equiv_quotient_of_eq h (quotient_group.mk x) = (quotient_group.mk x) := rfl /-- Let `A', A, B', B` be subgroups of `G`. If `A' ≤ B'` and `A ≤ B`, then there is a map `A / (A' ⊓ A) →* B / (B' ⊓ B)` induced by the inclusions. -/ @[to_additive "Let `A', A, B', B` be subgroups of `G`. If `A' ≤ B'` and `A ≤ B`, then there is a map `A / (A' ⊓ A) →+ B / (B' ⊓ B)` induced by the inclusions."] def quotient_map_subgroup_of_of_le {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' ≤ B') (h : A ≤ B) : quotient (A'.subgroup_of A) →* quotient (B'.subgroup_of B) := map _ _ (subgroup.inclusion h) $ by simp [subgroup.subgroup_of, subgroup.comap_comap]; exact subgroup.comap_mono h' @[simp, to_additive] lemma quotient_map_subgroup_of_of_le_coe {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' ≤ B') (h : A ≤ B) (x : A) : quotient_map_subgroup_of_of_le h' h x = ↑(subgroup.inclusion h x : B) := rfl /-- Let `A', A, B', B` be subgroups of `G`. If `A' = B'` and `A = B`, then the quotients `A / (A' ⊓ A)` and `B / (B' ⊓ B)` are isomorphic. Applying this equiv is nicer than rewriting along the equalities, since the type of `(A'.subgroup_of A : subgroup A)` depends on on `A`. -/ @[to_additive "Let `A', A, B', B` be subgroups of `G`. If `A' = B'` and `A = B`, then the quotients `A / (A' ⊓ A)` and `B / (B' ⊓ B)` are isomorphic. Applying this equiv is nicer than rewriting along the equalities, since the type of `(A'.add_subgroup_of A : add_subgroup A)` depends on on `A`. "] def equiv_quotient_subgroup_of_of_eq {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' = B') (h : A = B) : quotient (A'.subgroup_of A) ≃* quotient (B'.subgroup_of B) := monoid_hom.to_mul_equiv (quotient_map_subgroup_of_of_le h'.le h.le) (quotient_map_subgroup_of_of_le h'.ge h.ge) (by { ext ⟨x, hx⟩, refl }) (by { ext ⟨x, hx⟩, refl }) section snd_isomorphism_thm open subgroup /-- **Noether's 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 section third_iso_thm variables (M : subgroup G) [nM : M.normal] include nM nN @[to_additive quotient_add_group.map_normal] instance map_normal : (M.map (quotient_group.mk' N)).normal := { conj_mem := begin rintro _ ⟨x, hx, rfl⟩ y, refine induction_on' y (λ y, ⟨y * x * y⁻¹, subgroup.normal.conj_mem nM x hx y, _⟩), simp only [mk'_apply, coe_mul, coe_inv] end } variables (h : N ≤ M) /-- The map from the third isomorphism theorem for groups: `(G / N) / (M / N) → G / M`. -/ @[to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux "The map from the third isomorphism theorem for additive groups: `(A / N) / (M / N) → A / M`."] def quotient_quotient_equiv_quotient_aux : quotient (M.map (mk' N)) →* quotient M := lift (M.map (mk' N)) (map N M (monoid_hom.id G) h) (by { rintro _ ⟨x, hx, rfl⟩, rw map_mk' N M _ _ x, exact (quotient_group.eq_one_iff _).mpr hx }) @[simp, to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux_coe] lemma quotient_quotient_equiv_quotient_aux_coe (x : quotient_group.quotient N) : quotient_quotient_equiv_quotient_aux N M h x = quotient_group.map N M (monoid_hom.id G) h x := quotient_group.lift_mk' _ _ x @[to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux_coe_coe] lemma quotient_quotient_equiv_quotient_aux_coe_coe (x : G) : quotient_quotient_equiv_quotient_aux N M h (x : quotient_group.quotient N) = x := quotient_group.lift_mk' _ _ x /-- **Noether's third isomorphism theorem** for groups: `(G / N) / (M / N) ≃ G / M`. -/ @[to_additive quotient_add_group.quotient_quotient_equiv_quotient "**Noether's third isomorphism theorem** for additive groups: `(A / N) / (M / N) ≃ A / M`."] def quotient_quotient_equiv_quotient : quotient_group.quotient (M.map (quotient_group.mk' N)) ≃* quotient_group.quotient M := monoid_hom.to_mul_equiv (quotient_quotient_equiv_quotient_aux N M h) (quotient_group.map _ _ (quotient_group.mk' N) (subgroup.le_comap_map _ _)) (by { ext, simp }) (by { ext, simp }) end third_iso_thm end quotient_group
d2c3608b98841b4c044fef50b6a61d4fd7fea190
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/meta/rb_map.lean
aeb9c231188396f6f352511ac5b353c6502cba99
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
7,893
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, Jeremy Avigad -/ prelude import init.data.ordering.basic init.function init.meta.name init.meta.format init.control.monad open format private meta def format_key {key} [has_to_format key] (k : key) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt k namespace native meta constant {u₁ u₂} rb_map : Type u₁ → Type u₂ → Type (max u₁ u₂) namespace rb_map meta constant mk_core {key : Type} (data : Type) : (key → key → ordering) → rb_map key data meta constant size {key : Type} {data : Type} : rb_map key data → nat meta constant empty {key : Type} {data : Type} : rb_map key data → bool meta constant insert {key : Type} {data : Type} : rb_map key data → key → data → rb_map key data meta constant erase {key : Type} {data : Type} : rb_map key data → key → rb_map key data meta constant contains {key : Type} {data : Type} : rb_map key data → key → bool meta constant find {key : Type} {data : Type} : rb_map key data → key → option data meta constant min {key : Type} {data : Type} : rb_map key data → option data meta constant max {key : Type} {data : Type} : rb_map key data → option data meta constant fold {key : Type} {data : Type} {α :Type} : rb_map key data → α → (key → data → α → α) → α attribute [inline] meta def mk (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : rb_map key data := mk_core data cmp open list section variables {key data : Type} meta def keys (m : rb_map key data) : list key := fold m [] (λk v ks, k :: ks) meta def values {key : Type} {data : Type} (m : rb_map key data) : list data := fold m [] (λk v vs, v :: vs) meta def to_list {key : Type} {data : Type} (m : rb_map key data) : list (key × data) := fold m [] (λk v res, (k, v) :: res) meta def mfold {key data α :Type} {m : Type → Type} [monad m] (mp : rb_map key data) (a : α) (fn : key → data → α → m α) : m α := mp.fold (return a) (λ k d act, act >>= fn k d) end section variables {key data data' : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] meta def of_list : list (key × data) → rb_map key data | [] := mk key data | ((k, v)::ls) := insert (of_list ls) k v meta def set_of_list : list key → rb_map key unit | [] := mk _ _ | (x::xs) := insert (set_of_list xs) x () meta def map (f : data → data') (m : rb_map key data) : rb_map key data' := fold m (mk _ _) (λk v res, insert res k (f v)) meta def for (m : rb_map key data) (f : data → data') : rb_map key data' := map f m meta def filter (m : rb_map key data) (f : data → Prop) [decidable_pred f] := fold m (mk _ _) $ λa b m', if f b then insert m' a b else m' end end rb_map meta def mk_rb_map {key data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : rb_map key data := rb_map.mk key data @[reducible] meta def nat_map (data : Type) := rb_map nat data namespace nat_map export rb_map (hiding mk) meta def mk (data : Type) : nat_map data := rb_map.mk nat data end nat_map meta def mk_nat_map {data : Type} : nat_map data := nat_map.mk data open rb_map prod section variables {key : Type} {data : Type} [has_to_format key] [has_to_format data] private meta def format_key_data (k : key) (d : data) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt k ++ space ++ to_fmt "←" ++ space ++ to_fmt d meta instance : has_to_format (rb_map key data) := ⟨λ m, group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ k d p, (fst p ++ format_key_data k d (snd p), ff)))) ++ to_fmt "⟩"⟩ end section variables {key : Type} {data : Type} [has_to_string key] [has_to_string data] private meta def key_data_to_string (k : key) (d : data) (first : bool) : string := (if first then "" else ", ") ++ to_string k ++ " ← " ++ to_string d meta instance : has_to_string (rb_map key data) := ⟨λ m, "⟨" ++ (fst (fold m ("", tt) (λ k d p, (fst p ++ key_data_to_string k d (snd p), ff)))) ++ "⟩"⟩ end /-- a variant of rb_maps that stores a list of elements for each key. `find` returns the list of elements in the opposite order that they were inserted. -/ meta def rb_lmap (key : Type) (data : Type) : Type := rb_map key (list data) namespace rb_lmap protected meta def mk (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : rb_lmap key data := rb_map.mk key (list data) meta def insert {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) (d : data) : rb_lmap key data := match (rb_map.find rbl k) with | none := rb_map.insert rbl k [d] | (some l) := rb_map.insert (rb_map.erase rbl k) k (d :: l) end meta def erase {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : rb_lmap key data := rb_map.erase rbl k meta def contains {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : bool := rb_map.contains rbl k meta def find {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : list data := match (rb_map.find rbl k) with | none := [] | (some l) := l end end rb_lmap meta def rb_set (key) := rb_map key unit meta def mk_rb_set {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : rb_set key := mk_rb_map namespace rb_set meta def insert {key} (s : rb_set key) (k : key) : rb_set key := rb_map.insert s k () meta def erase {key} (s : rb_set key) (k : key) : rb_set key := rb_map.erase s k meta def contains {key} (s : rb_set key) (k : key) : bool := rb_map.contains s k meta def size {key} (s : rb_set key) : nat := rb_map.size s meta def empty {key : Type} (s : rb_set key) : bool := rb_map.empty s meta def fold {key α : Type} (s : rb_set key) (a : α) (fn : key → α → α) : α := rb_map.fold s a (λ k _ a, fn k a) meta def mfold {key α :Type} {m : Type → Type} [monad m] (s : rb_set key) (a : α) (fn : key → α → m α) : m α := s.fold (return a) (λ k act, act >>= fn k) meta def to_list {key : Type} (s : rb_set key) : list key := s.fold [] list.cons meta instance {key} [has_to_format key] : has_to_format (rb_set key) := ⟨λ m, group $ to_fmt "{" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ k p, (fst p ++ format_key k (snd p), ff)))) ++ to_fmt "}"⟩ end rb_set end native open native @[reducible] meta def name_map (data : Type) := rb_map name data namespace name_map export native.rb_map (hiding mk) meta def mk (data : Type) : name_map data := rb_map.mk_core data name.cmp end name_map meta def mk_name_map {data : Type} : name_map data := name_map.mk data /-- An rb_map of `name`s. -/ meta constant name_set : Type meta constant mk_name_set : name_set namespace name_set meta constant insert : name_set → name → name_set meta constant erase : name_set → name → name_set meta constant contains : name_set → name → bool meta constant size : name_set → nat meta constant empty : name_set → bool meta constant fold {α :Type} : name_set → α → (name → α → α) → α meta def union (l r : name_set) : name_set := r.fold l (λ ns n, name_set.insert n ns) meta def to_list (s : name_set) : list name := s.fold [] list.cons meta instance : has_to_format name_set := ⟨λ m, group $ to_fmt "{" ++ nest 1 (fold m (to_fmt "", tt) (λ k p, (p.1 ++ format_key k p.2, ff))).1 ++ to_fmt "}"⟩ meta def of_list (l : list name) : name_set := list.foldl name_set.insert mk_name_set l meta def mfold {α :Type} {m : Type → Type} [monad m] (ns : name_set) (a : α) (fn : name → α → m α) : m α := ns.fold (return a) (λ k act, act >>= fn k) end name_set
eca5f9c9ec0698de3944b98ea995035b92ecc829
d1bbf1801b3dcb214451d48214589f511061da63
/src/analysis/calculus/deriv.lean
ecd28840db6ebeefff65ca57f8ede0a5b95e3615
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
73,984
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv import data.polynomial.derivative /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - sum of finitely many functions - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space big_operators filter open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝[s] x) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_strict_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L := has_fderiv_at_filter_iff_has_deriv_at_filter.mp /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := has_fderiv_at_filter_iff_has_deriv_at_filter /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x := has_fderiv_within_at_iff_has_deriv_within_at.mp lemma has_deriv_within_at.has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := has_deriv_within_at_iff_has_fderiv_within_at.mp /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := has_fderiv_at_filter_iff_has_deriv_at_filter lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x → has_deriv_at f (f' 1) x := has_fderiv_at_iff_has_deriv_at.mp lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x := by simp [has_strict_deriv_at, has_strict_fderiv_at] protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x := has_strict_fderiv_at_iff_has_strict_deriv_at.mp /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) : has_deriv_at f f' x := h.has_fderiv_at /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right, simp only [(∘)], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s \ {x}] x) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s] x) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[{x}ᶜ] x) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope @[simp] lemma has_deriv_within_at_diff_singleton : has_deriv_within_at f f' (s \ {x}) x ↔ has_deriv_within_at f f' s x := by simp only [has_deriv_within_at_iff_tendsto_slope, sdiff_idem_right] @[simp] lemma has_deriv_within_at_Ioi_iff_Ici [partial_order 𝕜] : has_deriv_within_at f f' (Ioi x) x ↔ has_deriv_within_at f f' (Ici x) x := by rw [← Ici_diff_left, has_deriv_within_at_diff_singleton] alias has_deriv_within_at_Ioi_iff_Ici ↔ has_deriv_within_at.Ici_of_Ioi has_deriv_within_at.Ioi_of_Ici @[simp] lemma has_deriv_within_at_Iio_iff_Iic [partial_order 𝕜] : has_deriv_within_at f f' (Iio x) x ↔ has_deriv_within_at f f' (Iic x) x := by rw [← Iic_diff_right, has_deriv_within_at_diff_singleton] alias has_deriv_within_at_Iio_iff_Iic ↔ has_deriv_within_at.Iic_of_Iio has_deriv_within_at.Iio_of_Iic theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) : deriv_within f s x = deriv f x := by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl } section congr /-! ### Congruence properties of derivatives -/ theorem filter.eventually_eq.has_deriv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := h₀.has_fderiv_at_filter_iff hx (by simp [h₁]) lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa hL.has_deriv_at_filter_iff hx rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x := h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx) lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw hL.fderiv_within_eq hs hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x := by { unfold deriv, rwa filter.eventually_eq.fderiv_eq } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (has_fderiv_at_filter_id x L).has_deriv_at_filter theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x := (has_strict_fderiv_at_id x).has_strict_deriv_at lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 := deriv_id x lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := (has_deriv_within_at_id x s).deriv_within hxs end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (has_fderiv_at_filter_const c x L).has_deriv_at_filter theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x := (has_strict_fderiv_at_const c x).has_strict_deriv_at theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := (has_deriv_within_at_const _ _ _).deriv_within hxs end const section continuous_linear_map /-! ### Derivative of continuous linear maps -/ variables (e : 𝕜 →L[𝕜] F) lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.has_fderiv_at_filter.has_deriv_at_filter lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.has_strict_fderiv_at.has_strict_deriv_at lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma continuous_linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end continuous_linear_map section linear_map /-! ### Derivative of bundled linear maps -/ variables (e : 𝕜 →ₗ[𝕜] F) lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.to_continuous_linear_map₁.has_deriv_at_filter lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.to_continuous_linear_map₁.has_strict_deriv_at lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_add_const hxs] lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x := by simp only [deriv, fderiv_add_const] theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c + f y) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_const_add hxs] lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x := by simp only [deriv, fderiv_const_add] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F} theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) : has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) : has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) : has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_deriv_at_filter.sum h theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) : has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_deriv_at_filter.sum h lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x := (has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs @[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x := (has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv end sum section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply] lemma deriv.neg : deriv (λy, -f y) x = - deriv f x := by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply] @[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv.neg end neg section neg2 /-! ### Derivative of the negation function (i.e `has_neg.neg`) -/ variables (s x L) theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L := has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _ theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x := has_deriv_at_filter_neg _ _ theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x := has_strict_deriv_at.neg $ has_strict_deriv_at_id _ lemma deriv_neg : deriv has_neg.neg x = -1 := has_deriv_at.deriv (has_deriv_at_neg x) @[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 := funext deriv_neg @[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 := deriv_neg x lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 := (has_deriv_within_at_neg x s).deriv_within hxs lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) := differentiable.neg differentiable_id lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s := differentiable_on.neg differentiable_on_id end neg2 section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_sub_const hxs] lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x := by simp only [deriv, fderiv_sub_const] theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c - f y) s x = -deriv_within f s x := by simp [deriv_within, fderiv_within_const_sub hxs] lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x := by simp only [← deriv_within_univ, deriv_within_const_sub unique_diff_within_at_univ] end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := h.tendsto_nhds hL theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := by simpa using (hg.comp x hh).has_deriv_at_filter theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg $ hh.continuous_within_at.tendsto_nhds_within hst) hh /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_strict_deriv_at.scomp (hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (g ∘ h) (h' • g') x := by simpa using (hg.comp x hh).has_strict_deriv_at theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of a scalar and vector functions -/ theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) {L : filter E} (hh₁ : has_deriv_at_filter h₁ h₁' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (h₁ ∘ f) (h₁' • f') x L := by { convert has_fderiv_at_filter.comp x hh₁ hf, ext x, simp [mul_comm] } theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) (hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (h₁ ∘ f) (h₁' • f') x := (hh₁.mono hf.continuous_at).comp_has_fderiv_at_filter x hf theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s} (x) (hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x := (hh₁.mono hf.continuous_within_at).comp_has_fderiv_at_filter x hf theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s t} (x) (hh₁ : has_deriv_within_at h₁ h₁' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : maps_to f s t) : has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x := (has_deriv_at_filter.mono hh₁ $ hf.continuous_within_at.tendsto_nhds_within hst).comp_has_fderiv_at_filter x hf /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_strict_deriv_at.comp (hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) : has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_deriv_at_filter (f^[n]) (f'^n) x L := begin have := hf.iterate hL hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_deriv_at (f^[n]) (f'^n) x := begin have := has_fderiv_at.iterate hf hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_deriv_within_at (f^[n]) (f'^n) s x := begin have := has_fderiv_within_at.iterate hf hx hs n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_deriv_at (f^[n]) (f'^n) x := begin have := hf.iterate hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) (λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)), { refine this.congr' _ (eventually_of_forall $ λ _, mul_one _), refine eventually.mono (mem_nhds_sets (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv' $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul, pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} : differentiable_within_at 𝕜 (λx, c x / d) s x := by simp [div_eq_inv_mul, differentiable_within_at.const_mul, hc] @[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : differentiable_at 𝕜 (λ x, c x / d) x := (hc.has_deriv_at.mul_const d⁻¹).differentiable_at lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜} : differentiable_on 𝕜 (λx, c x / d) s := by simp [div_eq_inv_mul, differentiable_on.const_mul, hc] @[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜} : differentiable 𝕜 (λx, c x / d) := by simp [div_eq_inv_mul, differentiable.const_mul, hc] lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d) s x = (deriv_within c s x) / d := by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs] @[simp] lemma deriv_div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : deriv (λx, c x / d) x = (deriv c x) / d := by simp [div_eq_inv_mul, deriv_const_mul, hc] end division theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) : has_strict_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x) (hf' : f' ≠ 0) : has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_deriv_at g f'⁻¹ a := (hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_deriv_at g f'⁻¹ a := (hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an nonzero derivative `f'` at `f.symm a`, then `f.symm` 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. -/ lemma local_homeomorph.has_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜} (ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) : has_deriv_at f.symm f'⁻¹ a := htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha) lemma has_deriv_at.eventually_ne (h : has_deriv_at f f' x) (hf' : f' ≠ 0) : ∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x := (has_deriv_at_iff_has_fderiv_at.1 h).eventually_ne ⟨∥f'∥⁻¹, λ z, by field_simp [norm_smul, mt norm_eq_zero.1 hf']⟩ theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a) (hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) : ¬differentiable_within_at 𝕜 g s a := begin intro hg, have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha, simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _) end theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) : ¬differentiable_at 𝕜 g a := begin intro hg, have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm, simpa using has_deriv_at_unique this (has_deriv_at_id a) end end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_strict_deriv_at (x : 𝕜) : has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_strict_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_strict_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := (p.has_strict_deriv_at x).has_deriv_at protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable {n : ℕ } lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) : has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x, { simp }, { rw [polynomial.derivative_C_mul_X_pow], simp } end lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := (has_strict_deriv_at_pow n x).has_deriv_at theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, nat.sub_zero, nat.cast_one] }, { simp only [function.iterate_succ_apply', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := hc.has_deriv_within_at.pow.differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := hc.has_deriv_at.pow.differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := hc.has_deriv_within_at.pow.deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := hc.has_deriv_at.pow.deriv end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_strict_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_strict_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] }, { exact this m hm } end lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := (has_strict_deriv_at_fpow m hx).has_deriv_at theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = (∏ i in finset.range k, (m - i) : ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [function.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], exact filter.eventually_eq.deriv_eq (eventually.mono (mem_nhds_sets is_open_ne hx) @ihk) } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in 𝓝[s \ {x}] x, (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in 𝓝[s] x, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : f' < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r := (hf.Ioi_of_Ici.limsup_slope_le' (lt_irrefl x) hr).frequently end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in 𝓝[s \ {x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in 𝓝[{x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.Ioi_of_Ici.limsup_norm_slope_le hr).frequently /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.Ioi_of_Ici.limsup_slope_norm_le hr).frequently, refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
216d90b4e7e65862387164e18f28dbd48fdfc075
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/connected_components.lean
a04a891f964cfaf6b80c98477e79e4fb890036ad
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,903
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.list.chain import category_theory.is_connected import category_theory.sigma.basic import category_theory.full_subcategory /-! # Connected components of a category > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Defines a type `connected_components J` indexing the connected components of a category, and the full subcategories giving each connected component: `component j : Type u₁`. We show that each `component j` is in fact connected. We show every category can be expressed as a disjoint union of its connected components, in particular `decomposed J` is the category (definitionally) given by the sigma-type of the connected components of `J`, and it is shown that this is equivalent to `J`. -/ universes v₁ v₂ v₃ u₁ u₂ noncomputable theory open category_theory.category namespace category_theory attribute [instance, priority 100] is_connected.is_nonempty variables {J : Type u₁} [category.{v₁} J] variables {C : Type u₂} [category.{u₁} C] /-- This type indexes the connected components of the category `J`. -/ def connected_components (J : Type u₁) [category.{v₁} J] : Type u₁ := quotient (zigzag.setoid J) instance [inhabited J] : inhabited (connected_components J) := ⟨quotient.mk' default⟩ /-- Given an index for a connected component, produce the actual component as a full subcategory. -/ @[derive category] def component (j : connected_components J) : Type u₁ := full_subcategory (λ k, quotient.mk' k = j) /-- The inclusion functor from a connected component to the whole category. -/ @[derive [full, faithful], simps {rhs_md := semireducible}] def component.ι (j) : component j ⥤ J := full_subcategory_inclusion _ /-- Each connected component of the category is nonempty. -/ instance (j : connected_components J) : nonempty (component j) := begin apply quotient.induction_on' j, intro k, refine ⟨⟨k, rfl⟩⟩, end instance (j : connected_components J) : inhabited (component j) := classical.inhabited_of_nonempty' /-- Each connected component of the category is connected. -/ instance (j : connected_components J) : is_connected (component j) := begin -- Show it's connected by constructing a zigzag (in `component j`) between any two objects apply is_connected_of_zigzag, rintro ⟨j₁, hj₁⟩ ⟨j₂, rfl⟩, -- We know that the underlying objects j₁ j₂ have some zigzag between them in `J` have h₁₂ : zigzag j₁ j₂ := quotient.exact' hj₁, -- Get an explicit zigzag as a list rcases list.exists_chain_of_relation_refl_trans_gen h₁₂ with ⟨l, hl₁, hl₂⟩, -- Everything which has a zigzag to j₂ can be lifted to the same component as `j₂`. let f : Π x, zigzag x j₂ → component (quotient.mk' j₂) := λ x h, ⟨x, quotient.sound' h⟩, -- Everything in our chosen zigzag from `j₁` to `j₂` has a zigzag to `j₂`. have hf : ∀ (a : J), a ∈ l → zigzag a j₂, { intros i hi, apply list.chain.induction (λ t, zigzag t j₂) _ hl₁ hl₂ _ _ _ (or.inr hi), { intros j k, apply relation.refl_trans_gen.head }, { apply relation.refl_trans_gen.refl } }, -- Now lift the zigzag from `j₁` to `j₂` in `J` to the same thing in `component j`. refine ⟨l.pmap f hf, _, _⟩, { refine @@list.chain_pmap_of_chain _ _ _ f (λ x y _ _ h, _) hl₁ h₁₂ _, exact zag_of_zag_obj (component.ι _) h }, { erw list.last_pmap _ f (j₁ :: l) (by simpa [h₁₂] using hf) (list.cons_ne_nil _ _), exact full_subcategory.ext _ _ hl₂ }, end /-- The disjoint union of `J`s connected components, written explicitly as a sigma-type with the category structure. This category is equivalent to `J`. -/ abbreviation decomposed (J : Type u₁) [category.{v₁} J] := Σ (j : connected_components J), component j /-- The inclusion of each component into the decomposed category. This is just `sigma.incl` but having this abbreviation helps guide typeclass search to get the right category instance on `decomposed J`. -/ -- This name may cause clashes further down the road, and so might need to be changed. abbreviation inclusion (j : connected_components J) : component j ⥤ decomposed J := sigma.incl _ /-- The forward direction of the equivalence between the decomposed category and the original. -/ @[simps {rhs_md := semireducible}] def decomposed_to (J : Type u₁) [category.{v₁} J] : decomposed J ⥤ J := sigma.desc component.ι @[simp] lemma inclusion_comp_decomposed_to (j : connected_components J) : inclusion j ⋙ decomposed_to J = component.ι j := rfl instance : full (decomposed_to J) := { preimage := begin rintro ⟨j', X, hX⟩ ⟨k', Y, hY⟩ f, dsimp at f, have : j' = k', rw [← hX, ← hY, quotient.eq'], exact relation.refl_trans_gen.single (or.inl ⟨f⟩), subst this, refine sigma.sigma_hom.mk f, end, witness' := begin rintro ⟨j', X, hX⟩ ⟨_, Y, rfl⟩ f, have : quotient.mk' Y = j', { rw [← hX, quotient.eq'], exact relation.refl_trans_gen.single (or.inr ⟨f⟩) }, subst this, refl, end } instance : faithful (decomposed_to J) := { map_injective' := begin rintro ⟨_, j, rfl⟩ ⟨_, k, hY⟩ ⟨f⟩ ⟨g⟩ e, change f = g at e, subst e, end } instance : ess_surj (decomposed_to J) := { mem_ess_image := λ j, ⟨⟨_, j, rfl⟩, ⟨iso.refl _⟩⟩ } instance : is_equivalence (decomposed_to J) := equivalence.of_fully_faithfully_ess_surj _ /-- This gives that any category is equivalent to a disjoint union of connected categories. -/ @[simps functor {rhs_md := semireducible}] def decomposed_equiv : decomposed J ≌ J := (decomposed_to J).as_equivalence end category_theory