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
ddad47567915a313799012748a44db952db9627b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/cse_perf_issue.lean
b2001985ddca7ccb51890258fa9a91c408820a24
[ "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
497
lean
def f : nat → bool | 0 := ff | _ := tt inductive tree | leaf : nat → tree | node : nat → tree → tree → tree def mk_tree : nat → nat → tree | 0 v := tree.leaf v | (n+1) v := let t := mk_tree n v in tree.node v t t def tst : tree → nat | (tree.leaf v) := v | (tree.node v l r) := match f v with | tt := tst l + tst l - tst l | ff := tst r end def tree.is_node : tree → bool | (tree.leaf v) := ff | _ := tt #eval timeit "tst" $ tst (mk_tree 100 10)
7471c37f9e9a58fe9640e24df68d1a0cebc765b2
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/data/fin/basic.lean
c1559a845393a462c5940cf33aa83b17a9ca02ca
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,101
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat.basic open nat structure fin (n : nat) := (val : nat) (is_lt : val < n) attribute [pp_using_anonymous_constructor] fin namespace fin def {u} elim0 {α : Type u} : fin 0 → α | ⟨_, h⟩ := absurd h (not_lt_zero _) variable {n : nat} lemma eq_of_veq : ∀ {i j : fin n}, (val i) = (val j) → i = j | ⟨iv, ilt₁⟩ ⟨.(iv), ilt₂⟩ rfl := rfl lemma veq_of_eq : ∀ {i j : fin n}, i = j → (val i) = (val j) | ⟨iv, ilt⟩ .(_) rfl := rfl lemma ne_of_vne {i j : fin n} (h : val i ≠ val j) : i ≠ j := λ h', absurd (veq_of_eq h') h lemma vne_of_ne {i j : fin n} (h : i ≠ j) : val i ≠ val j := λ h', absurd (eq_of_veq h') h end fin open fin instance (n : nat) : decidable_eq (fin n) | ⟨ival, ilt⟩ ⟨jval, jlt⟩ := match nat.decidable_eq ival jval with | is_true h₁ := is_true (eq_of_veq h₁) | is_false h₁ := is_false (λ h₂, absurd (veq_of_eq h₂) h₁) end
f1ec628fd0489e46d57af8b347d9b8e830c35c1f
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Data/KVMap.lean
5e37d469f27b29768dec72e2cb0901d9cde2f7a8
[ "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
6,136
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.Name namespace Lean inductive DataValue | ofString (v : String) | ofBool (v : Bool) | ofName (v : Name) | ofNat (v : Nat) | ofInt (v : Int) @[export lean_mk_bool_data_value] def mkBoolDataValueEx (b : Bool) : DataValue := DataValue.ofBool b @[export lean_data_value_bool] def DataValue.getBoolEx : DataValue → Bool | DataValue.ofBool b => b | _ => false def DataValue.beq : DataValue → DataValue → Bool | DataValue.ofString s₁, DataValue.ofString s₂ => s₁ = s₂ | DataValue.ofNat n₁, DataValue.ofNat n₂ => n₂ = n₂ | DataValue.ofBool b₁, DataValue.ofBool b₂ => b₁ = b₂ | _, _ => false def DataValue.sameCtor : DataValue → DataValue → Bool | DataValue.ofString _, DataValue.ofString _ => true | DataValue.ofBool _, DataValue.ofBool _ => true | DataValue.ofName _, DataValue.ofName _ => true | DataValue.ofNat _, DataValue.ofNat _ => true | DataValue.ofInt _, DataValue.ofInt _ => true | _, _ => false instance DataValue.HasBeq : HasBeq DataValue := ⟨DataValue.beq⟩ @[export lean_data_value_to_string] def DataValue.str : DataValue → String | DataValue.ofString v => v | DataValue.ofBool v => toString v | DataValue.ofName v => toString v | DataValue.ofNat v => toString v | DataValue.ofInt v => toString v instance DataValue.hasToString : HasToString DataValue := ⟨DataValue.str⟩ instance string2DataValueOld : HasCoe String DataValue := ⟨DataValue.ofString⟩ instance bool2DataValueOld : HasCoe Bool DataValue := ⟨DataValue.ofBool⟩ instance name2DataValueOld : HasCoe Name DataValue := ⟨DataValue.ofName⟩ instance nat2DataValueOld : HasCoe Nat DataValue := ⟨DataValue.ofNat⟩ instance int2DataValueOld : HasCoe Int DataValue := ⟨DataValue.ofInt⟩ instance string2DataValue : Coe String DataValue := ⟨DataValue.ofString⟩ instance bool2DataValue : Coe Bool DataValue := ⟨DataValue.ofBool⟩ instance name2DataValue : Coe Name DataValue := ⟨DataValue.ofName⟩ instance nat2DataValue : Coe Nat DataValue := ⟨DataValue.ofNat⟩ instance int2DataValue : Coe Int DataValue := ⟨DataValue.ofInt⟩ /- Remark: we do not use RBMap here because we need to manipulate KVMap objects in C++ and RBMap is implemented in Lean. So, we use just a List until we can generate C++ code from Lean code. -/ structure KVMap := (entries : List (Name × DataValue) := []) namespace KVMap instance : Inhabited KVMap := ⟨{}⟩ instance : HasToString KVMap := ⟨fun m => toString m.entries⟩ def empty : KVMap := {} def isEmpty : KVMap → Bool | ⟨m⟩ => m.isEmpty def size (m : KVMap) : Nat := m.entries.length def findCore : List (Name × DataValue) → Name → Option DataValue | [], k' => none | (k,v)::m, k' => if k == k' then some v else findCore m k' def find : KVMap → Name → Option DataValue | ⟨m⟩, k => findCore m k def findD (m : KVMap) (k : Name) (d₀ : DataValue) : DataValue := (m.find k).getD d₀ def insertCore : List (Name × DataValue) → Name → DataValue → List (Name × DataValue) | [], k', v' => [(k',v')] | (k,v)::m, k', v' => if k == k' then (k, v') :: m else (k, v) :: insertCore m k' v' def insert : KVMap → Name → DataValue → KVMap | ⟨m⟩, k, v => ⟨insertCore m k v⟩ def contains (m : KVMap) (n : Name) : Bool := (m.find n).isSome def getString (m : KVMap) (k : Name) (defVal := "") : String := match m.find k with | some (DataValue.ofString v) => v | _ => defVal def getNat (m : KVMap) (k : Name) (defVal := 0) : Nat := match m.find k with | some (DataValue.ofNat v) => v | _ => defVal def getInt (m : KVMap) (k : Name) (defVal : Int := 0) : Int := match m.find k with | some (DataValue.ofInt v) => v | _ => defVal def getBool (m : KVMap) (k : Name) (defVal := false) : Bool := match m.find k with | some (DataValue.ofBool v) => v | _ => defVal def getName (m : KVMap) (k : Name) (defVal := Name.anonymous) : Name := match m.find k with | some (DataValue.ofName v) => v | _ => defVal def setString (m : KVMap) (k : Name) (v : String) : KVMap := m.insert k (DataValue.ofString v) def setNat (m : KVMap) (k : Name) (v : Nat) : KVMap := m.insert k (DataValue.ofNat v) def setInt (m : KVMap) (k : Name) (v : Int) : KVMap := m.insert k (DataValue.ofInt v) def setBool (m : KVMap) (k : Name) (v : Bool) : KVMap := m.insert k (DataValue.ofBool v) def setName (m : KVMap) (k : Name) (v : Name) : KVMap := m.insert k (DataValue.ofName v) def subsetAux : List (Name × DataValue) → KVMap → Bool | [], m₂ => true | (k, v₁)::m₁, m₂ => match m₂.find k with | some v₂ => v₁ == v₂ && subsetAux m₁ m₂ | none => false def subset : KVMap → KVMap → Bool | ⟨m₁⟩, m₂ => subsetAux m₁ m₂ def eqv (m₁ m₂ : KVMap) : Bool := subset m₁ m₂ && subset m₂ m₁ instance : HasBeq KVMap := ⟨eqv⟩ class isKVMapVal (α : Type) := (defVal : α) (set : KVMap → Name → α → KVMap) (get : KVMap → Name → α → α) export isKVMapVal (set) @[inline] def get {α : Type} [isKVMapVal α] (m : KVMap) (k : Name) (defVal := isKVMapVal.defVal) : α := isKVMapVal.get m k defVal instance boolVal : isKVMapVal Bool := { defVal := false, set := setBool, get := fun k n v => getBool k n v } instance natVal : isKVMapVal Nat := { defVal := 0, set := setNat, get := fun k n v => getNat k n v } instance intVal : isKVMapVal Int := { defVal := 0, set := setInt, get := fun k n v => getInt k n v } instance nameVal : isKVMapVal Name := { defVal := Name.anonymous, set := setName, get := fun k n v => getName k n v } instance stringVal : isKVMapVal String := { defVal := "", set := setString, get := fun k n v => getString k n v } end KVMap end Lean
297b233ef1a9520aa91d2a5bd6e8297a3159aaad
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/liouville/residual.lean
18c376df92c2ff4191d21d94d725e30e5aa34224
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,812
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import number_theory.liouville.basic import topology.metric_space.baire import topology.instances.irrational /-! # Density of Liouville numbers In this file we prove that the set of Liouville numbers form a dense `Gδ` set. We also prove a similar statement about irrational numbers. -/ open_locale filter open filter set metric lemma set_of_liouville_eq_Inter_Union : {x | liouville x} = ⋂ n : ℕ, ⋃ (a b : ℤ) (hb : 1 < b), ball (a / b) (1 / b ^ n) \ {a / b} := begin ext x, simp only [mem_Inter, mem_Union, liouville, mem_set_of_eq, exists_prop, mem_diff, mem_singleton_iff, mem_ball, real.dist_eq, and_comm] end lemma is_Gδ_set_of_liouville : is_Gδ {x | liouville x} := begin rw set_of_liouville_eq_Inter_Union, refine is_Gδ_Inter (λ n, is_open.is_Gδ _), refine is_open_Union (λ a, is_open_Union $ λ b, is_open_Union $ λ hb, _), exact is_open_ball.inter is_closed_singleton.is_open_compl end lemma set_of_liouville_eq_irrational_inter_Inter_Union : {x | liouville x} = {x | irrational x} ∩ ⋂ n : ℕ, ⋃ (a b : ℤ) (hb : 1 < b), ball (a / b) (1 / b ^ n) := begin refine subset.antisymm _ _, { refine subset_inter (λ x hx, hx.irrational) _, rw set_of_liouville_eq_Inter_Union, exact Inter_mono (λ n, Union₂_mono $ λ a b, Union_mono $ λ hb, diff_subset _ _) }, { simp only [inter_Inter, inter_Union, set_of_liouville_eq_Inter_Union], refine Inter_mono (λ n, Union₂_mono $ λ a b, Union_mono $ λ hb, _), rw [inter_comm], refine diff_subset_diff subset.rfl (singleton_subset_iff.2 ⟨a / b, _⟩), norm_cast } end /-- The set of Liouville numbers is a residual set. -/ lemma eventually_residual_liouville : ∀ᶠ x in residual ℝ, liouville x := begin rw [filter.eventually, set_of_liouville_eq_irrational_inter_Inter_Union], refine eventually_residual_irrational.and _, refine eventually_residual.2 ⟨_, _, rat.dense_embedding_coe_real.dense.mono _, subset.rfl⟩, { exact is_Gδ_Inter (λ n, is_open.is_Gδ $ is_open_Union $ λ a, is_open_Union $ λ b, is_open_Union $ λ hb, is_open_ball) }, { rintro _ ⟨r, rfl⟩, simp only [mem_Inter, mem_Union], refine λ n, ⟨r.num * 2, r.denom * 2, _, _⟩, { have := int.coe_nat_le.2 r.pos, rw int.coe_nat_one at this, linarith }, { convert mem_ball_self _ using 2, { norm_cast, field_simp }, { refine one_div_pos.2 (pow_pos (int.cast_pos.2 _) _), exact mul_pos (int.coe_nat_pos.2 r.pos) zero_lt_two } } } end /-- The set of Liouville numbers in dense. -/ lemma dense_liouville : dense {x | liouville x} := dense_of_mem_residual eventually_residual_liouville
0df6cef77dabb98005eca627f7212b3ab3fa297d
69bc7d0780be17e452d542a93f9599488f1c0c8e
/11-14-2019.lean
affc20e3e44ae06dac39b62b4438bf887da84dec
[]
no_license
joek13/cs2102-notes
b7352285b1d1184fae25594f89f5926d74e6d7b4
25bb18788641b20af9cf3c429afe1da9b2f5eafb
refs/heads/master
1,673,461,162,867
1,575,561,090,000
1,575,561,090,000
207,573,549
0
0
null
null
null
null
UTF-8
Lean
false
false
575
lean
-- Why use LEAN? /- "Is this stuff useful?" - Functional programming is hot - much of FB Messenger is written in reason, an ungodly bastard child of JavaScript and OCaml - Boolean satisfiability is NP-complete, so it is reducible to a number of other "hard" problems - practical SAT solvers still take exponential time - Predicate logic - language of math, - language of specificaiton - Design and implementation of programming language - Proofs: - the language of verification - provable security - provable safety - provable privacy -/
abaa728146676bfe14ce35dfde422f2e25b2aa5f
82e44445c70db0f03e30d7be725775f122d72f3e
/src/ring_theory/ideal/basic.lean
803cad28ff2c3c91033096f90fcc3243a69ec65f
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
36,102
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.zorn import order.atoms import order.compactly_generated /-! # Ideals over a ring This file defines `ideal R`, the type of ideals over a commutative ring `R`. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `•` is interpreted as `*`. ## TODO Support one-sided ideals, and ideals over non-commutative rings. See `algebra.ring_quot` for quotients of non-commutative rings. -/ universes u v w variables {α : Type u} {β : Type v} open set function open_locale classical big_operators /-- A (left) ideal in a semiring `R` is an additive submonoid `s` such that `a * b ∈ s` whenever `b ∈ s`. If `R` is a ring, then `s` is an additive subgroup. -/ @[reducible] def ideal (R : Type u) [semiring R] := submodule R R section semiring namespace ideal variables [semiring α] (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 variables (a) lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem a variables {a} @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left _ hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := h.exists_left_inv in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one @[simp] theorem unit_mul_mem_iff_mem {x y : α} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, λ h, I.mul_mem_left y h⟩, obtain ⟨y', hy'⟩ := hy.exists_left_inv, have := I.mul_mem_left y' h, rwa [← mul_assoc, hy', one_mul] at this, end /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot @[simp] lemma span_zero : span (0 : set α) = ⊥ := by rw [←set.singleton_zero, span_singleton_eq_bot] @[simp] lemma span_one : span (1 : set α) = ⊤ := by rw [←set.singleton_one, span_singleton_one] /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : α → α → Prop) : ideal α := submodule.span α { x | ∃ (a b) (h : r a b), x + b = a } /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ class is_prime (I : ideal α) : Prop := (ne_top' : I ≠ ⊤) (mem_or_mem' : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I) theorem is_prime_iff {I : ideal α} : is_prime I ↔ I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ theorem is_prime.ne_top {I : ideal α} (hI : I.is_prime) : I ≠ ⊤ := hI.1 theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.mem_or_mem (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { rw pow_zero at H, exact (mt (eq_top_iff_one _).2 hI.1).elim H }, { rw pow_succ at H, exact or.cases_on (hI.mem_or_mem H) id ih } end lemma not_is_prime_iff {I : ideal α} : ¬ I.is_prime ↔ I = ⊤ ∨ ∃ (x ∉ I) (y ∉ I), x * y ∈ I := begin simp_rw [ideal.is_prime_iff, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, λ ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem lemma bot_prime {R : Type*} [integral_domain R] : (⊥ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), λ x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ class is_maximal (I : ideal α) : Prop := (out : is_coatom I) theorem is_maximal_def {I : ideal α} : I.is_maximal ↔ is_coatom I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_maximal.ne_top {I : ideal α} (h : I.is_maximal) : I ≠ ⊤ := (is_maximal_def.1 h).1 theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := is_maximal_def.trans $ and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.1.2 _ h)⟩ instance : is_coatomic (ideal α) := begin apply complete_lattice.coatomic_of_top_compact, rw ←span_singleton_one, exact submodule.singleton_span_is_compact_element 1, end /-- **Krull's theorem**: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := let ⟨m, hm⟩ := (eq_top_or_exists_le_coatom I).resolve_left hI in ⟨m, ⟨⟨hm.1⟩, hm.2⟩⟩ variables (α) /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial α] : ∃ M : ideal α, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (⊥ : ideal α) bot_ne_top in ⟨I, hI⟩ variables {α} instance [nontrivial α] : nontrivial (ideal α) := begin rcases @exists_maximal α _ _ with ⟨M, hM, _⟩, exact nontrivial_of_ne M ⊤ hM end /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [comm_semiring R] {P : ideal R} (hmax : ∀ m : ideal R, P < m → ¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊤ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, ∃ i ∈ I, y * x + i = 1 := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, z, hz, hy⟩, refine ⟨y, z, _, hy.symm⟩, rwa ← span_eq I, end section lattice variables {R : Type u} [semiring R] lemma mem_sup_left {S T : ideal R} : ∀ {x : R}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : ideal R} : ∀ {x : R}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Type*} {S : ι → ideal R} (i : ι) : ∀ {x : R}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : ∀ {x : R}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ι : Type*} {I : ι → ideal R} {x : R} : x ∈ infi I ↔ ∀ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (⊥ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice section pi variables (ι : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ι → α) := { carrier := { x | ∀ i, x i ∈ I }, zero_mem' := λ i, I.zero_mem, add_mem' := λ a b ha hb i, I.add_mem (ha i) (hb i), smul_mem' := λ a b hb i, I.mul_mem_left (a i) (hb i) } lemma mem_pi (x : ι → α) : x ∈ I.pi ι ↔ ∀ i, x i ∈ I := iff.rfl end pi end ideal end semiring section comm_semiring variables {a b : α} -- A separate namespace definition is needed because the variables were historically in a different -- order. namespace ideal variables [comm_semiring α] (I : ideal α) @[simp] theorem mul_unit_mem_iff_mem {x y : α} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x ▸ unit_mul_mem_iff_mem I hy lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {α : Type u} [integral_domain α] {x y : α} : span ({x} : set α) = span ({y} : set α) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_singleton_mul_right_unit {a : α} (h2 : is_unit a) (x : α) : span ({x * a} : set α) = span {x} := begin apply le_antisymm, { rw span_singleton_le_span_singleton, use a}, { rw span_singleton_le_span_singleton, rw is_unit.mul_right_dvd h2} end lemma span_singleton_mul_left_unit {a : α} (h2 : is_unit a) (x : α) : span ({a * x} : set α) = span {x} := by rw [mul_comm, span_singleton_mul_right_unit h2] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime_iff, prime, span_singleton_eq_top, hp, mem_span_singleton] theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin let J : ideal α := submodule.span α (insert x ↑I), have IJ : I ≤ J := (set.subset.trans (subset_insert _ _) subset_span), have xJ : x ∈ J := ideal.subset_span (set.mem_insert x I), cases is_maximal_iff.1 H with _ oJ, specialize oJ J x IJ hx xJ, rcases submodule.mem_span_insert.mp oJ with ⟨a, b, h, oe⟩, obtain (F : y * 1 = y * (a • x + b)) := congr_arg (λ g : α, y * g) oe, rw [← mul_one y, F, mul_add, mul_comm, smul_eq_mul, mul_assoc], refine submodule.add_mem I (I.mul_mem_left a hxy) (submodule.smul_mem I y _), rwa submodule.span_eq at h, end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [integral_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : span ({b₁ * b₂} : set β) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] variables (b) lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left b h variables {b} lemma pow_mem_of_mem (ha : a ∈ I) (n : ℕ) (hn : 0 < n) : a ^ n ∈ I := nat.cases_on n (not.elim dec_trivial) (λ m hm, (pow_succ a m).symm ▸ I.mul_mem_right (a^m) ha) hn theorem is_prime.mul_mem_iff_mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I ↔ x ∈ I ∨ y ∈ I := λ x y, ⟨hI.mem_or_mem, by { rintro (h | h), exacts [I.mul_mem_right y h, I.mul_mem_left x h] }⟩ theorem is_prime.pow_mem_iff_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (hn : 0 < n) : r ^ n ∈ I ↔ r ∈ I := ⟨hI.mem_of_pow_mem n, (λ hr, I.pow_mem_of_mem hr n hn)⟩ end ideal end comm_semiring section ring namespace ideal variables [ring α] (I : ideal α) {a b : α} 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 mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' end ideal end ring section division_ring variables {K : Type u} [division_ring K] (I : ideal K) namespace ideal /-- All ideals in a division ring are trivial. -/ lemma eq_bot_or_top : I = ⊥ ∨ I = ⊤ := begin rw or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using I.mul_mem_left r⁻¹ hr, end lemma eq_bot_of_prime [h : I.is_prime] : I = ⊥ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal : is_maximal (⊥ : ideal K) := ⟨⟨λ h, absurd ((eq_top_iff_one (⊤ : ideal K)).mp rfl) (by rw ← h; simp), λ I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩⟩ end ideal end division_ring section comm_ring namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} /-- The quotient `R/I` of a ring `R` by an ideal `I`. The ideal quotient of `I` is defined to equal the quotient of `I` as an `R`-submodule of `R`. This definition is marked `reducible` so that typeclass instances can be shared between `ideal.quotient I` and `submodule.quotient I`. -/ -- Note that at present `ideal` means a left-ideal, -- so this quotient is only useful in a commutative ring. -- We should develop quotients by two-sided ideals as well. @[reducible] def quotient (I : ideal α) := I.quotient namespace quotient variables {I} {x y : α} instance (I : ideal α) : has_one I.quotient := ⟨submodule.quotient.mk 1⟩ instance (I : ideal α) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, submodule.quotient.mk (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin have F := I.add_mem (I.mul_mem_left a₂ h₁) (I.mul_mem_right b₁ h₂), have : a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁, { rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] }, rw ← this at F, change _ ∈ _, convert F, end⟩ instance (I : ideal α) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg submodule.quotient.mk (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (right_distrib a b c), ..submodule.quotient.add_comm_group I } /-- The ring homomorphism from a ring `R` to a quotient ring `R/I`. -/ def mk (I : ideal α) : α →+* I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ instance : inhabited (quotient I) := ⟨mk I 37⟩ protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I @[simp] theorem mk_eq_mk (x : α) : (submodule.quotient.mk x : quotient I) = mk I x := rfl lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected theorem nontrivial {I : ideal α} (hI : I ≠ ⊤) : nontrivial I.quotient := ⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩ lemma mk_surjective : function.surjective (mk I) := λ y, quotient.induction_on' y (λ x, exists.intro x rfl) /-- If `I` is an ideal of a commutative ring `R`, if `q : R → R/I` is the quotient map, and if `s ⊆ R` is a subset, then `q⁻¹(q(s)) = ⋃ᵢ(i + s)`, the union running over all `i ∈ I`. -/ lemma quotient_ring_saturate (I : ideal α) (s : set α) : mk I ⁻¹' (mk I '' s) = (⋃ x : I, (λ y, x.1 + y) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq], exact ⟨λ ⟨a, a_in, h⟩, ⟨⟨_, I.neg_mem h⟩, a, a_in, by simp⟩, λ ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub]; exact I.neg_mem hi⟩⟩ end instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), .. quotient.comm_ring I, .. quotient.nontrivial hI.1 } lemma is_integral_domain_iff_prime (I : ideal α) : is_integral_domain I.quotient ↔ I.is_prime := ⟨ λ ⟨h1, h2, h3⟩, ⟨zero_ne_one_iff.1 $ @zero_ne_one _ _ ⟨h1⟩, λ x y h, by { simp only [←eq_zero_iff_mem, (mk I).map_mul] at ⊢ h, exact h3 _ _ h}⟩, λ h, by exactI integral_domain.to_is_integral_domain I.quotient⟩ lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, rcases hI.exists_inv (mt eq_zero_iff_mem.2 h) with ⟨b, c, hc, abc⟩, rw [mul_comm] at abc, refine ⟨mk _ b, quot.sound _⟩, --quot.sound hb rw ← eq_sub_iff_add_eq' at abc, rw [abc, ← neg_mem_iff, neg_sub] at hc, convert hc, end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, ..quotient.integral_domain I } /-- If the quotient by an ideal is a field, then the ideal is maximal. -/ theorem maximal_of_is_field (I : ideal α) (hqf : is_field I.quotient) : I.is_maximal := begin apply ideal.is_maximal_iff.2, split, { intro h, rcases hqf.exists_pair_ne with ⟨⟨x⟩, ⟨y⟩, hxy⟩, exact hxy (ideal.quotient.eq.2 (mul_one (x - y) ▸ I.mul_mem_left _ h)) }, { intros J x hIJ hxnI hxJ, rcases hqf.mul_inv_cancel (mt ideal.quotient.eq_zero_iff_mem.1 hxnI) with ⟨⟨y⟩, hy⟩, rw [← zero_add (1 : α), ← sub_self (x * y), sub_add], refine J.sub_mem (J.mul_mem_right _ hxJ) (hIJ (ideal.quotient.eq.1 hy)) } end /-- The quotient of a ring by an ideal is a field iff the ideal is maximal. -/ theorem maximal_ideal_iff_is_field_quotient (I : ideal α) : I.is_maximal ↔ is_field I.quotient := ⟨λ h, @field.to_is_field I.quotient (@ideal.quotient.field _ _ I h), λ h, maximal_of_is_field I h⟩ variable [comm_ring β] /-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero, lift it to the quotient by this ideal. -/ def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S →+* β := { to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h], map_one' := f.map_one, map_zero' := f.map_zero, map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add, map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul } @[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : lift S f H (mk S a) = f a := rfl end quotient /-- Quotienting by equal ideals gives equivalent rings. See also `submodule.quot_equiv_of_eq`. -/ def quot_equiv_of_eq {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) : I.quotient ≃+* J.quotient := { map_mul' := by { rintro ⟨x⟩ ⟨y⟩, refl }, .. submodule.quot_equiv_of_eq I J h } section pi variables (ι : Type v) /-- `R^n/I^n` is a `R/I`-module. -/ instance module_pi : module (I.quotient) (I.pi ι).quotient := begin refine { smul := λ c m, quotient.lift_on₂' c m (λ r m, submodule.quotient.mk $ r • m) _, .. }, { intros c₁ m₁ c₂ m₂ hc hm, change c₁ - c₂ ∈ I at hc, change m₁ - m₂ ∈ (I.pi ι) at hm, apply ideal.quotient.eq.2, have : c₁ • (m₂ - m₁) ∈ I.pi ι, { rw ideal.mem_pi, intro i, simp only [smul_eq_mul, pi.smul_apply, pi.sub_apply], apply ideal.mul_mem_left, rw ←ideal.neg_mem_iff, simpa only [neg_sub] using hm i }, rw [←ideal.add_mem_iff_left (I.pi ι) this, sub_eq_add_neg, add_comm, ←add_assoc, ←smul_add, sub_add_cancel, ←sub_eq_add_neg, ←sub_smul, ideal.mem_pi], exact λ i, I.mul_mem_right _ hc }, all_goals { rintro ⟨a⟩ ⟨b⟩ ⟨c⟩ <|> rintro ⟨a⟩, simp only [(•), submodule.quotient.quot_mk_eq_mk, ideal.quotient.mk_eq_mk], change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, simp [mul_assoc, mul_add, add_mul] } end /-- `R^n/I^n` is isomorphic to `(R/I)^n` as an `R/I`-module. -/ noncomputable def pi_quot_equiv : (I.pi ι).quotient ≃ₗ[I.quotient] (ι → I.quotient) := { to_fun := λ x, quotient.lift_on' x (λ f i, ideal.quotient.mk I (f i)) $ λ a b hab, funext (λ i, ideal.quotient.eq.2 (hab i)), map_add' := by { rintros ⟨_⟩ ⟨_⟩, refl }, map_smul' := by { rintros ⟨_⟩ ⟨_⟩, refl }, inv_fun := λ x, ideal.quotient.mk (I.pi ι) $ λ i, quotient.out' (x i), left_inv := begin rintro ⟨x⟩, exact ideal.quotient.eq.2 (λ i, ideal.quotient.eq.1 (quotient.out_eq' _)) end, right_inv := begin intro x, ext i, obtain ⟨r, hr⟩ := @quot.exists_rep _ _ (x i), simp_rw ←hr, convert quotient.out_eq' _ end } /-- If `f : R^n → R^m` is an `R`-linear map and `I ⊆ R` is an ideal, then the image of `I^n` is contained in `I^m`. -/ lemma map_pi {ι} [fintype ι] {ι' : Type w} (x : ι → α) (hi : ∀ i, x i ∈ I) (f : (ι → α) →ₗ[α] (ι' → α)) (i : ι') : f x i ∈ I := begin rw pi_eq_sum_univ x, simp only [finset.sum_apply, smul_eq_mul, linear_map.map_sum, pi.smul_apply, linear_map.map_smul], exact I.sum_mem (λ j hj, I.mul_mem_right _ (hi j)) end end pi end ideal end comm_ring namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : ¬ is_field R := λ ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : ¬ is_field R) : ∃ x ≠ (0 : R), ¬ is_unit x := begin have : ¬ _ := λ h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊢ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : ¬ is_field R ↔ ∃ I : ideal R, ⊥ < I ∧ I < ⊤ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := set_like.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (I.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : ¬ is_field R ↔ ∃ p : ideal R, p ≠ ⊥ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, λ ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ /-- When a ring is not a field, the maximal ideals are nontrivial. -/ lemma ne_bot_of_is_maximal_of_not_is_field [nontrivial R] {M : ideal R} (max : M.is_maximal) (not_field : ¬ is_field R) : M ≠ ⊥ := begin rintros h, rw h at max, rcases max with ⟨⟨h1, h2⟩⟩, obtain ⟨I, hIbot, hItop⟩ := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.mp not_field, exact ne_of_lt hItop (h2 I hIbot), end end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : ¬ is_field R) : ⊥ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, finish, intro mle, apply @irrefl _ (<) _ (⊤ : ideal R), have : M = ⊥ := eq_bot_iff.mpr mle, rw this at *, rwa hm.1.2 I Ibot at Itop, end end ideal variables {a b : α} /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [semiring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_semiring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end /-- A commutative ring is local if it has a unique maximal ideal. Note that `local_ring` is a predicate. -/ class local_ring (α : Type u) [comm_ring α] extends nontrivial α : Prop := (is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a))) namespace local_ring variables [comm_ring α] [local_ring α] lemma is_unit_or_is_unit_one_sub_self (a : α) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) : x + y ∈ nonunits α := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : α) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : α) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : α) * z) hu.symm, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (α) /-- The ideal of elements that are not units. -/ def maximal_ideal : ideal α := { carrier := nonunits α, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance maximal_ideal.is_maximal : (maximal_ideal α).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.mul_mem_left ↑u⁻¹ H } end lemma maximal_ideal_unique : ∃! I : ideal α, I.is_maximal := ⟨maximal_ideal α, maximal_ideal.is_maximal α, λ I hI, hI.eq_of_le (maximal_ideal.is_maximal α).1.1 $ λ x hx, hI.1.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {α} lemma eq_maximal_ideal {I : ideal α} (hI : I.is_maximal) : I = maximal_ideal α := unique_of_exists_unique (maximal_ideal_unique α) hI $ maximal_ideal.is_maximal α lemma le_maximal_ideal {J : ideal α} (hJ : J ≠ ⊤) : J ≤ maximal_ideal α := begin rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩, rwa ←eq_maximal_ideal hM1 end @[simp] lemma mem_maximal_ideal (x) : x ∈ maximal_ideal α ↔ x ∈ nonunits α := iff.rfl end local_ring lemma local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α := { exists_pair_ne := ⟨0, 1, hnze⟩, is_local := λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ _ hx H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end } lemma local_of_unique_max_ideal [comm_ring α] (h : ∃! I : ideal α, I.is_maximal) : local_ring α := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H lemma local_of_unique_nonzero_prime (R : Type u) [comm_ring R] (h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R := local_of_unique_max_ideal begin rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩, refine ⟨P, ⟨⟨hPnot_top, _⟩⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩, { refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _), exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm }, { rintro rfl, exact hPnot_top (hM.1.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) }, end lemma local_of_surjective {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] [nontrivial B] (f : A →+* B) (hf : function.surjective f) : local_ring B := { is_local := begin intros b, obtain ⟨a, rfl⟩ := hf b, apply (local_ring.is_unit_or_is_unit_one_sub_self a).imp f.is_unit_map _, rw [← f.map_one, ← f.map_sub], apply f.is_unit_map, end, .. ‹nontrivial B› } /-- A local ring homomorphism is a homomorphism between local rings such that the image of the maximal ideal of the source is contained within the maximal ideal of the target. -/ class is_local_ring_hom [semiring α] [semiring β] (f : α →+* β) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) instance is_local_ring_hom_id (A : Type*) [semiring A] : is_local_ring_hom (ring_hom.id A) := { map_nonunit := λ a, id } @[simp] lemma is_unit_map_iff {A B : Type*} [semiring A] [semiring B] (f : A →+* B) [is_local_ring_hom f] (a) : is_unit (f a) ↔ is_unit a := ⟨is_local_ring_hom.map_nonunit a, f.is_unit_map⟩ instance is_local_ring_hom_comp {A B C : Type*} [semiring A] [semiring B] [semiring C] (g : B →+* C) (f : A →+* B) [is_local_ring_hom g] [is_local_ring_hom f] : is_local_ring_hom (g.comp f) := { map_nonunit := λ a, is_local_ring_hom.map_nonunit a ∘ is_local_ring_hom.map_nonunit (f a) } @[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h theorem of_irreducible_map [semiring α] [semiring β] (f : α →+* β) [h : is_local_ring_hom f] {x : α} (hfx : irreducible (f x)) : irreducible x := ⟨λ h, hfx.not_unit $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in or.imp (H p) (H q) $ hfx.is_unit_or_is_unit $ f.map_mul p q ▸ congr_arg f hx⟩ section open local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variables (f : α →+* β) [is_local_ring_hom f] lemma map_nonunit (a) (h : a ∈ maximal_ideal α) : f a ∈ maximal_ideal β := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variable (α) /-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/ def residue_field := (maximal_ideal α).quotient noncomputable instance residue_field.field : field (residue_field α) := ideal.quotient.field (maximal_ideal α) noncomputable instance : inhabited (residue_field α) := ⟨37⟩ /-- The quotient map from a local ring to its residue field. -/ def residue : α →+* (residue_field α) := ideal.quotient.mk _ namespace residue_field variables {α β} /-- The map on residue fields induced by a local homomorphism between local rings -/ noncomputable def map (f : α →+* β) [is_local_ring_hom f] : residue_field α →+* residue_field β := ideal.quotient.lift (maximal_ideal α) ((ideal.quotient.mk _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field end local_ring namespace field variables [field α] @[priority 100] -- see Note [lower instance priority] instance : local_ring α := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit.mk0 a h } end field
c1e6c7ca287ac661b1fc515747508c3b286a79e1
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/algebra/free.lean
ff5780a845b93ea6c2c8bb110c8339effaee624d
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
17,070
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau 1. Free magma of a type (traversable, decidable equality). 2. Free semigroup of a magma. 3. Free semigroup of a type (traversable, decidable equality). 4. Free monoid of a semigroup. And finally, magma.free_semigroup (free_magma α) ≃ free_semigroup α. -/ import data.equiv.basic universes u v inductive free_magma (α : Type u) : Type u | of : α → free_magma | mul : free_magma → free_magma → free_magma namespace free_magma variables {α : Type u} instance : has_mul (free_magma α) := ⟨free_magma.mul⟩ @[elab_as_eliminator] protected lemma induction_on {C : free_magma α → Prop} (x) (ih1 : ∀ x, C (of x)) (ih2 : ∀ x y, C x → C y → C (x * y)) : C x := free_magma.rec_on x ih1 ih2 section lift variables {β : Type v} [has_mul β] (f : α → β) def lift : free_magma α → β | (of x) := f x | (mul x y) := lift x * lift y @[simp] lemma lift_of (x) : lift f (of x) = f x := rfl @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := rfl theorem lift_unique (f : free_magma α → β) (hf : ∀ x y, f (x * y) = f x * f y) : f = lift (f ∘ of) := funext $ λ x, free_magma.rec_on x (λ x, rfl) $ λ x y ih1 ih2, (hf x y).trans $ congr (congr_arg _ ih1) ih2 end lift section map variables {β : Type v} (f : α → β) def map : free_magma α → free_magma β := lift $ of ∘ f @[simp] lemma map_of (x) : map f (of x) = of (f x) := rfl @[simp] lemma map_mul (x y) : map f (x * y) = map f x * map f y := rfl end map section category instance : monad free_magma := { pure := λ _, of, bind := λ _ _ x f, lift f x } @[elab_as_eliminator] protected lemma induction_on' {C : free_magma α → Prop} (x) (ih1 : ∀ x, C (pure x)) (ih2 : ∀ x y, C x → C y → C (x * y)) : C x := free_magma.induction_on x ih1 ih2 variables {β : Type u} @[simp] lemma map_pure (f : α → β) (x) : (f <$> pure x : free_magma β) = pure (f x) := rfl @[simp] lemma map_mul' (f : α → β) (x y : free_magma α) : (f <$> (x * y)) = (f <$> x * f <$> y) := rfl @[simp] lemma pure_bind (f : α → free_magma β) (x) : (pure x >>= f) = f x := rfl @[simp] lemma mul_bind (f : α → free_magma β) (x y : free_magma α) : (x * y >>= f) = ((x >>= f) * (y >>= f)) := rfl @[simp] lemma pure_seq {α β : Type u} {f : α → β} {x : free_magma α} : pure f <*> x = f <$> x := rfl @[simp] lemma mul_seq {α β : Type u} {f g : free_magma (α → β)} {x : free_magma α} : (f * g) <*> x = (f <*> x) * (g <*> x) := rfl instance : is_lawful_monad free_magma.{u} := { pure_bind := λ _ _ _ _, rfl, bind_assoc := λ α β γ x f g, free_magma.induction_on' x (λ x, rfl) (λ x y ih1 ih2, by rw [mul_bind, mul_bind, mul_bind, ih1, ih2]), id_map := λ α x, free_magma.induction_on' x (λ _, rfl) (λ x y ih1 ih2, by rw [map_mul', ih1, ih2]) } protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) : free_magma α → m (free_magma β) | (of x) := of <$> F x | (mul x y) := (*) <$> traverse x <*> traverse y instance : traversable free_magma := ⟨@free_magma.traverse⟩ variables {m : Type u → Type u} [applicative m] (F : α → m β) @[simp] lemma traverse_pure (x) : traverse F (pure x : free_magma α) = pure <$> F x := rfl @[simp] lemma traverse_pure' : traverse F ∘ pure = λ x, (pure <$> F x : m (free_magma β)) := rfl @[simp] lemma traverse_mul (x y : free_magma α) : traverse F (x * y) = (*) <$> traverse F x <*> traverse F y := rfl @[simp] lemma traverse_mul' : function.comp (traverse F) ∘ @has_mul.mul (free_magma α) _ = λ x y, (*) <$> traverse F x <*> traverse F y := rfl @[simp] lemma traverse_eq (x) : free_magma.traverse F x = traverse F x := rfl @[simp] lemma mul_map_seq (x y : free_magma α) : ((*) <$> x <*> y : id (free_magma α)) = (x * y : free_magma α) := rfl instance : is_lawful_traversable free_magma.{u} := { id_traverse := λ α x, free_magma.induction_on x (λ x, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, mul_map_seq]), comp_traverse := λ F G hf1 hg1 hf2 hg2 α β γ f g x, free_magma.induction_on' x (λ x, by resetI; simp only [traverse_pure, traverse_pure'] with functor_norm) (λ x y ih1 ih2, by resetI; rw [traverse_mul, ih1, ih2, traverse_mul]; simp only [traverse_mul'] with functor_norm), naturality := λ F G hf1 hg1 hf2 hg2 η α β f x, free_magma.induction_on' x (λ x, by simp only [traverse_pure] with functor_norm) (λ x y ih1 ih2, by simp only [traverse_mul] with functor_norm; rw [ih1, ih2]), traverse_eq_map_id := λ α β f x, free_magma.induction_on x (λ _, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, map_mul', mul_map_seq]; refl) } end category instance [decidable_eq α] : decidable_eq (free_magma α) | (of p) (of x) := decidable_of_iff (p = x) ⟨congr_arg of, of.inj⟩ | (of p) (mul x y) := is_false $ λ H, free_magma.no_confusion H | (mul p q) (of x) := is_false $ λ H, free_magma.no_confusion H | (mul p q) (mul x y) := @decidable_of_iff (mul p q = mul x y) (p = x ∧ q = y) ⟨λ ⟨hpx, hqy⟩, hpx ▸ hqy ▸ rfl, mul.inj⟩ (@and.decidable _ _ (decidable_eq p x) (decidable_eq q y)) def repr' [has_repr α] : free_magma α → string | (of x) := repr x | (mul x y) := "( " ++ repr' x ++ " * " ++ repr' y ++ " )" instance [has_repr α] : has_repr (free_magma α) := ⟨repr'⟩ def length : free_magma α → ℕ | (of x) := 1 | (mul x y) := length x + length y end free_magma namespace magma inductive free_semigroup.r (α : Type u) [has_mul α] : α → α → Prop | intro : ∀ x y z, free_semigroup.r ((x * y) * z) (x * (y * z)) | left : ∀ w x y z, free_semigroup.r (w * ((x * y) * z)) (w * (x * (y * z))) def free_semigroup (α : Type u) [has_mul α] : Type u := quot $ free_semigroup.r α namespace free_semigroup variables {α : Type u} [has_mul α] def of : α → free_semigroup α := quot.mk _ @[elab_as_eliminator] protected lemma induction_on {C : free_semigroup α → Prop} (x : free_semigroup α) (ih : ∀ x, C (of x)) : C x := quot.induction_on x ih theorem of_mul_assoc (x y z : α) : of ((x * y) * z) = of (x * (y * z)) := quot.sound $ r.intro x y z theorem of_mul_assoc_left (w x y z : α) : of (w * ((x * y) * z)) = of (w * (x * (y * z))) := quot.sound $ r.left w x y z theorem of_mul_assoc_right (w x y z : α) : of (((w * x) * y) * z) = of ((w * (x * y)) * z) := by rw [of_mul_assoc, of_mul_assoc, of_mul_assoc, of_mul_assoc_left] instance : semigroup (free_semigroup α) := { mul := λ x y, begin refine quot.lift_on x (λ p, quot.lift_on y (λ q, (quot.mk _ $ p * q : free_semigroup α)) _) _, { rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); change of _ = of _, { rw of_mul_assoc_left }, { rw [← of_mul_assoc, of_mul_assoc_left, of_mul_assoc] } }, { refine quot.induction_on y (λ q, _), rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); change of _ = of _, { rw of_mul_assoc_right }, { rw [of_mul_assoc, of_mul_assoc, of_mul_assoc_left, of_mul_assoc_left, of_mul_assoc_left, ← of_mul_assoc c d, ← of_mul_assoc c d, of_mul_assoc_left] } } end, mul_assoc := λ x y z, quot.induction_on x $ λ p, quot.induction_on y $ λ q, quot.induction_on z $ λ r, of_mul_assoc p q r } theorem of_mul (x y : α) : of (x * y) = of x * of y := rfl section lift variables {β : Type v} [semigroup β] (f : α → β) def lift (hf : ∀ x y, f (x * y) = f x * f y) : free_semigroup α → β := quot.lift f $ by rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); simp only [hf, mul_assoc] @[simp] lemma lift_of {hf} (x : α) : lift f hf (of x) = f x := rfl @[simp] lemma lift_mul {hf} (x y) : lift f hf (x * y) = lift f hf x * lift f hf y := quot.induction_on x $ λ p, quot.induction_on y $ λ q, hf p q theorem lift_unique (f : free_semigroup α → β) (hf : ∀ x y, f (x * y) = f x * f y) : f = lift (f ∘ of) (λ p q, hf (of p) (of q)) := funext $ λ x, quot.induction_on x $ λ p, rfl end lift variables {β : Type v} [has_mul β] (f : α → β) def map (hf : ∀ x y, f (x * y) = f x * f y) : free_semigroup α → free_semigroup β := lift (of ∘ f) (λ x y, congr_arg of $ hf x y) @[simp] lemma map_of {hf} (x) : map f hf (of x) = of (f x) := rfl @[simp] lemma map_mul {hf} (x y) : map f hf (x * y) = map f hf x * map f hf y := lift_mul _ _ _ end free_semigroup end magma def free_semigroup (α : Type u) : Type u := α × list α namespace free_semigroup variables {α : Type u} instance : semigroup (free_semigroup α) := { mul := λ L1 L2, (L1.1, L1.2 ++ L2.1 :: L2.2), mul_assoc := λ L1 L2 L3, prod.ext rfl $ list.append_assoc _ _ _ } def of (x : α) : free_semigroup α := (x, []) @[elab_as_eliminator] protected lemma induction_on {C : free_semigroup α → Prop} (x) (ih1 : ∀ x, C (of x)) (ih2 : ∀ x y, C (of x) → C y → C (of x * y)) : C x := let ⟨x, L⟩ := x in list.rec_on L ih1 (λ hd tl ih x, ih2 x (hd, tl) (ih1 x) (ih hd)) x section lift variables {β : Type v} [semigroup β] (f : α → β) def lift' : α → list α → β | x [] := f x | x (hd::tl) := f x * lift' hd tl def lift (x : free_semigroup α) : β := lift' f x.1 x.2 @[simp] lemma lift_of (x : α) : lift f (of x) = f x := rfl @[simp] lemma lift_of_mul (x y) : lift f (of x * y) = f x * lift f y := rfl @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := free_semigroup.induction_on x (λ p, rfl) (λ p x ih1 ih2, by rw [mul_assoc, lift_of_mul, lift_of_mul, mul_assoc, ih2]) theorem lift_unique (f : free_semigroup α → β) (hf : ∀ x y, f (x * y) = f x * f y) : f = lift (f ∘ of) := funext $ λ ⟨x, L⟩, list.rec_on L (λ x, rfl) (λ hd tl ih x, (hf (of x) (hd, tl)).trans $ congr_arg _ $ ih _) x end lift section map variables {β : Type v} (f : α → β) def map : free_semigroup α → free_semigroup β := lift $ of ∘ f @[simp] lemma map_of (x) : map f (of x) = of (f x) := rfl @[simp] lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ end map section category instance : monad free_semigroup := { pure := λ _, of, bind := λ _ _ x f, lift f x } @[elab_as_eliminator] protected lemma induction_on' {C : free_semigroup α → Prop} (x) (ih1 : ∀ x, C (pure x)) (ih2 : ∀ x y, C (pure x) → C y → C (pure x * y)) : C x := free_semigroup.induction_on x ih1 ih2 @[simp] lemma map_pure {α β : Type u} (f : α → β) (x) : (f <$> pure x : free_semigroup β) = pure (f x) := rfl @[simp] lemma map_mul' {α β : Type u} (f : α → β) (x y : free_semigroup α) : (f <$> (x * y)) = (f <$> x * f <$> y) := map_mul _ _ _ @[simp] lemma pure_bind {α β : Type u} (f : α → free_semigroup β) (x) : (pure x >>= f) = f x := rfl @[simp] lemma mul_bind {α β : Type u} (f : α → free_semigroup β) (x y : free_semigroup α) : (x * y >>= f) = ((x >>= f) * (y >>= f)) := lift_mul _ _ _ @[simp] lemma pure_seq {α β : Type u} {f : α → β} {x : free_semigroup α} : pure f <*> x = f <$> x := rfl @[simp] lemma mul_seq {α β : Type u} {f g : free_semigroup (α → β)} {x : free_semigroup α} : (f * g) <*> x = (f <*> x) * (g <*> x) := mul_bind _ _ _ instance : is_lawful_monad free_semigroup.{u} := { pure_bind := λ _ _ _ _, rfl, bind_assoc := λ α β γ x f g, free_semigroup.induction_on' x (λ x, rfl) (λ x y ih1 ih2, by rw [mul_bind, mul_bind, mul_bind, ih1, ih2]), id_map := λ α x, free_semigroup.induction_on' x (λ _, rfl) (λ x y ih1 ih2, by rw [map_mul', ih1, ih2]) } def traverse' {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) : α → list α → m (free_semigroup β) | x [] := pure <$> F x | x (hd::tl) := (*) <$> (pure <$> F x) <*> traverse' hd tl protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) (x : free_semigroup α) : m (free_semigroup β) := traverse' F x.1 x.2 instance : traversable free_semigroup := ⟨@free_semigroup.traverse⟩ variables {β : Type u} {m : Type u → Type u} [applicative m] (F : α → m β) @[simp] lemma traverse_pure (x) : traverse F (pure x : free_semigroup α) = pure <$> F x := rfl @[simp] lemma traverse_pure' : traverse F ∘ pure = λ x, (pure <$> F x : m (free_semigroup β)) := rfl section variables [is_lawful_applicative m] @[simp] lemma traverse_mul (x y : free_semigroup α) : traverse F (x * y) = (*) <$> traverse F x <*> traverse F y := let ⟨x, L1⟩ := x, ⟨y, L2⟩ := y in list.rec_on L1 (λ x, rfl) (λ hd tl ih x, show (*) <$> pure <$> F x <*> traverse F ((hd, tl) * (y, L2) : free_semigroup α) = (*) <$> ((*) <$> pure <$> F x <*> traverse F (hd, tl)) <*> traverse F (y, L2), by rw ih; simp only [(∘), (mul_assoc _ _ _).symm] with functor_norm) x @[simp] lemma traverse_mul' : function.comp (traverse F) ∘ @has_mul.mul (free_semigroup α) _ = λ x y, (*) <$> traverse F x <*> traverse F y := funext $ λ x, funext $ λ y, traverse_mul F x y end @[simp] lemma traverse_eq (x) : free_semigroup.traverse F x = traverse F x := rfl @[simp] lemma mul_map_seq (x y : free_semigroup α) : ((*) <$> x <*> y : id (free_semigroup α)) = (x * y : free_semigroup α) := rfl instance : is_lawful_traversable free_semigroup.{u} := { id_traverse := λ α x, free_semigroup.induction_on x (λ x, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, mul_map_seq]), comp_traverse := λ F G hf1 hg1 hf2 hg2 α β γ f g x, free_semigroup.induction_on' x (λ x, by resetI; simp only [traverse_pure, traverse_pure'] with functor_norm) (λ x y ih1 ih2, by resetI; rw [traverse_mul, ih1, ih2, traverse_mul]; simp only [traverse_mul'] with functor_norm), naturality := λ F G hf1 hg1 hf2 hg2 η α β f x, free_semigroup.induction_on' x (λ x, by simp only [traverse_pure] with functor_norm) (λ x y ih1 ih2, by resetI; simp only [traverse_mul] with functor_norm; rw [ih1, ih2]), traverse_eq_map_id := λ α β f x, free_semigroup.induction_on x (λ _, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, map_mul', mul_map_seq]; refl) } end category instance [decidable_eq α] : decidable_eq (free_semigroup α) := prod.decidable_eq end free_semigroup namespace semigroup def free_monoid : Type u → Type u := option namespace free_monoid attribute [reducible] free_monoid instance (α : Type u) [semigroup α] : monoid (free_monoid α) := { mul := option.lift_or_get (*), mul_assoc := is_associative.assoc _, one := failure, one_mul := is_left_id.left_id _, mul_one := is_right_id.right_id _ } attribute [semireducible] free_monoid def of {α : Type u} : α → free_monoid α := some variables {α : Type u} [semigroup α] @[elab_as_eliminator] protected lemma induction_on {C : free_monoid α → Prop} (x : free_monoid α) (h1 : C 1) (hof : ∀ x, C (of x)) : C x := option.rec_on x h1 hof @[simp] lemma of_mul (x y : α) : of (x * y) = of x * of y := rfl section lift variables {β : Type v} [monoid β] (f : α → β) def lift (x : free_monoid α) : β := option.rec_on x 1 f @[simp] lemma lift_of (x) : lift f (of x) = f x := rfl @[simp] lemma lift_one : lift f 1 = 1 := rfl @[simp] lemma lift_mul (hf : ∀ x y, f (x * y) = f x * f y) (x y) : lift f (x * y) = lift f x * lift f y := free_monoid.induction_on x (by rw [one_mul, lift_one, one_mul]) $ λ x, free_monoid.induction_on y (by rw [mul_one, lift_one, mul_one]) $ λ y, hf x y theorem lift_unique (f : free_monoid α → β) (hf : f 1 = 1) : f = lift (f ∘ of) := funext $ λ x, free_monoid.induction_on x hf $ λ x, rfl end lift variables {β : Type v} [semigroup β] (f : α → β) def map : free_monoid α → free_monoid β := lift $ of ∘ f @[simp] lemma map_of (x) : map f (of x) = of (f x) := rfl @[simp] lemma map_mul (hf : ∀ x y, f (x * y) = f x * f y) (x y) : map f (x * y) = map f x * map f y := lift_mul _ (λ x y, congr_arg of $ hf x y) _ _ end free_monoid end semigroup def free_semigroup_free_magma (α : Type u) : magma.free_semigroup (free_magma α) ≃ free_semigroup α := { to_fun := magma.free_semigroup.lift (free_magma.lift free_semigroup.of) (free_magma.lift_mul _), inv_fun := free_semigroup.lift (magma.free_semigroup.of ∘ free_magma.of), left_inv := λ x, magma.free_semigroup.induction_on x $ λ p, by rw magma.free_semigroup.lift_of; exact free_magma.induction_on p (λ x, by rw [free_magma.lift_of, free_semigroup.lift_of]) (λ x y ihx ihy, by rw [free_magma.lift_mul, free_semigroup.lift_mul, ihx, ihy, magma.free_semigroup.of_mul]), right_inv := λ x, free_semigroup.induction_on x (λ x, by rw [free_semigroup.lift_of, magma.free_semigroup.lift_of, free_magma.lift_of]) (λ x y ihx ihy, by rw [free_semigroup.lift_mul, magma.free_semigroup.lift_mul, ihx, ihy]) } @[simp] lemma free_semigroup_free_magma_mul {α : Type u} (x y) : free_semigroup_free_magma α (x * y) = free_semigroup_free_magma α x * free_semigroup_free_magma α y := magma.free_semigroup.lift_mul _ _ _
d7beaf52f706bbe6dc8a510fd949127f8db91308
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.6.lean
5617fc22f54f39b70eda49c8cc560b78e222aae2
[]
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
657
lean
import standard namespace hide inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A definition Prop.is_inhabited [instance] : inhabited Prop := inhabited.mk true definition bool.is_inhabited [instance] : inhabited bool := inhabited.mk bool.tt definition nat.is_inhabited [instance] : inhabited nat := inhabited.mk nat.zero definition unit.is_inhabited [instance] : inhabited unit := inhabited.mk unit.star definition default (A : Type) [H : inhabited A] : A := inhabited.rec (λ a, a) H -- BEGIN check default Prop -- Prop check default nat -- ℕ check default bool -- bool check default unit -- unit -- END end hide
6127ad3933312c60d260c55d4b4cdc9f8ed0f7ad
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Meta/Closure.lean
a21ea2fa86b83dad6196401a54bd647cf76bf991
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
14,239
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.MetavarContext import Lean.Environment import Lean.Util.FoldConsts import Lean.Meta.Basic import Lean.Meta.Check /-! This module provides functions for "closing" open terms and creating auxiliary definitions. Here, we say a term is "open" if it contains free/meta-variables. The "closure" is performed by lambda abstracting the free/meta-variables. Recall that in dependent type theory lambda abstracting a let-variable may produce type incorrect terms. For example, given the context ```lean (n : Nat := 20) (x : Vector α n) (y : Vector α 20) ``` the term `x = y` is correct. However, its closure using lambda abstractions is not. ```lean fun (n : Nat) (x : Vector α n) (y : Vector α 20) => x = y ``` A previous version of this module would address this issue by always use let-expressions to abstract let-vars. In the example above, it would produce ```lean let n : Nat := 20; fun (x : Vector α n) (y : Vector α 20) => x = y ``` This approach produces correct result, but produces unsatisfactory results when we want to create auxiliary definitions. For example, consider the context ```lean (x : Nat) (y : Nat := fact x) ``` and the term `h (g y)`, now suppose we want to create an auxiliary definition for `y`. The previous version of this module would compute the auxiliary definition ```lean def aux := fun (x : Nat) => let y : Nat := fact x; h (g y) ``` and would return the term `aux x` as a substitute for `h (g y)`. This is correct, but we will re-evaluate `fact x` whenever we use `aux`. In this module, we produce ```lean def aux := fun (y : Nat) => h (g y) ``` Note that in this particular case, it is safe to lambda abstract the let-varible `y`. This module uses the following approach to decide whether it is safe or not to lambda abstract a let-variable. 1) We enable zeta-expansion tracking in `MetaM`. That is, whenever we perform type checking if a let-variable needs to zeta expanded, we store it in the set `zetaFVarIds`. We say a let-variable is zeta expanded when we replace it with its value. 2) We use the `MetaM` type checker `check` to type check the expression we want to close, and the type of the binders. 3) If a let-variable is not in `zetaFVarIds`, we lambda abstract it. Remark: We still use let-expressions for let-variables in `zetaFVarIds`, but we move the `let` inside the lambdas. The idea is to make sure the auxiliary definition does not have an interleaving of `lambda` and `let` expressions. Thus, if the let-variable occurs in the type of one of the lambdas, we simply zeta-expand it there. As a final example consider the context ```lean (x_1 : Nat) (x_2 : Nat) (x_3 : Nat) (x : Nat := fact (10 + x_1 + x_2 + x_3)) (ty : Type := Nat → Nat) (f : ty := fun x => x) (n : Nat := 20) (z : f 10) ``` and we use this module to compute an auxiliary definition for the term ```lean (let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10) ``` we obtain ```lean def aux (x : Nat) (f : Nat → Nat) (z : Nat) : Nat×Nat := let n : Nat := 20; (let y : {v // v=n} := {val := 20, property := ex._proof_1}; y.val+n+f x, z+10) ``` BTW, this module also provides the `zeta : Bool` flag. When set to true, it expands all let-variables occurring in the target expression. -/ namespace Lean.Meta namespace Closure structure ToProcessElement where fvarId : FVarId newFVarId : FVarId deriving Inhabited structure Context where zeta : Bool structure State where visitedLevel : LevelMap Level := {} visitedExpr : ExprStructMap Expr := {} levelParams : Array Name := #[] nextLevelIdx : Nat := 1 levelArgs : Array Level := #[] newLocalDecls : Array LocalDecl := #[] newLocalDeclsForMVars : Array LocalDecl := #[] newLetDecls : Array LocalDecl := #[] nextExprIdx : Nat := 1 exprMVarArgs : Array Expr := #[] exprFVarArgs : Array Expr := #[] toProcess : Array ToProcessElement := #[] abbrev ClosureM := ReaderT Context $ StateRefT State MetaM @[inline] def visitLevel (f : Level → ClosureM Level) (u : Level) : ClosureM Level := do if !u.hasMVar && !u.hasParam then pure u else let s ← get match s.visitedLevel.find? u with | some v => pure v | none => do let v ← f u modify fun s => { s with visitedLevel := s.visitedLevel.insert u v } pure v @[inline] def visitExpr (f : Expr → ClosureM Expr) (e : Expr) : ClosureM Expr := do if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then pure e else let s ← get match s.visitedExpr.find? e with | some r => pure r | none => let r ← f e modify fun s => { s with visitedExpr := s.visitedExpr.insert e r } pure r def mkNewLevelParam (u : Level) : ClosureM Level := do let s ← get let p := (`u).appendIndexAfter s.nextLevelIdx modify fun s => { s with levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelArgs := s.levelArgs.push u } pure $ mkLevelParam p partial def collectLevelAux : Level → ClosureM Level | u@(Level.succ v) => return u.updateSucc! (← visitLevel collectLevelAux v) | u@(Level.max v w) => return u.updateMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w) | u@(Level.imax v w) => return u.updateIMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w) | u@(Level.mvar ..) => mkNewLevelParam u | u@(Level.param ..) => mkNewLevelParam u | u@(Level.zero) => pure u def collectLevel (u : Level) : ClosureM Level := do -- u ← instantiateLevelMVars u visitLevel collectLevelAux u def preprocess (e : Expr) : ClosureM Expr := do let e ← instantiateMVars e let ctx ← read -- If we are not zeta-expanding let-decls, then we use `check` to find -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. if !ctx.zeta then check e pure e /-- Remark: This method does not guarantee unique user names. The correctness of the procedure does not rely on unique user names. Recall that the pretty printer takes care of unintended collisions. -/ def mkNextUserName : ClosureM Name := do let s ← get let n := (`_x).appendIndexAfter s.nextExprIdx modify fun s => { s with nextExprIdx := s.nextExprIdx + 1 } pure n def pushToProcess (elem : ToProcessElement) : ClosureM Unit := modify fun s => { s with toProcess := s.toProcess.push elem } partial def collectExprAux (e : Expr) : ClosureM Expr := do let collect (e : Expr) := visitExpr collectExprAux e match e with | Expr.proj _ _ s => return e.updateProj! (← collect s) | Expr.forallE _ d b _ => return e.updateForallE! (← collect d) (← collect b) | Expr.lam _ d b _ => return e.updateLambdaE! (← collect d) (← collect b) | Expr.letE _ t v b _ => return e.updateLet! (← collect t) (← collect v) (← collect b) | Expr.app f a => return e.updateApp! (← collect f) (← collect a) | Expr.mdata _ b => return e.updateMData! (← collect b) | Expr.sort u => return e.updateSort! (← collectLevel u) | Expr.const _ us => return e.updateConst! (← us.mapM collectLevel) | Expr.mvar mvarId => let mvarDecl ← mvarId.getDecl let type ← preprocess mvarDecl.type let type ← collect type let newFVarId ← mkFreshFVarId let userName ← mkNextUserName modify fun s => { s with newLocalDeclsForMVars := s.newLocalDeclsForMVars.push $ LocalDecl.cdecl default newFVarId userName type BinderInfo.default, exprMVarArgs := s.exprMVarArgs.push e } return mkFVar newFVarId | Expr.fvar fvarId => match (← read).zeta, (← fvarId.getValue?) with | true, some value => collect (← preprocess value) | _, _ => let newFVarId ← mkFreshFVarId pushToProcess ⟨fvarId, newFVarId⟩ return mkFVar newFVarId | e => pure e def collectExpr (e : Expr) : ClosureM Expr := do let e ← preprocess e visitExpr collectExprAux e partial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement) : ToProcessElement × Array ToProcessElement := if h : i < toProcess.size then let elem' := toProcess.get ⟨i, h⟩ if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then pickNextToProcessAux lctx (i+1) (toProcess.set ⟨i, h⟩ elem) elem' else pickNextToProcessAux lctx (i+1) toProcess elem else (elem, toProcess) def pickNextToProcess? : ClosureM (Option ToProcessElement) := do let lctx ← getLCtx let s ← get if s.toProcess.isEmpty then pure none else modifyGet fun s => let elem := s.toProcess.back let toProcess := s.toProcess.pop let (elem, toProcess) := pickNextToProcessAux lctx 0 toProcess elem (some elem, { s with toProcess := toProcess }) def pushFVarArg (e : Expr) : ClosureM Unit := modify fun s => { s with exprFVarArgs := s.exprFVarArgs.push e } def pushLocalDecl (newFVarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : ClosureM Unit := do let type ← collectExpr type modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| LocalDecl.cdecl default newFVarId userName type bi } partial def process : ClosureM Unit := do match (← pickNextToProcess?) with | none => pure () | some ⟨fvarId, newFVarId⟩ => match (← fvarId.getDecl) with | .cdecl _ _ userName type bi => pushLocalDecl newFVarId userName type bi pushFVarArg (mkFVar fvarId) process | .ldecl _ _ userName type val _ => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl Recall that if `fvarId` is in `zetaFVarIds`, then we zeta-expanded it during type checking (see `check` at `collectExpr`). Our type checker may zeta-expand declarations that are not needed, but this check is conservative, and seems to work well in practice. -/ pushLocalDecl newFVarId userName type pushFVarArg (mkFVar fvarId) process else /- Dependent let-decl -/ let type ← collectExpr type let val ← collectExpr val modify fun s => { s with newLetDecls := s.newLetDecls.push <| LocalDecl.ldecl default newFVarId userName type val false } /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of newFVarId at `newLocalDecls` -/ modify fun s => { s with newLocalDecls := s.newLocalDecls.map (·.replaceFVarId newFVarId val) } process @[inline] def mkBinding (isLambda : Bool) (decls : Array LocalDecl) (b : Expr) : Expr := let xs := decls.map LocalDecl.toExpr let b := b.abstract xs decls.size.foldRev (init := b) fun i b => let decl := decls[i]! match decl with | LocalDecl.cdecl _ _ n ty bi => let ty := ty.abstractRange i xs if isLambda then Lean.mkLambda n bi ty b else Lean.mkForall n bi ty b | LocalDecl.ldecl _ _ n ty val nonDep => if b.hasLooseBVar 0 then let ty := ty.abstractRange i xs let val := val.abstractRange i xs mkLet n ty val b nonDep else b.lowerLooseBVars 1 1 def mkLambda (decls : Array LocalDecl) (b : Expr) : Expr := mkBinding true decls b def mkForall (decls : Array LocalDecl) (b : Expr) : Expr := mkBinding false decls b structure MkValueTypeClosureResult where levelParams : Array Name type : Expr value : Expr levelArgs : Array Level exprArgs : Array Expr def mkValueTypeClosureAux (type : Expr) (value : Expr) : ClosureM (Expr × Expr) := do resetZetaFVarIds withTrackingZeta do let type ← collectExpr type let value ← collectExpr value process pure (type, value) def mkValueTypeClosure (type : Expr) (value : Expr) (zeta : Bool) : MetaM MkValueTypeClosureResult := do let ((type, value), s) ← ((mkValueTypeClosureAux type value).run { zeta := zeta }).run {} let newLocalDecls := s.newLocalDecls.reverse ++ s.newLocalDeclsForMVars let newLetDecls := s.newLetDecls.reverse let type := mkForall newLocalDecls (mkForall newLetDecls type) let value := mkLambda newLocalDecls (mkLambda newLetDecls value) pure { type := type, value := value, levelParams := s.levelParams, levelArgs := s.levelArgs, exprArgs := s.exprFVarArgs.reverse ++ s.exprMVarArgs } end Closure /-- Create an auxiliary definition with the given name, type and value. The parameters `type` and `value` may contain free and meta variables. A "closure" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on, and `t_j`s are free and meta variables `type` and `value` depend on. -/ def mkAuxDefinition (name : Name) (type : Expr) (value : Expr) (zeta : Bool := false) (compile : Bool := true) : MetaM Expr := do let result ← Closure.mkValueTypeClosure type value zeta let env ← getEnv let decl := Declaration.defnDecl { name := name levelParams := result.levelParams.toList type := result.type value := result.value hints := ReducibilityHints.regular (getMaxHeight env result.value + 1) safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe } addDecl decl if compile then compileDecl decl return mkAppN (mkConst name result.levelArgs.toList) result.exprArgs /-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/ def mkAuxDefinitionFor (name : Name) (value : Expr) (zeta : Bool := false) : MetaM Expr := do let type ← inferType value let type := type.headBeta mkAuxDefinition name type value (zeta := zeta) end Lean.Meta
e674ef54c04b6a0779d71e6e44c00ab14f7ca1ff
076f5040b63237c6dd928c6401329ed5adcb0e44
/instructor-notes/2019.10.14.prop_logic/prop_logic.lean
8da1292a39c6fd2ad46cd3b08d1454d84a73c017
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
1,563
lean
namespace prop_logic /- *** SYNTAX *** -/ inductive var : Type | mkVar : ℕ → var inductive unOp : Type | notOp inductive binOp : Type | andOp | orOp | xorOp | implOp | iffOp inductive pExp : Type | litExp : bool → pExp | varExp : var → pExp | unOpExp : unOp → pExp → pExp | binOpExp : binOp → pExp → pExp → pExp open var open pExp open unOp open binOp -- Shorthand notations def pTrue := litExp tt def pFalse := litExp ff def pNot := unOpExp notOp def pAnd := binOpExp andOp def pOr := binOpExp orOp def pXor := binOpExp xorOp def pImpl := binOpExp implOp def pIff := binOpExp iffOp -- conventional notation notation e1 ∧ e2 := pAnd e1 e2 notation e1 ∨ e2 := pOr e1 e2 notation ¬ e := pNot e notation e1 ⇒ e2 := pImpl e1 e2 notation e1 ⊕ e2 := pXor e1 e2 notation e1 ↔ e2 := pIff e1 e2 /- *** SEMANTICS *** -/ def interpUnOp : unOp → (bool → bool) | notOp := bnot def bimpl : bool → bool → bool | tt ff := ff | _ _ := tt def biff : bool → bool → bool | tt tt := tt | ff ff := tt | _ _ := ff def interpBinOp : binOp → (bool → bool → bool) | andOp := band | orOp := bor | xorOp := bxor | implOp := bimpl | iffOp := biff /- Given a pExp and an interpretation for the variables, evaluate the pExp to determine its Boolean truth value. -/ def pEval : pExp → (var → bool) → bool | (litExp b) i := b | (varExp v) i := i v | (unOpExp op e) i := (interpUnOp op) (pEval e i) | (binOpExp op e1 e2) i := (interpBinOp op) (pEval e1 i) (pEval e2 i) end prop_logic
80a9ea0f45d15199364ceb308d6c1f6d42668932
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/meta/mk_inhabited_instance.lean
fc10252c47fea86916dbe186e24e8541e87d2a94
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,683
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 is inhabited. -/ prelude import init.meta.interactive_base import init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics namespace tactic open expr environment list /- Retrieve the name of the type we are building an inhabitant instance for. -/ private meta def get_inhabited_type_name : tactic name := do { (app (const n ls) t) ← target >>= whnf, when (n ≠ `inhabited) failed, (const I ls) ← return (get_app_fn t), return I } <|> fail "mk_inhabited_instance tactic failed, target type is expected to be of the form (inhabited ...)" /- Try to synthesize constructor argument using type class resolution -/ private meta def mk_inhabited_arg : tactic unit := do tgt ← target, inh ← mk_app `inhabited [tgt], inst ← mk_instance inh, mk_app `inhabited.default [inst] >>= exact private meta def try_constructors : nat → nat → tactic unit | 0 n := failed | (i+1) n := do {constructor_idx (n - i), all_goals mk_inhabited_arg, done} <|> try_constructors i n meta def mk_inhabited_instance : tactic unit := do I ← get_inhabited_type_name, env ← get_env, let n := length (constructors_of env I), when (n = 0) (fail format!"mk_inhabited_instance failed, type '{I}' does not have constructors"), constructor, (try_constructors n n) <|> (fail format!"mk_inhabited_instance failed, failed to build instance using all constructors of '{I}'") end tactic
0424f8ed146b5c1daf522a6f01709abca6a4e72d
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/02_Dependent_Type_Theory.org.5.lean
898a58c84435444768e74b74a8ccd3c59bc4b26f
[]
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
256
lean
/- page 14 -/ import standard import data.nat data.prod open nat prod -- BEGIN constants A B : Type check prod -- Type → Type → Type check prod A -- Type → Type check prod A B -- Type check prod nat nat -- Type₁ -- END
427151d7f4b2a7133a6f23889117e185c80ce1c8
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/abst.lean
a5061e5e6957541ac399e5dca0d6ee7fb0f8bd0b
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
195
lean
import Int. axiom PlusComm(a b : Int) : a + b = b + a. variable a : Int. check (funext (fun x : Int, (PlusComm a x))). set_option pp::implicit true. check (funext (fun x : Int, (PlusComm a x))).
ee40678195f3de940b18ee19a13feca15c5b727f
c777c32c8e484e195053731103c5e52af26a25d1
/src/field_theory/minpoly/basic.lean
1538c6bad695a580b4e635595d18c6a57962a727
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
7,910
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johan Commelin -/ import ring_theory.integral_closure /-! # Minimal polynomials This file defines the minimal polynomial of an element `x` of an `A`-algebra `B`, under the assumption that x is integral over `A`, and derives some basic properties such as ireducibility under the assumption `B` is a domain. -/ open_locale classical polynomial open polynomial set function variables {A B : Type*} section min_poly_def variables (A) [comm_ring A] [ring B] [algebra A B] /-- Suppose `x : B`, where `B` is an `A`-algebra. The minimal polynomial `minpoly A x` of `x` is a monic polynomial with coefficients in `A` of smallest degree that has `x` as its root, if such exists (`is_integral A x`) or zero otherwise. For example, if `V` is a `𝕜`-vector space for some field `𝕜` and `f : V →ₗ[𝕜] V` then the minimal polynomial of `f` is `minpoly 𝕜 f`. -/ noncomputable def minpoly (x : B) : A[X] := if hx : is_integral A x then degree_lt_wf.min _ hx else 0 end min_poly_def namespace minpoly section ring variables [comm_ring A] [ring B] [algebra A B] variables {x : B} /-- A minimal polynomial is monic. -/ lemma monic (hx : is_integral A x) : monic (minpoly A x) := by { delta minpoly, rw dif_pos hx, exact (degree_lt_wf.min_mem _ hx).1 } /-- A minimal polynomial is nonzero. -/ lemma ne_zero [nontrivial A] (hx : is_integral A x) : minpoly A x ≠ 0 := (monic hx).ne_zero lemma eq_zero (hx : ¬ is_integral A x) : minpoly A x = 0 := dif_neg hx variables (A x) /-- An element is a root of its minimal polynomial. -/ @[simp] lemma aeval : aeval x (minpoly A x) = 0 := begin delta minpoly, split_ifs with hx, { exact (degree_lt_wf.min_mem _ hx).2 }, { exact aeval_zero _ } end /-- A minimal polynomial is not `1`. -/ lemma ne_one [nontrivial B] : minpoly A x ≠ 1 := begin intro h, refine (one_ne_zero : (1 : B) ≠ 0) _, simpa using congr_arg (polynomial.aeval x) h end lemma map_ne_one [nontrivial B] {R : Type*} [semiring R] [nontrivial R] (f : A →+* R) : (minpoly A x).map f ≠ 1 := begin by_cases hx : is_integral A x, { exact mt ((monic hx).eq_one_of_map_eq_one f) (ne_one A x) }, { rw [eq_zero hx, polynomial.map_zero], exact zero_ne_one }, end /-- A minimal polynomial is not a unit. -/ lemma not_is_unit [nontrivial B] : ¬ is_unit (minpoly A x) := begin haveI : nontrivial A := (algebra_map A B).domain_nontrivial, by_cases hx : is_integral A x, { exact mt (monic hx).eq_one_of_is_unit (ne_one A x) }, { rw [eq_zero hx], exact not_is_unit_zero } end lemma mem_range_of_degree_eq_one (hx : (minpoly A x).degree = 1) : x ∈ (algebra_map A B).range := begin have h : is_integral A x, { by_contra h, rw [eq_zero h, degree_zero, ←with_bot.coe_one] at hx, exact (ne_of_lt (show ⊥ < ↑1, from with_bot.bot_lt_coe 1) hx) }, have key := minpoly.aeval A x, rw [eq_X_add_C_of_degree_eq_one hx, (minpoly.monic h).leading_coeff, C_1, one_mul, aeval_add, aeval_C, aeval_X, ←eq_neg_iff_add_eq_zero, ←ring_hom.map_neg] at key, exact ⟨-(minpoly A x).coeff 0, key.symm⟩, end /-- The defining property of the minimal polynomial of an element `x`: it is the monic polynomial with smallest degree that has `x` as its root. -/ lemma min {p : A[X]} (pmonic : p.monic) (hp : polynomial.aeval x p = 0) : degree (minpoly A x) ≤ degree p := begin delta minpoly, split_ifs with hx, { exact le_of_not_lt (degree_lt_wf.not_lt_min _ hx ⟨pmonic, hp⟩) }, { simp only [degree_zero, bot_le] } end lemma unique' {p : A[X]} (hm : p.monic) (hp : polynomial.aeval x p = 0) (hl : ∀ q : A[X], degree q < degree p → q = 0 ∨ polynomial.aeval x q ≠ 0) : p = minpoly A x := begin nontriviality A, have hx : is_integral A x := ⟨p, hm, hp⟩, obtain h | h := hl _ ((minpoly A x).degree_mod_by_monic_lt hm), swap, { exact (h $ (aeval_mod_by_monic_eq_self_of_root hm hp).trans $ aeval A x).elim }, obtain ⟨r, hr⟩ := (dvd_iff_mod_by_monic_eq_zero hm).1 h, rw hr, have hlead := congr_arg leading_coeff hr, rw [mul_comm, leading_coeff_mul_monic hm, (monic hx).leading_coeff] at hlead, have : nat_degree r ≤ 0, { have hr0 : r ≠ 0 := by { rintro rfl, exact ne_zero hx (mul_zero p ▸ hr) }, apply_fun nat_degree at hr, rw hm.nat_degree_mul' hr0 at hr, apply nat.le_of_add_le_add_left, rw add_zero, exact hr.symm.trans_le (nat_degree_le_nat_degree $ min A x hm hp) }, rw [eq_C_of_nat_degree_le_zero this, ← nat.eq_zero_of_le_zero this, ← leading_coeff, ← hlead, C_1, mul_one], end @[nontriviality] lemma subsingleton [subsingleton B] : minpoly A x = 1 := begin nontriviality A, have := minpoly.min A x monic_one (subsingleton.elim _ _), rw degree_one at this, cases le_or_lt (minpoly A x).degree 0 with h h, { rwa (monic ⟨1, monic_one, by simp⟩ : (minpoly A x).monic).degree_le_zero_iff_eq_one at h }, { exact (this.not_lt h).elim }, end end ring section comm_ring variables [comm_ring A] section ring variables [ring B] [algebra A B] variables {x : B} /-- The degree of a minimal polynomial, as a natural number, is positive. -/ lemma nat_degree_pos [nontrivial B] (hx : is_integral A x) : 0 < nat_degree (minpoly A x) := begin rw pos_iff_ne_zero, intro ndeg_eq_zero, have eq_one : minpoly A x = 1, { rw eq_C_of_nat_degree_eq_zero ndeg_eq_zero, convert C_1, simpa only [ndeg_eq_zero.symm] using (monic hx).leading_coeff }, simpa only [eq_one, alg_hom.map_one, one_ne_zero] using aeval A x end /-- The degree of a minimal polynomial is positive. -/ lemma degree_pos [nontrivial B] (hx : is_integral A x) : 0 < degree (minpoly A x) := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos hx) /-- If `B/A` is an injective ring extension, and `a` is an element of `A`, then the minimal polynomial of `algebra_map A B a` is `X - C a`. -/ lemma eq_X_sub_C_of_algebra_map_inj (a : A) (hf : function.injective (algebra_map A B)) : minpoly A (algebra_map A B a) = X - C a := begin nontriviality A, refine (unique' A _ (monic_X_sub_C a) _ _).symm, { rw [map_sub, aeval_C, aeval_X, sub_self] }, simp_rw or_iff_not_imp_left, intros q hl h0, rw [← nat_degree_lt_nat_degree_iff h0, nat_degree_X_sub_C, nat.lt_one_iff] at hl, rw eq_C_of_nat_degree_eq_zero hl at h0 ⊢, rwa [aeval_C, map_ne_zero_iff _ hf, ← C_ne_zero], end end ring section is_domain variables [ring B] [algebra A B] variables {x : B} /-- If `a` strictly divides the minimal polynomial of `x`, then `x` cannot be a root for `a`. -/ lemma aeval_ne_zero_of_dvd_not_unit_minpoly {a : A[X]} (hx : is_integral A x) (hamonic : a.monic) (hdvd : dvd_not_unit a (minpoly A x)) : polynomial.aeval x a ≠ 0 := begin refine λ ha, (min A x hamonic ha).not_lt (degree_lt_degree _), obtain ⟨b, c, hu, he⟩ := hdvd, have hcm := hamonic.of_mul_monic_left (he.subst $ monic hx), rw [he, hamonic.nat_degree_mul hcm], apply nat.lt_add_of_zero_lt_left _ _ (lt_of_not_le $ λ h, hu _), rw [eq_C_of_nat_degree_le_zero h, ← nat.eq_zero_of_le_zero h, ← leading_coeff, hcm.leading_coeff, C_1], exact is_unit_one, end variables [is_domain A] [is_domain B] /-- A minimal polynomial is irreducible. -/ lemma irreducible (hx : is_integral A x) : irreducible (minpoly A x) := begin refine (irreducible_of_monic (monic hx) $ ne_one A x).2 (λ f g hf hg he, _), rw [← hf.is_unit_iff, ← hg.is_unit_iff], by_contra' h, have heval := congr_arg (polynomial.aeval x) he, rw [aeval A x, aeval_mul, mul_eq_zero] at heval, cases heval, { exact aeval_ne_zero_of_dvd_not_unit_minpoly hx hf ⟨hf.ne_zero, g, h.2, he.symm⟩ heval }, { refine aeval_ne_zero_of_dvd_not_unit_minpoly hx hg ⟨hg.ne_zero, f, h.1, _⟩ heval, rw [mul_comm, he] }, end end is_domain end comm_ring end minpoly
abadb62fca04ed38dd3544a610de14156fcae31c
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/02_Dependent_Type_Theory.org.17.lean
5cd2ff556b428f1155e89a62e7b9990b93ab9d73
[]
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
1,122
lean
/- page 20 -/ import standard import data.nat open nat constants (m n : nat) (p q : bool) definition m_plus_n : nat := m + n check m_plus_n print m_plus_n -- again, Lean can infer the type definition m_plus_n' := m + n print m_plus_n' definition double (x : nat) : nat := x + x print double check double 3 eval double 3 -- 6 definition square (x : nat) := x * x print square check square 3 eval square 3 -- 9 definition do_twice (f : nat → nat) (x : nat) : nat := f (f x) eval do_twice double 2 -- 8 definition quadruple := do_twice double print quadruple check quadruple 9 eval quadruple 9 open function definition octuple := double ∘ do_twice double print octuple check octuple 9 eval octuple 9 definition Do_Twice : ((ℕ → ℕ) → (ℕ → ℕ)) → (ℕ → ℕ) → (ℕ -> ℕ) := λ f, f ∘ f /- Do_Twice do_twice double 2 ⟹ (do_twice ∘ do_twice) double 2 ⟹ do_twice (do_twice double) 2 ⟹ do_twice (double ∘ double) 2 ⟹ ((double ∘ double) ∘ (double ∘ double)) 2 ⟹ double (double (double (double 2))) ⟹ 32 -/ eval Do_Twice do_twice double 2
5c1a7cec80ac8e49b47c0a2c16816e2685316412
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/rat/default_auto.lean
37e704f69135731065c9e7665fc8e1f59fc5581a
[]
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
303
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.rat.floor import Mathlib.PostPort namespace Mathlib end Mathlib
76e79f378f26f3ed0be7d526d57f297d7bdbefb7
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/fun_info.lean
f1ee04ce0d3250bee750154ed3c93d0848d6780f
[ "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
4,502
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.format init.function structure param_info := (is_implicit : bool) -- is an implicit parameter. (is_inst_implicit : bool) -- is a typeclass instance (is_prop : bool) (has_fwd_deps : bool) (is_dec_inst : bool) (back_deps : list nat) -- previous parameters it depends on open format list decidable private meta def ppfield {α : Type} [has_to_format α] (fname : string) (v : α) : format := group $ to_fmt fname ++ space ++ to_fmt ":=" ++ space ++ nest (fname.length + 4) (to_fmt v) private meta def concat_fields (f₁ f₂ : format) : format := if is_nil f₁ then f₂ else if is_nil f₂ then f₁ else f₁ ++ to_fmt "," ++ line ++ f₂ local infix `+++`:65 := concat_fields meta def param_info.to_format : param_info → format | (param_info.mk i ii p d di ds) := group ∘ cbrace $ when i "implicit" +++ when ii "inst_implicit" +++ when p "prop" +++ when d "has_fwd_deps" +++ when di "is_dec_inst" +++ when (length ds > 0) (to_fmt "back_deps := " ++ to_fmt ds) meta instance : has_to_format param_info := has_to_format.mk param_info.to_format structure fun_info := (params : list param_info) (result_deps : list nat) -- parameters the result type depends on meta def fun_info_to_format : fun_info → format | (fun_info.mk ps ds) := group ∘ dcbrace $ ppfield "params" ps +++ ppfield "result_deps" ds meta instance : has_to_format fun_info := has_to_format.mk fun_info_to_format /-- specialized is true if the result of fun_info has been specifialized using this argument. For example, consider the function f : Pi (α : Type), α -> α Now, suppse we request get_specialize fun_info for the application f unit a fun_info_manager returns two param_info objects: 1) specialized = true 2) is_subsingleton = true Note that, in general, the second argument of f is not a subsingleton, but it is in this particular case/specialization. \remark This bit is only set if it is a dependent parameter. Moreover, we only set is_specialized IF another parameter becomes a subsingleton -/ structure subsingleton_info := (specialized : bool) (is_subsingleton : bool) meta def subsingleton_info_to_format : subsingleton_info → format | (subsingleton_info.mk s ss) := group ∘ cbrace $ when s "specialized" +++ when ss "subsingleton" meta instance : has_to_format subsingleton_info := has_to_format.mk subsingleton_info_to_format namespace tactic /-- If nargs is not none, then return information assuming the function has only nargs arguments. -/ meta constant get_fun_info (f : expr) (nargs : option nat := none) (md := semireducible) : tactic fun_info meta constant get_subsingleton_info (f : expr) (nargs : option nat := none) (md := semireducible) : tactic (list subsingleton_info) /-- `get_spec_subsingleton_info t` return subsingleton parameter information for the function application t of the form `f a_1 ... a_n`. This tactic is more precise than `get_subsingleton_info f` and `get_subsingleton_info_n f n` Example: given `f : Pi (α : Type), α -> α`, `get_spec_subsingleton_info` for `f unit b` returns a fun_info with two param_info 1) specialized = tt 2) is_subsingleton = tt The second argument is marked as subsingleton only because the resulting information is taking into account the first argument. -/ meta constant get_spec_subsingleton_info (t : expr) (md := semireducible) : tactic (list subsingleton_info) meta constant get_spec_prefix_size (t : expr) (nargs : nat) (md := semireducible) : tactic nat private meta def is_next_explicit : list param_info → bool | [] := tt | (p::ps) := bnot p.is_implicit && bnot p.is_inst_implicit meta def fold_explicit_args_aux {α} (f : α → expr → tactic α) : list expr → list param_info → α → tactic α | [] _ a := return a | (e::es) ps a := if is_next_explicit ps then f a e >>= fold_explicit_args_aux es ps.tail else fold_explicit_args_aux es ps.tail a meta def fold_explicit_args {α} (e : expr) (a : α) (f : α → expr → tactic α) : tactic α := if e.is_app then do info ← get_fun_info e.get_app_fn (some e.get_app_num_args), fold_explicit_args_aux f e.get_app_args info.params a else return a end tactic
8f8a049b4ae5387bb79e87d08feee67e211c8a12
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_312.lean
c079d5153bd08f765c611daf4b88d34a48c94a69
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
311
lean
variables p q : Prop -- BEGIN example (h : p ∧ q) : q ∧ p := begin split, -- By and introduction, it suffices to prove both `q` and `p`. show q, from h.right, -- We show `q` by right and elimination on `h`. show p, from h.left, -- We show `p` by left and elimination on `h`. end -- END
09b52454da7a387244231b0bb190df690b163652
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/ideal/local_ring.lean
887c8460300367593156892632d8b0afa695f59b
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
17,589
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.algebra.basic import ring_theory.ideal.operations import ring_theory.jacobson_ideal import logic.equiv.transfer_instance /-! # Local rings Define local rings as commutative rings having a unique maximal ideal. ## Main definitions * `local_ring`: A predicate on commutative semirings, stating that for any pair of elements that adds up to `1`, one of them is a unit. This is shown to be equivalent to the condition that there exists a unique maximal ideal. * `local_ring.maximal_ideal`: The unique maximal ideal for a local rings. Its carrier set is the set of non units. * `is_local_ring_hom`: A predicate on semiring homomorphisms, requiring that it maps nonunits to nonunits. For local rings, this means that the image of the unique maximal ideal is again contained in the unique maximal ideal. * `local_ring.residue_field`: The quotient of a local ring by its maximal ideal. -/ universes u v w u' variables {R : Type u} {S : Type v} {T : Type w} {K : Type u'} /-- A semiring is local if it is nontrivial and `a` or `b` is a unit whenever `a + b = 1`. Note that `local_ring` is a predicate. -/ class local_ring (R : Type u) [semiring R] extends nontrivial R : Prop := of_is_unit_or_is_unit_of_add_one :: (is_unit_or_is_unit_of_add_one {a b : R} (h : a + b = 1) : is_unit a ∨ is_unit b) section comm_semiring variables [comm_semiring R] namespace local_ring lemma of_is_unit_or_is_unit_of_is_unit_add [nontrivial R] (h : ∀ a b : R, is_unit (a + b) → is_unit a ∨ is_unit b) : local_ring R := ⟨λ a b hab, h a b $ hab.symm ▸ is_unit_one⟩ /-- A semiring is local if it is nontrivial and the set of nonunits is closed under the addition. -/ lemma of_nonunits_add [nontrivial R] (h : ∀ a b : R, a ∈ nonunits R → b ∈ nonunits R → a + b ∈ nonunits R) : local_ring R := ⟨λ a b hab, or_iff_not_and_not.2 $ λ H, h a b H.1 H.2 $ hab.symm ▸ is_unit_one⟩ /-- A semiring is local if it has a unique maximal ideal. -/ lemma of_unique_max_ideal (h : ∃! I : ideal R, I.is_maximal) : local_ring R := @of_nonunits_add _ _ (nontrivial_of_ne (0 : R) 1 $ let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from Iuniq Ix Ixmax ▸ Hx, have ymemI : y ∈ I, from Iuniq Iy Iymax ▸ Hy, Imax.1.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H lemma of_unique_nonzero_prime (h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R := of_unique_max_ideal begin rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩, refine ⟨P, ⟨⟨hPnot_top, _⟩⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩, { refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _), exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm }, { rintro rfl, exact hPnot_top (hM.1.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) }, end variables [local_ring R] lemma is_unit_or_is_unit_of_is_unit_add {a b : R} (h : is_unit (a + b)) : is_unit a ∨ is_unit b := begin rcases h with ⟨u, hu⟩, rw [←units.inv_mul_eq_one, mul_add] at hu, apply or.imp _ _ (is_unit_or_is_unit_of_add_one hu); exact is_unit_of_mul_is_unit_right, end lemma nonunits_add {a b : R} (ha : a ∈ nonunits R) (hb : b ∈ nonunits R) : a + b ∈ nonunits R:= λ H, not_or ha hb (is_unit_or_is_unit_of_is_unit_add H) variables (R) /-- The ideal of elements that are not units. -/ def maximal_ideal : ideal R := { carrier := nonunits R, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance maximal_ideal.is_maximal : (maximal_ideal R).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.mul_mem_left ↑u⁻¹ H } end lemma maximal_ideal_unique : ∃! I : ideal R, I.is_maximal := ⟨maximal_ideal R, maximal_ideal.is_maximal R, λ I hI, hI.eq_of_le (maximal_ideal.is_maximal R).1.1 $ λ x hx, hI.1.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {R} lemma eq_maximal_ideal {I : ideal R} (hI : I.is_maximal) : I = maximal_ideal R := unique_of_exists_unique (maximal_ideal_unique R) hI $ maximal_ideal.is_maximal R lemma le_maximal_ideal {J : ideal R} (hJ : J ≠ ⊤) : J ≤ maximal_ideal R := begin rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩, rwa ←eq_maximal_ideal hM1 end @[simp] lemma mem_maximal_ideal (x) : x ∈ maximal_ideal R ↔ x ∈ nonunits R := iff.rfl lemma is_field_iff_maximal_ideal_eq : is_field R ↔ maximal_ideal R = ⊥ := not_iff_not.mp ⟨ring.ne_bot_of_is_maximal_of_not_is_field infer_instance, λ h, ring.not_is_field_iff_exists_prime.mpr ⟨_, h, ideal.is_maximal.is_prime' _⟩⟩ end local_ring end comm_semiring section comm_ring variables [comm_ring R] namespace local_ring lemma of_is_unit_or_is_unit_one_sub_self [nontrivial R] (h : ∀ a : R, is_unit a ∨ is_unit (1 - a)) : local_ring R := ⟨λ a b hab, add_sub_cancel' a b ▸ hab.symm ▸ h a⟩ variables [local_ring R] lemma is_unit_or_is_unit_one_sub_self (a : R) : is_unit a ∨ is_unit (1 - a) := is_unit_or_is_unit_of_is_unit_add $ (add_sub_cancel'_right a 1).symm ▸ is_unit_one lemma is_unit_of_mem_nonunits_one_sub_self (a : R) (h : 1 - a ∈ nonunits R) : is_unit a := or_iff_not_imp_right.1 (is_unit_or_is_unit_one_sub_self a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : R) (h : a ∈ nonunits R) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_unit_or_is_unit_one_sub_self a) h lemma of_surjective' [comm_ring S] [nontrivial S] (f : R →+* S) (hf : function.surjective f) : local_ring S := of_is_unit_or_is_unit_one_sub_self begin intros b, obtain ⟨a, rfl⟩ := hf b, apply (is_unit_or_is_unit_one_sub_self a).imp f.is_unit_map _, rw [← f.map_one, ← f.map_sub], apply f.is_unit_map, end lemma jacobson_eq_maximal_ideal (I : ideal R) (h : I ≠ ⊤) : I.jacobson = local_ring.maximal_ideal R := begin apply le_antisymm, { exact Inf_le ⟨local_ring.le_maximal_ideal h, local_ring.maximal_ideal.is_maximal R⟩ }, { exact le_Inf (λ J (hJ : I ≤ J ∧ J.is_maximal), le_of_eq (local_ring.eq_maximal_ideal hJ.2).symm) } end end local_ring end comm_ring /-- A local ring homomorphism is a homomorphism `f` between local rings such that `a` in the domain is a unit if `f a` is a unit for any `a`. See `local_ring.local_hom_tfae` for other equivalent definitions. -/ class is_local_ring_hom [semiring R] [semiring S] (f : R →+* S) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) section variables [semiring R] [semiring S] [semiring T] instance is_local_ring_hom_id (R : Type*) [semiring R] : is_local_ring_hom (ring_hom.id R) := { map_nonunit := λ a, id } @[simp] lemma is_unit_map_iff (f : R →+* S) [is_local_ring_hom f] (a) : is_unit (f a) ↔ is_unit a := ⟨is_local_ring_hom.map_nonunit a, f.is_unit_map⟩ @[simp] lemma map_mem_nonunits_iff (f : R →+* S) [is_local_ring_hom f] (a) : f a ∈ nonunits S ↔ a ∈ nonunits R := ⟨λ h ha, h $ (is_unit_map_iff f a).mpr ha, λ h ha, h $ (is_unit_map_iff f a).mp ha⟩ instance is_local_ring_hom_comp (g : S →+* T) (f : R →+* S) [is_local_ring_hom g] [is_local_ring_hom f] : is_local_ring_hom (g.comp f) := { map_nonunit := λ a, is_local_ring_hom.map_nonunit a ∘ is_local_ring_hom.map_nonunit (f a) } instance is_local_ring_hom_equiv (f : R ≃+* S) : is_local_ring_hom (f : R →+* S) := { map_nonunit := λ a ha, begin convert (f.symm : S →+* R).is_unit_map ha, exact (ring_equiv.symm_apply_apply f a).symm, end } @[simp] lemma is_unit_of_map_unit (f : R →+* S) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h theorem of_irreducible_map (f : R →+* S) [h : is_local_ring_hom f] {x} (hfx : irreducible (f x)) : irreducible x := ⟨λ h, hfx.not_unit $ is_unit.map f h, λ p q hx, let ⟨H⟩ := h in or.imp (H p) (H q) $ hfx.is_unit_or_is_unit $ f.map_mul p q ▸ congr_arg f hx⟩ lemma is_local_ring_hom_of_comp (f : R →+* S) (g : S →+* T) [is_local_ring_hom (g.comp f)] : is_local_ring_hom f := ⟨λ a ha, (is_unit_map_iff (g.comp f) _).mp (g.is_unit_map ha)⟩ /-- If `f : R →+* S` is a local ring hom, then `R` is a local ring if `S` is. -/ lemma _root_.ring_hom.domain_local_ring {R S : Type*} [comm_semiring R] [comm_semiring S] [H : _root_.local_ring S] (f : R →+* S) [is_local_ring_hom f] : _root_.local_ring R := begin haveI : nontrivial R := pullback_nonzero f f.map_zero f.map_one, apply local_ring.of_nonunits_add, intros a b, simp_rw [←map_mem_nonunits_iff f, f.map_add], exact local_ring.nonunits_add end end section open local_ring variables [comm_semiring R] [local_ring R] [comm_semiring S] [local_ring S] /-- The image of the maximal ideal of the source is contained within the maximal ideal of the target. -/ lemma map_nonunit (f : R →+* S) [is_local_ring_hom f] (a : R) (h : a ∈ maximal_ideal R) : f a ∈ maximal_ideal S := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring section variables [comm_semiring R] [local_ring R] [comm_semiring S] [local_ring S] /-- A ring homomorphism between local rings is a local ring hom iff it reflects units, i.e. any preimage of a unit is still a unit. https://stacks.math.columbia.edu/tag/07BJ -/ theorem local_hom_tfae (f : R →+* S) : tfae [is_local_ring_hom f, f '' (maximal_ideal R).1 ⊆ maximal_ideal S, (maximal_ideal R).map f ≤ maximal_ideal S, maximal_ideal R ≤ (maximal_ideal S).comap f, (maximal_ideal S).comap f = maximal_ideal R] := begin tfae_have : 1 → 2, rintros _ _ ⟨a,ha,rfl⟩, resetI, exact map_nonunit f a ha, tfae_have : 2 → 4, exact set.image_subset_iff.1, tfae_have : 3 ↔ 4, exact ideal.map_le_iff_le_comap, tfae_have : 4 → 1, intro h, fsplit, exact λ x, not_imp_not.1 (@h x), tfae_have : 1 → 5, intro, resetI, ext, exact not_iff_not.2 (is_unit_map_iff f x), tfae_have : 5 → 4, exact λ h, le_of_eq h.symm, tfae_finish, end end lemma of_surjective [comm_semiring R] [local_ring R] [comm_semiring S] [nontrivial S] (f : R →+* S) [is_local_ring_hom f] (hf : function.surjective f) : local_ring S := of_is_unit_or_is_unit_of_is_unit_add begin intros a b hab, obtain ⟨a, rfl⟩ := hf a, obtain ⟨b, rfl⟩ := hf b, rw ←map_add at hab, exact (is_unit_or_is_unit_of_is_unit_add $ is_local_ring_hom.map_nonunit _ hab).imp f.is_unit_map f.is_unit_map end /-- If `f : R →+* S` is a surjective local ring hom, then the induced units map is surjective. -/ lemma surjective_units_map_of_local_ring_hom [comm_ring R] [comm_ring S] (f : R →+* S) (hf : function.surjective f) (h : is_local_ring_hom f) : function.surjective (units.map $ f.to_monoid_hom) := begin intro a, obtain ⟨b,hb⟩ := hf (a : S), use (is_unit_of_map_unit f _ (by { rw hb, exact units.is_unit _})).unit, ext, exact hb, end section variables (R) [comm_ring R] [local_ring R] [comm_ring S] [local_ring S] [comm_ring T] [local_ring T] /-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/ @[derive [ring, comm_ring, inhabited]] def residue_field := R ⧸ maximal_ideal R noncomputable instance residue_field.field : field (residue_field R) := ideal.quotient.field (maximal_ideal R) /-- The quotient map from a local ring to its residue field. -/ def residue : R →+* (residue_field R) := ideal.quotient.mk _ instance residue_field.algebra : algebra R (residue_field R) := ideal.quotient.algebra _ lemma residue_field.algebra_map_eq : algebra_map R (residue_field R) = residue R := rfl instance : is_local_ring_hom (local_ring.residue R) := ⟨λ a ha, not_not.mp (ideal.quotient.eq_zero_iff_mem.not.mp (is_unit_iff_ne_zero.mp ha))⟩ variables {R} namespace residue_field /-- A local ring homomorphism into a field can be descended onto the residue field. -/ def lift {R S : Type*} [comm_ring R] [local_ring R] [field S] (f : R →+* S) [is_local_ring_hom f] : local_ring.residue_field R →+* S := ideal.quotient.lift _ f (λ a ha, classical.by_contradiction (λ h, ha (is_unit_of_map_unit f a (is_unit_iff_ne_zero.mpr h)))) lemma lift_comp_residue {R S : Type*} [comm_ring R] [local_ring R] [field S] (f : R →+* S) [is_local_ring_hom f] : (lift f).comp (residue R) = f := ring_hom.ext (λ _, rfl) @[simp] lemma lift_residue_apply {R S : Type*} [comm_ring R] [local_ring R] [field S] (f : R →+* S) [is_local_ring_hom f] (x) : lift f (residue R x) = f x := rfl /-- The map on residue fields induced by a local homomorphism between local rings -/ def map (f : R →+* S) [is_local_ring_hom f] : residue_field R →+* residue_field S := ideal.quotient.lift (maximal_ideal R) ((ideal.quotient.mk _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end /-- Applying `residue_field.map` to the identity ring homomorphism gives the identity ring homomorphism. -/ @[simp] lemma map_id : local_ring.residue_field.map (ring_hom.id R) = ring_hom.id (local_ring.residue_field R) := ideal.quotient.ring_hom_ext $ ring_hom.ext $ λx, rfl /-- The composite of two `residue_field.map`s is the `residue_field.map` of the composite. -/ lemma map_comp (f : T →+* R) (g : R →+* S) [is_local_ring_hom f] [is_local_ring_hom g] : local_ring.residue_field.map (g.comp f) = (local_ring.residue_field.map g).comp (local_ring.residue_field.map f) := ideal.quotient.ring_hom_ext $ ring_hom.ext $ λx, rfl lemma map_comp_residue (f : R →+* S) [is_local_ring_hom f] : (residue_field.map f).comp (residue R) = (residue S).comp f := rfl lemma map_residue (f : R →+* S) [is_local_ring_hom f] (r : R) : residue_field.map f (residue R r) = residue S (f r) := rfl lemma map_id_apply (x : residue_field R) : map (ring_hom.id R) x = x := fun_like.congr_fun map_id x @[simp] lemma map_map (f : R →+* S) (g : S →+* T) (x : residue_field R) [is_local_ring_hom f] [is_local_ring_hom g] : map g (map f x) = map (g.comp f) x := fun_like.congr_fun (map_comp f g).symm x /-- A ring isomorphism defines an isomorphism of residue fields. -/ @[simps apply] def map_equiv (f : R ≃+* S) : local_ring.residue_field R ≃+* local_ring.residue_field S := { to_fun := map (f : R →+* S), inv_fun := map (f.symm : S →+* R), left_inv := λ x, by simp only [map_map, ring_equiv.symm_comp, map_id, ring_hom.id_apply], right_inv := λ x, by simp only [map_map, ring_equiv.comp_symm, map_id, ring_hom.id_apply], map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _ } @[simp] lemma map_equiv.symm (f : R ≃+* S) : (map_equiv f).symm = map_equiv f.symm := rfl @[simp] lemma map_equiv_trans (e₁ : R ≃+* S) (e₂ : S ≃+* T) : map_equiv (e₁.trans e₂) = (map_equiv e₁).trans (map_equiv e₂) := ring_equiv.to_ring_hom_injective $ map_comp (e₁ : R →+* S) (e₂ : S →+* T) @[simp] lemma map_equiv_refl : map_equiv (ring_equiv.refl R) = ring_equiv.refl _ := ring_equiv.to_ring_hom_injective map_id /-- The group homomorphism from `ring_aut R` to `ring_aut k` where `k` is the residue field of `R`. -/ @[simps] def map_aut : ring_aut R →* ring_aut (local_ring.residue_field R) := { to_fun := map_equiv, map_mul' := λ e₁ e₂, map_equiv_trans e₂ e₁, map_one' := map_equiv_refl } section mul_semiring_action variables (G : Type*) [group G] [mul_semiring_action G R] /-- If `G` acts on `R` as a `mul_semiring_action`, then it also acts on `residue_field R`. -/ instance : mul_semiring_action G (local_ring.residue_field R) := mul_semiring_action.comp_hom _ $ map_aut.comp (mul_semiring_action.to_ring_aut G R) @[simp] lemma residue_smul (g : G) (r : R) : residue R (g • r) = g • residue R r := rfl end mul_semiring_action end residue_field lemma ker_eq_maximal_ideal [field K] (φ : R →+* K) (hφ : function.surjective φ) : φ.ker = maximal_ideal R := local_ring.eq_maximal_ideal $ (ring_hom.ker_is_maximal_of_surjective φ) hφ lemma is_local_ring_hom_residue : is_local_ring_hom (local_ring.residue R) := begin constructor, intros a ha, by_contra, erw ideal.quotient.eq_zero_iff_mem.mpr ((local_ring.mem_maximal_ideal _).mpr h) at ha, exact ha.ne_zero rfl, end end end local_ring namespace field variables (K) [field K] open_locale classical @[priority 100] -- see Note [lower instance priority] instance : local_ring K := local_ring.of_is_unit_or_is_unit_one_sub_self $ λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit.mk0 a h end field lemma local_ring.maximal_ideal_eq_bot {R : Type*} [field R] : local_ring.maximal_ideal R = ⊥ := local_ring.is_field_iff_maximal_ideal_eq.mp (field.to_is_field R) namespace ring_equiv @[reducible] protected lemma local_ring {A B : Type*} [comm_semiring A] [local_ring A] [comm_semiring B] (e : A ≃+* B) : local_ring B := begin haveI := e.symm.to_equiv.nontrivial, exact local_ring.of_surjective (e : A →+* B) e.surjective end end ring_equiv
c54bfca299f4f1f764a42f94958ded348068f190
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/matrix/charpoly/linear_map.lean
d37988acc241bbd8900652013b958a34710ebc90
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,311
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import linear_algebra.matrix.charpoly.coeff import linear_algebra.matrix.to_lin /-! # Calyley-Hamilton theorem for f.g. modules. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a fixed finite spanning set `b : ι → M` of a `R`-module `M`, we say that a matrix `M` represents an endomorphism `f : M →ₗ[R] M` if the matrix as an endomorphism of `ι → R` commutes with `f` via the projection `(ι → R) →ₗ[R] M` given by `b`. We show that every endomorphism has a matrix representation, and if `f.range ≤ I • ⊤` for some ideal `I`, we may furthermore obtain a matrix representation whose entries fall in `I`. This is used to conclude the Cayley-Hamilton theorem for f.g. modules over arbitrary rings. -/ variables {ι : Type*} [fintype ι] variables {M : Type*} [add_comm_group M] (R : Type*) [comm_ring R] [module R M] (I : ideal R) variables (b : ι → M) (hb : submodule.span R (set.range b) = ⊤) open_locale big_operators open_locale polynomial /-- The composition of a matrix (as an endomporphism of `ι → R`) with the projection `(ι → R) →ₗ[R] M`. -/ def pi_to_module.from_matrix [decidable_eq ι] : matrix ι ι R →ₗ[R] (ι → R) →ₗ[R] M := (linear_map.llcomp R _ _ _ (fintype.total R R b)).comp alg_equiv_matrix'.symm.to_linear_map lemma pi_to_module.from_matrix_apply [decidable_eq ι] (A : matrix ι ι R) (w : ι → R) : pi_to_module.from_matrix R b A w = fintype.total R R b (A.mul_vec w) := rfl lemma pi_to_module.from_matrix_apply_single_one [decidable_eq ι] (A : matrix ι ι R) (j : ι) : pi_to_module.from_matrix R b A (pi.single j 1) = ∑ (i : ι), A i j • b i := begin rw [pi_to_module.from_matrix_apply, fintype.total_apply, matrix.mul_vec_single], simp_rw [mul_one] end /-- The endomorphisms of `M` acts on `(ι → R) →ₗ[R] M`, and takes the projection to a `(ι → R) →ₗ[R] M`. -/ def pi_to_module.from_End : (module.End R M) →ₗ[R] (ι → R) →ₗ[R] M := linear_map.lcomp _ _ (fintype.total R R b) lemma pi_to_module.from_End_apply (f : module.End R M) (w : ι → R) : pi_to_module.from_End R b f w = f (fintype.total R R b w) := rfl lemma pi_to_module.from_End_apply_single_one [decidable_eq ι] (f : module.End R M) (i : ι) : pi_to_module.from_End R b f (pi.single i 1) = f (b i) := begin rw pi_to_module.from_End_apply, congr, convert fintype.total_apply_single R b i 1, rw one_smul, end lemma pi_to_module.from_End_injective (hb : submodule.span R (set.range b) = ⊤) : function.injective (pi_to_module.from_End R b) := begin intros x y e, ext m, obtain ⟨m, rfl⟩ : m ∈ (fintype.total R R b).range, { rw (fintype.range_total R b).trans hb, trivial }, exact (linear_map.congr_fun e m : _) end section variables {R} [decidable_eq ι] /-- We say that a matrix represents an endomorphism of `M` if the matrix acting on `ι → R` is equal to `f` via the projection `(ι → R) →ₗ[R] M` given by a fixed (spanning) set. -/ def matrix.represents (A : matrix ι ι R) (f : module.End R M) : Prop := pi_to_module.from_matrix R b A = pi_to_module.from_End R b f variables {b} lemma matrix.represents.congr_fun {A : matrix ι ι R} {f : module.End R M} (h : A.represents b f) (x) : fintype.total R R b (A.mul_vec x) = f (fintype.total R R b x) := linear_map.congr_fun h x lemma matrix.represents_iff {A : matrix ι ι R} {f : module.End R M} : A.represents b f ↔ ∀ x, fintype.total R R b (A.mul_vec x) = f (fintype.total R R b x) := ⟨λ e x, e.congr_fun x, λ H, linear_map.ext $ λ x, H x⟩ lemma matrix.represents_iff' {A : matrix ι ι R} {f : module.End R M} : A.represents b f ↔ ∀ j, ∑ (i : ι), A i j • b i = f (b j) := begin split, { intros h i, have := linear_map.congr_fun h (pi.single i 1), rwa [pi_to_module.from_End_apply_single_one, pi_to_module.from_matrix_apply_single_one] at this }, { intros h, ext, simp_rw [linear_map.comp_apply, linear_map.coe_single, pi_to_module.from_End_apply_single_one, pi_to_module.from_matrix_apply_single_one], apply h } end lemma matrix.represents.mul {A A' : matrix ι ι R} {f f' : module.End R M} (h : A.represents b f) (h' : matrix.represents b A' f') : (A * A').represents b (f * f') := begin delta matrix.represents pi_to_module.from_matrix at ⊢, rw [linear_map.comp_apply, alg_equiv.to_linear_map_apply, map_mul], ext, dsimp [pi_to_module.from_End], rw [← h'.congr_fun, ← h.congr_fun], refl, end lemma matrix.represents.one : (1 : matrix ι ι R).represents b 1 := begin delta matrix.represents pi_to_module.from_matrix, rw [linear_map.comp_apply, alg_equiv.to_linear_map_apply, map_one], ext, refl end lemma matrix.represents.add {A A' : matrix ι ι R} {f f' : module.End R M} (h : A.represents b f) (h' : matrix.represents b A' f') : (A + A').represents b (f + f') := begin delta matrix.represents at ⊢ h h', rw [map_add, map_add, h, h'], end lemma matrix.represents.zero : (0 : matrix ι ι R).represents b 0 := begin delta matrix.represents, rw [map_zero, map_zero], end lemma matrix.represents.smul {A : matrix ι ι R} {f : module.End R M} (h : A.represents b f) (r : R) : (r • A).represents b (r • f) := begin delta matrix.represents at ⊢ h, rw [map_smul, map_smul, h], end lemma matrix.represents.eq {A : matrix ι ι R} {f f' : module.End R M} (h : A.represents b f) (h' : A.represents b f') : f = f' := pi_to_module.from_End_injective R b hb (h.symm.trans h') variables (b R) /-- The subalgebra of `matrix ι ι R` that consists of matrices that actually represent endomorphisms on `M`. -/ def matrix.is_representation : subalgebra R (matrix ι ι R) := { carrier := { A | ∃ f : module.End R M, A.represents b f }, mul_mem' := λ A₁ A₂ ⟨f₁, e₁⟩ ⟨f₂, e₂⟩, ⟨f₁ * f₂, e₁.mul e₂⟩, one_mem' := ⟨1, matrix.represents.one⟩, add_mem' := λ A₁ A₂ ⟨f₁, e₁⟩ ⟨f₂, e₂⟩, ⟨f₁ + f₂, e₁.add e₂⟩, zero_mem' := ⟨0, matrix.represents.zero⟩, algebra_map_mem' := λ r, ⟨r • 1, matrix.represents.one.smul r⟩ } /-- The map sending a matrix to the endomorphism it represents. This is an `R`-algebra morphism. -/ noncomputable def matrix.is_representation.to_End : matrix.is_representation R b →ₐ[R] module.End R M := { to_fun := λ A, A.2.some, map_one' := (1 : matrix.is_representation R b).2.some_spec.eq hb matrix.represents.one, map_mul' := λ A₁ A₂, (A₁ * A₂).2.some_spec.eq hb (A₁.2.some_spec.mul A₂.2.some_spec), map_zero' := (0 : matrix.is_representation R b).2.some_spec.eq hb matrix.represents.zero, map_add' := λ A₁ A₂, (A₁ + A₂).2.some_spec.eq hb (A₁.2.some_spec.add A₂.2.some_spec), commutes' := λ r, (r • 1 : matrix.is_representation R b).2.some_spec.eq hb (matrix.represents.one.smul r) } lemma matrix.is_representation.to_End_represents (A : matrix.is_representation R b) : (A : matrix ι ι R).represents b (matrix.is_representation.to_End R b hb A) := A.2.some_spec lemma matrix.is_representation.eq_to_End_of_represents (A : matrix.is_representation R b) {f : module.End R M} (h : (A : matrix ι ι R).represents b f) : matrix.is_representation.to_End R b hb A = f := A.2.some_spec.eq hb h lemma matrix.is_representation.to_End_exists_mem_ideal (f : module.End R M) (I : ideal R) (hI : f.range ≤ I • ⊤) : ∃ M, matrix.is_representation.to_End R b hb M = f ∧ ∀ i j, M.1 i j ∈ I := begin have : ∀ x, f x ∈ (ideal.finsupp_total ι M I b).range, { rw [ideal.range_finsupp_total, hb], exact λ x, hI (f.mem_range_self x) }, choose bM' hbM', let A : matrix ι ι R := λ i j, bM' (b j) i, have : A.represents b f, { rw matrix.represents_iff', dsimp [A], intro j, specialize hbM' (b j), rwa ideal.finsupp_total_apply_eq_of_fintype at hbM' }, exact ⟨⟨A, f, this⟩, matrix.is_representation.eq_to_End_of_represents R b hb ⟨A, f, this⟩ this, λ i j, (bM' (b j) i).prop⟩, end lemma matrix.is_representation.to_End_surjective : function.surjective (matrix.is_representation.to_End R b hb) := begin intro f, obtain ⟨M, e, -⟩ := matrix.is_representation.to_End_exists_mem_ideal R b hb f ⊤ _, exact ⟨M, e⟩, simp, end end /-- The **Cayley-Hamilton Theorem** for f.g. modules over arbitrary rings states that for each `R`-endomorphism `φ` of an `R`-module `M` such that `φ(M) ≤ I • M` for some ideal `I`, there exists some `n` and some `aᵢ ∈ Iⁱ` such that `φⁿ + a₁ φⁿ⁻¹ + ⋯ + aₙ = 0`. This is the version found in Eisenbud 4.3, which is slightly weaker than Matsumura 2.1 (this lacks the constraint on `n`), and is slightly stronger than Atiyah-Macdonald 2.4. -/ lemma linear_map.exists_monic_and_coeff_mem_pow_and_aeval_eq_zero_of_range_le_smul [module.finite R M] (f : module.End R M) (I : ideal R) (hI : f.range ≤ I • ⊤) : ∃ p : R[X], p.monic ∧ (∀ k, p.coeff k ∈ I ^ (p.nat_degree - k)) ∧ polynomial.aeval f p = 0 := begin classical, casesI subsingleton_or_nontrivial R, { exactI ⟨0, polynomial.monic_of_subsingleton _, by simp⟩ }, obtain ⟨s : finset M, hs : submodule.span R (s : set M) = ⊤⟩ := module.finite.out, obtain ⟨A, rfl, h⟩ := matrix.is_representation.to_End_exists_mem_ideal R (coe : s → M) (by rw [subtype.range_coe_subtype, finset.set_of_mem, hs]) f I hI, refine ⟨A.1.charpoly, A.1.charpoly_monic, _, _⟩, { rw A.1.charpoly_nat_degree_eq_dim, exact coeff_charpoly_mem_ideal_pow h }, { rw [polynomial.aeval_alg_hom_apply, ← map_zero (matrix.is_representation.to_End R coe _)], congr' 1, ext1, rw [polynomial.aeval_subalgebra_coe, subtype.val_eq_coe, matrix.aeval_self_charpoly, subalgebra.coe_zero] }, { apply_instance } end lemma linear_map.exists_monic_and_aeval_eq_zero [module.finite R M] (f : module.End R M) : ∃ p : R[X], p.monic ∧ polynomial.aeval f p = 0 := (linear_map.exists_monic_and_coeff_mem_pow_and_aeval_eq_zero_of_range_le_smul R f ⊤ (by simp)).imp (λ p h, h.imp_right and.elim_right)
e50c3f12a2b8b9928d39d5079f55c4dfbe3afda5
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/convex/specific_functions.lean
1a1a6dd6303e60cacc3b3aba56976764f85cfec1
[ "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
9,729
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel -/ import analysis.calculus.mean_value import analysis.special_functions.pow_deriv /-! # Collection of convex functions In this file we prove that the following functions are convex: * `strict_convex_on_exp` : The exponential function is strictly convex. * `even.convex_on_pow`, `even.strict_convex_on_pow` : For an even `n : ℕ`, `λ x, x ^ n` is convex and strictly convex when `2 ≤ n`. * `convex_on_pow`, `strict_convex_on_pow` : For `n : ℕ`, `λ x, x ^ n` is convex on $[0, +∞)$ and strictly convex when `2 ≤ n`. * `convex_on_zpow`, `strict_convex_on_zpow` : For `m : ℤ`, `λ x, x ^ m` is convex on $[0, +∞)$ and strictly convex when `m ≠ 0, 1`. * `convex_on_rpow`, `strict_convex_on_rpow` : For `p : ℝ`, `λ x, x ^ p` is convex on $[0, +∞)$ when `1 ≤ p` and strictly convex when `1 < p`. * `strict_concave_on_log_Ioi`, `strict_concave_on_log_Iio`: `real.log` is strictly concave on $(0, +∞)$ and $(-∞, 0)$ respectively. ## TODO For `p : ℝ`, prove that `λ x, x ^ p` is concave when `0 ≤ p ≤ 1` and strictly concave when `0 < p < 1`. -/ open real set open_locale big_operators /-- The norm of a real normed space is convex. Also see `seminorm.convex_on`. -/ lemma convex_on_norm {E : Type*} [normed_group E] [normed_space ℝ E] : convex_on ℝ univ (norm : E → ℝ) := ⟨convex_univ, λ x y hx hy a b ha hb hab, calc ∥a • x + b • y∥ ≤ ∥a • x∥ + ∥b • y∥ : norm_add_le _ _ ... = a * ∥x∥ + b * ∥y∥ : by rw [norm_smul, norm_smul, real.norm_of_nonneg ha, real.norm_of_nonneg hb]⟩ /-- `exp` is strictly convex on the whole real line. -/ lemma strict_convex_on_exp : strict_convex_on ℝ univ exp := strict_convex_on_univ_of_deriv2_pos differentiable_exp (λ x, (iter_deriv_exp 2).symm ▸ exp_pos x) /-- `exp` is convex on the whole real line. -/ lemma convex_on_exp : convex_on ℝ univ exp := strict_convex_on_exp.convex_on /-- `x^n`, `n : ℕ` is convex on the whole real line whenever `n` is even -/ lemma even.convex_on_pow {n : ℕ} (hn : even n) : convex_on ℝ set.univ (λ x : ℝ, x^n) := begin apply convex_on_univ_of_deriv2_nonneg differentiable_pow, { simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] }, { intro x, rcases nat.even.sub_even hn (nat.even_bit0 1) with ⟨k, hk⟩, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub, hk, pow_mul'], exact mul_nonneg (nat.cast_nonneg _) (pow_two_nonneg _) } end /-- `x^n`, `n : ℕ` is strictly convex on the whole real line whenever `n ≠ 0` is even. -/ lemma even.strict_convex_on_pow {n : ℕ} (hn : even n) (h : n ≠ 0) : strict_convex_on ℝ set.univ (λ x : ℝ, x^n) := begin apply strict_mono.strict_convex_on_univ_of_deriv differentiable_pow, rw deriv_pow', replace h := nat.pos_of_ne_zero h, exact strict_mono.const_mul (odd.strict_mono_pow $ nat.even.sub_odd h hn $ nat.odd_iff.2 rfl) (nat.cast_pos.2 h), end /-- `x^n`, `n : ℕ` is convex on `[0, +∞)` for all `n` -/ lemma convex_on_pow (n : ℕ) : convex_on ℝ (Ici 0) (λ x : ℝ, x^n) := begin apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on differentiable_on_pow, { simp only [deriv_pow'], exact (@differentiable_on_pow ℝ _ _ _).const_mul (n : ℝ) }, { intros x hx, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub], exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (interior_subset hx) _) } end /-- `x^n`, `n : ℕ` is strictly convex on `[0, +∞)` for all `n` greater than `2`. -/ lemma strict_convex_on_pow {n : ℕ} (hn : 2 ≤ n) : strict_convex_on ℝ (Ici 0) (λ x : ℝ, x^n) := begin apply strict_mono_on.strict_convex_on_of_deriv (convex_Ici _) (continuous_on_pow _) differentiable_on_pow, rw [deriv_pow', interior_Ici], exact λ x (hx : 0 < x) y hy hxy, mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_left hxy hx.le $ nat.sub_pos_of_lt hn) (nat.cast_pos.2 $ zero_lt_two.trans_le hn), end lemma finset.prod_nonneg_of_card_nonpos_even {α β : Type*} [linear_ordered_comm_ring β] {f : α → β} [decidable_pred (λ x, f x ≤ 0)] {s : finset α} (h0 : even (s.filter (λ x, f x ≤ 0)).card) : 0 ≤ ∏ x in s, f x := calc 0 ≤ (∏ x in s, ((if f x ≤ 0 then (-1:β) else 1) * f x)) : finset.prod_nonneg (λ x _, by { split_ifs with hx hx, by simp [hx], simp at hx ⊢, exact le_of_lt hx }) ... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one, mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul] lemma int_prod_range_nonneg (m : ℤ) (n : ℕ) (hn : even n) : 0 ≤ ∏ k in finset.range n, (m - k) := begin rcases hn with ⟨n, rfl⟩, induction n with n ihn, { simp }, rw [nat.succ_eq_add_one, mul_add, mul_one, bit0, ← add_assoc, finset.prod_range_succ, finset.prod_range_succ, mul_assoc], refine mul_nonneg ihn _, generalize : (1 + 1) * n = k, cases le_or_lt m k with hmk hmk, { have : m ≤ k + 1, from hmk.trans (lt_add_one ↑k).le, exact mul_nonneg_of_nonpos_of_nonpos (sub_nonpos_of_le hmk) (sub_nonpos_of_le this) }, { exact mul_nonneg (sub_nonneg_of_le hmk.le) (sub_nonneg_of_le hmk) } end lemma int_prod_range_pos {m : ℤ} {n : ℕ} (hn : even n) (hm : m ∉ Ico (0 : ℤ) n) : 0 < ∏ k in finset.range n, (m - k) := begin refine (int_prod_range_nonneg m n hn).lt_of_ne (λ h, hm _), rw [eq_comm, finset.prod_eq_zero_iff] at h, obtain ⟨a, ha, h⟩ := h, rw sub_eq_zero.1 h, exact ⟨int.coe_zero_le _, int.coe_nat_lt.2 $ finset.mem_range.1 ha⟩, end /-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` -/ lemma convex_on_zpow (m : ℤ) : convex_on ℝ (Ioi 0) (λ x : ℝ, x^m) := begin have : ∀ n : ℤ, differentiable_on ℝ (λ x, x ^ n) (Ioi (0 : ℝ)), from λ n, differentiable_on_zpow _ _ (or.inl $ lt_irrefl _), apply convex_on_of_deriv2_nonneg (convex_Ioi 0); try { simp only [interior_Ioi, deriv_zpow'] }, { exact (this _).continuous_on }, { exact this _ }, { exact (this _).const_mul _ }, { intros x hx, simp only [iter_deriv_zpow, ← int.cast_coe_nat, ← int.cast_sub, ← int.cast_prod], refine mul_nonneg (int.cast_nonneg.2 _) (zpow_nonneg (le_of_lt hx) _), exact int_prod_range_nonneg _ _ (nat.even_bit0 1) } end /-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` except `0` and `1`. -/ lemma strict_convex_on_zpow {m : ℤ} (hm₀ : m ≠ 0) (hm₁ : m ≠ 1) : strict_convex_on ℝ (Ioi 0) (λ x : ℝ, x^m) := begin have : ∀ n : ℤ, differentiable_on ℝ (λ x, x ^ n) (Ioi (0 : ℝ)), from λ n, differentiable_on_zpow _ _ (or.inl $ lt_irrefl _), apply strict_convex_on_of_deriv2_pos (convex_Ioi 0), { exact (this _).continuous_on }, all_goals { rw interior_Ioi }, { exact this _ }, intros x hx, simp only [iter_deriv_zpow, ← int.cast_coe_nat, ← int.cast_sub, ← int.cast_prod], refine mul_pos (int.cast_pos.2 _) (zpow_pos_of_pos hx _), refine int_prod_range_pos (nat.even_bit0 1) (λ hm, _), norm_cast at hm, rw ←finset.coe_Ico at hm, fin_cases hm, { exact hm₀ rfl }, { exact hm₁ rfl } end lemma convex_on_rpow {p : ℝ} (hp : 1 ≤ p) : convex_on ℝ (Ici 0) (λ x : ℝ, x^p) := begin have A : deriv (λ (x : ℝ), x ^ p) = λ x, p * x^(p-1), by { ext x, simp [hp] }, apply convex_on_of_deriv2_nonneg (convex_Ici 0), { exact continuous_on_id.rpow_const (λ x _, or.inr (zero_le_one.trans hp)) }, { exact (differentiable_rpow_const hp).differentiable_on }, { rw A, assume x hx, replace hx : x ≠ 0, by { simp at hx, exact ne_of_gt hx }, simp [differentiable_at.differentiable_within_at, hx] }, { assume x hx, replace hx : 0 < x, by simpa using hx, suffices : 0 ≤ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], apply mul_nonneg (le_trans zero_le_one hp), exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg hx.le _) } end lemma strict_convex_on_rpow {p : ℝ} (hp : 1 < p) : strict_convex_on ℝ (Ici 0) (λ x : ℝ, x^p) := begin have A : deriv (λ (x : ℝ), x ^ p) = λ x, p * x^(p-1), by { ext x, simp [hp.le] }, apply strict_convex_on_of_deriv2_pos (convex_Ici 0), { exact continuous_on_id.rpow_const (λ x _, or.inr (zero_le_one.trans hp.le)) }, { exact (differentiable_rpow_const hp.le).differentiable_on }, rw interior_Ici, rintro x (hx : 0 < x), suffices : 0 < p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], exact mul_pos (zero_lt_one.trans hp) (mul_pos (sub_pos_of_lt hp) (rpow_pos_of_pos hx _)), end lemma strict_concave_on_log_Ioi : strict_concave_on ℝ (Ioi 0) log := begin have h₁ : Ioi 0 ⊆ ({0} : set ℝ)ᶜ, { exact λ x (hx : 0 < x) (hx' : x = 0), hx.ne' hx' }, refine strict_concave_on_open_of_deriv2_neg (convex_Ioi 0) is_open_Ioi (differentiable_on_log.mono h₁) (λ x (hx : 0 < x), _), rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x < 0, rw [deriv_log', deriv_inv], exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne'), end lemma strict_concave_on_log_Iio : strict_concave_on ℝ (Iio 0) log := begin have h₁ : Iio 0 ⊆ ({0} : set ℝ)ᶜ, { exact λ x (hx : x < 0) (hx' : x = 0), hx.ne hx' }, refine strict_concave_on_open_of_deriv2_neg (convex_Iio 0) is_open_Iio (differentiable_on_log.mono h₁) (λ x (hx : x < 0), _), rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x < 0, rw [deriv_log', deriv_inv], exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne), end
e9dfdb8ba796e9932b61ad3b4dfc6d3709fb32cc
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/tactic/norm_num.lean
2f70b045f3c1b7256b0a41fb4c2780ef7589c0dc
[ "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
64,661
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro -/ import data.rat.cast import data.rat.meta_defs /-! # `norm_num` Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `≤`. -/ universes u v w namespace tactic namespace instance_cache /-- Faster version of `mk_app ``bit0 [e]`. -/ meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]) /-- Faster version of `mk_app ``bit1 [e]`. -/ meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) end instance_cache end tactic open tactic /-! Each lemma in this file is written the way it is to exactly match (with no defeq reduction allowed) the conclusion of some lemma generated by the proof procedure that uses it. That proof procedure should describe the shape of the generated lemma in its docstring. -/ namespace norm_num variable {α : Type u} lemma subst_into_add {α} [has_add α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := by rw [prl, prr, prt] lemma subst_into_mul {α} [has_mul α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := by rw [prl, prr, prt] lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] /-- The result type of `match_numeral`, either `0`, `1`, or a top level decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/ meta inductive match_numeral_result | zero | one | bit0 (e : expr) | bit1 (e : expr) | other /-- Unfold the top level constructor of the numeral expression. -/ meta def match_numeral : expr → match_numeral_result | `(bit0 %%e) := match_numeral_result.bit0 e | `(bit1 %%e) := match_numeral_result.bit1 e | `(@has_zero.zero _ _) := match_numeral_result.zero | `(@has_one.one _ _) := match_numeral_result.one | _ := match_numeral_result.other theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _ theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable. (It may prove garbage instead of failing if `a + 1 = b` is false.) -/ meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr) | c e r := match match_numeral e with | zero := c.mk_app ``zero_succ [] | one := c.mk_app ``one_succ [] | bit0 e := c.mk_app ``bit0_succ [e] | bit1 e := do let r := r.app_arg, (c, p) ← prove_succ c e r, c.mk_app ``bit1_succ [e, r, p] | _ := failed end end /-- Given `a` natural numeral, returns `(b, ⊢ a + 1 = b)`. -/ meta def prove_succ' (c : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, (c, b) ← c.of_nat (na + 1), (c, p) ← prove_succ c a b, return (c, b, p) theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_assoc] theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc] theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc] theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit0 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit0 a + bit1 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result meta mutual def prove_add_nat, prove_adc_nat with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := c.mk_app ``zero_add [b] | _, zero := c.mk_app ``add_zero [a] | _, one := prove_succ c a r | one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p] | _, _ := failed end with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p] | _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p] | one, one := c.mk_app ``adc_one_one [] | bit0 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p] | one, bit0 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p] | bit1 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p] | one, bit1 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p] | _, _ := failed end /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/ add_decl_doc prove_add_nat /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/ add_decl_doc prove_adc_nat /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/ meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, nb ← b.to_nat, (c, r) ← c.of_nat (na + nb), (c, p) ← prove_add_nat c a b r, return (c, r, p) end theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul] theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) : a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add] theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h) theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α) (hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) : bit1 a * bit1 b = bit1 e := by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/ meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic a b := match match_numeral a, match_numeral b with | zero, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, zero := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p) | _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p) | bit0 a, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p], (ic, c') ← ic.mk_bit0 c, (ic, c') ← ic.mk_bit0 c', return (ic, c', p) | bit0 a, _ := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | _, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | bit1 a, bit1 b := do (ic, c, pc) ← prove_mul_nat ic a b, (ic, d, pd) ← prove_add_nat' ic a b, (ic, c') ← ic.mk_bit0 c, (ic, e, pe) ← prove_add_nat' ic c' d, (ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe], (ic, e') ← ic.mk_bit1 e, return (ic, e', p) | _, _ := failed end end section open match_numeral_result /-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/ meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr) | e := match match_numeral e with | one := c.mk_app ``zero_lt_one' [] | bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p] | bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p] | _ := failed end end /-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/ meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr) | `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂, c.mk_app ``div_pos [e₁, e₂, p₁, p₂] | e := prove_pos_nat c e /-- `match_neg (- e) = some e`, otherwise `none` -/ meta def match_neg : expr → option expr | `(- %%e) := some e | _ := none /-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/ meta def match_sign : expr → expr ⊕ bool | `(- %%e) := sum.inl e | `(has_zero.zero) := sum.inr ff | _ := sum.inr tt theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1 /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero' (c : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_neg a with | some a := do (c, p) ← prove_ne_zero' a, c.mk_app ``ne_zero_neg [a, p] | none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p] end theorem clear_denom_div {α} [division_ring α] (a b b' c d : α) (h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c := by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀] /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom' (prove_ne_zero : instance_cache → expr → ℚ → tactic (instance_cache × expr)) (c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) : tactic (instance_cache × expr × expr) := if na.denom = 1 then prove_mul_nat c a d else do [_, _, a, b] ← return a.get_app_args, (c, b') ← c.of_nat (nd / na.denom), (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, _, p₁) ← prove_mul_nat c b b', (c, r, p₂) ← prove_mul_nat c a b', (c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂], return (c, r, p) theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a := lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h) theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a := one_lt_bit1.2 h theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b := bit0_lt_bit0.2 theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b := lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _) theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b := lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h) theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b := bit1_lt_bit1.2 theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a := le_of_lt (lt_one_bit0 _ h) -- deliberately strong hypothesis because bit1 0 is not a numeral theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a := le_of_lt (lt_one_bit1 _ h) theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b := bit0_le_bit0.2 theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b := le_of_lt (lt_bit0_bit1 _ _ h) theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b := le_of_lt (lt_bit1_bit0 _ _ h) theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b := bit1_le_bit1.2 theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a := bit0_le_bit0.2 theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a := le_bit0_bit1 _ _ theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b := le_bit1_bit0 _ _ theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b := bit1_le_bit1.2 h theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit0 b := (bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit1 b := (bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h /-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/ meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr) | e@`(has_zero.zero) := ic.mk_app ``le_refl [e] | e := if ic.α = `(ℕ) then return (ic, `(nat.zero_le).mk_app [e]) else do (ic, p) ← prove_pos ic e, ic.mk_app ``nonneg_pos [e, p] section open match_numeral_result /-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/ meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_numeral a with | one := ic.mk_app ``le_refl [a] | bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p] | bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p] | _ := failed end meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache) with prove_le_nat : expr → expr → tactic (instance_cache × expr) | a b := if a = b then ic.mk_app ``le_refl [a] else match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p] | _, _ := failed end with prove_sle_nat : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p] | _, _ := failed end /-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/ add_decl_doc prove_le_nat /-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/ add_decl_doc prove_sle_nat /-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/ meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_pos ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p] | _, _ := failed end end theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b := lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀) /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_lt_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_lt_nat ic a' b', ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p] lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b := lt_trans (neg_neg_of_pos ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do -- we have to switch the order of `a` and `b` because `a < b ↔ -b < -a` (ic, p) ← prove_lt_nonneg_rat ic b a (-nb) (-na), ic.mk_app ``neg_lt_neg [b, a, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_pos ic a, ic.mk_app ``neg_neg_of_pos [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_pos ic a, (ic, pb) ← prove_pos ic b, ic.mk_app ``lt_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_pos ic b | sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb end theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b := le_of_mul_le_mul_right (by rwa [ha, hb]) h₀ /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_le_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_le_nat ic a' b', ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p] lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b := le_trans (neg_nonpos_of_nonneg ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_le_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_nonneg ic a, ic.mk_app ``neg_nonpos_of_nonneg [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_nonneg ic a, (ic, pb) ← prove_nonneg ic b, ic.mk_app ``le_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_nonneg ic b | sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb end /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove `⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/ meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na < nb then do (ic, p) ← prove_lt_rat ic a b na nb, ic.mk_app ``ne_of_lt [a, b, p] else do (ic, p) ← prove_lt_rat ic b a nb na, ic.mk_app ``ne_of_gt [a, b, p] theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ nat.cast_bit0 _ theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ nat.cast_bit1 _ theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ int.cast_bit0 _ theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ int.cast_bit1 _ theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ rat.cast_bit0 _ theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ rat.cast_bit1 _ /-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (nc, e) ← nc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``nat_cast_zero [], return (ic, nc, e, p) | match_numeral_result.one := do (nc, e) ← nc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``nat_cast_one [], return (ic, nc, e, p) | match_numeral_result.bit0 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a0) ← nc.mk_bit0 a, (ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p], return (ic, nc, a0, p) | match_numeral_result.bit1 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a1) ← nc.mk_bit1 a, (ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p], return (ic, nc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (zc, e) ← zc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``int_cast_zero [], return (ic, zc, e, p) | match_numeral_result.one := do (zc, e) ← zc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``int_cast_one [], return (ic, zc, e, p) | match_numeral_result.bit0 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a0) ← zc.mk_bit0 a, (ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p], return (ic, zc, a0, p) | match_numeral_result.bit1 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a1) ← zc.mk_bit1 a, (ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p], return (ic, zc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (qc, e) ← qc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``rat.cast_zero [], return (ic, qc, e, p) | match_numeral_result.one := do (qc, e) ← qc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``rat.cast_one [], return (ic, qc, e, p) | match_numeral_result.bit0 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a0) ← qc.mk_bit0 a, (ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p], return (ic, qc, a0, p) | match_numeral_result.bit1 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a1) ← qc.mk_bit1 a, (ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p], return (ic, qc, a1, p) | _ := failed end theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' := ha ▸ hb ▸ rat.cast_div _ _ /-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := if na'.denom = 1 then prove_rat_uncast_nat ic qc cz_inst a' else do [_, _, a', b'] ← return a'.get_app_args, (ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a', (ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b', (qc, e) ← qc.mk_app ``has_div.div [a, b], (ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb], return (ic, qc, e, p) theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ int.cast_neg _ theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ rat.cast_neg _ /-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, zc, a, p) ← prove_int_uncast_nat ic zc a', (zc, e) ← zc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``int_cast_neg [a, a', p], return (ic, zc, e, p) | none := prove_int_uncast_nat ic zc a' end /-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'), (qc, e) ← qc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p], return (ic, qc, e, p) | none := prove_rat_uncast_nonneg ic qc cz_inst a' na' end theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt nat.cast_inj.1 h theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt int.cast_inj.1 h theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt rat.cast_inj.1 h /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods: * Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order * Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`. This requires that the base type be `char_zero`, and also that it be a `division_ring` so that the coercion from `ℚ` is well defined. We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero` rings and semirings. -/ meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr) | ic a b na nb := prove_ne_rat ic a b na nb <|> do cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance, if na.denom = 1 ∧ nb.denom = 1 then if na ≥ 0 ∧ nb ≥ 0 then do guard (ic.α ≠ `(ℕ)), nc ← mk_instance_cache `(ℕ), (ic, nc, a', pa) ← prove_nat_uncast ic nc a, (ic, nc, b', pb) ← prove_nat_uncast ic nc b, (nc, p) ← prove_ne_rat nc a' b' na nb, ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℤ)), zc ← mk_instance_cache `(ℤ), (ic, zc, a', pa) ← prove_int_uncast ic zc a, (ic, zc, b', pb) ← prove_int_uncast ic zc b, (zc, p) ← prove_ne_rat zc a' b' na nb, ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℚ)), qc ← mk_instance_cache `(ℚ), (ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na, (ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb, (qc, p) ← prove_ne_rat qc a' b' na nb, ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero (ic : instance_cache) : expr → ℚ → tactic (instance_cache × expr) | a na := do (ic, z) ← ic.mk_app ``has_zero.zero [], prove_ne ic a z na 0 /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom : instance_cache → expr → expr → ℚ → ℕ → tactic (instance_cache × expr × expr) := prove_clear_denom' prove_ne_zero theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α) (h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c') (h : a' + b' = c') : a + b = c := mul_right_cancel₀ h₀ $ by rwa [add_mul, ha, hb, hc] /-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_add_nat ic a b c else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_ne_zero ic d (rat.of_int nd), (ic, a', pa) ← prove_clear_denom ic a d na nd, (ic, b', pb) ← prove_clear_denom ic b d nb nd, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, p) ← prove_add_nat ic a' b' c', ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p] theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c := h ▸ by simp theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c := h ▸ by simp theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c := h ▸ by simp theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c := h ▸ by simp theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c := h ▸ by simp /-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) : tactic (instance_cache × expr) := match match_neg ea, match_neg eb, match_neg ec with | some ea, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c), ic.mk_app ``add_neg_neg [ea, eb, ec, p] | some ea, none, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a), ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p] | some ea, none, none := do (ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b, ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p] | none, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b), ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p] | none, some eb, none := do (ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a, ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p] | _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c end /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/ meta def prove_add_rat' (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_rat, nb ← b.to_rat, let nc := na + nb, (ic, c) ← ic.of_rat nc, (ic, p) ← prove_add_rat ic a b c na nb nc, return (ic, c, p) theorem clear_denom_simple_nat {α} [division_ring α] (a : α) : (1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩ theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) : b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩ /-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)` where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/ meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) : tactic (instance_cache × expr × expr × expr) := if na.denom = 1 then do (c, d) ← c.mk_app ``has_one.one [], (c, p) ← c.mk_app ``clear_denom_simple_nat [a], return (c, d, a, p) else do [α, _, a, b] ← return a.get_app_args, (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀], return (c, b, a, p) theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α) (ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b') (hc : c * d = c') (hd : d₁ * d₂ = d) (h : a' * b' = c') : a * b = c := mul_right_cancel₀ ha.1 $ mul_right_cancel₀ hb.1 $ by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a] /-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_mul_nat ic a b else do let nc := na * nb, (ic, c) ← ic.of_rat nc, (ic, d₁, a', pa) ← prove_clear_denom_simple ic a na, (ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb, (ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, _, p) ← prove_mul_nat ic a' b', (ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p], return (ic, c, p) theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb), (ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p], return (ic, c, p) | sum.inr ff, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, sum.inr ff := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | sum.inl a, sum.inr tt := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb, (ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb), (ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb end theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b := h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div] theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := inv_one theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a := by rw [one_div, inv_inv₀] theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a := inv_eq_one_div _ theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a := by simp only [inv_eq_one_div, one_div_div] /-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/ meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr) | ic e n := match match_sign e with | sum.inl e := do (ic, e', p) ← prove_inv ic e (-n), (ic, r) ← ic.mk_app ``has_neg.neg [e'], (ic, p) ← ic.mk_app ``inv_neg [e, e', p], return (ic, r, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``inv_zero [], return (ic, e, p) | sum.inr tt := if n.num = 1 then if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_one [], return (ic, e, p) else do let e := e.app_arg, (ic, p) ← ic.mk_app ``inv_one_div [e], return (ic, e, p) else if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_div_one [e], e ← infer_type p, return (ic, e.app_arg, p) else do [_, _, a, b] ← return e.get_app_args, (ic, e') ← ic.mk_app ``has_div.div [b, a], (ic, p) ← ic.mk_app ``inv_div [a, b], return (ic, e', p) end theorem div_eq {α} [division_ring α] (a b b' c : α) (hb : b⁻¹ = b') (h : a * b' = c) : a / b = c := by rwa [ ← hb, ← div_eq_mul_inv] at h /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/ meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := do (ic, b', pb) ← prove_inv ic b nb, (ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹, (ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p], return (ic, c, p) /-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/ meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := match match_sign a with | sum.inl a := do (ic, p) ← ic.mk_app ``neg_neg [a], return (ic, a, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``neg_zero [], return (ic, a, p) | sum.inr tt := do (ic, a') ← ic.mk_app ``has_neg.neg [a], p ← mk_eq_refl a', return (ic, a', p) end theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c := by rwa [← hb, ← sub_eq_add_neg] at h theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c := by rwa sub_neg_eq_add /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := match match_sign b with | sum.inl b := do (ic, c, p) ← prove_add_rat' ic a b, (ic, p) ← ic.mk_app ``sub_neg [a, b, c, p], return (ic, c, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``sub_zero [a], return (ic, a, p) | sum.inr tt := do (ic, b', pb) ← prove_neg ic b, (ic, c, p) ← prove_add_rat' ic a b', (ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p], return (ic, c, p) end theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c := h ▸ add_tsub_cancel_left _ _ theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 := tsub_eq_zero_iff_le.mpr $ h ▸ nat.le_add_right _ _ /-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) := do na ← a.to_nat, nb ← b.to_nat, if nb ≤ na then do (ic, c) ← ic.of_nat (na - nb), (ic, p) ← prove_add_nat ic b c a, return (c, `(sub_nat_pos).mk_app [a, b, c, p]) else do (ic, c) ← ic.of_nat (nb - na), (ic, p) ← prove_add_nat ic a c b, return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p]) /-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals. Also handles nat subtraction. Does not do recursive simplification; that is, `1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level `simp` call in `norm_num.derive`. -/ meta def eval_field : expr → tactic (expr × expr) | `(%%e₁ + %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, let n₃ := n₁ + n₂, (c, e₃) ← c.of_rat n₃, (_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃, return (e₃, p) | `(%%e₁ * %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂ | `(- %%e) := do c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_neg c e | `(@has_sub.sub %%α %%inst %%a %%b) := do c ← mk_instance_cache α, if α = `(nat) then prove_sub_nat c a b else prod.snd <$> prove_sub c a b | `(has_inv.inv %%e) := do n ← e.to_rat, c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_inv c e n | `(%%e₁ / %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_div c e₁ e₂ n₁ n₂ | _ := failed lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ) (h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c := h₂ ▸ by simp [pow_bit0, h] lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ) (h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c := by rw [← h₃, ← h₂]; simp [pow_bit1, h] section open match_numeral_result /-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/ meta def prove_pow (a : expr) (na : ℚ) : instance_cache → expr → tactic (instance_cache × expr × expr) | ic b := match match_numeral b with | zero := do (ic, p) ← ic.mk_app ``pow_zero [a], (ic, o) ← ic.mk_app ``has_one.one [], return (ic, o, p) | one := do (ic, p) ← ic.mk_app ``pow_one [a], return (ic, a, p) | bit0 b := do (ic, c', p) ← prove_pow ic b, nc' ← expr.to_rat c', (ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc', (ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂], return (ic, c, p) | bit1 b := do (ic, c₁, p) ← prove_pow ic b, nc₁ ← expr.to_rat c₁, (ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁, (ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na, (ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃], return (ic, c, p) | _ := failed end end lemma zpow_pos {α} [div_inv_monoid α] (a : α) (b : ℤ) (b' : ℕ) (c : α) (hb : b = b') (h : a ^ b' = c) : a ^ b = c := by rw [← h, hb, zpow_coe_nat] lemma zpow_neg {α} [div_inv_monoid α] (a : α) (b : ℤ) (b' : ℕ) (c c' : α) (b0 : 0 < b') (hb : b = b') (h : a ^ b' = c) (hc : c⁻¹ = c') : a ^ -b = c' := by rw [← hc, ← h, hb, zpow_neg_coe_of_pos _ b0] /-- Given `a` a rational numeral and `b : ℤ`, returns `(c, ⊢ a ^ b = c)`. -/ meta def prove_zpow (ic zc nc : instance_cache) (a : expr) (na : ℚ) (b : expr) : tactic (instance_cache × instance_cache × instance_cache × expr × expr) := match match_sign b with | sum.inl b := do (zc, nc, b', hb) ← prove_nat_uncast zc nc b, (ic, c, h) ← prove_pow a na ic b', (ic, c', hc) ← c.to_rat >>= prove_inv ic c, (ic, p) ← ic.mk_app ``zpow_neg [a, b, b', c, c', hb, h, hc], pure (ic, zc, nc, c', p) | sum.inr ff := do (ic, o) ← ic.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``zpow_zero [a], pure (ic, zc, nc, o, p) | sum.inr tt := do (zc, nc, b', hb) ← prove_nat_uncast zc nc b, (ic, c, h) ← prove_pow a na ic b', (ic, p) ← ic.mk_app ``zpow_pos [a, b, b', c, hb, h], pure (ic, zc, nc, c, p) end /-- Evaluates expressions of the form `a ^ b`, `monoid.npow a b` or `nat.pow a b`. -/ meta def eval_pow : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, match m with | `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂ | `(@div_inv_monoid.has_pow %%_ %%_) := do zc ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (prod.snd ∘ prod.snd ∘ prod.snd) <$> prove_zpow c zc nc e₁ n₁ e₂ | _ := failed end | `(monoid.npow %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_pow e₁ n₁ c e₂ | `(div_inv_monoid.zpow %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, zc ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (prod.snd ∘ prod.snd ∘ prod.snd) <$> prove_zpow c zc nc e₁ n₁ e₂ | _ := failed /-- Given `⊢ p`, returns `(true, ⊢ p = true)`. -/ meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk `(true) <$> mk_app ``eq_true_intro [p] /-- Given `⊢ ¬ p`, returns `(false, ⊢ p = false)`. -/ meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk `(false) <$> mk_app ``eq_false_intro [p] theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false := eq_false_intro $ not_not_intro rfl /-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/ meta def eval_ineq : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p else if n₁ = n₂ then do (_, p) ← c.mk_app ``lt_irrefl [e₁], false_intro p else do (c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'], false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (_, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else prove_le_rat c e₁ e₂ n₁ n₂, true_intro p else do (c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq | `(%%e₁ ≠ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁] else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p | _ := failed theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁ /-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral. (We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure that towers of successors coming from e.g. `induction` are a common case.) -/ meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr) | `(nat.succ %%a) := do (ic, n, b, p₁) ← prove_nat_succ a, let n' := n + 1, (ic, c) ← ic.of_nat n', (ic, p₂) ← prove_add_nat ic b `(1) c, return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂]) | e := do n ← e.to_nat, p ← mk_eq_refl e, return (ic, n, e, p) lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c := h₂ ▸ h ▸ int.div_neg _ _ lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c := (int.mod_neg _ _).trans h /-- Given `a`,`b` numerals in `nat` or `int`, * `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)` * `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)` -/ meta def prove_div_mod (ic : instance_cache) : expr → expr → bool → tactic (instance_cache × expr × expr) | a b mod := match match_neg b with | some b := do (ic, c', p) ← prove_div_mod a b mod, if mod then return (ic, c', `(int_mod_neg).mk_app [a, b, c', p]) else do (ic, c, p₂) ← prove_neg ic c', return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂]) | none := do nb ← b.to_nat, na ← a.to_int, let nq := na / nb, let nr := na % nb, let nm := nq * nr, (ic, q) ← ic.of_int nq, (ic, r) ← ic.of_int nr, (ic, m, pm) ← prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb), (ic, p) ← prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na), (ic, p') ← prove_lt_nat ic r b, if ic.α = `(nat) then if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p']) else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p']) else if ic.α = `(int) then do (ic, p₀) ← prove_nonneg ic r, if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p']) else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p']) else failed end theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂ theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂ theorem int_to_nat_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : a.to_nat = b := by rw ← h; simp theorem int_to_nat_neg (a : ℤ) (h : 0 < a) : (-a).to_nat = 0 := by simp only [int.to_nat_of_nonpos, h.le, neg_nonpos] theorem nat_abs_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : a.nat_abs = b := by rw ← h; simp theorem nat_abs_neg (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : (-a).nat_abs = b := by rw ← h; simp theorem neg_succ_of_nat (a b : ℕ) (c : ℤ) (h₁ : a + 1 = b) (h₂ : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = c) : -[1+ a] = -c := by rw [← h₂, ← h₁, int.nat_cast_eq_coe_nat]; refl /-- Evaluates some extra numeric operations on `nat` and `int`, specifically `nat.succ`, `/` and `%`, and `∣` (divisibility). -/ meta def eval_nat_int_ext : expr → tactic (expr × expr) | e@`(nat.succ _) := do ic ← mk_instance_cache `(ℕ), (_, _, ep) ← prove_nat_succ ic e, return ep | `(%%a / %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b ff | `(%%a % %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b tt | `(%%a ∣ %%b) := do α ← infer_type a, ic ← mk_instance_cache α, th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else if α = `(int) then return `(dvd_eq_int) else failed, (ic, c, p₁) ← prove_div_mod ic b a tt, (ic, z) ← ic.mk_app ``has_zero.zero [], (e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq, return (e', th.mk_app [a, b, c, e', p₁, p₂]) | `(int.to_nat %%a) := do n ← a.to_int, ic ← mk_instance_cache `(ℤ), if n ≥ 0 then do nc ← mk_instance_cache `(ℕ), (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(int_to_nat_pos).mk_app [a, b, p]) else do a ← match_neg a, (_, p) ← prove_pos ic a, pure (`(0), `(int_to_nat_neg).mk_app [a, p]) | `(int.nat_abs %%a) := do n ← a.to_int, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), if n ≥ 0 then do (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(nat_abs_pos).mk_app [a, b, p]) else do a ← match_neg a, (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(nat_abs_neg).mk_app [a, b, p]) | `(int.neg_succ_of_nat %%a) := do na ← a.to_nat, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), let nb := na + 1, (nc, b) ← nc.of_nat nb, (nc, p₁) ← prove_add_nat nc a `(1) b, (ic, c) ← ic.of_nat nb, (_, _, _, p₂) ← prove_nat_uncast ic nc c, pure (`(-%%c : ℤ), `(neg_succ_of_nat).mk_app [a, b, c, p₁, p₂]) | _ := failed theorem int_to_nat_cast (a : ℕ) (b : ℤ) (h : (by haveI := @nat.cast_coe ℤ; exact a : ℤ) = b) : ↑a = b := eq.trans (by simp) h /-- Evaluates the `↑n` cast operation from `ℕ`, `ℤ`, `ℚ` to an arbitrary type `α`. -/ meta def eval_cast : expr → tactic (expr × expr) | `(@coe ℕ %%α %%inst %%a) := do if inst.is_app_of ``coe_to_lift then if inst.app_arg.is_app_of ``nat.cast_coe then do n ← a.to_nat, ic ← mk_instance_cache α, nc ← mk_instance_cache `(ℕ), (ic, b) ← ic.of_nat n, (_, _, _, p) ← prove_nat_uncast ic nc b, pure (b, p) else if inst.app_arg.is_app_of ``int.cast_coe then do n ← a.to_int, ic ← mk_instance_cache α, zc ← mk_instance_cache `(ℤ), (ic, b) ← ic.of_int n, (_, _, _, p) ← prove_int_uncast ic zc b, pure (b, p) else if inst.app_arg.is_app_of ``int.cast_coe then do n ← a.to_rat, cz_inst ← mk_mapp ``char_zero [α, none, none] >>= mk_instance, ic ← mk_instance_cache α, qc ← mk_instance_cache `(ℚ), (ic, b) ← ic.of_rat n, (_, _, _, p) ← prove_rat_uncast ic qc cz_inst b n, pure (b, p) else failed else if inst = `(@coe_base nat int int.has_coe) then do n ← a.to_nat, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (ic, b) ← ic.of_nat n, (_, _, _, p) ← prove_nat_uncast ic nc b, pure (b, `(int_to_nat_cast).mk_app [a, b, p]) else failed | _ := failed /-- This version of `derive` does not fail when the input is already a numeral -/ meta def derive.step (e : expr) : tactic (expr × expr) := eval_field e <|> eval_pow e <|> eval_ineq e <|> eval_cast e <|> eval_nat_int_ext e /-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put `@[norm_num]` on a tactic of type `expr → tactic (expr × expr)`; the tactic will be called on subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`, `12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the original expression is equal to the rewritten expression. Failure is used to indicate that this tactic does not apply to the term. For performance reasons, it is best to detect non-applicability as soon as possible so that the next tactic can have a go, so generally it will start with a pattern match and then checking that the arguments to the term are numerals or of the appropriate form, followed by proof construction, which should not fail. Propositions are treated like any other term. The normal form for propositions is `true` or `false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be used to help here. -/ @[user_attribute] protected meta def attr : user_attribute (expr → tactic (expr × expr)) unit := { name := `norm_num, descr := "Add norm_num derivers", cache_cfg := { mk_cache := λ ns, do { t ← ns.mfoldl (λ (t : expr → tactic (expr × expr)) n, do t' ← eval_expr (expr → tactic (expr × expr)) (expr.const n []), pure (λ e, t' e <|> t e)) (λ _, failed), pure (λ e, derive.step e <|> t e) }, dependencies := [] } } add_tactic_doc { name := "norm_num", category := doc_category.attr, decl_names := [`norm_num.attr], tags := ["arithmetic", "decision_procedure"] } /-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with additional reduction procedures. -/ meta def get_step : tactic (expr → tactic (expr × expr)) := norm_num.attr.get_cache /-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/ meta def derive' (step : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | e := do e ← instantiate_mvars e, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← step e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) /-- Simplify an expression bottom-up using the default `norm_num` set to simplify the subexpressions. -/ meta def derive (e : expr) : tactic (expr × expr) := do f ← get_step, derive' f e end norm_num /-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num1 (step : expr → tactic (expr × expr)) (loc : interactive.loc) : tactic unit := do ns ← loc.get_locals, success ← tactic.replace_at (norm_num.derive' step) ns loc.include_goal, when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction, monad.unlessb success $ done <|> fail "norm_num failed to simplify" /-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num (step : expr → tactic (expr × expr)) (hs : list simp_arg_type) (l : interactive.loc) : tactic unit := repeat1 $ orelse' (tactic.norm_num1 step l) $ interactive.simp_core {} (tactic.norm_num1 step (interactive.loc.ns [none])) ff (simp_arg_type.except ``one_div :: hs) [] l >> skip namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do f ← get_step, tactic.norm_num1 f loc /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := do f ← get_step, tactic.norm_num f hs l add_hint_tactic "norm_num" /-- Normalizes a numerical expression and tries to close the goal with the result. -/ meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ /-- Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. Add-on tactics marked as `@[norm_num]` can extend the behavior of `norm_num` to include other functions. This is used to support several other functions on `nat` like `prime`, `min_fac` and `factors`. ```lean import data.real.basic example : (2 : ℝ) + 2 = 4 := by norm_num example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num example : (73 : ℝ) < 789/2 := by norm_num example : 123456789 + 987654321 = 1111111110 := by norm_num example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num example : nat.prime (2^13 - 1) := by norm_num example : ¬ nat.prime (2^11 - 1) := by norm_num example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption ``` The variant `norm_num1` does not call `simp`. Both `norm_num` and `norm_num1` can be called inside the `conv` tactic. The tactic `apply_normed` normalises a numerical expression and tries to close the goal with the result. Compare: ```lean def a : ℕ := 2^100 #print a -- 2 ^ 100 def normed_a : ℕ := by apply_normed 2^100 #print normed_a -- 1267650600228229401496703205376 ``` -/ add_tactic_doc { name := "norm_num", category := doc_category.tactic, decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num, `tactic.interactive.apply_normed], tags := ["arithmetic", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive tactic.interactive open norm_num (derive) /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 : conv unit := replace_lhs derive /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) : conv unit := repeat1 $ orelse' norm_num1 $ conv.interactive.simp ff (simp_arg_type.except ``one_div :: hs) [] { discharger := tactic.interactive.norm_num1 (loc.ns [none]) } end conv.interactive
ad3e539138b065b5e01b79b607b98081f1b37ac5
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/tactic_paper_supplemental_material/monoid_cancellation/benchmark.lean
01de132ea8a7cd8705b6bfc5771d18d84eb30367
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
1,385
lean
-- You need to run this file using `lean -j0`, otherwise the timings -- will be influenced by parallel compilation. import .monoid .smt .simp .cancellation_solver .cancellation_solver_opt local infix * := star meta def build_plus_l : ℕ → tactic expr | 0 := tactic.to_expr ``(asM 0) | (n+1) := do x ← build_plus_l n, tactic.to_expr ``(asM %%(reflect n.succ) * %%x) meta def build_plus_r : ℕ → tactic expr | 0 := tactic.to_expr ``(asM 0) | (n+1) := do right ← build_plus_r n, tactic.to_expr ``(%%right * asM %%(reflect n.succ)) meta def x : pexpr := ``(1) #check tactic.to_expr meta def benchmark (n : ℕ) : tactic expr := do left ← build_plus_l n, right ← build_plus_r n, return `(%%left = (%%right : m)) open tactic monad meta def run_single_bench (n : ℕ) (t : tactic unit) := run_async $ do ty ← benchmark n, bench_goal ← mk_meta_var ty, set_goals [bench_goal], dunfold [`benchmark, `build_plus_l, `build_plus_r], timetac ("n = " ++ to_string n ++ ": ") (abstract t) meta def run_benchs (solver_name : string) (t : tactic unit) := do trace solver_name, sequence' $ do n ← list.range 11, n ← return (nat.mul 10 n), [run_single_bench n t] run_cmd run_benchs "simp" `[simp] run_cmd run_benchs "smt" `[cc] run_cmd run_benchs "cancellation_solver" `[solve] run_cmd run_benchs "cancellation_solver_opt" `[opt.solve]
00487c62c16f7bd72311d3026239ac14ed08dc88
61c3861020ef87c6c325fc3c3dcbabf5d6b07985
/types/eq.lean
af20dc9cd054eb2df3fea0288fdf5753fab18f59
[ "Apache-2.0" ]
permissive
jonas-frey/hott3
a623be2959e8a713c03fa1b0f34bf76a561dfa87
a944051b4eb5919bdc70978ee15fcbb48a824811
refs/heads/master
1,628,408,720,559
1,510,267,042,000
1,510,267,042,000
106,760,764
0
0
null
1,507,856,238,000
1,507,856,238,000
null
UTF-8
Lean
false
false
21,299
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 Partially ported from Coq HoTT Theorems about path types (identity types) -/ import .sigma universes u v w hott_theory namespace hott open eq hott.sigma equiv is_equiv is_trunc namespace eq /- Path spaces -/ section variables {A : Type u} {B : Type v} {a a₁ a₂ a₃ a₄ a' : A} {b b1 b2 : B} {f g : A → B} {h : B → A} {p p' p'' : a₁ = a₂} /- The path spaces of a path space are not, of course, determined; they are just the higher-dimensional structure of the original space. -/ /- some lemmas about whiskering or other higher paths -/ @[hott] def whisker_left_con_right (p : a₁ = a₂) {q q' q'' : a₂ = a₃} (r : q = q') (s : q' = q'') : whisker_left p (r ⬝ s) = whisker_left p r ⬝ whisker_left p s := begin induction p, induction r, induction s, reflexivity end @[hott] def whisker_right_con_right (q : a₂ = a₃) (r : p = p') (s : p' = p'') : whisker_right q (r ⬝ s) = whisker_right q r ⬝ whisker_right q s := begin induction q, induction r, induction s, reflexivity end @[hott] def whisker_left_con_left (p : a₁ = a₂) (p' : a₂ = a₃) {q q' : a₃ = a₄} (r : q = q') : whisker_left (p ⬝ p') r = con.assoc _ _ _ ⬝ whisker_left p (whisker_left p' r) ⬝ con.assoc' _ _ _ := begin induction p', induction p, induction r, induction q, reflexivity end @[hott] def whisker_right_con_left {p p' : a₁ = a₂} (q : a₂ = a₃) (q' : a₃ = a₄) (r : p = p') : whisker_right (q ⬝ q') r = con.assoc' _ _ _ ⬝ whisker_right q' (whisker_right q r) ⬝ con.assoc _ _ _ := begin induction q', induction q, induction r, induction p, reflexivity end @[hott] def whisker_left_inv_left (p : a₂ = a₁) {q q' : a₂ = a₃} (r : q = q') : (con_inv_cancel_left _ _).inverse ⬝ whisker_left p (whisker_left p⁻¹ r) ⬝ (con_inv_cancel_left _ _) = r := begin induction p, induction r, induction q, reflexivity end @[hott] def whisker_left_inv (p : a₁ = a₂) {q q' : a₂ = a₃} (r : q = q') : whisker_left p r⁻¹ = (whisker_left p r)⁻¹ := by induction r; reflexivity @[hott] def whisker_right_inv {p p' : a₁ = a₂} (q : a₂ = a₃) (r : p = p') : whisker_right q r⁻¹ = (whisker_right q r)⁻¹ := by induction r; reflexivity @[hott] def ap_eq_apd10 {B : A → Type _} {f g : Πa, B a} (p : f = g) (a : A) : ap (λh : Π a, B a, h a) p = apd10 p a := by induction p; reflexivity @[hott] def inverse2_right_inv (r : p = p') : r ◾ inverse2 r ⬝ con.right_inv p' = con.right_inv p := by induction r;induction p;reflexivity @[hott] def inverse2_left_inv (r : p = p') : inverse2 r ◾ r ⬝ con.left_inv p' = con.left_inv p := by induction r;induction p;reflexivity @[hott] def ap_con_right_inv (f : A → B) (p : a₁ = a₂) : ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p) ⬝ con.right_inv (ap f p) = ap (ap f) (con.right_inv p) := by induction p;reflexivity @[hott] def ap_con_left_inv (f : A → B) (p : a₁ = a₂) : ap_con f p⁻¹ p ⬝ whisker_right _ (ap_inv f p) ⬝ con.left_inv (ap f p) = ap (ap f) (con.left_inv p) := by induction p;reflexivity @[hott] def idp_con_whisker_left {q q' : a₂ = a₃} (r : q = q') : (idp_con _).inverse ⬝ whisker_left idp r = r ⬝ (idp_con _).inverse := by induction r;induction q;reflexivity @[hott] def whisker_left_idp_con {q q' : a₂ = a₃} (r : q = q') : whisker_left idp r ⬝ !idp_con = !idp_con ⬝ r := by induction r;induction q;reflexivity @[hott] def eq.cases_helper {A : Type u} {a b : A} (x : a = b) (C : Sort v) : (∀ b' : A, ∀ x' : a = b', ∀ hb : b = b', ∀ hx : x =[hb] x', C) → C := by induction x; intro h; apply h; refl @[hott] def idp_con_idp {p : a = a} (q : p = idp) : idp_con p ⬝ q = ap (λp, idp ⬝ p) q := by eq_cases q; refl @[hott] def ap_is_constant {A B : Type _} {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q = p x ⬝ (p y)⁻¹ := by induction q; symmetry; apply con.right_inv @[hott] def inv2_inv {p q : a = a'} (r : p = q) : inverse2 r⁻¹ = (inverse2 r)⁻¹ := by induction r;reflexivity @[hott] def inv2_con {p p' p'' : a = a'} (r : p = p') (r' : p' = p'') : inverse2 (r ⬝ r') = inverse2 r ⬝ inverse2 r' := by induction r';induction r;reflexivity @[hott] def con2_inv {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂) : (r₁ ◾ r₂)⁻¹ = r₁⁻¹ ◾ r₂⁻¹ := by induction r₁;induction r₂;reflexivity @[hott] def eq_con_inv_of_con_eq_whisker_left {A : Type _} {a a₂ a₃ : A} {p : a = a₂} {q q' : a₂ = a₃} {r : a = a₃} (s' : q = q') (s : p ⬝ q' = r) : eq_con_inv_of_con_eq (whisker_left p s' ⬝ s) = eq_con_inv_of_con_eq s ⬝ whisker_left r (inverse2 s')⁻¹ := by induction s';induction q;induction s;reflexivity @[hott] def right_inv_eq_idp {A : Type _} {a : A} {p : a = a} (r : p = idpath a) : con.right_inv p = r ◾ inverse2 r := by eq_cases r; reflexivity /- Transporting in path spaces. There are potentially a lot of these lemmas, so we adopt a uniform naming scheme: - `l` means the left endpoint varies - `r` means the right endpoint varies - `F` means application of a function to that (varying) endpoint. -/ @[hott] def eq_transport_l (p : a₁ = a₂) (q : a₁ = a₃) : transport (λx, x = a₃) p q = p⁻¹ ⬝ q := by induction p; exact !idp_con⁻¹ @[hott] def eq_transport_r (p : a₂ = a₃) (q : a₁ = a₂) : transport (λx, a₁ = x) p q = q ⬝ p := by induction p; reflexivity @[hott] def eq_transport_lr (p : a₁ = a₂) (q : a₁ = a₁) : transport (λx, x = x) p q = p⁻¹ ⬝ q ⬝ p := by induction p; exact !idp_con⁻¹ @[hott] def eq_transport_Fl (p : a₁ = a₂) (q : f a₁ = b) : transport (λx, f x = b) p q = (ap f p)⁻¹ ⬝ q := by induction p; exact !idp_con⁻¹ @[hott] def eq_transport_Fr (p : a₁ = a₂) (q : b = f a₁) : transport (λx, b = f x) p q = q ⬝ (ap f p) := by induction p; reflexivity @[hott] def eq_transport_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : transport (λx, f x = g x) p q = (ap f p)⁻¹ ⬝ q ⬝ (ap g p) := by induction p; exact !idp_con⁻¹ @[hott] def eq_transport_FlFr_D {B : A → Type _} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁) : transport (λx, f x = g x) p q = (apdt f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apdt g p) := by eq_cases p; hsimp @[hott] def eq_transport_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : transport (λx, h (f x) = x) p q = (ap h (ap f p))⁻¹ ⬝ q ⬝ p := by induction p; exact !idp_con⁻¹ @[hott] def eq_transport_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : transport (λx, x = h (f x)) p q = p⁻¹ ⬝ q ⬝ (ap h (ap f p)) := by induction p; exact !idp_con⁻¹ /- Pathovers -/ -- In the comment we give the fibration of the pathover -- we should probably try to do everything just with pathover_eq (defined in cubical.square), @[hott] def eq_pathover_l (p : a₁ = a₂) (q : a₁ = a₃) : q =[p; λ x, x = a₃] p⁻¹ ⬝ q := by induction p; induction q; exact idpo @[hott] def eq_pathover_r (p : a₂ = a₃) (q : a₁ = a₂) : q =[p; λ x, a₁ = x] q ⬝ p := by induction p; induction q; exact idpo @[hott] def eq_pathover_lr (p : a₁ = a₂) (q : a₁ = a₁) : q =[p; λ x, x = x] p⁻¹ ⬝ q ⬝ p := by induction p; dsimp [inverse]; rwr [idp_con]; exact idpo @[hott] def eq_pathover_Fl (p : a₁ = a₂) (q : f a₁ = b) : q =[p; λ x, f x = b] (ap f p)⁻¹ ⬝ q := by induction p; induction q; exact idpo @[hott] def eq_pathover_Fl' (p : a₁ = a₂) (q : f a₂ = b) : (ap f p) ⬝ q =[p; λ x, f x = b] q := by induction p; induction q; exact idpo @[hott] def eq_pathover_Fr (p : a₁ = a₂) (q : b = f a₁) : q =[p; λ x, b = f x] q ⬝ (ap f p) := by induction p; exact idpo @[hott] def eq_pathover_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p; λ x, f x = g x] (ap f p)⁻¹ ⬝ q ⬝ (ap g p) := by induction p; hsimp @[hott] def eq_pathover_FlFr_D {B : A → Type _} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p; λ x, f x = g x] (apdt f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apdt g p) := by induction p; hsimp @[hott] def eq_pathover_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : q =[p; λ x, h (f x) = x] (ap h (ap f p))⁻¹ ⬝ q ⬝ p := by induction p; hsimp @[hott] def eq_pathover_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : q =[p; λ x, x = h (f x)] p⁻¹ ⬝ q ⬝ (ap h (ap f p)) := by induction p; hsimp @[hott] def eq_pathover_r_idp (p : a₁ = a₂) : idp =[p; λ x, a₁ = x] p := by induction p; exact idpo @[hott] def eq_pathover_l_idp (p : a₁ = a₂) : idp =[p; λ x, x = a₁] p⁻¹ := by induction p; exact idpo @[hott] def eq_pathover_l_idp' (p : a₁ = a₂) : idp =[p⁻¹; λ x, x = a₂] p := by induction p; exact idpo -- The Functorial action of paths is [ap]. /- Equivalences between path spaces -/ /- [is_equiv_ap] is in init.equiv -/ @[hott] def equiv_ap (f : A → B) [H : is_equiv f] (a₁ a₂ : A) : (a₁ = a₂) ≃ (f a₁ = f a₂) := equiv.mk (ap f) (by apply_instance) /- Path operations are equivalences -/ @[hott, instance] def is_equiv_eq_inverse (a₁ a₂ : A) : is_equiv (inverse : a₁ = a₂ → a₂ = a₁) := is_equiv.mk inverse inverse inv_inv inv_inv (λp, by induction p; refl) @[hott] def eq_equiv_eq_symm (a₁ a₂ : A) : (a₁ = a₂) ≃ (a₂ = a₁) := equiv.mk inverse (by apply_instance) @[hott, instance] def is_equiv_concat_left (p : a₁ = a₂) (a₃ : A) : is_equiv (concat p : a₂ = a₃ → a₁ = a₃) := is_equiv.mk (concat p) (concat p⁻¹) (con_inv_cancel_left p) (inv_con_cancel_left p) begin abstract { intro q, induction p;induction q;reflexivity } end @[hott] def equiv_eq_closed_left (a₃ : A) (p : a₁ = a₂) : (a₁ = a₃) ≃ (a₂ = a₃) := equiv.mk (concat p⁻¹) (by apply_instance) @[hott, instance] def is_equiv_concat_right (p : a₂ = a₃) (a₁ : A) : is_equiv (λq : a₁ = a₂, q ⬝ p) := is_equiv.mk (λq, q ⬝ p) (λq, q ⬝ p⁻¹) (λq, inv_con_cancel_right q p) (λq, con_inv_cancel_right q p) (λq, by induction p;induction q;reflexivity) @[hott] def equiv_eq_closed_right (a₁ : A) (p : a₂ = a₃) : (a₁ = a₂) ≃ (a₁ = a₃) := equiv.mk (λq, q ⬝ p) (by apply_instance) @[hott] def eq_equiv_eq_closed (p : a₁ = a₂) (q : a₃ = a₄) : (a₁ = a₃) ≃ (a₂ = a₄) := equiv.trans (equiv_eq_closed_left a₃ p) (equiv_eq_closed_right a₂ q) @[hott] def loop_equiv_eq_closed {A : Type _} {a a' : A} (p : a = a') : (a = a) ≃ (a' = a') := eq_equiv_eq_closed p p @[hott] def is_equiv_whisker_left (p : a₁ = a₂) (q r : a₂ = a₃) : is_equiv (whisker_left p : q = r → p ⬝ q = p ⬝ r) := begin fapply adjointify, {intro s, apply cancel_left _ s}, {intro s, apply concat, {apply whisker_left_con_right}, apply concat, tactic.swap, apply (whisker_left_inv_left p s), apply concat2, {apply concat, {apply whisker_left_con_right}, apply concat2, {induction p, induction q, reflexivity}, {reflexivity}}, {induction p, induction r, reflexivity}}, {intro s, induction s, induction q, induction p, reflexivity} end @[hott] def eq_equiv_con_eq_con_left (p : a₁ = a₂) (q r : a₂ = a₃) : (q = r) ≃ (p ⬝ q = p ⬝ r) := equiv.mk _ (is_equiv_whisker_left _ _ _) @[hott] def is_equiv_whisker_right {p q : a₁ = a₂} (r : a₂ = a₃) : is_equiv (λs, whisker_right r s : p = q → p ⬝ r = q ⬝ r) := begin fapply adjointify, {intro s, apply cancel_right _ s}, {intro s, induction r, eq_cases s, induction q, dsimp at *, induction hb, rwr eq_of_pathover_idp hx}, {intro s, induction s, induction r, induction p, reflexivity} end @[hott] def eq_equiv_con_eq_con_right (p q : a₁ = a₂) (r : a₂ = a₃) : (p = q) ≃ (p ⬝ r = q ⬝ r) := equiv.mk _ (is_equiv_whisker_right _) local attribute [hsimp] con.assoc /- The following proofs can be simplified a bit by concatenating previous equivalences. However, these proofs have the advantage that the inverse is definitionally equal to what we would expect -/ @[hott] def is_equiv_con_eq_of_eq_inv_con (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_eq_of_eq_inv_con : p = r⁻¹ ⬝ q → r ⬝ p = q) := begin fapply adjointify, { apply eq_inv_con_of_con_eq}, { intro s, induction r, hsimp [con_eq_of_eq_inv_con,eq_inv_con_of_con_eq] }, { intro s, induction r, hsimp [con_eq_of_eq_inv_con,eq_inv_con_of_con_eq] }, end @[hott] def eq_inv_con_equiv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : (p = r⁻¹ ⬝ q) ≃ (r ⬝ p = q) := equiv.mk _ (is_equiv_con_eq_of_eq_inv_con _ _ _) @[hott] def is_equiv_con_eq_of_eq_con_inv (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_eq_of_eq_con_inv : r = q ⬝ p⁻¹ → r ⬝ p = q) := begin fapply adjointify, { apply eq_con_inv_of_con_eq}, { intro s, induction p, refl }, { intro s, induction p, refl }, end @[hott] def eq_con_inv_equiv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : (r = q ⬝ p⁻¹) ≃ (r ⬝ p = q) := equiv.mk _ (is_equiv_con_eq_of_eq_con_inv _ _ _) @[hott] def is_equiv_inv_con_eq_of_eq_con (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂) : is_equiv (inv_con_eq_of_eq_con : p = r ⬝ q → r⁻¹ ⬝ p = q) := begin fapply adjointify, { apply eq_con_of_inv_con_eq}, { intro s, induction r, hsimp [inv_con_eq_of_eq_con,eq_con_of_inv_con_eq] }, { intro s, induction r, hsimp [inv_con_eq_of_eq_con,eq_con_of_inv_con_eq] }, end @[hott] def eq_con_equiv_inv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂) : (p = r ⬝ q) ≃ (r⁻¹ ⬝ p = q) := equiv.mk _ (is_equiv_inv_con_eq_of_eq_con _ _ _) @[hott] def is_equiv_con_inv_eq_of_eq_con (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_inv_eq_of_eq_con : r = q ⬝ p → r ⬝ p⁻¹ = q) := begin fapply adjointify, { apply eq_con_of_con_inv_eq}, { intro s, induction p, refl }, { intro s, induction p, refl }, end @[hott] def eq_con_equiv_con_inv_eq (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁) : (r = q ⬝ p) ≃ (r ⬝ p⁻¹ = q) := equiv.mk _ (is_equiv_con_inv_eq_of_eq_con _ _ _) local attribute [instance] is_equiv_inv_con_eq_of_eq_con is_equiv_con_inv_eq_of_eq_con is_equiv_con_eq_of_eq_con_inv is_equiv_con_eq_of_eq_inv_con @[hott] def is_equiv_eq_con_of_inv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_of_inv_con_eq : r⁻¹ ⬝ q = p → q = r ⬝ p) := is_equiv_inv (@inv_con_eq_of_eq_con _ _ _ _ q p r) @[hott] def is_equiv_eq_con_of_con_inv_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_of_con_inv_eq : q ⬝ p⁻¹ = r → q = r ⬝ p) := is_equiv_inv (@con_inv_eq_of_eq_con _ _ _ _ p r q) @[hott] def is_equiv_eq_con_inv_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_inv_of_con_eq : r ⬝ p = q → r = q ⬝ p⁻¹) := is_equiv_inv (@con_eq_of_eq_con_inv _ _ _ _ p q r) @[hott] def is_equiv_eq_inv_con_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_inv_con_of_con_eq : r ⬝ p = q → p = r⁻¹ ⬝ q) := is_equiv_inv (@con_eq_of_eq_inv_con _ _ _ _ p q r) @[hott] def is_equiv_con_inv_eq_idp (p q : a₁ = a₂) : is_equiv (con_inv_eq_idp : p = q → p ⬝ q⁻¹ = idp) := begin fapply adjointify, { apply eq_of_con_inv_eq_idp}, { intro s, induction q, dsimp [con_inv_eq_idp, eq_of_con_inv_eq_idp] at *, eq_cases s, reflexivity}, { intro s, induction s, induction p, reflexivity}, end @[hott] def is_equiv_inv_con_eq_idp (p q : a₁ = a₂) : is_equiv (inv_con_eq_idp : p = q → q⁻¹ ⬝ p = idp) := begin fapply adjointify, { apply eq_of_inv_con_eq_idp}, { intro s, induction q, apply is_equiv_rect (eq_equiv_con_eq_con_left idp p idp) _ _ s; intro s', eq_cases s', refl }, { intro s, induction s, induction p, reflexivity}, end @[hott] def eq_equiv_con_inv_eq_idp (p q : a₁ = a₂) : (p = q) ≃ (p ⬝ q⁻¹ = idp) := equiv.mk _ (is_equiv_con_inv_eq_idp _ _) @[hott] def eq_equiv_inv_con_eq_idp (p q : a₁ = a₂) : (p = q) ≃ (q⁻¹ ⬝ p = idp) := equiv.mk _ (is_equiv_inv_con_eq_idp _ _) /- Pathover Equivalences -/ @[hott] def eq_pathover_equiv_l (p : a₁ = a₂) (q : a₁ = a₃) (r : a₂ = a₃) : q =[p; λ x, x = a₃] r ≃ q = p ⬝ r := by induction p; exact pathover_idp _ _ _ ⬝e equiv_eq_closed_right _ !idp_con.inverse @[hott] def eq_pathover_equiv_r (p : a₂ = a₃) (q : a₁ = a₂) (r : a₁ = a₃) : q =[p; λ x, a₁ = x] r ≃ q ⬝ p = r := by induction p; apply pathover_idp @[hott] def eq_pathover_equiv_lr (p : a₁ = a₂) (q : a₁ = a₁) (r : a₂ = a₂) : q =[p; λ x, x = x] r ≃ q ⬝ p = p ⬝ r := by induction p; exact pathover_idp _ _ _ ⬝e equiv_eq_closed_right _ !idp_con.inverse @[hott] def eq_pathover_equiv_Fl (p : a₁ = a₂) (q : f a₁ = b) (r : f a₂ = b) : q =[p; λ x, f x = b] r ≃ q = ap f p ⬝ r := by induction p; exact pathover_idp _ _ _ ⬝e equiv_eq_closed_right _ !idp_con⁻¹ @[hott] def eq_pathover_equiv_Fr (p : a₁ = a₂) (q : b = f a₁) (r : b = f a₂) : q =[p; λ x, b = f x] r ≃ q ⬝ ap f p = r := by induction p; apply pathover_idp @[hott] def eq_pathover_equiv_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) (r : f a₂ = g a₂) : q =[p; λ x, f x = g x] r ≃ q ⬝ ap g p = ap f p ⬝ r := by induction p; exact pathover_idp _ _ _ ⬝e equiv_eq_closed_right _ !idp_con⁻¹ @[hott] def eq_pathover_equiv_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) (r : h (f a₂) = a₂) : q =[p; λ x, h (f x) = x] r ≃ q ⬝ p = ap h (ap f p) ⬝ r := by induction p; exact pathover_idp _ _ _ ⬝e equiv_eq_closed_right _ !idp_con⁻¹ @[hott] def eq_pathover_equiv_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) (r : a₂ = h (f a₂)) : q =[p; λ x, x = h (f x)] r ≃ q ⬝ ap h (ap f p) = p ⬝ r := by induction p; exact pathover_idp _ _ _ ⬝e equiv_eq_closed_right _ !idp_con⁻¹ -- a lot of this library still needs to be ported from Coq HoTT -- the behavior of equality in other types is described in the corresponding type files -- encode decode method open is_trunc @[hott] def encode_decode_method' (a₀ a : A) (code : A → Type _) (c₀ : code a₀) (decode : Π(a : A) (c : code a), a₀ = a) (encode_decode : Π(a : A) (c : code a), c₀ =[decode a c] c) (decode_encode : decode a₀ c₀ = idp) : (a₀ = a) ≃ code a := begin fapply equiv.MK, { intro p, exact p ▸ c₀}, { apply decode}, { intro c, apply tr_eq_of_pathover, apply encode_decode}, { intro p, induction p, apply decode_encode}, end end section parameters {A : Type _} (a₀ : A) (code : A → Type _) (H : is_contr (Σa, code a)) (p : (center (Σa, code a)).1 = a₀) include p @[hott] protected def encode {a : A} (q : a₀ = a) : code a := (p ⬝ q) ▸ (center (Σa, code a)).2 @[hott] protected def decode' {a : A} (c : code a) : a₀ = a := (@is_prop.elim (Σ a, code a) _ ⟨a₀, encode idp⟩ ⟨a, c⟩)..1 @[hott] protected def decode {a : A} (c : code a) : a₀ = a := (decode' (encode idp))⁻¹ ⬝ decode' c @[hott] def total_space_method (a : A) : (a₀ = a) ≃ code a := begin fapply equiv.MK, { exact hott.eq.encode}, { exact hott.eq.decode}, { intro c, induction p, apply tr_eq_of_pathover, dsimp [eq.decode, eq.decode', eq.encode, eq_fst], rwr [idp_con, is_prop_elim_self], dsimp, rwr idp_con, refine @sigma.rec_on _ _ (λx, x.2 =[((@is_prop.elim (Σ a, code a) _ ⟨x.1, x.2⟩ ⟨a, c⟩)..1: _); code] c) (center (sigma code)) _, intros a c, apply eq_snd}, { intro q, induction q, dsimp [eq.encode], apply con.left_inv, }, end end @[hott] def encode_decode_method {A : Type _} (a₀ a : A) (code : A → Type _) (c₀ : code a₀) (decode : Π(a : A) (c : code a), a₀ = a) (encode_decode : Π(a : A) (c : code a), c₀ =[decode a c] c) : (a₀ = a) ≃ code a := begin fapply total_space_method, { fapply @is_contr.mk, { exact ⟨a₀, c₀⟩}, { intro p, fapply sigma_eq, apply decode, exact p.2, apply encode_decode}}, { reflexivity} end end eq end hott
2e3d163b44fa84e9a5f5e3a73aefe50cc8d2d6c8
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/algebra/group/hom.lean
d6ea468be6c1f39efbf941a41490a3aaa7ed465a
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
15,250
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import algebra.group.commute /-! # monoid and group homomorphisms This file defines the bundled structures for monoid and group homomorphisms. Namely, we define `monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp., additive) monoids or groups. We also define coercion to a function, and usual operations: composition, identity homomorphism, pointwise multiplication and pointwise inversion. ## Notations * `→*` for bundled monoid homs (also use for group homs) * `→+` for bundled add_monoid homs (also use for add_group homs) ## implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `group_hom` -- the idea is that `monoid_hom` is used. The constructor for `monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `monoid_hom.mk'` will construct group homs (i.e. monoid homs between groups) given only a proof that multiplication is preserved, 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 `monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. Historically this file also included definitions of unbundled homomorphism classes; they were deprecated and moved to `deprecated/group`. ## Tags monoid_hom, add_monoid_hom -/ variables {M : Type*} {N : Type*} {P : Type*} -- monoids {G : Type*} {H : Type*} -- groups /-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/ structure add_monoid_hom (M : Type*) (N : Type*) [add_monoid M] [add_monoid N] := (to_fun : M → N) (map_zero' : to_fun 0 = 0) (map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y) infixr ` →+ `:25 := add_monoid_hom /-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/ @[to_additive] structure monoid_hom (M : Type*) (N : Type*) [monoid M] [monoid N] := (to_fun : M → N) (map_one' : to_fun 1 = 1) (map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y) infixr ` →* `:25 := monoid_hom @[to_additive] instance {M : Type*} {N : Type*} {mM : monoid M} {mN : monoid N} : has_coe_to_fun (M →* N) := ⟨_, monoid_hom.to_fun⟩ namespace monoid_hom variables {mM : monoid M} {mN : monoid N} {mP : monoid P} variables [group G] [comm_group H] include mM mN @[simp, to_additive] lemma to_fun_eq_coe (f : M →* N) : f.to_fun = f := rfl @[simp, to_additive] lemma coe_mk (f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl @[to_additive] theorem congr_fun {f g : M →* N} (h : f = g) (x : M) : f x = g x := congr_arg (λ h : M →* N, h x) h @[to_additive] theorem congr_arg (f : M →* N) {x y : M} (h : x = y) : f x = f y := congr_arg (λ x : M, f x) h @[to_additive] lemma coe_inj ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g := by cases f; cases g; cases h; refl @[ext, to_additive] lemma ext ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) attribute [ext] _root_.add_monoid_hom.ext @[to_additive] lemma ext_iff {f g : M →* N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- If `f` is a monoid homomorphism then `f 1 = 1`. -/ @[simp, to_additive] lemma map_one (f : M →* N) : f 1 = 1 := f.map_one' /-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/ add_decl_doc add_monoid_hom.map_zero /-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/ @[simp, to_additive] lemma map_mul (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b /-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/ add_decl_doc add_monoid_hom.map_add @[to_additive] lemma map_mul_eq_one (f : M →* N) {a b : M} (h : a * b = 1) : f a * f b = 1 := by rw [← f.map_mul, h, f.map_one] /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too."] lemma map_exists_right_inv (f : M →* N) {x : M} (hx : ∃ y, x * y = 1) : ∃ y, f x * y = 1 := let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩ /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/ @[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_add_unit.map`."] lemma map_exists_left_inv (f : M →* N) {x : M} (hx : ∃ y, y * x = 1) : ∃ y, y * f x = 1 := let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩ omit mN mM /-- The identity map from a monoid to itself. -/ @[to_additive] def id (M : Type*) [monoid M] : M →* M := { to_fun := id, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The identity map from an additive monoid to itself. -/ add_decl_doc add_monoid_hom.id @[simp, to_additive] lemma id_apply {M : Type*} [monoid M] (x : M) : id M x = x := rfl include mM mN mP /-- Composition of monoid morphisms as a monoid morphism. -/ @[to_additive] def comp (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp } /-- Composition of additive monoid morphisms as an additive monoid morphism. -/ add_decl_doc add_monoid_hom.comp @[simp, to_additive] lemma comp_apply (g : N →* P) (f : M →* N) (x : M) : g.comp f x = g (f x) := rfl /-- Composition of monoid homomorphisms is associative. -/ @[to_additive] lemma comp_assoc {Q : Type*} [monoid Q] (f : M →* N) (g : N →* P) (h : P →* Q) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[to_additive] lemma cancel_right {g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ @[to_additive] lemma cancel_left {g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit mP @[simp, to_additive] lemma comp_id (f : M →* N) : f.comp (id M) = f := ext $ λ x, rfl @[simp, to_additive] lemma id_comp (f : M →* N) : (id N).comp f = f := ext $ λ x, rfl end monoid_hom section End namespace monoid variables (M) [monoid M] /-- The monoid of endomorphisms. -/ protected def End := M →* M namespace End instance : monoid (monoid.End M) := { mul := monoid_hom.comp, one := monoid_hom.id M, mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _, mul_one := monoid_hom.comp_id, one_mul := monoid_hom.id_comp } instance : inhabited (monoid.End M) := ⟨1⟩ instance : has_coe_to_fun (monoid.End M) := ⟨_, monoid_hom.to_fun⟩ end End @[simp] lemma coe_one : ((1 : monoid.End M) : M → M) = id := rfl @[simp] lemma coe_mul (f g) : ((f * g : monoid.End M) : M → M) = f ∘ g := rfl end monoid namespace add_monoid variables (A : Type*) [add_monoid A] /-- The monoid of endomorphisms. -/ protected def End := A →+ A namespace End instance : monoid (add_monoid.End A) := { mul := add_monoid_hom.comp, one := add_monoid_hom.id A, mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _, mul_one := add_monoid_hom.comp_id, one_mul := add_monoid_hom.id_comp } instance : inhabited (add_monoid.End A) := ⟨1⟩ instance : has_coe_to_fun (add_monoid.End A) := ⟨_, add_monoid_hom.to_fun⟩ end End @[simp] lemma coe_one : ((1 : add_monoid.End A) : A → A) = id := rfl @[simp] lemma coe_mul (f g) : ((f * g : add_monoid.End A) : A → A) = f ∘ g := rfl end add_monoid end End namespace monoid_hom variables [mM : monoid M] [mN : monoid N] [mP : monoid P] variables [group G] [comm_group H] include mM mN /-- `1` is the monoid homomorphism sending all elements to `1`. -/ @[to_additive] instance : has_one (M →* N) := ⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩ /-- `0` is the additive monoid homomorphism sending all elements to `0`. -/ add_decl_doc add_monoid_hom.has_zero @[simp, to_additive] lemma one_apply (x : M) : (1 : M →* N) x = 1 := rfl @[to_additive] instance : inhabited (M →* N) := ⟨1⟩ omit mM mN /-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism sending `x` to `f x * g x`. -/ @[to_additive] instance {M N} {mM : monoid M} [comm_monoid N] : has_mul (M →* N) := ⟨λ f g, { to_fun := λ m, f m * g m, map_one' := show f 1 * g 1 = 1, by simp, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩ /-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the additive monoid morphism sending `x` to `f x + g x`. -/ add_decl_doc add_monoid_hom.has_add @[simp, to_additive] lemma mul_apply {M N} {mM : monoid M} {mN : comm_monoid N} (f g : M →* N) (x : M) : (f * g) x = f x * g x := rfl /-- (M →* N) is a comm_monoid if N is commutative. -/ @[to_additive] instance {M N} [monoid M] [comm_monoid N] : comm_monoid (M →* N) := { mul := (*), mul_assoc := by intros; ext; apply mul_assoc, one := 1, one_mul := by intros; ext; apply one_mul, mul_one := by intros; ext; apply mul_one, mul_comm := by intros; ext; apply mul_comm } /-- `flip` arguments of `f : M →* N →* P` -/ @[to_additive "`flip` arguments of `f : M →+ N →+ P`"] def flip {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) : N →* M →* P := { to_fun := λ y, ⟨λ x, f x y, by rw [f.map_one, one_apply], λ x₁ x₂, by rw [f.map_mul, mul_apply]⟩, map_one' := ext $ λ x, (f x).map_one, map_mul' := λ y₁ y₂, ext $ λ x, (f x).map_mul y₁ y₂ } @[simp, to_additive] lemma flip_apply {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) (x : M) (y : N) : f.flip y x = f x y := rfl /-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/ @[to_additive "If two homomorphism from an additive group to an additive monoid are equal at `x`, then they are equal at `-x`." ] lemma eq_on_inv {G} [group G] [monoid M] {f g : G →* M} {x : G} (h : f x = g x) : f x⁻¹ = g x⁻¹ := left_inv_eq_right_inv (f.map_mul_eq_one $ inv_mul_self x) $ h.symm ▸ g.map_mul_eq_one $ mul_inv_self x /-- Group homomorphisms preserve inverse. -/ @[simp, to_additive] theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ := eq_inv_of_mul_eq_one $ f.map_mul_eq_one $ inv_mul_self g /-- Group homomorphisms preserve division. -/ @[simp, to_additive] theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) : f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv] /-- A homomorphism from a group to a monoid is injective iff its kernel is trivial. -/ @[to_additive] lemma injective_iff {G H} [group G] [monoid H] (f : G →* H) : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h x hfx, h $ hfx.trans f.map_one.symm, λ h x y hxy, mul_inv_eq_one.1 $ h _ $ by rw [f.map_mul, hxy, ← f.map_mul, mul_inv_self, f.map_one]⟩ include mM /-- Makes a group homomomorphism from a proof that the map preserves multiplication. -/ @[to_additive] def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G := { to_fun := f, map_mul' := map_mul, map_one' := mul_self_iff_eq_one.1 $ by rw [←map_mul, mul_one] } /-- Makes an additive group homomomorphism from a proof that the map preserves multiplication. -/ add_decl_doc add_monoid_hom.mk' @[simp, to_additive] lemma coe_mk' {f : M → G} (map_mul : ∀ a b : M, f (a * b) = f a * f b) : ⇑(mk' f map_mul) = f := rfl omit mM /-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`. -/ @[to_additive "Makes an additive group homomorphism from a proof that the map preserves the operation `λ a b, a + -b`. See also `add_monoid_hom.of_map_sub` for a version using `λ a b, a - b`."] def of_map_mul_inv {H : Type*} [group H] (f : G → H) (map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) : G →* H := mk' f $ λ x y, calc f (x * y) = f x * (f $ 1 * 1⁻¹ * y⁻¹)⁻¹ : by simp only [one_mul, one_inv, ← map_div, inv_inv] ... = f x * f y : by { simp only [map_div], simp only [mul_right_inv, one_mul, inv_inv] } @[simp, to_additive] lemma coe_of_map_mul_inv {H : Type*} [group H] (f : G → H) (map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) : ⇑(of_map_mul_inv f map_div) = f := rfl /-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending `x` to `(f x)⁻¹`. -/ @[to_additive] instance {M G} [monoid M] [comm_group G] : has_inv (M →* G) := ⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩ /-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the homomorphism sending `x` to `-(f x)`. -/ add_decl_doc add_monoid_hom.has_neg @[simp, to_additive] lemma inv_apply {M G} {mM : monoid M} {gG : comm_group G} (f : M →* G) (x : M) : f⁻¹ x = (f x)⁻¹ := rfl /-- If `G` is a commutative group, then `M →* G` a commutative group too. -/ @[to_additive] instance {M G} [monoid M] [comm_group G] : comm_group (M →* G) := { inv := has_inv.inv, mul_left_inv := by intros; ext; apply mul_left_inv, ..monoid_hom.comm_monoid } /-- If `G` is an additive commutative group, then `M →+ G` an additive commutative group too. -/ add_decl_doc add_monoid_hom.add_comm_group end monoid_hom namespace add_monoid_hom variables [add_group G] [add_group H] /-- Additive group homomorphisms preserve subtraction. -/ @[simp] theorem map_sub (f : G →+ H) (g h : G) : f (g - h) = (f g) - (f h) := f.map_add_neg g h /-- Define a morphism of additive groups given a map which respects difference. -/ def of_map_sub (f : G → H) (hf : ∀ x y, f (x - y) = f x - f y) : G →+ H := of_map_add_neg f hf @[simp] lemma coe_of_map_sub (f : G → H) (hf : ∀ x y, f (x - y) = f x - f y) : ⇑(of_map_sub f hf) = f := rfl end add_monoid_hom section commute variables [monoid M] [monoid N] {a x y : M} @[simp, to_additive] protected lemma semiconj_by.map (h : semiconj_by a x y) (f : M →* N) : semiconj_by (f a) (f x) (f y) := by simpa only [semiconj_by, f.map_mul] using congr_arg f h @[simp, to_additive] protected lemma commute.map (h : commute x y) (f : M →* N) : commute (f x) (f y) := h.map f end commute
c4ba7a86e43124bfaa82e4e5d00212a061046905
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/05_Interacting_with_Lean.org.8.lean
826e576ad13bdc6e2be24ae59a374b6b24f199c1
[]
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
133
lean
/- page 67 -/ import standard import standard algebra.ordered_ring open nat algebra -- BEGIN check @neg_neg check pred_succ -- END
5820b0966f08a70ccae53c699b72a47123d1e491
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/environment.lean
df5b54321e3c1bf5147d2940df1a3db64504e068
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
20,304
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.io import init.util import init.data.bytearray import init.lean.declaration import init.lean.smap namespace Lean /- Opaque environment extension state. It is essentially the Lean version of a C `void *` TODO: mark opaque -/ def EnvExtensionState : Type := NonScalar instance EnvExtensionState.inhabited : Inhabited EnvExtensionState := inferInstanceAs (Inhabited NonScalar) /- TODO: mark opaque. -/ def ModuleIdx := Nat instance ModuleIdx.inhabited : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat) abbrev ConstMap := SMap Name ConstantInfo Name.quickLt /- Environment fields that are not used often. -/ structure EnvironmentHeader := (trustLevel : UInt32 := 0) (quotInit : Bool := false) (mainModule : Name := default _) (imports : Array Name := Array.empty) /- TODO: mark opaque. -/ structure Environment := (const2ModIdx : HashMap Name ModuleIdx) (constants : ConstMap) (extensions : Array EnvExtensionState) (header : EnvironmentHeader := {}) namespace Environment instance : Inhabited Environment := ⟨{ const2ModIdx := {}, constants := {}, extensions := Array.empty }⟩ @[export lean.environment_add_core] def add (env : Environment) (cinfo : ConstantInfo) : Environment := { constants := env.constants.insert cinfo.name cinfo, .. env } @[export lean.environment_find_core] def find (env : Environment) (n : Name) : Option ConstantInfo := /- It is safe to use `find'` because we never overwrite imported declarations. -/ env.constants.find' n def contains (env : Environment) (n : Name) : Bool := env.constants.contains n def imports (env : Environment) : Array Name := env.header.imports @[export lean.environment_set_main_module_core] def setMainModule (env : Environment) (m : Name) : Environment := { header := { mainModule := m, .. env.header }, .. env } @[export lean.environment_main_module_core] def mainModule (env : Environment) : Name := env.header.mainModule @[export lean.environment_mark_quot_init_core] private def markQuotInit (env : Environment) : Environment := { header := { quotInit := true, .. env.header } , .. env } @[export lean.environment_quot_init_core] private def isQuotInit (env : Environment) : Bool := env.header.quotInit @[export lean.environment_trust_level_core] private def getTrustLevel (env : Environment) : UInt32 := env.header.trustLevel def getModuleIdxFor (env : Environment) (c : Name) : Option ModuleIdx := env.const2ModIdx.find c def isConstructor (env : Environment) (c : Name) : Bool := match env.find c with | ConstantInfo.ctorInfo _ => true | _ => false /-- Type check, add and compile the given declaration. TODO: better error handling, we are forgetting the information produced by the C++ type checker and compiler. -/ @[extern "lean_add_and_compile"] constant addAndCompile (env : @& Environment) (o : @& Options) (d : @& Declaration) : Option Environment := default _ end Environment /- "Raw" environment extension. TODO: mark opaque. -/ structure EnvExtension (σ : Type) := (idx : Nat) (initial : σ) namespace EnvExtension unsafe def setStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := { extensions := env.extensions.set ext.idx (unsafeCast s), .. env } @[implementedBy setStateUnsafe] constant setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := default _ unsafe def getStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := let s : EnvExtensionState := env.extensions.get ext.idx; @unsafeCast _ _ ⟨ext.initial⟩ s @[implementedBy getStateUnsafe] constant getState {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := ext.initial @[inline] unsafe def modifyStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := { extensions := env.extensions.modify ext.idx $ fun s => let s : σ := (@unsafeCast _ _ ⟨ext.initial⟩ s); let s : σ := f s; unsafeCast s, .. env } @[implementedBy modifyStateUnsafe] constant modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := default _ end EnvExtension private def mkEnvExtensionsRef : IO (IO.Ref (Array (EnvExtension EnvExtensionState))) := IO.mkRef Array.empty @[init mkEnvExtensionsRef] private constant envExtensionsRef : IO.Ref (Array (EnvExtension EnvExtensionState)) := default _ instance EnvExtension.Inhabited (σ : Type) [Inhabited σ] : Inhabited (EnvExtension σ) := ⟨{ idx := 0, initial := default _ }⟩ unsafe def registerEnvExtensionUnsafe {σ : Type} (initState : σ) : IO (EnvExtension σ) := do initializing ← IO.initializing; unless initializing $ throw (IO.userError ("failed to register environment, extensions can only be registered during initialization")); exts ← envExtensionsRef.get; let idx := exts.size; let ext : EnvExtension σ := { idx := idx, initial := initState }; envExtensionsRef.modify (fun exts => exts.push (unsafeCast ext)); pure ext /- Environment extensions can only be registered during initialization. Reasons: 1- Our implementation assumes the number of extensions does not change after an environment object is created. 2- We do not use any synchronization primitive to access `envExtensionsRef`. -/ @[implementedBy registerEnvExtensionUnsafe] constant registerEnvExtension {σ : Type} (initState : σ) : IO (EnvExtension σ) := default _ private def mkInitialExtensionStates : IO (Array EnvExtensionState) := do exts ← envExtensionsRef.get; pure $ exts.map $ fun ext => ext.initial @[export lean.mk_empty_environment_core] def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do initializing ← IO.initializing; when initializing $ throw (IO.userError "environment objects cannot be created during initialization"); exts ← mkInitialExtensionStates; pure { const2ModIdx := {}, constants := {}, header := { trustLevel := trustLevel }, extensions := exts } structure PersistentEnvExtensionState (α : Type) (σ : Type) := (importedEntries : Array (Array α)) -- entries per imported module (state : σ) /- An environment extension with support for storing/retrieving entries from a .olean file. - α is the entry type. - σ is the actual state. TODO: mark opaque. -/ structure PersistentEnvExtension (α : Type) (σ : Type) extends EnvExtension (PersistentEnvExtensionState α σ) := (name : Name) (addImportedFn : Array (Array α) → σ) (addEntryFn : σ → α → σ) (exportEntriesFn : σ → Array α) (statsFn : σ → Format) /- Opaque persistent environment extension entry. It is essentially a C `void *` TODO: mark opaque -/ def EnvExtensionEntry := NonScalar instance EnvExtensionEntry.inhabited : Inhabited EnvExtensionEntry := inferInstanceAs (Inhabited NonScalar) instance PersistentEnvExtensionState.inhabited {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) := ⟨{importedEntries := Array.empty, state := default _ }⟩ instance PersistentEnvExtension.inhabited {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α σ) := ⟨{ toEnvExtension := { idx := 0, initial := default _ }, name := default _, addImportedFn := fun _ => default _, addEntryFn := fun s _ => s, exportEntriesFn := fun _ => Array.empty, statsFn := fun _ => Format.nil }⟩ namespace PersistentEnvExtension def getModuleEntries {α σ : Type} (ext : PersistentEnvExtension α σ) (env : Environment) (m : ModuleIdx) : Array α := (ext.toEnvExtension.getState env).importedEntries.get m def addEntry {α σ : Type} (ext : PersistentEnvExtension α σ) (env : Environment) (a : α) : Environment := ext.toEnvExtension.modifyState env $ fun s => let state := ext.addEntryFn s.state a; { state := state, .. s } def getState {α σ : Type} (ext : PersistentEnvExtension α σ) (env : Environment) : σ := (ext.toEnvExtension.getState env).state def setState {α σ : Type} (ext : PersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { state := s, .. ps } def modifyState {α σ : Type} (ext : PersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { state := f (ps.state), .. ps } end PersistentEnvExtension private def mkPersistentEnvExtensionsRef : IO (IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionState))) := IO.mkRef Array.empty @[init mkPersistentEnvExtensionsRef] private constant persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionState)) := default _ structure PersistentEnvExtensionDescr (α σ : Type) := (name : Name) (addImportedFn : Array (Array α) → σ) (addEntryFn : σ → α → σ) (exportEntriesFn : σ → Array α) (statsFn : σ → Format := fun _ => Format.nil) unsafe def registerPersistentEnvExtensionUnsafe {α σ : Type} (descr : PersistentEnvExtensionDescr α σ) : IO (PersistentEnvExtension α σ) := do let s : PersistentEnvExtensionState α σ := { importedEntries := Array.empty, state := descr.addImportedFn Array.empty }; pExts ← persistentEnvExtensionsRef.get; when (pExts.any (fun ext => ext.name == descr.name)) $ throw (IO.userError ("invalid environment extension, '" ++ toString descr.name ++ "' has already been used")); ext ← registerEnvExtension s; let pExt : PersistentEnvExtension α σ := { toEnvExtension := ext, name := descr.name, addImportedFn := descr.addImportedFn, addEntryFn := descr.addEntryFn, exportEntriesFn := descr.exportEntriesFn, statsFn := descr.statsFn }; persistentEnvExtensionsRef.modify (fun pExts => pExts.push (unsafeCast pExt)); pure pExt @[implementedBy registerPersistentEnvExtensionUnsafe] constant registerPersistentEnvExtension {α σ : Type} (descr : PersistentEnvExtensionDescr α σ) : IO (PersistentEnvExtension α σ) := default _ /- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/ def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α (List α × σ) @[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ := as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState structure SimplePersistentEnvExtensionDescr (α σ : Type) := (name : Name) (addEntryFn : σ → α → σ) (addImportedFn : Array (Array α) → σ) (toArrayFn : List α → Array α := fun es => es.toArray) def registerSimplePersistentEnvExtension {α σ : Type} (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) := registerPersistentEnvExtension { name := descr.name, addImportedFn := fun as => ([], descr.addImportedFn as), addEntryFn := fun s e => match s with | (entries, s) => (e::entries, descr.addEntryFn s e), exportEntriesFn := fun s => descr.toArrayFn s.1.reverse, statsFn := fun s => format "number of local entries: " ++ format s.1.length } namespace SimplePersistentEnvExtension instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) := inferInstanceAs (Inhabited (PersistentEnvExtension α (List α × σ))) def getEntries {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α := (PersistentEnvExtension.getState ext env).1 def getState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ := (PersistentEnvExtension.getState ext env).2 def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s)) def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s)) end SimplePersistentEnvExtension /- API for creating extensions in C++. This API will eventually be deleted. -/ def CPPExtensionState := NonScalar instance CPPExtensionState.inhabited : Inhabited CPPExtensionState := inferInstanceAs (Inhabited NonScalar) @[export lean.register_extension_core] unsafe def registerCPPExtension (initial : CPPExtensionState) : Option Nat := unsafeIO (do ext ← registerEnvExtension initial; pure ext.idx) @[export lean.set_extension_core] unsafe def setCPPExtensionState (env : Environment) (idx : Nat) (s : CPPExtensionState) : Option Environment := unsafeIO (do exts ← envExtensionsRef.get; pure $ (exts.get idx).setState env s) @[export lean.get_extension_core] unsafe def getCPPExtensionState (env : Environment) (idx : Nat) : Option CPPExtensionState := unsafeIO (do exts ← envExtensionsRef.get; pure $ (exts.get idx).getState env) /- Legacy support for Modification objects -/ /- Opaque modification object. It is essentially a C `void *`. In Lean 3, a .olean file is essentially a collection of modification objects. This type represents the modification objects implemented in C++. We will eventually delete this type as soon as we port the remaining Lean 3 legacy code. TODO: mark opaque -/ def Modification := NonScalar instance Modification.inhabited : Inhabited Modification := inferInstanceAs (Inhabited NonScalar) def regModListExtension : IO (EnvExtension (List Modification)) := registerEnvExtension [] @[init regModListExtension] constant modListExtension : EnvExtension (List Modification) := default _ /- The C++ code uses this function to store the given modification object into the environment. -/ @[export lean.environment_add_modification_core] def addModification (env : Environment) (mod : Modification) : Environment := modListExtension.modifyState env $ fun mods => mod :: mods /- mkModuleData invokes this function to convert a list of modification objects into a serialized byte array. -/ @[extern 2 "lean_serialize_modifications"] constant serializeModifications : List Modification → IO ByteArray := default _ @[extern 3 "lean_perform_serialized_modifications"] constant performModifications : Environment → ByteArray → IO Environment := default _ /- Content of a .olean file. We use `compact.cpp` to generate the image of this object in disk. -/ structure ModuleData := (imports : Array Name) (constants : Array ConstantInfo) (entries : Array (Name × Array EnvExtensionEntry)) (serialized : ByteArray) -- Legacy support: serialized modification objects instance ModuleData.inhabited : Inhabited ModuleData := ⟨{imports := default _, constants := default _, entries := default _, serialized := default _}⟩ @[extern 3 "lean_save_module_data"] constant saveModuleData (fname : @& String) (m : ModuleData) : IO Unit := default _ @[extern 2 "lean_read_module_data"] constant readModuleData (fname : @& String) : IO ModuleData := default _ def mkModuleData (env : Environment) : IO ModuleData := do pExts ← persistentEnvExtensionsRef.get; let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold (fun i result => let state := (pExts.get i).getState env; let exportEntriesFn := (pExts.get i).exportEntriesFn; let extName := (pExts.get i).name; result.push (extName, exportEntriesFn state)) Array.empty; bytes ← serializeModifications (modListExtension.getState env); pure { imports := env.header.imports, constants := env.constants.foldStage2 (fun cs _ c => cs.push c) Array.empty, entries := entries, serialized := bytes } @[export lean.write_module_core] def writeModule (env : Environment) (fname : String) : IO Unit := do modData ← mkModuleData env; saveModuleData fname modData @[extern 2 "lean_find_olean"] constant findOLean (modName : Name) : IO String := default _ partial def importModulesAux : List Name → (NameSet × Array ModuleData) → IO (NameSet × Array ModuleData) | [] r := pure r | (m::ms) (s, mods) := if s.contains m then importModulesAux ms (s, mods) else do let s := s.insert m; mFile ← findOLean m; mod ← readModuleData mFile; (s, mods) ← importModulesAux mod.imports.toList (s, mods); let mods := mods.push mod; importModulesAux ms (s, mods) private partial def getEntriesFor (mod : ModuleData) (extId : Name) : Nat → Array EnvExtensionState | i := if i < mod.entries.size then let curr := mod.entries.get i; if curr.1 == extId then curr.2 else getEntriesFor (i+1) else Array.empty private def setImportedEntries (env : Environment) (mods : Array ModuleData) : IO Environment := do pExtDescrs ← persistentEnvExtensionsRef.get; pure $ mods.iterate env $ fun _ mod env => pExtDescrs.iterate env $ fun _ extDescr env => let entries := getEntriesFor mod extDescr.name 0; extDescr.toEnvExtension.modifyState env $ fun s => { importedEntries := s.importedEntries.push entries, .. s } private def finalizePersistentExtensions (env : Environment) : IO Environment := do pExtDescrs ← persistentEnvExtensionsRef.get; pure $ pExtDescrs.iterate env $ fun _ extDescr env => extDescr.toEnvExtension.modifyState env $ fun s => { state := extDescr.addImportedFn s.importedEntries, .. s } @[export lean.import_modules_core] def importModules (modNames : List Name) (trustLevel : UInt32 := 0) : IO Environment := do (_, mods) ← importModulesAux modNames ({}, Array.empty); let const2ModIdx := mods.iterate {} $ fun (modIdx) (mod : ModuleData) (m : HashMap Name ModuleIdx) => mod.constants.iterate m $ fun _ cinfo m => m.insert cinfo.name modIdx.val; constants ← mods.miterate SMap.empty $ fun _ (mod : ModuleData) (cs : ConstMap) => mod.constants.miterate cs $ fun _ cinfo cs => do { when (cs.contains cinfo.name) $ throw (IO.userError ("import failed, environment already contains '" ++ toString cinfo.name ++ "'")); pure $ cs.insert cinfo.name cinfo }; let constants := constants.switch; exts ← mkInitialExtensionStates; let env : Environment := { const2ModIdx := const2ModIdx, constants := constants, extensions := exts, header := { quotInit := !modNames.isEmpty, -- We assume `core.lean` initializes quotient module trustLevel := trustLevel, imports := modNames.toArray } }; env ← setImportedEntries env mods; env ← finalizePersistentExtensions env; env ← mods.miterate env $ fun _ mod env => performModifications env mod.serialized; pure env namespace Environment @[export lean.display_stats_core] def displayStats (env : Environment) : IO Unit := do pExtDescrs ← persistentEnvExtensionsRef.get; let numModules := ((pExtDescrs.get 0).toEnvExtension.getState env).importedEntries.size; IO.println ("direct imports: " ++ toString env.header.imports); IO.println ("number of imported modules: " ++ toString numModules); IO.println ("number of consts: " ++ toString env.constants.size); IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1); IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2); IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets); IO.println ("map depth for local consts: " ++ toString env.constants.maxDepth); IO.println ("trust level: " ++ toString env.header.trustLevel); IO.println ("number of extensions: " ++ toString env.extensions.size); pExtDescrs.mfor $ fun extDescr => do { IO.println ("extension '" ++ toString extDescr.name ++ "'"); let s := extDescr.toEnvExtension.getState env; let fmt := extDescr.statsFn s.state; unless fmt.isNil (IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state)))); IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0)); pure () }; pure () end Environment end Lean
21c28c1c7014db4e09d0c62e8a77e3d2e51864da
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/topology/algebra/module.lean
4be6df33addb01d8967a3f3eda60d8a65c3892b3
[ "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
72,118
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov, Frédéric Dupuis, Heather Macbeth -/ import topology.algebra.ring import topology.algebra.mul_action import topology.uniform_space.uniform_embedding import algebra.algebra.basic import linear_algebra.projection import linear_algebra.pi /-! # Theory of topological modules and continuous linear maps. We use the class `has_continuous_smul` for topological (semi) modules and topological vector spaces. In this file we define continuous (semi-)linear maps, as semilinear maps between topological modules which are continuous. The set of continuous semilinear maps between the topological `R₁`-module `M` and `R₂`-module `M₂` with respect to the `ring_hom` `σ` is denoted by `M →SL[σ] M₂`. Plain linear maps are denoted by `M →L[R] M₂` and star-linear maps by `M →L⋆[R] M₂`. The corresponding notation for equivalences is `M ≃SL[σ] M₂`, `M ≃L[R] M₂` and `M ≃L⋆[R] M₂`. -/ open filter open_locale topological_space big_operators filter universes u v w u' section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] lemma has_continuous_smul.of_nhds_zero [topological_ring R] [topological_add_group M] (hmul : tendsto (λ p : R × M, p.1 • p.2) (𝓝 0 ×ᶠ (𝓝 0)) (𝓝 0)) (hmulleft : ∀ m : M, tendsto (λ a : R, a • m) (𝓝 0) (𝓝 0)) (hmulright : ∀ a : R, tendsto (λ m : M, a • m) (𝓝 0) (𝓝 0)) : has_continuous_smul R M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨a₀, m₀⟩, have key : ∀ p : R × M, p.1 • p.2 = a₀ • m₀ + ((p.1 - a₀) • m₀ + a₀ • (p.2 - m₀) + (p.1 - a₀) • (p.2 - m₀)), { rintro ⟨a, m⟩, simp [sub_smul, smul_sub], abel }, rw funext key, clear key, refine tendsto_const_nhds.add (tendsto.add (tendsto.add _ _) _), { rw [sub_self, zero_smul], apply (hmulleft m₀).comp, rw [show (λ p : R × M, p.1 - a₀) = (λ a, a - a₀) ∘ prod.fst, by {ext, refl }, nhds_prod_eq], have : tendsto (λ a, a - a₀) (𝓝 a₀) (𝓝 0), { rw ← sub_self a₀, exact tendsto_id.sub tendsto_const_nhds }, exact this.comp tendsto_fst }, { rw [sub_self, smul_zero], apply (hmulright a₀).comp, rw [show (λ p : R × M, p.2 - m₀) = (λ m, m - m₀) ∘ prod.snd, by {ext, refl }, nhds_prod_eq], have : tendsto (λ m, m - m₀) (𝓝 m₀) (𝓝 0), { rw ← sub_self m₀, exact tendsto_id.sub tendsto_const_nhds }, exact this.comp tendsto_snd }, { rw [sub_self, zero_smul, nhds_prod_eq, show (λ p : R × M, (p.fst - a₀) • (p.snd - m₀)) = (λ p : R × M, p.1 • p.2) ∘ (prod.map (λ a, a - a₀) (λ m, m - m₀)), by { ext, refl }], apply hmul.comp (tendsto.prod_map _ _); { rw ← sub_self , exact tendsto_id.sub tendsto_const_nhds } }, end⟩ end section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [has_continuous_add M] [module R M] [has_continuous_smul R M] /-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then `⊤` is the only submodule of `M` with a nonempty interior. This is the case, e.g., if `R` is a nondiscrete normed field. -/ lemma submodule.eq_top_of_nonempty_interior' [ne_bot (𝓝[{x : R | is_unit x}] 0)] (s : submodule R M) (hs : (interior (s:set M)).nonempty) : s = ⊤ := begin rcases hs with ⟨y, hy⟩, refine (submodule.eq_top_iff'.2 $ λ x, _), rw [mem_interior_iff_mem_nhds] at hy, have : tendsto (λ c:R, y + c • x) (𝓝[{x : R | is_unit x}] 0) (𝓝 (y + (0:R) • x)), from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul tendsto_const_nhds), rw [zero_smul, add_zero] at this, obtain ⟨_, hu : y + _ • _ ∈ s, u, rfl⟩ := nonempty_of_mem (inter_mem (mem_map.1 (this hy)) self_mem_nhds_within), have hy' : y ∈ ↑s := mem_of_mem_nhds hy, rwa [s.add_mem_iff_right hy', ←units.smul_def, s.smul_mem_iff' u] at hu, end variables (R M) /-- Let `R` be a topological ring such that zero is not an isolated point (e.g., a nondiscrete normed field, see `normed_field.punctured_nhds_ne_bot`). Let `M` be a nontrivial module over `R` such that `c • x = 0` implies `c = 0 ∨ x = 0`. Then `M` has no isolated points. We formulate this using `ne_bot (𝓝[{x}ᶜ] x)`. This lemma is not an instance because Lean would need to find `[has_continuous_smul ?m_1 M]` with unknown `?m_1`. We register this as an instance for `R = ℝ` in `real.punctured_nhds_module_ne_bot`. One can also use `haveI := module.punctured_nhds_ne_bot R M` in a proof. -/ lemma module.punctured_nhds_ne_bot [nontrivial M] [ne_bot (𝓝[{0}ᶜ] (0 : R))] [no_zero_smul_divisors R M] (x : M) : ne_bot (𝓝[{x}ᶜ] x) := begin rcases exists_ne (0 : M) with ⟨y, hy⟩, suffices : tendsto (λ c : R, x + c • y) (𝓝[{0}ᶜ] 0) (𝓝[{x}ᶜ] x), from this.ne_bot, refine tendsto.inf _ (tendsto_principal_principal.2 $ _), { convert tendsto_const_nhds.add ((@tendsto_id R _).smul_const y), rw [zero_smul, add_zero] }, { intros c hc, simpa [hy] using hc } end end section closure variables {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [module R M] [has_continuous_smul R M] lemma submodule.closure_smul_self_subset (s : submodule R M) : (λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M))) ⊆ closure (s : set M) := calc (λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M))) = (λ p : R × M, p.1 • p.2) '' (closure ((set.univ : set R).prod s)) : by simp [closure_prod_eq] ... ⊆ closure ((λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod s)) : image_closure_subset_closure_image continuous_smul ... = closure s : begin congr, ext x, refine ⟨_, λ hx, ⟨⟨1, x⟩, ⟨set.mem_univ _, hx⟩, one_smul R _⟩⟩, rintros ⟨⟨c, y⟩, ⟨hc, hy⟩, rfl⟩, simp [s.smul_mem c hy] end lemma submodule.closure_smul_self_eq (s : submodule R M) : (λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M))) = closure (s : set M) := set.subset.antisymm s.closure_smul_self_subset (λ x hx, ⟨⟨1, x⟩, ⟨set.mem_univ _, hx⟩, one_smul R _⟩) variables [has_continuous_add M] /-- The (topological-space) closure of a submodule of a topological `R`-module `M` is itself a submodule. -/ def submodule.topological_closure (s : submodule R M) : submodule R M := { carrier := closure (s : set M), smul_mem' := λ c x hx, s.closure_smul_self_subset ⟨⟨c, x⟩, ⟨set.mem_univ _, hx⟩, rfl⟩, ..s.to_add_submonoid.topological_closure } @[simp] lemma submodule.topological_closure_coe (s : submodule R M) : (s.topological_closure : set M) = closure (s : set M) := rfl instance submodule.topological_closure_has_continuous_smul (s : submodule R M) : has_continuous_smul R (s.topological_closure) := { continuous_smul := begin apply continuous_induced_rng, change continuous (λ p : R × s.topological_closure, p.1 • (p.2 : M)), continuity, end, ..s.to_add_submonoid.topological_closure_has_continuous_add } lemma submodule.submodule_topological_closure (s : submodule R M) : s ≤ s.topological_closure := subset_closure lemma submodule.is_closed_topological_closure (s : submodule R M) : is_closed (s.topological_closure : set M) := by convert is_closed_closure lemma submodule.topological_closure_minimal (s : submodule R M) {t : submodule R M} (h : s ≤ t) (ht : is_closed (t : set M)) : s.topological_closure ≤ t := closure_minimal h ht lemma submodule.topological_closure_mono {s : submodule R M} {t : submodule R M} (h : s ≤ t) : s.topological_closure ≤ t.topological_closure := s.topological_closure_minimal (h.trans t.submodule_topological_closure) t.is_closed_topological_closure end closure /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] extends M →ₛₗ[σ] M₂ := (cont : continuous to_fun . tactic.interactive.continuity') notation M ` →SL[`:25 σ `] ` M₂ := continuous_linear_map σ M M₂ notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map (ring_hom.id R) M M₂ notation M ` →L⋆[`:25 R `] ` M₂ := continuous_linear_map (@star_ring_aut R _ _ : R →+* R) M M₂ /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ @[nolint has_inhabited_instance] structure continuous_linear_equiv {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) {σ' : S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [module R M] [module S M₂] extends M ≃ₛₗ[σ] M₂ := (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') notation M ` ≃SL[`:50 σ `] ` M₂ := continuous_linear_equiv σ M M₂ notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv (ring_hom.id R) M M₂ notation M ` ≃L⋆[`:50 R `] ` M₂ := continuous_linear_equiv (@star_ring_aut R _ _ : R →+* R) M M₂ namespace continuous_linear_map section semiring /-! ### Properties that hold for non-necessarily commutative semirings. -/ variables {R₁ : Type*} [semiring R₁] {R₂ : Type*} [semiring R₂] {R₃ : Type*} [semiring R₃] {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {M₁ : Type*} [topological_space M₁] [add_comm_monoid M₁] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [module R₁ M₁] [module R₂ M₂] [module R₃ M₃] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M₁ →SL[σ₁₂] M₂) (M₁ →ₛₗ[σ₁₂] M₂) := ⟨to_linear_map⟩ -- make the coercion the preferred form @[simp] lemma to_linear_map_eq_coe (f : M₁ →SL[σ₁₂] M₂) : f.to_linear_map = f := rfl /-- Coerce continuous linear maps to functions. -/ -- see Note [function coercion] instance to_fun : has_coe_to_fun (M₁ →SL[σ₁₂] M₂) (λ _, M₁ → M₂) := ⟨λ f, f⟩ @[simp] lemma coe_mk (f : M₁ →ₛₗ[σ₁₂] M₂) (h) : (mk f h : M₁ →ₛₗ[σ₁₂] M₂) = f := rfl @[simp] lemma coe_mk' (f : M₁ →ₛₗ[σ₁₂] M₂) (h) : (mk f h : M₁ → M₂) = f := rfl @[continuity] protected lemma continuous (f : M₁ →SL[σ₁₂] M₂) : continuous f := f.2 theorem coe_injective : function.injective (coe : (M₁ →SL[σ₁₂] M₂) → (M₁ →ₛₗ[σ₁₂] M₂)) := by { intros f g H, cases f, cases g, congr' } @[simp, norm_cast] lemma coe_inj {f g : M₁ →SL[σ₁₂] M₂} : (f : M₁ →ₛₗ[σ₁₂] M₂) = g ↔ f = g := coe_injective.eq_iff theorem coe_fn_injective : @function.injective (M₁ →SL[σ₁₂] M₂) (M₁ → M₂) coe_fn := linear_map.coe_injective.comp coe_injective @[ext] theorem ext {f g : M₁ →SL[σ₁₂] M₂} (h : ∀ x, f x = g x) : f = g := coe_fn_injective $ funext h theorem ext_iff {f g : M₁ →SL[σ₁₂] M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (f g : M₁ →SL[σ₁₂] M₂) (c : R₁) (h : M₂ →SL[σ₂₃] M₃) (x y z : M₁) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : M₁) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_smulₛₗ : f (c • x) = (σ₁₂ c) • f x := (to_linear_map _).map_smulₛₗ _ _ @[simp] lemma map_smul [module R₁ M₂] (f : M₁ →L[R₁] M₂)(c : R₁) (x : M₁) : f (c • x) = c • f x := by simp only [ring_hom.id_apply, map_smulₛₗ] @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M₁] [module S M₁] [has_scalar R M₂] [module S M₂] [linear_map.compatible_smul M₁ M₂ R S] (f : M₁ →L[S] M₂) (c : R) (x : M₁) : f (c • x) = c • f x := linear_map.compatible_smul.map_smul f c x lemma map_sum {ι : Type*} (s : finset ι) (g : ι → M₁) : f (∑ i in s, g i) = ∑ i in s, f (g i) := f.to_linear_map.map_sum @[simp, norm_cast] lemma coe_coe : ((f : M₁ →ₛₗ[σ₁₂] M₂) : (M₁ → M₂)) = (f : M₁ → M₂) := rfl @[ext] theorem ext_ring [topological_space R₁] {f g : R₁ →L[R₁] M₁} (h : f 1 = g 1) : f = g := coe_inj.1 $ linear_map.ext_ring h theorem ext_ring_iff [topological_space R₁] {f g : R₁ →L[R₁] M₁} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ /-- If two continuous linear maps are equal on a set `s`, then they are equal on the closure of the `submodule.span` of this set. -/ lemma eq_on_closure_span [t2_space M₂] {s : set M₁} {f g : M₁ →SL[σ₁₂] M₂} (h : set.eq_on f g s) : set.eq_on f g (closure (submodule.span R₁ s : set M₁)) := (linear_map.eq_on_span' h).closure f.continuous g.continuous /-- If the submodule generated by a set `s` is dense in the ambient module, then two continuous linear maps equal on `s` are equal. -/ lemma ext_on [t2_space M₂] {s : set M₁} (hs : dense (submodule.span R₁ s : set M₁)) {f g : M₁ →SL[σ₁₂] M₂} (h : set.eq_on f g s) : f = g := ext $ λ x, eq_on_closure_span h (hs x) /-- Under a continuous linear map, the image of the `topological_closure` of a submodule is contained in the `topological_closure` of its image. -/ lemma _root_.submodule.topological_closure_map [ring_hom_surjective σ₁₂] [topological_space R₁] [topological_space R₂] [has_continuous_smul R₁ M₁] [has_continuous_add M₁] [has_continuous_smul R₂ M₂] [has_continuous_add M₂] (f : M₁ →SL[σ₁₂] M₂) (s : submodule R₁ M₁) : (s.topological_closure.map (f : M₁ →ₛₗ[σ₁₂] M₂)) ≤ (s.map (f : M₁ →ₛₗ[σ₁₂] M₂)).topological_closure := image_closure_subset_closure_image f.continuous /-- Under a dense continuous linear map, a submodule whose `topological_closure` is `⊤` is sent to another such submodule. That is, the image of a dense set under a map with dense range is dense. -/ lemma _root_.dense_range.topological_closure_map_submodule [ring_hom_surjective σ₁₂] [topological_space R₁] [topological_space R₂] [has_continuous_smul R₁ M₁] [has_continuous_add M₁] [has_continuous_smul R₂ M₂] [has_continuous_add M₂] {f : M₁ →SL[σ₁₂] M₂} (hf' : dense_range f) {s : submodule R₁ M₁} (hs : s.topological_closure = ⊤) : (s.map (f : M₁ →ₛₗ[σ₁₂] M₂)).topological_closure = ⊤ := begin rw set_like.ext'_iff at hs ⊢, simp only [submodule.topological_closure_coe, submodule.top_coe, ← dense_iff_closure_eq] at hs ⊢, exact hf'.dense_image f.continuous hs end /-- The continuous map that is constantly zero. -/ instance: has_zero (M₁ →SL[σ₁₂] M₂) := ⟨⟨0, continuous_zero⟩⟩ instance : inhabited (M₁ →SL[σ₁₂] M₂) := ⟨0⟩ @[simp] lemma default_def : default (M₁ →SL[σ₁₂] M₂) = 0 := rfl @[simp] lemma zero_apply : (0 : M₁ →SL[σ₁₂] M₂) x = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : M₁ →SL[σ₁₂] M₂) : M₁ →ₛₗ[σ₁₂] M₂) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[norm_cast] lemma coe_zero' : ((0 : M₁ →SL[σ₁₂] M₂) : M₁ → M₂) = 0 := rfl instance unique_of_left [subsingleton M₁] : unique (M₁ →SL[σ₁₂] M₂) := coe_injective.unique instance unique_of_right [subsingleton M₂] : unique (M₁ →SL[σ₁₂] M₂) := coe_injective.unique section variables (R₁ M₁) /-- the identity map as a continuous linear map. -/ def id : M₁ →L[R₁] M₁ := ⟨linear_map.id, continuous_id⟩ end instance : has_one (M₁ →L[R₁] M₁) := ⟨id R₁ M₁⟩ lemma one_def : (1 : M₁ →L[R₁] M₁) = id R₁ M₁ := rfl lemma id_apply : id R₁ M₁ x = x := rfl @[simp, norm_cast] lemma coe_id : (id R₁ M₁ : M₁ →ₗ[R₁] M₁) = linear_map.id := rfl @[simp, norm_cast] lemma coe_id' : (id R₁ M₁ : M₁ → M₁) = _root_.id := rfl @[simp, norm_cast] lemma coe_eq_id {f : M₁ →L[R₁] M₁} : (f : M₁ →ₗ[R₁] M₁) = linear_map.id ↔ f = id _ _ := by rw [← coe_id, coe_inj] @[simp] lemma one_apply : (1 : M₁ →L[R₁] M₁) x = x := rfl section add variables [has_continuous_add M₂] instance : has_add (M₁ →SL[σ₁₂] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ lemma continuous_nsmul (n : ℕ) : continuous (λ (x : M₂), n • x) := begin induction n with n ih, { simp [continuous_const] }, { simp [nat.succ_eq_add_one, add_smul], exact ih.add continuous_id } end @[continuity] lemma continuous.nsmul {α : Type*} [topological_space α] {n : ℕ} {f : α → M₂} (hf : continuous f) : continuous (λ (x : α), n • (f x)) := (continuous_nsmul n).comp hf @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, norm_cast] lemma coe_add : (((f + g) : M₁ →SL[σ₁₂] M₂) : M₁ →ₛₗ[σ₁₂] M₂) = f + g := rfl @[norm_cast] lemma coe_add' : (((f + g) : M₁ →SL[σ₁₂] M₂) : M₁ → M₂) = (f : M₁ → M₂) + g := rfl instance : add_comm_monoid (M₁ →SL[σ₁₂] M₂) := { zero := (0 : M₁ →SL[σ₁₂] M₂), add := (+), zero_add := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_zero := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_comm := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], add_assoc := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm], nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := by simp, map_smul' := by simp [smul_comm n] }, nsmul_zero' := λ f, by { ext, simp }, nsmul_succ' := λ n f, by { ext, simp [nat.succ_eq_one_add, add_smul] } } @[simp, norm_cast] lemma coe_sum {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) : ↑(∑ d in t, f d) = (∑ d in t, f d : M₁ →ₛₗ[σ₁₂] M₂) := (add_monoid_hom.mk (coe : (M₁ →SL[σ₁₂] M₂) → (M₁ →ₛₗ[σ₁₂] M₂)) rfl (λ _ _, rfl)).map_sum _ _ @[simp, norm_cast] lemma coe_sum' {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) : ⇑(∑ d in t, f d) = ∑ d in t, f d := by simp only [← coe_coe, coe_sum, linear_map.coe_fn_sum] lemma sum_apply {ι : Type*} (t : finset ι) (f : ι → M₁ →SL[σ₁₂] M₂) (b : M₁) : (∑ d in t, f d) b = ∑ d in t, f d b := by simp only [coe_sum', finset.sum_apply] end add variables {σ₁₃ : R₁ →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] /-- Composition of bounded linear maps. -/ def comp (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : M₁ →SL[σ₁₃] M₃ := ⟨(g : M₂ →ₛₗ[σ₂₃] M₃).comp ↑f, g.2.comp f.2⟩ infixr ` ∘L `:80 := @continuous_linear_map.comp _ _ _ _ _ _ (ring_hom.id _) (ring_hom.id _) _ _ _ _ _ _ _ _ _ _ _ _ (ring_hom.id _) ring_hom_comp_triple.ids @[simp, norm_cast] lemma coe_comp : ((h.comp f) : (M₁ →ₛₗ[σ₁₃] M₃)) = (h : M₂ →ₛₗ[σ₂₃] M₃).comp (f : M₁ →ₛₗ[σ₁₂] M₂) := rfl include σ₁₃ @[simp, norm_cast] lemma coe_comp' : ((h.comp f) : (M₁ → M₃)) = (h : M₂ → M₃) ∘ f := rfl lemma comp_apply (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) (x : M₁) : (g.comp f) x = g (f x) := rfl omit σ₁₃ @[simp] theorem comp_id : f.comp (id R₁ M₁) = f := ext $ λ x, rfl @[simp] theorem id_comp : (id R₂ M₂).comp f = f := ext $ λ x, rfl include σ₁₃ @[simp] theorem comp_zero (g : M₂ →SL[σ₂₃] M₃) : g.comp (0 : M₁ →SL[σ₁₂] M₂) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : M₂ →SL[σ₂₃] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [has_continuous_add M₂] [has_continuous_add M₃] (g : M₂ →SL[σ₂₃] M₃) (f₁ f₂ : M₁ →SL[σ₁₂] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [has_continuous_add M₃] (g₁ g₂ : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } omit σ₁₃ theorem comp_assoc {R₄ : Type*} [semiring R₄] [module R₄ M₄] {σ₁₄ : R₁ →+* R₄} {σ₂₄ : R₂ →+* R₄} {σ₃₄ : R₃ →+* R₄} [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] [ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄] (h : M₃ →SL[σ₃₄] M₄) (g : M₂ →SL[σ₂₃] M₃) (f : M₁ →SL[σ₁₂] M₂) : (h.comp g).comp f = h.comp (g.comp f) := rfl instance : has_mul (M₁ →L[R₁] M₁) := ⟨comp⟩ lemma mul_def (f g : M₁ →L[R₁] M₁) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : M₁ →L[R₁] M₁) : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (f g : M₁ →L[R₁] M₁) (x : M₁) : (f * g) x = f (g x) := rfl /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ protected def prod [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) : M₁ →L[R₁] (M₂ × M₃) := ⟨(f₁ : M₁ →ₗ[R₁] M₂).prod f₂, f₁.2.prod_mk f₂.2⟩ @[simp, norm_cast] lemma coe_prod [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) : (f₁.prod f₂ : M₁ →ₗ[R₁] M₂ × M₃) = linear_map.prod f₁ f₂ := rfl @[simp, norm_cast] lemma prod_apply [module R₁ M₂] [module R₁ M₃] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₁ →L[R₁] M₃) (x : M₁) : f₁.prod f₂ x = (f₁ x, f₂ x) := rfl section variables (R₁ M₁ M₂) /-- The left injection into a product is a continuous linear map. -/ def inl [module R₁ M₂] : M₁ →L[R₁] M₁ × M₂ := (id R₁ M₁).prod 0 /-- The right injection into a product is a continuous linear map. -/ def inr [module R₁ M₂] : M₂ →L[R₁] M₁ × M₂ := (0 : M₂ →L[R₁] M₁).prod (id R₁ M₂) end @[simp] lemma inl_apply [module R₁ M₂] (x : M₁) : inl R₁ M₁ M₂ x = (x, 0) := rfl @[simp] lemma inr_apply [module R₁ M₂] (x : M₂) : inr R₁ M₁ M₂ x = (0, x) := rfl @[simp, norm_cast] lemma coe_inl [module R₁ M₂] : (inl R₁ M₁ M₂ : M₁ →ₗ[R₁] M₁ × M₂) = linear_map.inl R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_inr [module R₁ M₂] : (inr R₁ M₁ M₂ : M₂ →ₗ[R₁] M₁ × M₂) = linear_map.inr R₁ M₁ M₂ := rfl /-- Kernel of a continuous linear map. -/ def ker (f : M₁ →SL[σ₁₂] M₂) : submodule R₁ M₁ := (f : M₁ →ₛₗ[σ₁₂] M₂).ker @[norm_cast] lemma ker_coe : (f : M₁ →ₛₗ[σ₁₂] M₂).ker = f.ker := rfl @[simp] lemma mem_ker {f : M₁ →SL[σ₁₂] M₂} {x} : x ∈ f.ker ↔ f x = 0 := linear_map.mem_ker lemma is_closed_ker [t1_space M₂] : is_closed (f.ker : set M₁) := continuous_iff_is_closed.1 f.cont _ is_closed_singleton @[simp] lemma apply_ker (x : f.ker) : f x = 0 := mem_ker.1 x.2 lemma is_complete_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [module R₁ M'] [t1_space M₂] (f : M' →SL[σ₁₂] M₂) : is_complete (f.ker : set M') := f.is_closed_ker.is_complete instance complete_space_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [module R₁ M'] [t1_space M₂] (f : M' →SL[σ₁₂] M₂) : complete_space f.ker := f.is_closed_ker.complete_space_coe @[simp] lemma ker_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : ker (f.prod g) = ker f ⊓ ker g := linear_map.ker_prod f g /-- Range of a continuous linear map. -/ def range [ring_hom_surjective σ₁₂] (f : M₁ →SL[σ₁₂] M₂) : submodule R₂ M₂ := (f : M₁ →ₛₗ[σ₁₂] M₂).range lemma range_coe [ring_hom_surjective σ₁₂] : (f.range : set M₂) = set.range f := linear_map.range_coe _ lemma mem_range [ring_hom_surjective σ₁₂] {f : M₁ →SL[σ₁₂] M₂} {y} : y ∈ f.range ↔ ∃ x, f x = y := linear_map.mem_range lemma mem_range_self [ring_hom_surjective σ₁₂] (f : M₁ →SL[σ₁₂] M₂) (x : M₁) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ lemma range_prod_le [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : range (f.prod g) ≤ (range f).prod (range g) := (f : M₁ →ₗ[R₁] M₂).range_prod_le g /-- Restrict codomain of a continuous linear map. -/ def cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : M₁ →SL[σ₁₂] p := { cont := continuous_subtype_mk h f.continuous, to_linear_map := (f : M₁ →ₛₗ[σ₁₂] M₂).cod_restrict p h} @[norm_cast] lemma coe_cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : (f.cod_restrict p h : M₁ →ₛₗ[σ₁₂] p) = (f : M₁ →ₛₗ[σ₁₂] M₂).cod_restrict p h := rfl @[simp] lemma coe_cod_restrict_apply (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) (x) : (f.cod_restrict p h x : M₂) = f x := rfl @[simp] lemma ker_cod_restrict (f : M₁ →SL[σ₁₂] M₂) (p : submodule R₂ M₂) (h : ∀ x, f x ∈ p) : ker (f.cod_restrict p h) = ker f := (f : M₁ →ₛₗ[σ₁₂] M₂).ker_cod_restrict p h /-- Embedding of a submodule into the ambient space as a continuous linear map. -/ def subtype_val (p : submodule R₁ M₁) : p →L[R₁] M₁ := { cont := continuous_subtype_val, to_linear_map := p.subtype } @[simp, norm_cast] lemma coe_subtype_val (p : submodule R₁ M₁) : (subtype_val p : p →ₗ[R₁] M₁) = p.subtype := rfl @[simp, norm_cast] lemma subtype_val_apply (p : submodule R₁ M₁) (x : p) : (subtype_val p : p → M₁) x = x := rfl variables (R₁ M₁ M₂) /-- `prod.fst` as a `continuous_linear_map`. -/ def fst [module R₁ M₂] : M₁ × M₂ →L[R₁] M₁ := { cont := continuous_fst, to_linear_map := linear_map.fst R₁ M₁ M₂ } /-- `prod.snd` as a `continuous_linear_map`. -/ def snd [module R₁ M₂] : M₁ × M₂ →L[R₁] M₂ := { cont := continuous_snd, to_linear_map := linear_map.snd R₁ M₁ M₂ } variables {R₁ M₁ M₂} @[simp, norm_cast] lemma coe_fst [module R₁ M₂] : (fst R₁ M₁ M₂ : M₁ × M₂ →ₗ[R₁] M₁) = linear_map.fst R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_fst' [module R₁ M₂] : (fst R₁ M₁ M₂ : M₁ × M₂ → M₁) = prod.fst := rfl @[simp, norm_cast] lemma coe_snd [module R₁ M₂] : (snd R₁ M₁ M₂ : M₁ × M₂ →ₗ[R₁] M₂) = linear_map.snd R₁ M₁ M₂ := rfl @[simp, norm_cast] lemma coe_snd' [module R₁ M₂] : (snd R₁ M₁ M₂ : M₁ × M₂ → M₂) = prod.snd := rfl @[simp] lemma fst_prod_snd [module R₁ M₂] : (fst R₁ M₁ M₂).prod (snd R₁ M₁ M₂) = id R₁ (M₁ × M₂) := ext $ λ ⟨x, y⟩, rfl @[simp] lemma fst_comp_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : (fst R₁ M₂ M₃).comp (f.prod g) = f := ext $ λ x, rfl @[simp] lemma snd_comp_prod [module R₁ M₂] [module R₁ M₃] (f : M₁ →L[R₁] M₂) (g : M₁ →L[R₁] M₃) : (snd R₁ M₂ M₃).comp (f.prod g) = g := ext $ λ x, rfl /-- `prod.map` of two continuous linear maps. -/ def prod_map [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : (M₁ × M₃) →L[R₁] (M₂ × M₄) := (f₁.comp (fst R₁ M₁ M₃)).prod (f₂.comp (snd R₁ M₁ M₃)) @[simp, norm_cast] lemma coe_prod_map [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : (f₁.prod_map f₂ : (M₁ × M₃) →ₗ[R₁] (M₂ × M₄)) = ((f₁ : M₁ →ₗ[R₁] M₂).prod_map (f₂ : M₃ →ₗ[R₁] M₄)) := rfl @[simp, norm_cast] lemma coe_prod_map' [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (f₁ : M₁ →L[R₁] M₂) (f₂ : M₃ →L[R₁] M₄) : ⇑(f₁.prod_map f₂) = prod.map f₁ f₂ := rfl /-- The continuous linear map given by `(x, y) ↦ f₁ x + f₂ y`. -/ def coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : (M₁ × M₂) →L[R₁] M₃ := ⟨linear_map.coprod f₁ f₂, (f₁.cont.comp continuous_fst).add (f₂.cont.comp continuous_snd)⟩ @[norm_cast, simp] lemma coe_coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : (f₁.coprod f₂ : (M₁ × M₂) →ₗ[R₁] M₃) = linear_map.coprod f₁ f₂ := rfl @[simp] lemma coprod_apply [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) (x) : f₁.coprod f₂ x = f₁ x.1 + f₂ x.2 := rfl lemma range_coprod [module R₁ M₂] [module R₁ M₃] [has_continuous_add M₃] (f₁ : M₁ →L[R₁] M₃) (f₂ : M₂ →L[R₁] M₃) : (f₁.coprod f₂).range = f₁.range ⊔ f₂.range := linear_map.range_coprod _ _ section variables {R S : Type*} [semiring R] [semiring S] [module R M₁] [module R M₂] [module R S] [module S M₂] [is_scalar_tower R S M₂] [topological_space S] [has_continuous_smul S M₂] /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`). See also `continuous_linear_map.smul_rightₗ` and `continuous_linear_map.smul_rightL`. -/ def smul_right (c : M₁ →L[R] S) (f : M₂) : M₁ →L[R] M₂ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : M₁ →L[R] S} {f : M₂} {x : M₁} : (smul_right c f : M₁ → M₂) x = c x • f := rfl end variables [module R₁ M₂] [topological_space R₁] [has_continuous_smul R₁ M₂] @[simp] lemma smul_right_one_one (c : R₁ →L[R₁] M₂) : smul_right (1 : R₁ →L[R₁] R₁) (c 1) = c := by ext; simp [← continuous_linear_map.map_smul_of_tower] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R₁ →L[R₁] R₁) f = smul_right (1 : R₁ →L[R₁] R₁) f' ↔ f = f' := by simp only [ext_ring_iff, smul_right_apply, one_apply, one_smul] lemma smul_right_comp [has_continuous_mul R₁] {x : M₂} {c : R₁} : (smul_right (1 : R₁ →L[R₁] R₁) x).comp (smul_right (1 : R₁ →L[R₁] R₁) c) = smul_right (1 : R₁ →L[R₁] R₁) (c • x) := by { ext, simp [mul_smul] } end semiring section pi variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [module R M₂] {ι : Type*} {φ : ι → Type*} [∀i, topological_space (φ i)] [∀i, add_comm_monoid (φ i)] [∀i, module R (φ i)] /-- `pi` construction for continuous linear functions. From a family of continuous linear functions it produces a continuous linear function into a family of topological modules. -/ def pi (f : Πi, M →L[R] φ i) : M →L[R] (Πi, φ i) := ⟨linear_map.pi (λ i, f i), continuous_pi (λ i, (f i).continuous)⟩ @[simp] lemma coe_pi' (f : Π i, M →L[R] φ i) : ⇑(pi f) = λ c i, f i c := rfl @[simp] lemma coe_pi (f : Π i, M →L[R] φ i) : (pi f : M →ₗ[R] Π i, φ i) = linear_map.pi (λ i, f i) := rfl lemma pi_apply (f : Πi, M →L[R] φ i) (c : M) (i : ι) : pi f c i = f i c := rfl lemma pi_eq_zero (f : Πi, M →L[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by { simp only [ext_iff, pi_apply, function.funext_iff], exact forall_swap } lemma pi_zero : pi (λi, 0 : Πi, M →L[R] φ i) = 0 := ext $ λ _, rfl lemma pi_comp (f : Πi, M →L[R] φ i) (g : M₂ →L[R] M) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of topological modules are continuous linear maps. -/ def proj (i : ι) : (Πi, φ i) →L[R] φ i := ⟨linear_map.proj i, continuous_apply _⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →L[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →L[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := linear_map.infi_ker_proj variables (R φ) /-- If `I` and `J` are complementary index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃L[R] (Πi:I, φ i) := ⟨ linear_map.infi_ker_proj_equiv R φ hd hu, continuous_pi (λ i, begin have := @continuous_subtype_coe _ _ (λ x, x ∈ (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i))), have := continuous.comp (by exact continuous_apply i) this, exact this end), continuous_subtype_mk _ (continuous_pi (λ i, begin dsimp, split_ifs; [apply continuous_apply, exact continuous_zero] end)) ⟩ end pi section ring variables {R : Type*} [ring R] {R₂ : Type*} [ring R₂] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [module R M] [module R₂ M₂] {σ₁₂ : R →+* R₂} section variables (f g : M →SL[σ₁₂] M₂) (x y : M) @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma sub_apply' (x : M) : ((f : M →ₛₗ[σ₁₂] M₂) - g) x = f x - g x := rfl end section variables [module R M₂] [module R M₃] [module R M₄] variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) lemma range_prod_eq {f : M →L[R] M₂} {g : M →L[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (f.prod g) = (range f).prod (range g) := linear_map.range_prod_eq h lemma ker_prod_ker_le_ker_coprod [has_continuous_add M₃] (f : M →L[R] M₃) (g : M₂ →L[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := linear_map.ker_prod_ker_le_ker_coprod f.to_linear_map g.to_linear_map lemma ker_coprod_of_disjoint_range [has_continuous_add M₃] (f : M →L[R] M₃) (g : M₂ →L[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := linear_map.ker_coprod_of_disjoint_range f.to_linear_map g.to_linear_map hd end section variables [topological_add_group M₂] variables (f g : M →SL[σ₁₂] M₂) (x y : M) instance : has_neg (M →SL[σ₁₂] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, norm_cast] lemma coe_neg : (((-f) : M →SL[σ₁₂] M₂) : M →ₛₗ[σ₁₂] M₂) = -(f : M →ₛₗ[σ₁₂] M₂) := rfl @[norm_cast] lemma coe_neg' : (((-f) : M →SL[σ₁₂] M₂) : M → M₂) = -(f : M → M₂) := rfl instance : has_sub (M →SL[σ₁₂] M₂) := ⟨λ f g, ⟨f - g, f.2.sub g.2⟩⟩ lemma continuous_zsmul : ∀ (n : ℤ), continuous (λ (x : M₂), n • x) | (n : ℕ) := by { simp only [coe_nat_zsmul], exact continuous_nsmul _ } | -[1+ n] := by { simp only [zsmul_neg_succ_of_nat], exact (continuous_nsmul _).neg } @[continuity] lemma continuous.zsmul {α : Type*} [topological_space α] {n : ℤ} {f : α → M₂} (hf : continuous f) : continuous (λ (x : α), n • (f x)) := (continuous_zsmul n).comp hf instance : add_comm_group (M →SL[σ₁₂] M₂) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := by simp, map_smul' := by simp [smul_comm n] }, zsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := by simp, map_smul' := by simp [smul_comm n] }, zsmul_zero' := λ f, by { ext, simp }, zsmul_succ' := λ n f, by { ext, simp [add_smul, add_comm] }, zsmul_neg' := λ n f, by { ext, simp [nat.succ_eq_add_one, add_smul] }, .. continuous_linear_map.add_comm_monoid, .. }; intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm, sub_eq_add_neg] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl @[simp, norm_cast] lemma coe_sub : (((f - g) : M →SL[σ₁₂] M₂) : M →ₛₗ[σ₁₂] M₂) = f - g := rfl @[simp, norm_cast] lemma coe_sub' : (((f - g) : M →SL[σ₁₂] M₂) : M → M₂) = (f : M → M₂) - g := rfl end instance [topological_add_group M] : ring (M →L[R] M) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } lemma smul_right_one_pow [topological_space R] [topological_ring R] (c : R) (n : ℕ) : (smul_right (1 : R →L[R] R) c)^n = smul_right (1 : R →L[R] R) (c^n) := begin induction n with n ihn, { ext, simp }, { rw [pow_succ, ihn, mul_def, smul_right_comp, smul_eq_mul, pow_succ'] } end section variables {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁] /-- Given a right inverse `f₂ : M₂ →L[R] M` to `f₁ : M →L[R] M₂`, `proj_ker_of_right_inverse f₁ f₂ h` is the projection `M →L[R] f₁.ker` along `f₂.range`. -/ def proj_ker_of_right_inverse [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) : M →L[R] f₁.ker := (id R M - f₂.comp f₁).cod_restrict f₁.ker $ λ x, by simp [h (f₁ x)] @[simp] lemma coe_proj_ker_of_right_inverse_apply [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (x : M) : (f₁.proj_ker_of_right_inverse f₂ h x : M) = x - f₂ (f₁ x) := rfl @[simp] lemma proj_ker_of_right_inverse_apply_idem [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (x : f₁.ker) : f₁.proj_ker_of_right_inverse f₂ h x = x := subtype.ext_iff_val.2 $ by simp @[simp] lemma proj_ker_of_right_inverse_comp_inv [topological_add_group M] (f₁ : M →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M) (h : function.right_inverse f₂ f₁) (y : M₂) : f₁.proj_ker_of_right_inverse f₂ h (f₂ y) = 0 := subtype.ext_iff_val.2 $ by simp [h y] end end ring section smul variables {R S : Type*} [semiring R] [semiring S] [topological_space S] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [module R M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] [module R M₃] [module S M₃] [smul_comm_class R S M₃] [has_continuous_smul S M₃] instance : has_scalar S (M →L[R] M₃) := ⟨λ c f, ⟨c • f, (continuous_const.smul f.2 : continuous (λ x, c • f x))⟩⟩ variables (c : S) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M) @[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl variables [module S M₂] [has_continuous_smul S M₂] [smul_comm_class R S M₂] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, norm_cast] lemma coe_smul : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • f := rfl @[simp, norm_cast] lemma coe_smul' : (((c • f) : M →L[R] M₂) : M → M₂) = c • f := rfl @[simp] lemma comp_smul [linear_map.compatible_smul M₂ M₃ S R] : h.comp (c • f) = c • (h.comp f) := by { ext x, exact h.map_smul_of_tower c (f x) } /-- `continuous_linear_map.prod` as an `equiv`. -/ @[simps apply] def prod_equiv : ((M →L[R] M₂) × (M →L[R] M₃)) ≃ (M →L[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ⟨(fst _ _ _).comp f, (snd _ _ _).comp f⟩, left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl } lemma prod_ext_iff {f g : M × M₂ →L[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := by { simp only [← coe_inj, linear_map.prod_ext_iff], refl } @[ext] lemma prod_ext {f g : M × M₂ →L[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ variables [has_continuous_add M₂] instance : module S (M →L[R] M₂) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, by exact one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } variables (S) [has_continuous_add M₃] /-- `continuous_linear_map.prod` as a `linear_equiv`. -/ @[simps apply] def prodₗ : ((M →L[R] M₂) × (M →L[R] M₃)) ≃ₗ[S] (M →L[R] M₂ × M₃) := { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, .. prod_equiv } end smul section smul_rightₗ variables {R S T M M₂ : Type*} [ring R] [ring S] [ring T] [module R S] [add_comm_group M₂] [module R M₂] [module S M₂] [is_scalar_tower R S M₂] [topological_space S] [topological_space M₂] [has_continuous_smul S M₂] [topological_space M] [add_comm_group M] [module R M] [topological_add_group M₂] [topological_space T] [module T M₂] [has_continuous_smul T M₂] [smul_comm_class R T M₂] [smul_comm_class S T M₂] /-- Given `c : E →L[𝕜] 𝕜`, `c.smul_rightₗ` is the linear map from `F` to `E →L[𝕜] F` sending `f` to `λ e, c e • f`. See also `continuous_linear_map.smul_rightL`. -/ def smul_rightₗ (c : M →L[R] S) : M₂ →ₗ[T] (M →L[R] M₂) := { to_fun := c.smul_right, map_add' := λ x y, by { ext e, apply smul_add }, map_smul' := λ a x, by { ext e, dsimp, apply smul_comm } } @[simp] lemma coe_smul_rightₗ (c : M →L[R] S) : ⇑(smul_rightₗ c : M₂ →ₗ[T] (M →L[R] M₂)) = c.smul_right := rfl end smul_rightₗ section comm_ring variables {R : Type*} [comm_ring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] [has_continuous_smul R M₃] variables [topological_add_group M₂] [has_continuous_smul R M₂] instance : algebra R (M₂ →L[R] M₂) := algebra.of_module smul_comp (λ _ _ _, comp_smul _ _ _) end comm_ring section restrict_scalars variables {A M M₂ : Type*} [ring A] [add_comm_group M] [add_comm_group M₂] [module A M] [module A M₂] [topological_space M] [topological_space M₂] (R : Type*) [ring R] [module R M] [module R M₂] [linear_map.compatible_smul M M₂ R A] /-- If `A` is an `R`-algebra, then a continuous `A`-linear map can be interpreted as a continuous `R`-linear map. We assume `linear_map.compatible_smul M M₂ R A` to match assumptions of `linear_map.map_smul_of_tower`. -/ def restrict_scalars (f : M →L[A] M₂) : M →L[R] M₂ := ⟨(f : M →ₗ[A] M₂).restrict_scalars R, f.continuous⟩ variable {R} @[simp, norm_cast] lemma coe_restrict_scalars (f : M →L[A] M₂) : (f.restrict_scalars R : M →ₗ[R] M₂) = (f : M →ₗ[A] M₂).restrict_scalars R := rfl @[simp] lemma coe_restrict_scalars' (f : M →L[A] M₂) : ⇑(f.restrict_scalars R) = f := rfl @[simp] lemma restrict_scalars_zero : (0 : M →L[A] M₂).restrict_scalars R = 0 := rfl section variable [topological_add_group M₂] @[simp] lemma restrict_scalars_add (f g : M →L[A] M₂) : (f + g).restrict_scalars R = f.restrict_scalars R + g.restrict_scalars R := rfl @[simp] lemma restrict_scalars_neg (f : M →L[A] M₂) : (-f).restrict_scalars R = -f.restrict_scalars R := rfl end variables {S : Type*} [ring S] [topological_space S] [module S M₂] [has_continuous_smul S M₂] [smul_comm_class A S M₂] [smul_comm_class R S M₂] @[simp] lemma restrict_scalars_smul (c : S) (f : M →L[A] M₂) : (c • f).restrict_scalars R = c • f.restrict_scalars R := rfl variables (A M M₂ R S) [topological_add_group M₂] /-- `continuous_linear_map.restrict_scalars` as a `linear_map`. See also `continuous_linear_map.restrict_scalarsL`. -/ def restrict_scalarsₗ : (M →L[A] M₂) →ₗ[S] (M →L[R] M₂) := { to_fun := restrict_scalars R, map_add' := restrict_scalars_add, map_smul' := restrict_scalars_smul } variables {A M M₂ R S} @[simp] lemma coe_restrict_scalarsₗ : ⇑(restrict_scalarsₗ A M M₂ R S) = restrict_scalars R := rfl end restrict_scalars end continuous_linear_map namespace continuous_linear_equiv section add_comm_monoid variables {R₁ : Type*} [semiring R₁] {R₂ : Type*} [semiring R₂] {R₃ : Type*} [semiring R₃] {M₁ : Type*} [topological_space M₁] [add_comm_monoid M₁] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [module R₁ M₁] [module R₂ M₂] [module R₃ M₃] {σ₁₂ : R₁ →+* R₂} {σ₂₁ : R₂ →+* R₁} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {σ₂₃ : R₂ →+* R₃} {σ₃₂ : R₃ →+* R₂} [ring_hom_inv_pair σ₂₃ σ₃₂] [ring_hom_inv_pair σ₃₂ σ₂₃] {σ₁₃ : R₁ →+* R₃} {σ₃₁ : R₃ →+* R₁} [ring_hom_inv_pair σ₁₃ σ₃₁] [ring_hom_inv_pair σ₃₁ σ₁₃] [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₃₂ σ₂₁ σ₃₁] include σ₂₁ /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M₁ ≃SL[σ₁₂] M₂) : M₁ →SL[σ₁₂] M₂ := { cont := e.continuous_to_fun, ..e.to_linear_equiv.to_linear_map } /-- Coerce continuous linear equivs to continuous linear maps. -/ instance : has_coe (M₁ ≃SL[σ₁₂] M₂) (M₁ →SL[σ₁₂] M₂) := ⟨to_continuous_linear_map⟩ /-- Coerce continuous linear equivs to maps. -/ -- see Note [function coercion] instance : has_coe_to_fun (M₁ ≃SL[σ₁₂] M₂) (λ _, M₁ → M₂) := ⟨λ f, f⟩ @[simp] theorem coe_def_rev (e : M₁ ≃SL[σ₁₂] M₂) : e.to_continuous_linear_map = e := rfl theorem coe_apply (e : M₁ ≃SL[σ₁₂] M₂) (b : M₁) : (e : M₁ →SL[σ₁₂] M₂) b = e b := rfl @[simp] lemma coe_to_linear_equiv (f : M₁ ≃SL[σ₁₂] M₂) : ⇑f.to_linear_equiv = f := rfl @[simp, norm_cast] lemma coe_coe (e : M₁ ≃SL[σ₁₂] M₂) : ((e : M₁ →SL[σ₁₂] M₂) : M₁ → M₂) = e := rfl lemma to_linear_equiv_injective : function.injective (to_linear_equiv : (M₁ ≃SL[σ₁₂] M₂) → (M₁ ≃ₛₗ[σ₁₂] M₂)) | ⟨e, _, _⟩ ⟨e', _, _⟩ rfl := rfl @[ext] lemma ext {f g : M₁ ≃SL[σ₁₂] M₂} (h : (f : M₁ → M₂) = g) : f = g := to_linear_equiv_injective $ linear_equiv.ext $ congr_fun h lemma coe_injective : function.injective (coe : (M₁ ≃SL[σ₁₂] M₂) → (M₁ →SL[σ₁₂] M₂)) := λ e e' h, ext $ funext $ continuous_linear_map.ext_iff.1 h @[simp, norm_cast] lemma coe_inj {e e' : M₁ ≃SL[σ₁₂] M₂} : (e : M₁ →SL[σ₁₂] M₂) = e' ↔ e = e' := coe_injective.eq_iff /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : M₁ ≃ₜ M₂ := { to_equiv := e.to_linear_equiv.to_equiv, ..e } @[simp] lemma coe_to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : ⇑e.to_homeomorph = e := rfl lemma image_closure (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e '' closure s = closure (e '' s) := e.to_homeomorph.image_closure s lemma preimage_closure (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e ⁻¹' closure s = closure (e ⁻¹' s) := e.to_homeomorph.preimage_closure s @[simp] lemma is_closed_image (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} : is_closed (e '' s) ↔ is_closed s := e.to_homeomorph.is_closed_image lemma map_nhds_eq (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : map e (𝓝 x) = 𝓝 (e x) := e.to_homeomorph.map_nhds_eq x -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M₁ ≃SL[σ₁₂] M₂) : e (0 : M₁) = 0 := (e : M₁ →SL[σ₁₂] M₂).map_zero @[simp] lemma map_add (e : M₁ ≃SL[σ₁₂] M₂) (x y : M₁) : e (x + y) = e x + e y := (e : M₁ →SL[σ₁₂] M₂).map_add x y @[simp] lemma map_smulₛₗ (e : M₁ ≃SL[σ₁₂] M₂) (c : R₁) (x : M₁) : e (c • x) = σ₁₂ c • (e x) := (e : M₁ →SL[σ₁₂] M₂).map_smulₛₗ c x omit σ₂₁ @[simp] lemma map_smul [module R₁ M₂] (e : M₁ ≃L[R₁] M₂) (c : R₁) (x : M₁) : e (c • x) = c • (e x) := (e : M₁ →L[R₁] M₂).map_smul c x include σ₂₁ @[simp] lemma map_eq_zero_iff (e : M₁ ≃SL[σ₁₂] M₂) {x : M₁} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff attribute [continuity] continuous_linear_equiv.continuous_to_fun continuous_linear_equiv.continuous_inv_fun @[continuity] protected lemma continuous (e : M₁ ≃SL[σ₁₂] M₂) : continuous (e : M₁ → M₂) := e.continuous_to_fun protected lemma continuous_on (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} : continuous_on (e : M₁ → M₂) s := e.continuous.continuous_on protected lemma continuous_at (e : M₁ ≃SL[σ₁₂] M₂) {x : M₁} : continuous_at (e : M₁ → M₂) x := e.continuous.continuous_at protected lemma continuous_within_at (e : M₁ ≃SL[σ₁₂] M₂) {s : set M₁} {x : M₁} : continuous_within_at (e : M₁ → M₂) s x := e.continuous.continuous_within_at lemma comp_continuous_on_iff {α : Type*} [topological_space α] (e : M₁ ≃SL[σ₁₂] M₂) {f : α → M₁} {s : set α} : continuous_on (e ∘ f) s ↔ continuous_on f s := e.to_homeomorph.comp_continuous_on_iff _ _ lemma comp_continuous_iff {α : Type*} [topological_space α] (e : M₁ ≃SL[σ₁₂] M₂) {f : α → M₁} : continuous (e ∘ f) ↔ continuous f := e.to_homeomorph.comp_continuous_iff omit σ₂₁ /-- An extensionality lemma for `R ≃L[R] M`. -/ lemma ext₁ [topological_space R₁] {f g : R₁ ≃L[R₁] M₁} (h : f 1 = g 1) : f = g := ext $ funext $ λ x, mul_one x ▸ by rw [← smul_eq_mul, map_smul, h, map_smul] section variables (R₁ M₁) /-- The identity map as a continuous linear equivalence. -/ @[refl] protected def refl : M₁ ≃L[R₁] M₁ := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. linear_equiv.refl R₁ M₁ } end @[simp, norm_cast] lemma coe_refl : (continuous_linear_equiv.refl R₁ M₁ : M₁ →L[R₁] M₁) = continuous_linear_map.id R₁ M₁ := rfl @[simp, norm_cast] lemma coe_refl' : (continuous_linear_equiv.refl R₁ M₁ : M₁ → M₁) = id := rfl /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M₁ ≃SL[σ₁₂] M₂) : M₂ ≃SL[σ₂₁] M₁ := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } include σ₂₁ @[simp] lemma symm_to_linear_equiv (e : M₁ ≃SL[σ₁₂] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } @[simp] lemma symm_to_homeomorph (e : M₁ ≃SL[σ₁₂] M₂) : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl lemma symm_map_nhds_eq (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : map e.symm (𝓝 (e x)) = 𝓝 x := e.to_homeomorph.symm_map_nhds_eq x omit σ₂₁ include σ₂₁ σ₃₂ σ₃₁ /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) : M₁ ≃SL[σ₁₃] M₃ := { continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun, continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun, .. e₁.to_linear_equiv.trans e₂.to_linear_equiv } include σ₁₃ @[simp] lemma trans_to_linear_equiv (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } omit σ₁₃ σ₂₁ σ₃₂ σ₃₁ /-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/ def prod [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) : (M₁ × M₃) ≃L[R₁] (M₂ × M₄) := { continuous_to_fun := e.continuous_to_fun.prod_map e'.continuous_to_fun, continuous_inv_fun := e.continuous_inv_fun.prod_map e'.continuous_inv_fun, .. e.to_linear_equiv.prod e'.to_linear_equiv } @[simp, norm_cast] lemma prod_apply [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) (x) : e.prod e' x = (e x.1, e' x.2) := rfl @[simp, norm_cast] lemma coe_prod [module R₁ M₂] [module R₁ M₃] [module R₁ M₄] (e : M₁ ≃L[R₁] M₂) (e' : M₃ ≃L[R₁] M₄) : (e.prod e' : (M₁ × M₃) →L[R₁] (M₂ × M₄)) = (e : M₁ →L[R₁] M₂).prod_map (e' : M₃ →L[R₁] M₄) := rfl include σ₂₁ theorem bijective (e : M₁ ≃SL[σ₁₂] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective theorem injective (e : M₁ ≃SL[σ₁₂] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective theorem surjective (e : M₁ ≃SL[σ₁₂] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective include σ₃₂ σ₃₁ σ₁₃ @[simp] theorem trans_apply (e₁ : M₁ ≃SL[σ₁₂] M₂) (e₂ : M₂ ≃SL[σ₂₃] M₃) (c : M₁) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl omit σ₃₂ σ₃₁ σ₁₃ @[simp] theorem apply_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) (c : M₂) : e (e.symm c) = c := e.1.right_inv c @[simp] theorem symm_apply_apply (e : M₁ ≃SL[σ₁₂] M₂) (b : M₁) : e.symm (e b) = b := e.1.left_inv b include σ₁₂ σ₂₃ σ₁₃ σ₃₁ @[simp] theorem symm_trans_apply (e₁ : M₂ ≃SL[σ₂₁] M₁) (e₂ : M₃ ≃SL[σ₃₂] M₂) (c : M₁) : (e₂.trans e₁).symm c = e₂.symm (e₁.symm c) := rfl omit σ₁₂ σ₂₃ σ₁₃ σ₃₁ @[simp] theorem symm_image_image (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e.symm '' (e '' s) = s := e.to_linear_equiv.to_equiv.symm_image_image s @[simp] theorem image_symm_image (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e '' (e.symm '' s) = s := e.symm.symm_image_image s include σ₃₂ σ₃₁ @[simp, norm_cast] lemma comp_coe (f : M₁ ≃SL[σ₁₂] M₂) (f' : M₂ ≃SL[σ₂₃] M₃) : (f' : M₂ →SL[σ₂₃] M₃).comp (f : M₁ →SL[σ₁₂] M₂) = (f.trans f' : M₁ →SL[σ₁₃] M₃) := rfl omit σ₃₂ σ₃₁ σ₂₁ @[simp] theorem coe_comp_coe_symm (e : M₁ ≃SL[σ₁₂] M₂) : (e : M₁ →SL[σ₁₂] M₂).comp (e.symm : M₂ →SL[σ₂₁] M₁) = continuous_linear_map.id R₂ M₂ := continuous_linear_map.ext e.apply_symm_apply @[simp] theorem coe_symm_comp_coe (e : M₁ ≃SL[σ₁₂] M₂) : (e.symm : M₂ →SL[σ₂₁] M₁).comp (e : M₁ →SL[σ₁₂] M₂) = continuous_linear_map.id R₁ M₁ := continuous_linear_map.ext e.symm_apply_apply include σ₂₁ @[simp] lemma symm_comp_self (e : M₁ ≃SL[σ₁₂] M₂) : (e.symm : M₂ → M₁) ∘ (e : M₁ → M₂) = id := by{ ext x, exact symm_apply_apply e x } @[simp] lemma self_comp_symm (e : M₁ ≃SL[σ₁₂] M₂) : (e : M₁ → M₂) ∘ (e.symm : M₂ → M₁) = id := by{ ext x, exact apply_symm_apply e x } @[simp] theorem symm_symm (e : M₁ ≃SL[σ₁₂] M₂) : e.symm.symm = e := by { ext x, refl } omit σ₂₁ @[simp] lemma refl_symm : (continuous_linear_equiv.refl R₁ M₁).symm = continuous_linear_equiv.refl R₁ M₁ := rfl include σ₂₁ theorem symm_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) (x : M₁) : e.symm.symm x = e x := rfl lemma symm_apply_eq (e : M₁ ≃SL[σ₁₂] M₂) {x y} : e.symm x = y ↔ x = e y := e.to_linear_equiv.symm_apply_eq lemma eq_symm_apply (e : M₁ ≃SL[σ₁₂] M₂) {x y} : y = e.symm x ↔ e y = x := e.to_linear_equiv.eq_symm_apply protected lemma image_eq_preimage (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₁) : e '' s = e.symm ⁻¹' s := e.to_linear_equiv.to_equiv.image_eq_preimage s protected lemma image_symm_eq_preimage (e : M₁ ≃SL[σ₁₂] M₂) (s : set M₂) : e.symm '' s = e ⁻¹' s := by rw [e.symm.image_eq_preimage, e.symm_symm] omit σ₂₁ /-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are inverse of each other. -/ def equiv_of_inverse (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ : M₂ →SL[σ₂₁] M₁) (h₁ : function.left_inverse f₂ f₁) (h₂ : function.right_inverse f₂ f₁) : M₁ ≃SL[σ₁₂] M₂ := { to_fun := f₁, continuous_to_fun := f₁.continuous, inv_fun := f₂, continuous_inv_fun := f₂.continuous, left_inv := h₁, right_inv := h₂, .. f₁ } include σ₂₁ @[simp] lemma equiv_of_inverse_apply (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ h₁ h₂ x) : equiv_of_inverse f₁ f₂ h₁ h₂ x = f₁ x := rfl @[simp] lemma symm_equiv_of_inverse (f₁ : M₁ →SL[σ₁₂] M₂) (f₂ h₁ h₂) : (equiv_of_inverse f₁ f₂ h₁ h₂).symm = equiv_of_inverse f₂ f₁ h₂ h₁ := rfl omit σ₂₁ variable (M₁) /-- The continuous linear equivalences from `M` to itself form a group under composition. -/ instance automorphism_group : group (M₁ ≃L[R₁] M₁) := { mul := λ f g, g.trans f, one := continuous_linear_equiv.refl R₁ M₁, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } variables {M₁} {R₄ : Type*} [semiring R₄] [module R₄ M₄] {σ₃₄ : R₃ →+* R₄} {σ₄₃ : R₄ →+* R₃} [ring_hom_inv_pair σ₃₄ σ₄₃] [ring_hom_inv_pair σ₄₃ σ₃₄] {σ₂₄ : R₂ →+* R₄} {σ₁₄ : R₁ →+* R₄} [ring_hom_comp_triple σ₂₁ σ₁₄ σ₂₄] [ring_hom_comp_triple σ₂₄ σ₄₃ σ₂₃] [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] include σ₂₁ σ₃₄ σ₂₃ σ₂₄ σ₁₃ /-- A pair of continuous (semi)linear equivalences generates an equivalence between the spaces of continuous linear maps. -/ @[simps] def arrow_congr_equiv (e₁₂ : M₁ ≃SL[σ₁₂] M₂) (e₄₃ : M₄ ≃SL[σ₄₃] M₃) : (M₁ →SL[σ₁₄] M₄) ≃ (M₂ →SL[σ₂₃] M₃) := { to_fun := λ f, (e₄₃ : M₄ →SL[σ₄₃] M₃).comp (f.comp (e₁₂.symm : M₂ →SL[σ₂₁] M₁)), inv_fun := λ f, (e₄₃.symm : M₃ →SL[σ₃₄] M₄).comp (f.comp (e₁₂ : M₁ →SL[σ₁₂] M₂)), left_inv := λ f, continuous_linear_map.ext $ λ x, by simp only [continuous_linear_map.comp_apply, symm_apply_apply, coe_coe], right_inv := λ f, continuous_linear_map.ext $ λ x, by simp only [continuous_linear_map.comp_apply, apply_symm_apply, coe_coe] } end add_comm_monoid section add_comm_group variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] variables [topological_add_group M₄] /-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ def skew_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) : (M × M₃) ≃L[R] M₂ × M₄ := { continuous_to_fun := (e.continuous_to_fun.comp continuous_fst).prod_mk ((e'.continuous_to_fun.comp continuous_snd).add $ f.continuous.comp continuous_fst), continuous_inv_fun := (e.continuous_inv_fun.comp continuous_fst).prod_mk (e'.continuous_inv_fun.comp $ continuous_snd.sub $ f.continuous.comp $ e.continuous_inv_fun.comp continuous_fst), .. e.to_linear_equiv.skew_prod e'.to_linear_equiv ↑f } @[simp] lemma skew_prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : e.skew_prod e' f x = (e x.1, e' x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : (e.skew_prod e' f).symm x = (e.symm x.1, e'.symm (x.2 - f (e.symm x.1))) := rfl end add_comm_group section ring variables {R : Type*} [ring R] {R₂ : Type*} [ring R₂] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R₂ M₂] variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] include σ₂₁ @[simp] lemma map_sub (e : M ≃SL[σ₁₂] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →SL[σ₁₂] M₂).map_sub x y @[simp] lemma map_neg (e : M ≃SL[σ₁₂] M₂) (x : M) : e (-x) = -e x := (e : M →SL[σ₁₂] M₂).map_neg x omit σ₂₁ section /-! The next theorems cover the identification between `M ≃L[𝕜] M`and the group of units of the ring `M →L[R] M`. -/ variables [topological_add_group M] /-- An invertible continuous linear map `f` determines a continuous equivalence from `M` to itself. -/ def of_unit (f : units (M →L[R] M)) : (M ≃L[R] M) := { to_linear_equiv := { to_fun := f.val, map_add' := by simp, map_smul' := by simp, inv_fun := f.inv, left_inv := λ x, show (f.inv * f.val) x = x, by {rw f.inv_val, simp}, right_inv := λ x, show (f.val * f.inv) x = x, by {rw f.val_inv, simp}, }, continuous_to_fun := f.val.continuous, continuous_inv_fun := f.inv.continuous } /-- A continuous equivalence from `M` to itself determines an invertible continuous linear map. -/ def to_unit (f : (M ≃L[R] M)) : units (M →L[R] M) := { val := f, inv := f.symm, val_inv := by {ext, simp}, inv_val := by {ext, simp} } variables (R M) /-- The units of the algebra of continuous `R`-linear endomorphisms of `M` is multiplicatively equivalent to the type of continuous linear equivalences between `M` and itself. -/ def units_equiv : units (M →L[R] M) ≃* (M ≃L[R] M) := { to_fun := of_unit, inv_fun := to_unit, left_inv := λ f, by {ext, refl}, right_inv := λ f, by {ext, refl}, map_mul' := λ x y, by {ext, refl} } @[simp] lemma units_equiv_apply (f : units (M →L[R] M)) (x : M) : units_equiv R M f x = f x := rfl end section variables (R) [topological_space R] [has_continuous_mul R] /-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `units R`. -/ def units_equiv_aut : units R ≃ (R ≃L[R] R) := { to_fun := λ u, equiv_of_inverse (continuous_linear_map.smul_right (1 : R →L[R] R) ↑u) (continuous_linear_map.smul_right (1 : R →L[R] R) ↑u⁻¹) (λ x, by simp) (λ x, by simp), inv_fun := λ e, ⟨e 1, e.symm 1, by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, symm_apply_apply], by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, apply_symm_apply]⟩, left_inv := λ u, units.ext $ by simp, right_inv := λ e, ext₁ $ by simp } variable {R} @[simp] lemma units_equiv_aut_apply (u : units R) (x : R) : units_equiv_aut R u x = x * u := rfl @[simp] lemma units_equiv_aut_apply_symm (u : units R) (x : R) : (units_equiv_aut R u).symm x = x * ↑u⁻¹ := rfl @[simp] lemma units_equiv_aut_symm_apply (e : R ≃L[R] R) : ↑((units_equiv_aut R).symm e) = e 1 := rfl end variables [module R M₂] [topological_add_group M] open _root_.continuous_linear_map (id fst snd subtype_val mem_ker) /-- A pair of continuous linear maps such that `f₁ ∘ f₂ = id` generates a continuous linear equivalence `e` between `M` and `M₂ × f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`, `(e x).1 = f₁ x`, and `(e (f₂ y)).2 = 0`. The map is given by `e x = (f₁ x, x - f₂ (f₁ x))`. -/ def equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M ≃L[R] M₂ × f₁.ker := equiv_of_inverse (f₁.prod (f₁.proj_ker_of_right_inverse f₂ h)) (f₂.coprod (subtype_val f₁.ker)) (λ x, by simp) (λ ⟨x, y⟩, by simp [h x]) @[simp] lemma fst_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (equiv_of_right_inverse f₁ f₂ h x).1 = f₁ x := rfl @[simp] lemma snd_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : ((equiv_of_right_inverse f₁ f₂ h x).2 : M) = x - f₂ (f₁ x) := rfl @[simp] lemma equiv_of_right_inverse_symm_apply (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂ × f₁.ker) : (equiv_of_right_inverse f₁ f₂ h).symm y = f₂ y.1 + y.2 := rfl end ring section variables (ι R M : Type*) [unique ι] [semiring R] [add_comm_monoid M] [module R M] [topological_space M] /-- If `ι` has a unique element, then `ι → M` is continuously linear equivalent to `M`. -/ def fun_unique : (ι → M) ≃L[R] M := { to_linear_equiv := linear_equiv.fun_unique ι R M, .. homeomorph.fun_unique ι M } variables {ι R M} @[simp] lemma coe_fun_unique : ⇑(fun_unique ι R M) = function.eval (default ι) := rfl @[simp] lemma coe_fun_unique_symm : ⇑(fun_unique ι R M).symm = function.const ι := rfl end end continuous_linear_equiv namespace continuous_linear_map open_locale classical variables {R : Type*} {M : Type*} {M₂ : Type*} [topological_space M] [topological_space M₂] section variables [semiring R] variables [add_comm_monoid M₂] [module R M₂] variables [add_comm_monoid M] [module R M] /-- Introduce a function `inverse` from `M →L[R] M₂` to `M₂ →L[R] M`, which sends `f` to `f.symm` if `f` is a continuous linear equivalence and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. -/ noncomputable def inverse : (M →L[R] M₂) → (M₂ →L[R] M) := λ f, if h : ∃ (e : M ≃L[R] M₂), (e : M →L[R] M₂) = f then ((classical.some h).symm : M₂ →L[R] M) else 0 /-- By definition, if `f` is invertible then `inverse f = f.symm`. -/ @[simp] lemma inverse_equiv (e : M ≃L[R] M₂) : inverse (e : M →L[R] M₂) = e.symm := begin have h : ∃ (e' : M ≃L[R] M₂), (e' : M →L[R] M₂) = ↑e := ⟨e, rfl⟩, simp only [inverse, dif_pos h], congr, exact_mod_cast (classical.some_spec h) end /-- By definition, if `f` is not invertible then `inverse f = 0`. -/ @[simp] lemma inverse_non_equiv (f : M →L[R] M₂) (h : ¬∃ (e' : M ≃L[R] M₂), ↑e' = f) : inverse f = 0 := dif_neg h end section variables [ring R] variables [add_comm_group M] [topological_add_group M] [module R M] variables [add_comm_group M₂] [module R M₂] @[simp] lemma ring_inverse_equiv (e : M ≃L[R] M) : ring.inverse ↑e = inverse (e : M →L[R] M) := begin suffices : ring.inverse ((((continuous_linear_equiv.units_equiv _ _).symm e) : M →L[R] M)) = inverse ↑e, { convert this }, simp, refl, end /-- The function `continuous_linear_equiv.inverse` can be written in terms of `ring.inverse` for the ring of self-maps of the domain. -/ lemma to_ring_inverse (e : M ≃L[R] M₂) (f : M →L[R] M₂) : inverse f = (ring.inverse ((e.symm : (M₂ →L[R] M)).comp f)) ∘L ↑e.symm := begin by_cases h₁ : ∃ (e' : M ≃L[R] M₂), ↑e' = f, { obtain ⟨e', he'⟩ := h₁, rw ← he', change _ = (ring.inverse ↑(e'.trans e.symm)) ∘L ↑e.symm, ext, simp }, { suffices : ¬is_unit ((e.symm : M₂ →L[R] M).comp f), { simp [this, h₁] }, contrapose! h₁, rcases h₁ with ⟨F, hF⟩, use (continuous_linear_equiv.units_equiv _ _ F).trans e, ext, dsimp, rw [coe_fn_coe_base' F, hF], simp } end lemma ring_inverse_eq_map_inverse : ring.inverse = @inverse R M M _ _ _ _ _ _ _ := begin ext, simp [to_ring_inverse (continuous_linear_equiv.refl R M)], end end end continuous_linear_map namespace submodule variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂] open continuous_linear_map /-- A submodule `p` is called *complemented* if there exists a continuous projection `M →ₗ[R] p`. -/ def closed_complemented (p : submodule R M) : Prop := ∃ f : M →L[R] p, ∀ x : p, f x = x lemma closed_complemented.has_closed_complement {p : submodule R M} [t1_space p] (h : closed_complemented p) : ∃ (q : submodule R M) (hq : is_closed (q : set M)), is_compl p q := exists.elim h $ λ f hf, ⟨f.ker, f.is_closed_ker, linear_map.is_compl_of_proj hf⟩ protected lemma closed_complemented.is_closed [topological_add_group M] [t1_space M] {p : submodule R M} (h : closed_complemented p) : is_closed (p : set M) := begin rcases h with ⟨f, hf⟩, have : ker (id R M - (subtype_val p).comp f) = p := linear_map.ker_id_sub_eq_of_proj hf, exact this ▸ (is_closed_ker _) end @[simp] lemma closed_complemented_bot : closed_complemented (⊥ : submodule R M) := ⟨0, λ x, by simp only [zero_apply, eq_zero_of_bot_submodule x]⟩ @[simp] lemma closed_complemented_top : closed_complemented (⊤ : submodule R M) := ⟨(id R M).cod_restrict ⊤ (λ x, trivial), λ x, subtype.ext_iff_val.2 $ by simp⟩ end submodule lemma continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : f₁.ker.closed_complemented := ⟨f₁.proj_ker_of_right_inverse f₂ h, f₁.proj_ker_of_right_inverse_apply_idem f₂ h⟩
bc83f745931cb94cd139489828d06f431c661241
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/homology/single.lean
22ced8ccea2d90b7a7ce5b0b5929220e41c5478c
[ "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
11,090
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.homology.homology /-! # Chain complexes supported in a single degree We define `single V j c : V ⥤ homological_complex V c`, which constructs complexes in `V` of shape `c`, supported in degree `j`. Similarly `single₀ V : V ⥤ chain_complex V ℕ` is the special case for `ℕ`-indexed chain complexes, with the object supported in degree `0`, but with better definitional properties. In `to_single₀_equiv` we characterize chain maps to a `ℕ`-indexed complex concentrated in degree 0; they are equivalent to `{ f : C.X 0 ⟶ X // C.d 1 0 ≫ f = 0 }`. (This is useful translating between a projective resolution and an augmented exact complex of projectives.) -/ open category_theory open category_theory.limits universes v u variables (V : Type u) [category.{v} V] [has_zero_morphisms V] [has_zero_object V] namespace homological_complex variables {ι : Type*} [decidable_eq ι] (c : complex_shape ι) local attribute [instance] has_zero_object.has_zero /-- The functor `V ⥤ homological_complex V c` creating a chain complex supported in a single degree. See also `chain_complex.single₀ : V ⥤ chain_complex V ℕ`, which has better definitional properties, if you are working with `ℕ`-indexed complexes. -/ @[simps] def single (j : ι) : V ⥤ homological_complex V c := { obj := λ A, { X := λ i, if i = j then A else 0, d := λ i j, 0, }, map := λ A B f, { f := λ i, if h : i = j then eq_to_hom (by { dsimp, rw if_pos h, }) ≫ f ≫ eq_to_hom (by { dsimp, rw if_pos h, }) else 0, }, map_id' := λ A, begin ext, dsimp, split_ifs with h, { subst h, simp, }, { rw if_neg h, simp, }, end, map_comp' := λ A B C f g, begin ext, dsimp, split_ifs with h, { subst h, simp, }, { simp, }, end, }. /-- The object in degree `j` of `(single V c h).obj A` is just `A`. -/ @[simps] def single_obj_X_self (j : ι) (A : V) : ((single V c j).obj A).X j ≅ A := eq_to_iso (by simp) @[simp] lemma single_map_f_self (j : ι) {A B : V} (f : A ⟶ B) : ((single V c j).map f).f j = (single_obj_X_self V c j A).hom ≫ f ≫ (single_obj_X_self V c j B).inv := by { simp, refl, } instance (j : ι) : faithful (single V c j) := { map_injective' := λ X Y f g w, begin have := congr_hom w j, dsimp at this, simp only [dif_pos] at this, rw [←is_iso.inv_comp_eq, inv_eq_to_hom, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp, ←is_iso.comp_inv_eq, category.assoc, inv_eq_to_hom, eq_to_hom_trans, eq_to_hom_refl, category.comp_id] at this, exact this, end, } instance (j : ι) : full (single V c j) := { preimage := λ X Y f, eq_to_hom (by simp) ≫ f.f j ≫ eq_to_hom (by simp), witness' := λ X Y f, begin ext i, dsimp, split_ifs, { subst h, simp, }, { symmetry, apply zero_of_target_iso_zero, dsimp, rw [if_neg h], }, end } end homological_complex open homological_complex namespace chain_complex local attribute [instance] has_zero_object.has_zero /-- `chain_complex.single₀ V` is the embedding of `V` into `chain_complex V ℕ` as chain complexes supported in degree 0. This is naturally isomorphic to `single V _ 0`, but has better definitional properties. -/ def single₀ : V ⥤ chain_complex V ℕ := { obj := λ X, { X := λ n, match n with | 0 := X | (n+1) := 0 end, d := λ i j, 0, }, map := λ X Y f, { f := λ n, match n with | 0 := f | (n+1) := 0 end, }, map_id' := λ X, by { ext n, cases n, refl, dsimp, unfold_aux, simp, }, map_comp' := λ X Y Z f g, by { ext n, cases n, refl, dsimp, unfold_aux, simp, } } @[simp] lemma single₀_obj_X_0 (X : V) : ((single₀ V).obj X).X 0 = X := rfl @[simp] lemma single₀_obj_X_succ (X : V) (n : ℕ) : ((single₀ V).obj X).X (n+1) = 0 := rfl @[simp] lemma single₀_obj_X_d (X : V) (i j : ℕ) : ((single₀ V).obj X).d i j = 0 := rfl @[simp] lemma single₀_obj_X_d_to (X : V) (j : ℕ) : ((single₀ V).obj X).d_to j = 0 := by { rw [d_to_eq ((single₀ V).obj X) rfl], simp, } @[simp] lemma single₀_obj_X_d_from (X : V) (i : ℕ) : ((single₀ V).obj X).d_from i = 0 := begin cases i, { rw [d_from_eq_zero], simp, }, { rw [d_from_eq ((single₀ V).obj X) rfl], simp, }, end @[simp] lemma single₀_map_f_0 {X Y : V} (f : X ⟶ Y) : ((single₀ V).map f).f 0 = f := rfl @[simp] lemma single₀_map_f_succ {X Y : V} (f : X ⟶ Y) (n : ℕ) : ((single₀ V).map f).f (n+1) = 0 := rfl section variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V] /-- Sending objects to chain complexes supported at `0` then taking `0`-th homology is the same as doing nothing. -/ noncomputable def homology_functor_0_single₀ : single₀ V ⋙ homology_functor V _ 0 ≅ (𝟭 V) := nat_iso.of_components (λ X, homology.congr _ _ (by simp) (by simp) ≪≫ homology_zero_zero) (λ X Y f, by { ext, dsimp [homology_functor], simp, }) /-- Sending objects to chain complexes supported at `0` then taking `(n+1)`-st homology is the same as the zero functor. -/ noncomputable def homology_functor_succ_single₀ (n : ℕ) : single₀ V ⋙ homology_functor V _ (n+1) ≅ 0 := nat_iso.of_components (λ X, homology.congr _ _ (by simp) (by simp) ≪≫ homology_zero_zero) (λ X Y f, by ext) end variables {V} /-- Morphisms from a `ℕ`-indexed chain complex `C` to a single object chain complex with `X` concentrated in degree 0 are the same as morphisms `f : C.X 0 ⟶ X` such that `C.d 1 0 ≫ f = 0`. -/ def to_single₀_equiv (C : chain_complex V ℕ) (X : V) : (C ⟶ (single₀ V).obj X) ≃ { f : C.X 0 ⟶ X // C.d 1 0 ≫ f = 0 } := { to_fun := λ f, ⟨f.f 0, by { rw ←f.comm 1 0, simp, }⟩, inv_fun := λ f, { f := λ i, match i with | 0 := f.1 | (n+1) := 0 end, comm' := λ i j h, begin rcases i with _|_|i; cases j; unfold_aux; simp only [comp_zero, zero_comp, single₀_obj_X_d], { rw [C.shape, zero_comp], simp, }, { exact f.2.symm, }, { rw [C.shape, zero_comp], simp [i.succ_succ_ne_one.symm] }, end, }, left_inv := λ f, begin ext i, rcases i, { refl, }, { ext, }, end, right_inv := by tidy, } variables (V) /-- `single₀` is the same as `single V _ 0`. -/ def single₀_iso_single : single₀ V ≅ single V _ 0 := nat_iso.of_components (λ X, { hom := { f := λ i, by { cases i; simpa using 𝟙 _, } }, inv := { f := λ i, by { cases i; simpa using 𝟙 _, } }, hom_inv_id' := by { ext (_|i); { dsimp, simp, }, }, inv_hom_id' := begin ext (_|i), { apply category.id_comp, }, { apply has_zero_object.to_zero_ext, }, end, }) (λ X Y f, by { ext (_|i); { dsimp, simp, }, }) instance : faithful (single₀ V) := faithful.of_iso (single₀_iso_single V).symm instance : full (single₀ V) := full.of_iso (single₀_iso_single V).symm end chain_complex namespace cochain_complex local attribute [instance] has_zero_object.has_zero /-- `cochain_complex.single₀ V` is the embedding of `V` into `cochain_complex V ℕ` as cochain complexes supported in degree 0. This is naturally isomorphic to `single V _ 0`, but has better definitional properties. -/ def single₀ : V ⥤ cochain_complex V ℕ := { obj := λ X, { X := λ n, match n with | 0 := X | (n+1) := 0 end, d := λ i j, 0, }, map := λ X Y f, { f := λ n, match n with | 0 := f | (n+1) := 0 end, }, map_id' := λ X, by { ext n, cases n, refl, dsimp, unfold_aux, simp, }, map_comp' := λ X Y Z f g, by { ext n, cases n, refl, dsimp, unfold_aux, simp, } } @[simp] lemma single₀_obj_X_0 (X : V) : ((single₀ V).obj X).X 0 = X := rfl @[simp] lemma single₀_obj_X_succ (X : V) (n : ℕ) : ((single₀ V).obj X).X (n+1) = 0 := rfl @[simp] lemma single₀_obj_X_d (X : V) (i j : ℕ) : ((single₀ V).obj X).d i j = 0 := rfl @[simp] lemma single₀_obj_X_d_from (X : V) (j : ℕ) : ((single₀ V).obj X).d_from j = 0 := by { rw [d_from_eq ((single₀ V).obj X) rfl], simp, } @[simp] lemma single₀_obj_X_d_to (X : V) (i : ℕ) : ((single₀ V).obj X).d_to i = 0 := begin cases i, { rw [d_to_eq_zero], simp, }, { rw [d_to_eq ((single₀ V).obj X) rfl], simp, }, end @[simp] lemma single₀_map_f_0 {X Y : V} (f : X ⟶ Y) : ((single₀ V).map f).f 0 = f := rfl @[simp] lemma single₀_map_f_succ {X Y : V} (f : X ⟶ Y) (n : ℕ) : ((single₀ V).map f).f (n+1) = 0 := rfl section variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V] /-- Sending objects to cochain complexes supported at `0` then taking `0`-th homology is the same as doing nothing. -/ noncomputable def homology_functor_0_single₀ : single₀ V ⋙ homology_functor V _ 0 ≅ (𝟭 V) := nat_iso.of_components (λ X, homology.congr _ _ (by simp) (by simp) ≪≫ homology_zero_zero) (λ X Y f, by { ext, dsimp [homology_functor], simp, }) /-- Sending objects to cochain complexes supported at `0` then taking `(n+1)`-st homology is the same as the zero functor. -/ noncomputable def homology_functor_succ_single₀ (n : ℕ) : single₀ V ⋙ homology_functor V _ (n+1) ≅ 0 := nat_iso.of_components (λ X, homology.congr _ _ (by simp) (by simp) ≪≫ homology_zero_zero) (λ X Y f, by ext) end variables {V} /-- Morphisms from a single object cochain complex with `X` concentrated in degree 0 to a `ℕ`-indexed cochain complex `C` are the same as morphisms `f : X ⟶ C.X 0` such that `f ≫ C.d 0 1 = 0`. -/ def from_single₀_equiv (C : cochain_complex V ℕ) (X : V) : ((single₀ V).obj X ⟶ C) ≃ { f : X ⟶ C.X 0 // f ≫ C.d 0 1 = 0 } := { to_fun := λ f, ⟨f.f 0, by { rw f.comm 0 1, simp, }⟩, inv_fun := λ f, { f := λ i, match i with | 0 := f.1 | (n+1) := 0 end, comm' := λ i j h, begin rcases j with _|_|j; cases i; unfold_aux; simp only [comp_zero, zero_comp, single₀_obj_X_d], { convert comp_zero, rw [C.shape], simp, }, { exact f.2, }, { convert comp_zero, rw [C.shape], simp only [complex_shape.up_rel, zero_add], exact (nat.one_lt_succ_succ j).ne }, end, }, left_inv := λ f, begin ext i, rcases i, { refl, }, { ext, }, end, right_inv := by tidy, } variables (V) /-- `single₀` is the same as `single V _ 0`. -/ def single₀_iso_single : single₀ V ≅ single V _ 0 := nat_iso.of_components (λ X, { hom := { f := λ i, by { cases i; simpa using 𝟙 _, } }, inv := { f := λ i, by { cases i; simpa using 𝟙 _, } }, hom_inv_id' := by { ext (_|i); { dsimp, simp, }, }, inv_hom_id' := begin ext (_|i), { apply category.id_comp, }, { apply has_zero_object.to_zero_ext, }, end, }) (λ X Y f, by { ext (_|i); { dsimp, simp, }, }) instance : faithful (single₀ V) := faithful.of_iso (single₀_iso_single V).symm instance : full (single₀ V) := full.of_iso (single₀_iso_single V).symm end cochain_complex
5c09f62ed0c79da2e59fbf7d80f0f8833da81fd5
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Init/Prelude.lean
3cde822aa9ae381409dd1d34f7eaf940ddf9420a
[ "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
71,490
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude universes u v w @[inline] def id {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a @[reducible] def inferInstance {α : Type u} [i : α] : α := i @[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /- 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 -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b from fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true | _, isTrue _, _ => rfl | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false | _, isTrue h₁, h₂ => absurd h₁ h₂ | _, isFalse h, _ => rfl theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h => match s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h => match s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance {α : Type u} [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance {p} [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class HasLessEq (α : Type u) where LessEq : α → α → Prop class HasLess (α : Type u) where Less : α → α → Prop export HasLess (Less) export HasLessEq (LessEq) class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → β → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) where pow : α → α → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → α → α class AndThen (α : Type u) where andThen : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α] : HPow α α α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) @[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := LessEq b a @[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := Less b a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_eq"] def Nat.beq : Nat → Nat → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eqOfBeqEqTrue : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have Eq (beq n m) true from h have Eq n m from eqOfBeqEqTrue this this ▸ rfl theorem Nat.neOfBeqEqFalse : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have Eq (beq n m) false from h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFalse this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eqOfBeqEqTrue h) | false => isFalse (neOfBeqEqFalse h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_le"] def Nat.ble : Nat → Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := Eq (ble n m) true instance : HasLessEq Nat where LessEq := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : HasLess Nat where Less := Nat.lt theorem Nat.notSuccLeZero : ∀ (n : Nat), LessEq (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.notLtZero (n : Nat) : Not (Less n 0) := notSuccLeZero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LessEq n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (Less n m) := decLe (succ n) m theorem Nat.zeroLe : (n : Nat) → LessEq 0 n | zero => rfl | succ n => rfl theorem Nat.succLeSucc {n m : Nat} (h : LessEq n m) : LessEq (succ n) (succ m) := h theorem Nat.zeroLtSucc (n : Nat) : Less 0 (succ n) := succLeSucc (zeroLe n) theorem Nat.leStep : {n m : Nat} → LessEq n m → LessEq n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h have LessEq n (succ m) from leStep this succLeSucc this set_option pp.raw true protected theorem Nat.leTrans : {n m k : Nat} → LessEq n m → LessEq m k → LessEq n k | zero, m, k, h₁, h₂ => zeroLe _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m k from h₂ show LessEq n k from Nat.leTrans h₁' h₂' protected theorem Nat.ltTrans {n m k : Nat} (h₁ : Less n m) : Less m k → Less n k := Nat.leTrans (leStep h₁) theorem Nat.leSucc : (n : Nat) → LessEq n (succ n) | zero => rfl | succ n => leSucc n theorem Nat.leSuccOfLe {n m : Nat} (h : LessEq n m) : LessEq n (succ m) := Nat.leTrans h (leSucc m) protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LessEq n m → Or (Eq n m) (Less n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zeroLe n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h match Nat.eqOrLtOfLe this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succLeSucc h) protected def Nat.leRefl : (n : Nat) → LessEq n n | zero => rfl | succ n => Nat.leRefl n protected theorem Nat.ltOrGe (n m : Nat) : Or (Less n m) (GreaterEq n m) := match m with | zero => Or.inr (zeroLe n) | succ m => match Nat.ltOrGe n m with | Or.inl h => Or.inl (leSuccOfLe h) | Or.inr h => match Nat.eqOrLtOfLe h with | Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.leAntisymm : {n m : Nat} → LessEq n m → LessEq m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m n from h₂ (Nat.leAntisymm h₁' h₂') ▸ rfl protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LessEq n m) (h₂ : Not (Eq n m)) : Less n m := match Nat.ltOrGe n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂ set_option bootstrap.genMatcherCode false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : Nat → Nat | 0 => 0 | succ a => a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub theorem Nat.predLePred : {n m : Nat} → LessEq n m → LessEq (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.leOfSuccLeSucc {n m : Nat} : LessEq (succ n) (succ m) → LessEq n m := predLePred theorem Nat.leOfLtSucc {m n : Nat} : Less m (succ n) → LessEq m n := leOfSuccLeSucc @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : Less val n theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (veqOfEq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eqOfVeq h) | isFalse h => isFalse (Fin.neOfVne h) instance {n} : HasLess (Fin n) where Less a b := Less a.val b.val instance {n} : HasLessEq (Fin n) where LessEq a b := LessEq a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (Less a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LessEq a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : Less n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 decide! def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : Less n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 decide! def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : Less n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 decide! instance : HasLess UInt32 where Less a b := Less a.val b.val instance : HasLessEq UInt32 where LessEq a b := LessEq a.val b.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (Less a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (Less n m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (LessEq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LessEq n m)) instance (a b : UInt32) : Decidable (Less a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LessEq a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : Less n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 decide! def USize.size : Nat := hPow 2 System.Platform.numBits theorem usizeSzEq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBitsEq with | _, Or.inl rfl => Or.inl (decide! : (Eq (hPow 2 32) (4294967296:Nat))) | _, Or.inr rfl => Or.inr (decide! : (Eq (hPow 2 64) (18446744073709551616:Nat))) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : Less n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usizeSzEq with | _, Or.inl rfl => decide! | _, Or.inr rfl => decide!) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : Less n 4294967296) : USize := { val := { val := n, isLt := match USize.size, usizeSzEq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.ltTrans h (decide! : Less 4294967296 18446744073709551616) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (Less n 0xd800) (And (Less 0xdfff n) (Less n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : Less n UInt32.size := match h with | Or.inl h => Nat.ltTrans h (decide! : Less 55296 UInt32.size) | Or.inr ⟨_, h⟩ => Nat.ltTrans h (decide! : Less 1114112 UInt32.size) @[extern "lean_uint32_of_nat"] private def Char.ofNatAux (n : Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := decide! }⟩, valid := Or.inl decide! }) theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (veqOfEq h') h theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eqOfVeq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eqOfVeq h) | isFalse h => isFalse (Char.neOfVne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LessEq v (UInt32.ofNatCore 0x7F decide!)) (UInt32.ofNatCore 1 decide!) (ite (LessEq v (UInt32.ofNatCore 0x7FF decide!)) (UInt32.ofNatCore 2 decide!) (ite (LessEq v (UInt32.ofNatCore 0xFFFF decide!)) (UInt32.ofNatCore 3 decide!) (UInt32.ofNatCore 4 decide!))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.lengthAux {α : Type u} : List α → Nat → Nat | nil, n => n | cons a as, n => lengthAux as (Nat.succ n) def List.length {α : Type u} (as : List α) : Nat := lengthAux as 0 theorem List.lengthConsEq {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ := match as with | nil => fun _ => rfl | cons a as => fun n => aux a as n.succ aux a as 0 def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → Less i as.length → α | nil, i, h => absurd h (Nat.notLtZero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have Less i.succ as.length.succ from lengthConsEq .. ▸ h get as i (Nat.leOfSuccLeSucc this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.sub b def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s, startPos := 0, stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (Less i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (Less i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (Less j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → f α → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α : Type u} → f α → f PUnit → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {β : Type u} → f PUnit → f β → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map := fun f x => bind x (Function.comp pure f) seq := fun f x => bind f fun y => Functor.map y x seqLeft := fun x y => bind x fun a => bind y (fun _ => pure a) seqRight := fun x y => bind x fun _ => y instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (Less j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orelse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r @[reducible] def Reader (ρ : Type u) := ReaderT ρ id namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet := fun f => MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set := fun s => liftM (m := m) (MonadStateOf.set s) modifyGet := fun f => monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error arbitrary s @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ PUnit) (y : EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error _ _ => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Type u) where hash : α → USize export Hashable (hash) @[extern "lean_usize_mix_hash"] constant mixHash (u₁ u₂ : USize) : USize @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : USize instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → USize → Name | num : Name → Nat → USize → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → USize | Name.anonymous => USize.ofNat32 1723 decide! | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (Less v USize.size) (fun h => USize.ofNatCore v h) (fun _ => USize.ofNat32 17 decide!))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) /- Synthesized token (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) /- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax where | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident _ _ _ _ => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ args => args.size | _ => 0 def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node k _ => node k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node k args => node k (args.setD i arg) | stx => stx /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info _ _ _ => some info | node _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (Less i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (pos := pos) ..) val, _ => some (pos.add val.bsize) | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (pos := pos) ..) val .., _ => some (pos.add val.bsize) | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (Less i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom src.getHeadInfo val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef := fun ref x => monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule), mainModule := mainModule, scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ constant MacroEnvPointed : PointedType.{0} def MacroEnv : Type := MacroEnvPointed.type instance : Inhabited MacroEnv where default := MacroEnvPointed.val structure Context where macroEnv : MacroEnv mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception MacroScope) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s, hAdd s 1))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope := fun ctx => pure ctx.currMacroScope getMainModule := fun ctx => pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope unsafe def mkMacroEnvImp (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv := unsafeCast expandMacro? @[implementedBy mkMacroEnvImp] constant mkMacroEnv (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv def expandMacroNotAvailable? (stx : Syntax) : MacroM (Option Syntax) := throwErrorAt stx "expandMacro has not been set" def mkMacroEnvSimple : MacroEnv := mkMacroEnv expandMacroNotAvailable? unsafe def expandMacro?Imp (stx : Syntax) : MacroM (Option Syntax) := bind read fun ctx => let f : Syntax → MacroM (Option Syntax) := unsafeCast (ctx.macroEnv) f stx /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ @[implementedBy expandMacro?Imp] constant expandMacro? : Syntax → MacroM (Option Syntax) end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
5f8458fca39e00ac9a6aa2a84188e822d67b6128
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/clifford_algebra/basic.lean
8b62307638848faa8f3d6004071d1b2b424f8d65
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,739
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.exterior_algebra.basic import linear_algebra.quadratic_form.basic /-! # Clifford Algebras 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 denoted as `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, 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`. -/ -- 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 /-- A Clifford algebra with a zero quadratic form is isomorphic to an `exterior_algebra` -/ def as_exterior : clifford_algebra (0 : quadratic_form R M) ≃ₐ[R] exterior_algebra R M := alg_equiv.of_alg_hom (clifford_algebra.lift 0 ⟨(exterior_algebra.ι R), by simp only [forall_const, ring_hom.map_zero, exterior_algebra.ι_sq_zero, quadratic_form.zero_apply]⟩) (exterior_algebra.lift R ⟨(ι (0 : quadratic_form R M)), by simp only [forall_const, ring_hom.map_zero, quadratic_form.zero_apply, ι_sq_scalar]⟩) (exterior_algebra.hom_ext $ linear_map.ext $ by simp only [alg_hom.comp_to_linear_map, linear_map.coe_comp, function.comp_app, alg_hom.to_linear_map_apply, exterior_algebra.lift_ι_apply, clifford_algebra.lift_ι_apply, alg_hom.to_linear_map_id, linear_map.id_comp, eq_self_iff_true, forall_const]) (clifford_algebra.hom_ext $ linear_map.ext $ by simp only [alg_hom.comp_to_linear_map, linear_map.coe_comp, function.comp_app, alg_hom.to_linear_map_apply, clifford_algebra.lift_ι_apply, exterior_algebra.lift_ι_apply, alg_hom.to_linear_map_id, linear_map.id_comp, eq_self_iff_true, forall_const]) /-- 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 @[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 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
820b7508e95046a43f1f7e351bf6aae5a4d3e34e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/monad/basic.lean
f17896aa6826bdefd9002e0dc814b9266750c21e
[ "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
5,328
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta, Adam Topaz -/ import category_theory.functor_category namespace category_theory open category universes v₁ u₁ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v₁} C] /-- The data of a monad on C consists of an endofunctor T together with natural transformations η : 𝟭 C ⟶ T and μ : T ⋙ T ⟶ T satisfying three equations: - T μ_X ≫ μ_X = μ_(TX) ≫ μ_X (associativity) - η_(TX) ≫ μ_X = 1_X (left unit) - Tη_X ≫ μ_X = 1_X (right unit) -/ class monad (T : C ⥤ C) := (η [] : 𝟭 _ ⟶ T) (μ [] : T ⋙ T ⟶ T) (assoc' : ∀ X : C, T.map (nat_trans.app μ X) ≫ μ.app _ = μ.app (T.obj X) ≫ μ.app _ . obviously) (left_unit' : ∀ X : C, η.app (T.obj X) ≫ μ.app _ = 𝟙 _ . obviously) (right_unit' : ∀ X : C, T.map (η.app X) ≫ μ.app _ = 𝟙 _ . obviously) restate_axiom monad.assoc' restate_axiom monad.left_unit' restate_axiom monad.right_unit' attribute [simp] monad.left_unit monad.right_unit notation `η_` := monad.η notation `μ_` := monad.μ /-- The data of a comonad on C consists of an endofunctor G together with natural transformations ε : G ⟶ 𝟭 C and δ : G ⟶ G ⋙ G satisfying three equations: - δ_X ≫ G δ_X = δ_X ≫ δ_(GX) (coassociativity) - δ_X ≫ ε_(GX) = 1_X (left counit) - δ_X ≫ G ε_X = 1_X (right counit) -/ class comonad (G : C ⥤ C) := (ε [] : G ⟶ 𝟭 _) (δ [] : G ⟶ (G ⋙ G)) (coassoc' : ∀ X : C, nat_trans.app δ _ ≫ G.map (δ.app X) = δ.app _ ≫ δ.app _ . obviously) (left_counit' : ∀ X : C, δ.app X ≫ ε.app (G.obj X) = 𝟙 _ . obviously) (right_counit' : ∀ X : C, δ.app X ≫ G.map (ε.app X) = 𝟙 _ . obviously) restate_axiom comonad.coassoc' restate_axiom comonad.left_counit' restate_axiom comonad.right_counit' attribute [simp] comonad.left_counit comonad.right_counit notation `ε_` := comonad.ε notation `δ_` := comonad.δ /-- A morphisms of monads is a natural transformation compatible with η and μ. -/ structure monad_hom (M N : C ⥤ C) [monad M] [monad N] extends nat_trans M N := (app_η' : ∀ {X}, (η_ M).app X ≫ app X = (η_ N).app X . obviously) (app_μ' : ∀ {X}, (μ_ M).app X ≫ app X = (M.map (app X) ≫ app (N.obj X)) ≫ (μ_ N).app X . obviously) restate_axiom monad_hom.app_η' restate_axiom monad_hom.app_μ' attribute [simp, reassoc] monad_hom.app_η monad_hom.app_μ /-- A morphisms of comonads is a natural transformation compatible with η and μ. -/ structure comonad_hom (M N : C ⥤ C) [comonad M] [comonad N] extends nat_trans M N := (app_ε' : ∀ {X}, app X ≫ (ε_ N).app X = (ε_ M).app X . obviously) (app_δ' : ∀ {X}, app X ≫ (δ_ N).app X = (δ_ M).app X ≫ app (M.obj X) ≫ N.map (app X) . obviously) restate_axiom comonad_hom.app_ε' restate_axiom comonad_hom.app_δ' attribute [simp, reassoc] comonad_hom.app_ε comonad_hom.app_δ namespace monad_hom variables {M N L K : C ⥤ C} [monad M] [monad N] [monad L] [monad K] @[ext] theorem ext (f g : monad_hom M N) : f.to_nat_trans = g.to_nat_trans → f = g := by {cases f, cases g, simp} variable (M) /-- The identity natural transformations is a morphism of monads. -/ def id : monad_hom M M := { ..𝟙 M } variable {M} instance : inhabited (monad_hom M M) := ⟨id _⟩ /-- The composition of two morphisms of monads. -/ def comp (f : monad_hom M N) (g : monad_hom N L) : monad_hom M L := { app := λ X, f.app X ≫ g.app X } @[simp] lemma id_comp (f : monad_hom M N) : (monad_hom.id M).comp f = f := by {ext, apply id_comp} @[simp] lemma comp_id (f : monad_hom M N) : f.comp (monad_hom.id N) = f := by {ext, apply comp_id} /-- Note: `category_theory.monad.bundled` provides a category instance for bundled monads.-/ @[simp] lemma assoc (f : monad_hom M N) (g : monad_hom N L) (h : monad_hom L K) : (f.comp g).comp h = f.comp (g.comp h) := by {ext, apply assoc} end monad_hom namespace comonad_hom variables {M N L K : C ⥤ C} [comonad M] [comonad N] [comonad L] [comonad K] @[ext] theorem ext (f g : comonad_hom M N) : f.to_nat_trans = g.to_nat_trans → f = g := by {cases f, cases g, simp} variable (M) /-- The identity natural transformations is a morphism of comonads. -/ def id : comonad_hom M M := { ..𝟙 M } variable {M} instance : inhabited (comonad_hom M M) := ⟨id _⟩ /-- The composition of two morphisms of comonads. -/ def comp (f : comonad_hom M N) (g : comonad_hom N L) : comonad_hom M L := { app := λ X, f.app X ≫ g.app X } @[simp] lemma id_comp (f : comonad_hom M N) : (comonad_hom.id M).comp f = f := by {ext, apply id_comp} @[simp] lemma comp_id (f : comonad_hom M N) : f.comp (comonad_hom.id N) = f := by {ext, apply comp_id} /-- Note: `category_theory.monad.bundled` provides a category instance for bundled comonads.-/ @[simp] lemma assoc (f : comonad_hom M N) (g : comonad_hom N L) (h : comonad_hom L K) : (f.comp g).comp h = f.comp (g.comp h) := by {ext, apply assoc} end comonad_hom namespace monad instance : monad (𝟭 C) := { η := 𝟙 _, μ := 𝟙 _ } end monad namespace comonad instance : comonad (𝟭 C) := { ε := 𝟙 _, δ := 𝟙_ } end comonad end category_theory
ac9610a5340186adbafcc1fdba8d3b7f5134d728
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/reduceArity.lean
8e125db5ddf52799f4715213e7ea3d2ee6ae33c6
[ "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
356
lean
import Lean open Lean Compiler LCNF @[noinline] def double (x : Nat) := x + x set_option pp.funBinderTypes true set_option trace.Compiler.result true in def g (n : Nat) (a b : α) (f : α → α) := match n with | 0 => a | n+1 => f (g n a b f) set_option trace.Compiler.result true in def h (n : Nat) (a : Nat) := g n a a double + g a n n double
d20f1734bb3304b3a2c1bc93834a3c75b429842a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/protectedAlias.lean
cd2781c72028eaf12843db3ad392d45e6dd627f7
[ "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
234
lean
protected def Nat.double (x : Nat) := 2*x namespace Ex export Nat (double) -- Add alias Ex.double for Nat.double end Ex open Ex #check Ex.double -- Ok #check double -- Error, `Ex.double` is alias for `Nat.double` which is protected
af184bfbf9ea703c174a34a381871163afd0403a
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.3.lean
041e67ac959504872acc76d6e5a92c999e012e2c
[]
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
229
lean
/- page 33 -/ import standard namespace hide constant implies : Prop → Prop → Prop constant Proof : Prop → Type -- BEGIN constant modus_ponens (p q : Prop) : Proof (implies p q) → Proof p → Proof q -- END end hide
f729fa4b8ef00c0d36a19d85ad3d1f2016b8f98f
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/order/filter/basic.lean
4c16563997198aa1a2acd34a9329e7530771cc5b
[ "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
103,447
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, Jeremy Avigad -/ import order.zorn import order.copy import data.set.finite import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 @[simp] lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets @[simp] lemma inter_mem_sets_iff {s t} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f := ⟨λ h, ⟨mem_sets_of_superset h (inter_subset_left s t), mem_sets_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem_sets⟩ lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ @[simp] lemma bInter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs]) @[simp] lemma bInter_finset_mem_sets {β : Type v} {s : β → set α} (is : finset β) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := bInter_mem_sets is.finite_to_set alias bInter_finset_mem_sets ← finset.Inter_mem_sets attribute [protected] finset.Inter_mem_sets @[simp] lemma sInter_mem_sets {s : set (set α)} (hfin : finite s) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by rw [sInter_eq_bInter, bInter_mem_sets hfin] @[simp] lemma Inter_mem_sets {β : Type v} {s : β → set α} [fintype β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f := by simpa using bInter_mem_sets finite_univ lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', `[dsimp only [set.mem_set_of_eq]], match e' with | some e := interactive.exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.refl _ end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, subset.trans hinter hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u h, generate_sets.basic h, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f, ∃t₂∈g, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ assume s hs, by simp [mem_top_sets.1 hs]) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ 𝓟) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ @[class] def ne_bot (f : filter α) := f ≠ ⊥ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := hf @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_not lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ne_bot_of_le_ne_bot hf hg lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_sets_of_superset hs (subset_union_left s t), mem_sets_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ supr_range lemma mem_infi_iff {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : {i | i ∈ I} → set α, (∀ i, V i ∈ s i) ∧ (⋂ i, V i) ⊆ U := begin rw [infi_eq_generate, mem_generate_iff], split, { rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, let V := λ i, ⋂₀ σ i, have V_in : ∀ i, V i ∈ s i, { rintro ⟨i, i_in⟩, rw sInter_mem_sets (σfin _), apply σsub }, exact ⟨I, Ifin, V, V_in, tinter⟩ }, { rintro ⟨I, Ifin, V, V_in, h⟩, refine ⟨range V, _, _, h⟩, { rintro _ ⟨i, rfl⟩, rw mem_Union, use [i, V_in i] }, { haveI : fintype {i : ι | i ∈ I} := finite.fintype Ifin, exact finite_range _ } }, end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ /-! ### Lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma nonempty_of_mem_sets {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_in_sets_eq_bot.mp hf)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem_sets α f hf s hs @[simp] lemma empty_nmem_sets (f : filter α) [ne_bot f] : ¬(∅ ∈ f) := λ h, (nonempty_of_mem_sets h).ne_empty rfl lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem_sets (univ_mem_sets : univ ∈ f) lemma compl_not_mem_sets {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f := λ hsc, (nonempty_of_mem_sets (inter_mem_sets h hsc)).ne_empty $ inter_compl_self s lemma filter_eq_bot_of_not_nonempty (f : filter α) (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot_sets), @nonempty_of_mem_sets _ _⟩ lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α := ⟨λ ⟨⟨f, g, hfg⟩⟩, by_contra $ λ h, hfg $ (filter_eq_bot_of_not_nonempty f h).trans (filter_eq_bot_of_not_nonempty g h).symm, λ ⟨x⟩, ⟨⟨⊤, ⊥, forall_sets_nonempty_iff_ne_bot.1 $ λ s hs, by rwa [mem_top_sets.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩⟩ lemma mem_sets_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := have ∅ ∈ f ⊓ 𝓟 sᶜ, from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : sᶜ ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := ext $ λ t, by simp [mem_binfi h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset ι, (⨅i∈t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := by rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp]; refl lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset ι, s ∈ ⨅i∈t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset (plift ι), s ∈ ⨅i∈t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup_sets, mem_join_sets] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_join_sets] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup_left (infi_le _ _) _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := begin intro h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃i, ∅ ∈ f i, from (mem_infi hd ∅).1 he, exact hb i (empty_in_sets_eq_bot.1 hi) end /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else assume h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x) lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀i, ne_bot (f i) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀i, ne_bot (f i)) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup_sets, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, 𝓟 (s x)) = 𝓟 (⋃i, s i) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_principal_sets, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_in_sets_eq_bot.symm.trans $ mem_principal_sets.trans subset_empty_iff @[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : sᶜ ∈ f) : f ⊓ 𝓟 s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal_sets, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, 𝓟 (f i)) = 𝓟 (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, 𝓟 (f i)) = 𝓟 (⋂i, f i) := by simpa using infi_principal_finset finset.univ f end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_sets_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot @[simp] lemma eventually_const {f : filter α} [ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h]) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_sets_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := inter_mem_sets_iff lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_all {ι} [fintype ι] {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by simpa only [filter.eventually, set_of_forall] using Inter_mem_sets @[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) := by simpa only [filter.eventually, set_of_forall] using bInter_mem_sets hI alias eventually_all_finite ← set.finite.eventually_all attribute [protected] set.finite.eventually_all @[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := I.finite_to_set.eventually_all alias eventually_all_finset ← finset.eventually_all attribute [protected] finset.eventually_all @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr_sets @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := compl_not_mem_sets h lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl lemma eventually_eq.rfl {l : filter α} {f : α → β} : f =ᶠ[l] f := eventually_eq.refl l f @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (function.uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := eventually_eq.rfl.le lemma eventually_le.rfl : f ≤ᶠ[l] f := eventually_le.refl l f @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ @[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) := h'.mp $ h.mono $ λ x, and.imp @[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) := h'.mp $ h.mono $ λ x, or.imp @[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) : (tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) := h.mono $ λ x, mt @[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : t' ≤ᶠ[l] s') : (s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma image_mem_map_iff (hf : function.injective m) : m '' s ∈ map m f ↔ s ∈ f := ⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩ lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_id' : filter.map (λ x, x) f = f := map_id @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_sets_of_superset t_in, rintros y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := begin classical, erw [← not_iff_not, not_not, not_not, filter.eventually_comap], simp only [not_exists, not_and], end end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure_sets, mem_principal_sets, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β, pure_bind, bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map, mem_join_sets, mem_set_of_eq, function.comp, mem_pure_sets] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f.sets ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintros ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem_sets] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := le_antisymm map_comap_le (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt) lemma image_mem_sets {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap h, exact image_mem_map W_in end lemma image_coe_mem_sets {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_sets (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : function.injective m) : comap m (map m f) = f := le_antisymm (assume s hs, mem_sets_of_superset (preimage_mem_comap $ image_mem_map hs) $ by simp only [preimage_image_eq s h]) le_comap_map lemma mem_comap_iff {f : filter β} {m : α → β} (inj : function.injective m) (large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f := by rw [← image_mem_map_iff inj, map_comap large] lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : l ≤ map f (comap f l) := assume s ⟨t, tl, ht⟩, have t ∩ u ⊆ s, from assume x ⟨xt, xu⟩, exists.elim (hf x xu) $ λ a faeq, by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt }, mem_sets_of_superset (inter_mem_sets tl ul) this theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf) theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : l ≤ map f (comap f l) := le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y) theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective hf l) lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := begin apply le_antisymm, { rw [map_le_iff_le_comap, comap_inf, comap_principal], have : (coe : s → α) ⁻¹' s = univ, by { ext x, simp }, rw [this, principal_univ], simp [le_refl _] }, { intros V V_in, rcases V_in with ⟨W, W_in, H⟩, rw mem_inf_sets, use [W, W_in, s, mem_principal_self s], erw [← image_subset_iff, subtype.image_preimage_coe] at H, exact H } end lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := let φ (x : s × s) : s.prod s := ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩ in begin rw show (coe : s × s → α × α) = coe ∘ φ, by ext x; cases x; refl, rw [← filter.map_map, ← filter.comap_comap], rw map_comap_of_surjective, exact subtype_coe_map_comap _ _, exact λ ⟨⟨a, b⟩, ⟨ha, hb⟩⟩, ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩ end lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_sets_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.refl _⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m := by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm] lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ (range m)ᶜ ∉ f := comap_ne_bot_iff_frequently lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot_iff_frequently.2 $ eventually.frequently hm lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine compl_compl s ▸ mt mem_sets_of_eq_bot _, rintros ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : function.surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem_sets' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_sets_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := not_congr map_eq_bot_iff lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [mem_infi hf, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (assume s hs, _), simp only [mem_inf_sets, exists_prop, mem_map, mem_preimage, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀ s ∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintros U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, rw ← image_subset_iff at h, use [f '' V, image_mem_map V_in, Z, Z_in], refine subset.trans _ h, have : f '' (V ∩ f ⁻¹' Z) ⊆ f '' (V ∩ W), from image_subset _ (inter_subset_inter_right _ ‹_›), rwa image_inter_preimage at this } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : function.injective (pure : α → filter α) := assume a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := mt empty_in_sets_eq_bot.2 $ not_mem_empty a @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure_sets, λ h s hs, mem_sets_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩) (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, exact singleton_mem_pure_sets }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs singleton_mem_pure_sets }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind_sets' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join_sets, mem_bind_sets', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind_sets, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse_sets : ∀(fs : list β') (us : list γ'), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃us:list (set α'), forall₂ (λb (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure_sets, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma le_map_of_right_inverse {mab : α → β} {mba : β → α} {f : filter α} {g : filter β} (h₁ : mab ∘ mba =ᶠ[g] id) (h₂ : tendsto mba g f) : g ≤ map mab f := by { rw [← @map_id _ g, ← map_congr h₁, ← map_map], exact map_mono h₂ } lemma tendsto_of_not_nonempty {f : α → β} {la : filter α} {lb : filter β} (h : ¬nonempty α) : tendsto f la lb := by simp only [filter_eq_bot_of_not_nonempty la h, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := le_trans (map_mono h) hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, tendsto_comap.comp h, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅i, x i) y := hi.mono_left $ infi_le _ _ lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map, filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map, mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λx, b) a (pure b) := tendsto_pure.2 $ univ_mem_sets' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot hb.eq_bot lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ 𝓟 p) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin revert h₀ h₁, simp only [tendsto_def, mem_inf_principal], intros h₀ h₁ s hs, apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)), rintros x ⟨hp₀, hp₁⟩, simp only [mem_preimage], by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅i, f i) ×ᶠ g = (⨅i, (f i) ×ᶠ g) := by rw [filter.prod, comap_infi, infi_inf]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅i, g i) = (⨅i, f ×ᶠ (g i)) := by rw [filter.prod, comap_infi, inf_infi]; simp only [filter.prod, eq_self_iff_true] @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λp:β×α, (p.2, p.1)) (g ×ᶠ f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma prod_map_map_eq' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) (F : filter α₁) (G : filter β₁) : (map f F) ×ᶠ (map g G) = map (prod.map f g) (F ×ᶠ G) := by { rw filter.prod_map_map_eq, refl } lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma pure_prod {a : α} {f : filter β} : pure a ×ᶠ f = map (prod.mk a) f := by rw [prod_eq, map_pure, pure_seq_eq_map] @[simp] lemma prod_pure {f : filter α} {b : β} : f ×ᶠ pure b = map (λ a, (a, b)) f := by rw [prod_eq, seq_pure, map_map] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := (not_congr prod_eq_bot).trans not_or_distrib lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β} (h : eq_on f g s) (hl : s ∈ l) : f =ᶠ[l] g := h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl lemma set.subset.eventually_le {α} {l : filter α} {s t : set α} (h : s ⊆ t) : s ≤ᶠ[l] t := filter.eventually_of_forall h
113c3b6f13f1cb79d5e7b30e8bc8bab0759606b9
9cba98daa30c0804090f963f9024147a50292fa0
/old/geom3d_series.lean
9e219a6d8dbd68d60dbe3c20794d5bad3b0ce2cd
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
24,366
lean
import .geom3d import ..time.time open_locale affine section foo universes u variables {tf : time_frame} (ts : time_space tf ) /- All proofs are commented out for now -/ abbreviation non_negative_time := time ts-- // x.coord >= 0} /-@[ext] structure geom3d_series {tf : time_frame} (ts : time_space tf ) := (series: list (non_negative_time ts)) -/ @[ext] structure geom3d_series {tf : time_frame} (ts : time_space tf ) := (series: list (non_negative_time ts × geom3d_frame)) --(ordered : ∀ i j : fin series.length, i<j → (series.nth_le i sorry).fst.val.coord > (series.nth_le j sorry).fst.val.coord) /--/ Multiple constraints so we don't have to deal with options. We just want to guarantee that when instantiating a timestamped vector with a series of frames, there definitionally will be a frame available that the vector satisfies. This is a reasonable expectation. Maybe double check with Dr. Elbaum -/ --(non_empty: series.length > 0) -- (has_zero: ∃ i : fin series.length, (series.nth_le i sorry).fst.val.coord = 0) /- def geom3d_series.insert {tf : time_frame} {ts : time_space tf } : geom3d_series ts → (non_negative_time ts × geom3d_frame) → geom3d_series ts | (⟨[],_,_,_⟩) tup := sorry | (⟨h::[],_,_,_⟩) tup := (⟨tup::h::[],sorry,sorry,sorry⟩) | (⟨h::t,_,_,_⟩) tup := if h.fst.val.coord > tup.fst.val.coord then let tail_call := geom3d_series.insert (⟨t,sorry,sorry,sorry⟩) tup in ⟨h::tail_call.series,sorry,sorry,sorry⟩ else ⟨tup::h::t,sorry,sorry,sorry⟩ -/ def geom3d_series.insert {tf : time_frame} {ts : time_space tf } : geom3d_series ts → (non_negative_time ts × geom3d_frame) → geom3d_series ts | (⟨[]⟩) tup := sorry | (⟨h::[]⟩) tup := (⟨tup::h::[]⟩) | (⟨h::t⟩) tup := if h.fst.coord > tup.fst.coord then let tail_call := geom3d_series.insert (⟨t⟩) tup in ⟨h::tail_call.series⟩ else ⟨tup::h::t⟩ @[simp,reducible] def find_helper : non_negative_time ts → list (non_negative_time ts × geom3d_frame) → (non_negative_time ts × geom3d_frame) | t_ ([]) := (mk_time _ 0, geom3d_std_frame) | t_ (h::[]) := h | t_ (h::t) := if t_.coord > h.fst.coord then h else find_helper t_ t @[simp,reducible] def geom3d_series.find {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : non_negative_time ts) := (find_helper ts t s.series).snd @[simp,reducible] def geom3d_series.find_space {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : non_negative_time ts) := spc.single (s.find t) @[simp,reducible] def geom3d_series.find_index {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : non_negative_time ts) := (find_helper ts t s.series).fst structure series_index (s : geom3d_series ts) := (idx : non_negative_time ts) instance index_is_setoid {s : geom3d_series ts} : setoid (series_index ts s) --there are infinite geom3d_space "types" := ⟨ λidx1 idx2, (s.find_index idx1.idx) = (s.find_index idx2.idx), sorry ⟩ #check @index_is_setoid def lift_si (ser : geom3d_series ts) : series_index ts ser → time ts := λsi, (ser.find_index si.idx) def lift_ {ser : geom3d_series ts} := quotient.lift (lift_si ts ser ) begin dsimp [has_equiv.equiv], unfold lift_si, unfold setoid.r, -- unfold index_rel, intros a b c, exact c, end @[simp,reducible] def find_helper'' { s : geom3d_series ts} : (quotient (@index_is_setoid tf ts s )) → list (non_negative_time ts × geom3d_frame) → (non_negative_time ts × geom3d_frame) | t_ ([]) := (mk_time _ 0, geom3d_std_frame) | t_ (h::[]) := h | t_ (h::t) := if (lift_ ts t_).coord > h.fst.coord then h else find_helper'' t_ t @[simp,reducible] def geom3d_series.find'' {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : quotient (@index_is_setoid tf ts s )) := (find_helper'' ts t s.series).snd @[simp,reducible] def geom3d_series.find_space'' {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : quotient (@index_is_setoid tf ts s )) := spc.single (s.find'' t) @[simp,reducible] def geom3d_series.find_index'' {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : quotient (@index_is_setoid tf ts s )) := (find_helper'' ts t s.series).fst @[simp,reducible] def find_helper' { s : geom3d_series ts} : (series_index ts s) → list (non_negative_time ts × geom3d_frame) → (non_negative_time ts × geom3d_frame) | t_ ([]) := (mk_time _ 0, geom3d_std_frame) | t_ (h::[]) := h | t_ (h::t) := if t_.idx.coord > h.fst.coord then h else find_helper' t_ t @[simp,reducible] def geom3d_series.find' {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : series_index ts s) := (find_helper' ts t s.series).snd @[simp,reducible] def geom3d_series.find_space' {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : series_index ts s) := spc.single (s.find' t) @[simp,reducible] def geom3d_series.find_index' {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : series_index ts s) := (find_helper' ts t s.series).fst /- inductive geom3d_rel (series : geom3d_series ts) : time ts → time ts → Prop | () -/ @[simp, reducible] def mk_displacement3d_timefixed_at_time {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : non_negative_time ts) (k₁ k₂ k₃ : scalar) := displacement3d.mk (mk_vectr (s.find_space t) ⟨[k₁,k₂,k₃],rfl⟩) @[simp, reducible] def mk_displacement3d_timefixed_at_time' {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : series_index ts s) (k₁ k₂ k₃ : scalar) := displacement3d.mk (mk_vectr (s.find_space' t) ⟨[k₁,k₂,k₃],rfl⟩) @[simp, reducible] def mk_displacement3d_timefixed_at_time'' {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : quotient (@index_is_setoid tf ts s )) (k₁ k₂ k₃ : scalar) := displacement3d.mk (mk_vectr (s.find_space'' t) ⟨[k₁,k₂,k₃],rfl⟩) /- def geom3d_series.insert {tf : time_frame} {ts : time_space tf } : geom3d_series ts → (non_negative_time ts × geom3d_frame) → geom3d_series ts | (⟨[]⟩) tup := sorry | (⟨h::[]⟩) tup := (⟨tup::h::[]⟩) | (⟨h::t⟩) tup := if h.fst.coord > tup.fst.coord then let tail_call := geom3d_series.insert (⟨t⟩) tup in ⟨h::tail_call.series⟩ else ⟨tup::h::t⟩ @[simp] def find_helper : non_negative_time ts → list (non_negative_time ts) → (non_negative_time ts) | t_ ([]) := (mk_time _ 0) | t_ (h::[]) := h | t_ (h::t) := if t_.coord > h.coord then h else find_helper t_ t @[simp] def geom3d_series.find {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : non_negative_time ts) := (find_helper ts t s.series).snd @[simp] def geom3d_series.find_space {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : non_negative_time ts) := spc.single (s.find t) @[simp] def geom3d_series.find_index {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : non_negative_time ts) := (find_helper ts t s.series) -/ /- inductive geom3d_rel (series : geom3d_series ts) : time ts → time ts → Prop | () -/ @[simp] def mk_displacement3d_timefixed_at_time {tf : time_frame} {ts : time_space tf } (s : geom3d_series ts) (t : non_negative_time ts) (k₁ k₂ k₃ : scalar) := displacement3d.mk (mk_vectr (s.find_space t) ⟨[k₁,k₂,k₃],rfl⟩) /- structure series_index (s : geom3d_series ts) := (idx : non_negative_time ts) def index_rel {s : geom3d_series ts} : series_index ts s → series_index ts s → Prop := λidx1 idx2, (s.find_index idx1.idx) = (s.find_index idx2.idx) instance idx_is_setoid {s : geom3d_series ts} : setoid (series_index ts s) --there are infinite geom3d_space "types" := ⟨ index_rel ts, sorry ⟩ -/ instance {s : geom3d_series ts} : has_equiv (series_index ts s) := by apply_instance /- instance {s : geom3d_series ts} : has_equiv (series_index ts s) := ⟨ index_rel ts ⟩-/ structure position3d_timefixed {f : geom3d_frame} (s : geom3d_space f ) extends point s @[ext] lemma position3d_timefixed.ext : ∀ {f : geom3d_frame} {s : geom3d_space f } (x y : position3d_timefixed s), x.to_point = y.to_point → x = y := begin intros f s x y e, cases x, cases y, simp *, have h₁ : ({to_point := x} : position3d_timefixed s).to_point = x := rfl, simp [h₁] at e, exact e end def position3d_timefixed.coords {f : geom3d_frame} {s : geom3d_space f } (t :position3d_timefixed s) := t.to_point.coords def position3d_timefixed.x {f : geom3d_frame} {s : geom3d_space f } (t :position3d_timefixed s) : scalar := (t.to_point.coords 0).coord def position3d_timefixed.y {f : geom3d_frame} {s : geom3d_space f } (t :position3d_timefixed s) : scalar := (t.to_point.coords 1).coord def position3d_timefixed.z {f : geom3d_frame} {s : geom3d_space f } (t :position3d_timefixed s) : scalar := (t.to_point.coords 2).coord @[simp] def mk_position3d_timefixed' {f : geom3d_frame} (s : geom3d_space f ) (p : point s) : position3d_timefixed s := position3d_timefixed.mk p @[simp] def mk_position3d_timefixed {f : geom3d_frame} (s : geom3d_space f ) (k₁ k₂ k₃ : scalar) : position3d_timefixed s := position3d_timefixed.mk (mk_point s ⟨[k₁,k₂,k₃],rfl⟩) @[simp] def mk_position3d_timefixed'' {f1 f2 f3 : geom1d_frame } { s1 : geom1d_space f1} {s2 : geom1d_space f2} { s3 : geom1d_space f3} (p1 : position1d s1) (p2 : position1d s2) (p3 : position1d s3 ) : position3d_timefixed (mk_prod_spc (mk_prod_spc s1 s2) s3) := ⟨mk_point_prod (mk_point_prod p1.to_point p2.to_point) p3.to_point⟩ structure displacement3d_timefixed {f : geom3d_frame} (s : geom3d_space f ) extends vectr s @[ext] lemma displacement3d_timefixed.ext : ∀ {f : geom3d_frame} {s : geom3d_space f } (x y : displacement3d_timefixed s), x.to_vectr = y.to_vectr → x = y := begin intros f s x y e, cases x, cases y, simp *, have h₁ : ({to_vectr := x} : displacement3d_timefixed s).to_vectr = x := rfl, simp [h₁] at e, exact e end def displacement3d_timefixed.coords {f : geom3d_frame} {s : geom3d_space f } (d :displacement3d_timefixed s) := d.to_vectr.coords @[simp] def mk_displacement3d_timefixed' {f : geom3d_frame} (s : geom3d_space f ) (v : vectr s) : displacement3d_timefixed s := displacement3d_timefixed.mk v @[simp] def mk_displacement3d_timefixed {f : geom3d_frame} (s : geom3d_space f ) (k₁ k₂ k₃ : scalar) : displacement3d_timefixed s := displacement3d_timefixed.mk (mk_vectr s ⟨[k₁,k₂,k₃],rfl⟩) @[simp] def mk_displacement3d_timefixed'' {f1 f2 f3 : geom1d_frame } { s1 : geom1d_space f1} {s2 : geom1d_space f2} { s3 : geom1d_space f3} (p1 : displacement1d s1) (p2 : displacement1d s2) (p3 : displacement1d s3 ) : displacement3d_timefixed (mk_prod_spc (mk_prod_spc s1 s2) s3) := ⟨mk_vectr_prod (mk_vectr_prod p1.to_vectr p2.to_vectr) p3.to_vectr⟩ @[simp] def mk_geom3d_frame {parent : geom3d_frame} {s : spc scalar parent} (p : position3d_timefixed s) (v0 : displacement3d_timefixed s) (v1 : displacement3d_timefixed s) (v2 : displacement3d_timefixed s) : geom3d_frame := (mk_frame p.to_point ⟨(λi, if i = 0 then v0.to_vectr else if i = 1 then v1.to_vectr else v2.to_vectr),sorry,sorry⟩) end foo section bar /- ************************************* Instantiate module scalar (vector scalar) ************************************* -/ namespace geom3d variables {f : geom3d_frame} {s : geom3d_space f } @[simp] def add_displacement3d_timefixed_displacement3d_timefixed (v3 v2 : displacement3d_timefixed s) : displacement3d_timefixed s := mk_displacement3d_timefixed' s (v3.to_vectr + v2.to_vectr) @[simp] def smul_displacement3d_timefixed (k : scalar) (v : displacement3d_timefixed s) : displacement3d_timefixed s := mk_displacement3d_timefixed' s (k • v.to_vectr) @[simp] def neg_displacement3d_timefixed (v : displacement3d_timefixed s) : displacement3d_timefixed s := mk_displacement3d_timefixed' s ((-1 : scalar) • v.to_vectr) @[simp] def sub_displacement3d_timefixed_displacement3d_timefixed (v3 v2 : displacement3d_timefixed s) : displacement3d_timefixed s := -- v3-v2 add_displacement3d_timefixed_displacement3d_timefixed v3 (neg_displacement3d_timefixed v2) instance has_add_displacement3d_timefixed : has_add (displacement3d_timefixed s) := ⟨ add_displacement3d_timefixed_displacement3d_timefixed ⟩ lemma add_assoc_displacement3d_timefixed : ∀ a b c : displacement3d_timefixed s, a + b + c = a + (b + c) := begin intros, ext, --cases a, repeat { have p3 : (a + b + c).to_vec = a.to_vec + b.to_vec + c.to_vec := rfl, have p2 : (a + (b + c)).to_vec = a.to_vec + (b.to_vec + c.to_vec) := rfl, rw [p3,p2], cc }, admit end instance add_semigroup_displacement3d_timefixed : add_semigroup (displacement3d_timefixed s) := ⟨ add_displacement3d_timefixed_displacement3d_timefixed, add_assoc_displacement3d_timefixed⟩ @[simp] def displacement3d_timefixed_zero := mk_displacement3d_timefixed s 0 0 0 instance has_zero_displacement3d_timefixed : has_zero (displacement3d_timefixed s) := ⟨displacement3d_timefixed_zero⟩ lemma zero_add_displacement3d_timefixed : ∀ a : displacement3d_timefixed s, 0 + a = a := begin intros,--ext, ext, admit, -- let h0 : (0 + a).to_vec = (0 : vectr s).to_vec + a.to_vec := rfl, --simp [h0], --exact zero_add _, --exact zero_add _, end lemma add_zero_displacement3d_timefixed : ∀ a : displacement3d_timefixed s, a + 0 = a := begin intros,ext, admit, --exact add_zero _, --exact add_zero _, end @[simp] def nsmul_displacement3d_timefixed : ℕ → (displacement3d_timefixed s) → (displacement3d_timefixed s) | nat.zero v := displacement3d_timefixed_zero --| 3 v := v | (nat.succ n) v := (add_displacement3d_timefixed_displacement3d_timefixed) v (nsmul_displacement3d_timefixed n v) instance add_monoid_displacement3d_timefixed : add_monoid (displacement3d_timefixed s) := ⟨ -- add_semigroup add_displacement3d_timefixed_displacement3d_timefixed, add_assoc_displacement3d_timefixed, -- has_zero displacement3d_timefixed_zero, -- new structure @zero_add_displacement3d_timefixed f s, add_zero_displacement3d_timefixed, nsmul_displacement3d_timefixed ⟩ instance has_neg_displacement3d_timefixed : has_neg (displacement3d_timefixed s) := ⟨neg_displacement3d_timefixed⟩ instance has_sub_displacement3d_timefixed : has_sub (displacement3d_timefixed s) := ⟨ sub_displacement3d_timefixed_displacement3d_timefixed⟩ lemma sub_eq_add_neg_displacement3d_timefixed : ∀ a b : displacement3d_timefixed s, a - b = a + -b := begin intros,ext, refl, end instance sub_neg_monoid_displacement3d_timefixed : sub_neg_monoid (displacement3d_timefixed s) := { neg := neg_displacement3d_timefixed , ..(show add_monoid (displacement3d_timefixed s), by apply_instance) } lemma add_left_neg_displacement3d_timefixed : ∀ a : displacement3d_timefixed s, -a + a = 0 := begin intros, ext, /- repeat { have h0 : (-a + a).to_vec = -a.to_vec + a.to_vec := rfl, simp [h0], have : (0:vec scalar) = (0:displacement3d_timefixed s).to_vectr.to_vec := rfl, simp *, }-/ admit, end instance : add_group (displacement3d_timefixed s) := { add_left_neg := begin exact add_left_neg_displacement3d_timefixed, end, ..(show sub_neg_monoid (displacement3d_timefixed s), by apply_instance), } lemma add_comm_displacement3d_timefixed : ∀ a b : displacement3d_timefixed s, a + b = b + a := begin intros, ext, /-repeat { have p3 : (a + b).to_vec = a.to_vec + b.to_vec:= rfl, have p2 : (b + a).to_vec = b.to_vec + a.to_vec := rfl, rw [p3,p2], cc } -/ admit, end instance add_comm_semigroup_displacement3d_timefixed : add_comm_semigroup (displacement3d_timefixed s) := ⟨ -- add_semigroup add_displacement3d_timefixed_displacement3d_timefixed, add_assoc_displacement3d_timefixed, add_comm_displacement3d_timefixed, ⟩ instance add_comm_monoid_displacement3d_timefixed : add_comm_monoid (displacement3d_timefixed s) := { add_comm := begin exact add_comm_displacement3d_timefixed end, ..(show add_monoid (displacement3d_timefixed s), by apply_instance) } instance has_scalar_displacement3d_timefixed : has_scalar scalar (displacement3d_timefixed s) := ⟨ smul_displacement3d_timefixed, ⟩ lemma one_smul_displacement3d_timefixed : ∀ b : displacement3d_timefixed s, (1 : scalar) • b = b := begin intros,ext, /-repeat { have h0 : ((3:scalar) • b).to_vec = ((3:scalar)•(b.to_vec)) := rfl, rw [h0], simp *, }-/ admit, end lemma mul_smul_displacement3d_timefixed : ∀ (x y : scalar) (b : displacement3d_timefixed s), (x * y) • b = x • y • b := begin intros, cases b, ext, exact mul_assoc x y _, end instance mul_action_displacement3d_timefixed : mul_action scalar (displacement3d_timefixed s) := ⟨ one_smul_displacement3d_timefixed, mul_smul_displacement3d_timefixed, ⟩ lemma smul_add_displacement3d_timefixed : ∀(r : scalar) (x y : displacement3d_timefixed s), r • (x + y) = r • x + r • y := begin intros, ext, repeat { have h0 : (r • (x + y)).to_vec = (r • (x.to_vec + y.to_vec)) := rfl, have h3 : (r•x + r•y).to_vec = (r•x.to_vec + r•y.to_vec) := rfl, rw [h0,h3], simp *, } ,admit, end lemma smul_zero_displacement3d_timefixed : ∀(r : scalar), r • (0 : displacement3d_timefixed s) = 0 := begin admit--intros, ext, exact mul_zero _, exact mul_zero _ end instance distrib_mul_action_K_displacement3d_timefixed : distrib_mul_action scalar (displacement3d_timefixed s) := ⟨ smul_add_displacement3d_timefixed, smul_zero_displacement3d_timefixed, ⟩ -- renaming vs template due to clash with name "s" for prevailing variable lemma add_smul_displacement3d_timefixed : ∀ (a b : scalar) (x : displacement3d_timefixed s), (a + b) • x = a • x + b • x := begin intros, ext, exact right_distrib _ _ _, end lemma zero_smul_displacement3d_timefixed : ∀ (x : displacement3d_timefixed s), (0 : scalar) • x = 0 := begin intros, ext, admit,--exact zero_mul _, exact zero_mul _ end instance module_K_displacement3d_timefixed : module scalar (displacement3d_timefixed s) := ⟨ add_smul_displacement3d_timefixed, zero_smul_displacement3d_timefixed ⟩ instance add_comm_group_displacement3d_timefixed : add_comm_group (displacement3d_timefixed s) := { add_comm := begin exact add_comm_displacement3d_timefixed end, ..(show add_group (displacement3d_timefixed s), by apply_instance) } instance : module scalar (displacement3d_timefixed s) := @geom3d.module_K_displacement3d_timefixed f s /- ******************** *** Affine space *** ******************** -/ /- Affine operations -/ instance : has_add (displacement3d_timefixed s) := ⟨add_displacement3d_timefixed_displacement3d_timefixed⟩ instance : has_zero (displacement3d_timefixed s) := ⟨displacement3d_timefixed_zero⟩ instance : has_neg (displacement3d_timefixed s) := ⟨neg_displacement3d_timefixed⟩ /- Lemmas needed to implement affine space API -/ @[simp] def sub_position3d_timefixed_position3d_timefixed {f : geom3d_frame} {s : geom3d_space f } (p3 p2 : position3d_timefixed s) : displacement3d_timefixed s := mk_displacement3d_timefixed' s (p3.to_point -ᵥ p2.to_point) @[simp] def add_position3d_timefixed_displacement3d_timefixed {f : geom3d_frame} {s : geom3d_space f } (p : position3d_timefixed s) (v : displacement3d_timefixed s) : position3d_timefixed s := mk_position3d_timefixed' s (v.to_vectr +ᵥ p.to_point) -- reorder assumes order is irrelevant @[simp] def add_displacement3d_timefixed_position3d_timefixed {f : geom3d_frame} {s : geom3d_space f } (v : displacement3d_timefixed s) (p : position3d_timefixed s) : position3d_timefixed s := mk_position3d_timefixed' s (v.to_vectr +ᵥ p.to_point) --@[simp] --def aff_displacement3d_timefixed_group_action : displacement3d_timefixed s → position3d_timefixed s → position3d_timefixed s := add_displacement3d_timefixed_position3d_timefixed scalar instance : has_vadd (displacement3d_timefixed s) (position3d_timefixed s) := ⟨add_displacement3d_timefixed_position3d_timefixed⟩ lemma zero_displacement3d_timefixed_vadd'_a3 : ∀ p : position3d_timefixed s, (0 : displacement3d_timefixed s) +ᵥ p = p := begin intros, ext,--exact zero_add _, admit--exact add_zero _ end lemma displacement3d_timefixed_add_assoc'_a3 : ∀ (g3 g2 : displacement3d_timefixed s) (p : position3d_timefixed s), g3 +ᵥ (g2 +ᵥ p) = (g3 + g2) +ᵥ p := begin intros, ext, repeat { have h0 : (g3 +ᵥ (g2 +ᵥ p)).to_pt = (g3.to_vec +ᵥ (g2.to_vec +ᵥ p.to_pt)) := rfl, have h3 : (g3 + g2 +ᵥ p).to_pt = (g3.to_vec +ᵥ g2.to_vec +ᵥ p.to_pt) := rfl, rw [h0,h3], simp *, simp [has_vadd.vadd, has_add.add, add_semigroup.add, add_zero_class.add, add_monoid.add, sub_neg_monoid.add, add_group.add, distrib.add, ring.add, division_ring.add], cc, }, admit, end instance displacement3d_timefixed_add_action: add_action (displacement3d_timefixed s) (position3d_timefixed s) := ⟨ zero_displacement3d_timefixed_vadd'_a3, begin let h0 := displacement3d_timefixed_add_assoc'_a3, intros, exact (h0 g₁ g₂ p).symm end⟩ --@[simp] --def aff_geom3d_group_sub : position3d_timefixed s → position3d_timefixed s → displacement3d_timefixed s := sub_geom3d_position3d_timefixed scalar instance position3d_timefixed_has_vsub : has_vsub (displacement3d_timefixed s) (position3d_timefixed s) := ⟨ sub_position3d_timefixed_position3d_timefixed⟩ instance : nonempty (position3d_timefixed s) := ⟨mk_position3d_timefixed s 0 0 0⟩ lemma position3d_timefixed_vsub_vadd_a3 : ∀ (p3 p2 : (position3d_timefixed s)), (p3 -ᵥ p2) +ᵥ p2 = p3 := begin /-intros, ext, --repeat { have h0 : (p3 -ᵥ p2 +ᵥ p2).to_pt = (p3.to_pt -ᵥ p2.to_pt +ᵥ p2.to_pt) := rfl, rw h0, simp [has_vsub.vsub, has_sub.sub, sub_neg_monoid.sub, add_group.sub, add_comm_group.sub, ring.sub, division_ring.sub], simp [has_vadd.vadd, has_add.add, distrib.add, ring.add, division_ring.add], let h0 : field.add p2.to_pt.to_prod.fst (field.sub p3.to_pt.to_prod.fst p2.to_pt.to_prod.fst) = field.add (field.sub p3.to_pt.to_prod.fst p2.to_pt.to_prod.fst) p2.to_pt.to_prod.fst := add_comm _ _, rw h0, exact sub_add_cancel _ _, have h0 : (p3 -ᵥ p2 +ᵥ p2).to_pt = (p3.to_pt -ᵥ p2.to_pt +ᵥ p2.to_pt) := rfl, rw h0, simp [has_vsub.vsub, has_sub.sub, sub_neg_monoid.sub, add_group.sub, add_comm_group.sub, ring.sub, division_ring.sub], simp [has_vadd.vadd, has_add.add, distrib.add, ring.add, division_ring.add], let h0 : field.add p2.to_pt.to_prod.snd (field.sub p3.to_pt.to_prod.snd p2.to_pt.to_prod.snd) = field.add (field.sub p3.to_pt.to_prod.snd p2.to_pt.to_prod.snd) p2.to_pt.to_prod.snd := add_comm _ _, rw h0, exact sub_add_cancel _ _,-/ admit end lemma position3d_timefixed_vadd_vsub_a3 : ∀ (g : displacement3d_timefixed s) (p : position3d_timefixed s), g +ᵥ p -ᵥ p = g := begin intros, ext, repeat { have h0 : ((g +ᵥ p -ᵥ p) : displacement3d_timefixed s).to_vectr = (g.to_vectr +ᵥ p.to_point -ᵥ p.to_point) := rfl, rw h0, simp *, } end instance aff_geom3d_torsor' : add_torsor (displacement3d_timefixed s) (position3d_timefixed s) := ⟨ begin exact position3d_timefixed_vsub_vadd_a3, end, begin exact position3d_timefixed_vadd_vsub_a3, end, ⟩ open_locale affine instance : affine_space (displacement3d_timefixed s) (position3d_timefixed s) := @geom3d.aff_geom3d_torsor' f s end geom3d -- ha ha end bar
ddd1b8e773c29c7b195f6486be5b8c7aadcbf72b
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/bernstein.lean
e26be5fe949374dfcfeaeb34b4979d091380f51e
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
12,833
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 analysis.specific_limits.basic import ring_theory.polynomial.bernstein import topology.continuous_function.polynomial import topology.continuous_function.compact /-! # Bernstein approximations and Weierstrass' theorem We prove that the Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. Our proof follows [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D. The original proof, due to [Bernstein](bernstein1912) in 1912, is probabilistic, and relies on Bernoulli's theorem, which gives bounds for how quickly the observed frequencies in a Bernoulli trial approach the underlying probability. The proof here does not directly rely on Bernoulli's theorem, but can also be given a probabilistic account. * Consider a weighted coin which with probability `x` produces heads, and with probability `1-x` produces tails. * The value of `bernstein n k x` is the probability that such a coin gives exactly `k` heads in a sequence of `n` tosses. * If such an appearance of `k` heads results in a payoff of `f(k / n)`, the `n`-th Bernstein approximation for `f` evaluated at `x` is the expected payoff. * The main estimate in the proof bounds the probability that the observed frequency of heads differs from `x` by more than some `δ`, obtaining a bound of `(4 * n * δ^2)⁻¹`, irrespective of `x`. * This ensures that for `n` large, the Bernstein approximation is (uniformly) close to the payoff function `f`. (You don't need to think in these terms to follow the proof below: it's a giant `calc` block!) This result proves Weierstrass' theorem that polynomials are dense in `C([0,1], ℝ)`, although we defer an abstract statement of this until later. -/ noncomputable theory open_locale classical open_locale big_operators open_locale bounded_continuous_function open_locale unit_interval /-- The Bernstein polynomials, as continuous functions on `[0,1]`. -/ def bernstein (n ν : ℕ) : C(I, ℝ) := (bernstein_polynomial ℝ n ν).to_continuous_map_on I @[simp] lemma bernstein_apply (n ν : ℕ) (x : I) : bernstein n ν x = n.choose ν * x^ν * (1-x)^(n-ν) := begin dsimp [bernstein, polynomial.to_continuous_map_on, polynomial.to_continuous_map, bernstein_polynomial], simp, end lemma bernstein_nonneg {n ν : ℕ} {x : I} : 0 ≤ bernstein n ν x := begin simp only [bernstein_apply], exact mul_nonneg (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (by unit_interval) _)) (pow_nonneg (by unit_interval) _), end /-! We now give a slight reformulation of `bernstein_polynomial.variance`. -/ namespace bernstein /-- Send `k : fin (n+1)` to the equally spaced points `k/n` in the unit interval. -/ def z {n : ℕ} (k : fin (n+1)) : I := ⟨(k : ℝ) / n, begin cases n, { norm_num }, { have h₁ : 0 < (n.succ : ℝ) := by exact_mod_cast (nat.succ_pos _), have h₂ : ↑k ≤ n.succ := by exact_mod_cast (fin.le_last k), rw [set.mem_Icc, le_div_iff h₁, div_le_iff h₁], norm_cast, simp [h₂], }, end⟩ local postfix `/ₙ`:90 := z lemma probability (n : ℕ) (x : I) : ∑ k : fin (n+1), bernstein n k x = 1 := begin have := bernstein_polynomial.sum ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range] at this, exact this, end lemma variance {n : ℕ} (h : 0 < (n : ℝ)) (x : I) : ∑ k : fin (n+1), (x - k/ₙ : ℝ)^2 * bernstein n k x = x * (1-x) / n := begin have h' : (n : ℝ) ≠ 0 := ne_of_gt h, apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', apply_fun (λ x : ℝ, x * n) using group_with_zero.mul_right_injective h', dsimp, conv_lhs { simp only [finset.sum_mul, z], }, conv_rhs { rw div_mul_cancel _ h', }, have := bernstein_polynomial.variance ℝ n, apply_fun (λ p, polynomial.aeval (x : ℝ) p) at this, simp [alg_hom.map_sum, finset.sum_range, ←polynomial.nat_cast_mul] at this, convert this using 1, { congr' 1, funext k, rw [mul_comm _ (n : ℝ), mul_comm _ (n : ℝ), ←mul_assoc, ←mul_assoc], congr' 1, field_simp [h], ring, }, { ring, }, end end bernstein open bernstein local postfix `/ₙ`:2000 := z /-- The `n`-th approximation of a continuous function on `[0,1]` by Bernstein polynomials, given by `∑ k, f (k/n) * bernstein n k x`. -/ def bernstein_approximation (n : ℕ) (f : C(I, ℝ)) : C(I, ℝ) := ∑ k : fin (n+1), f k/ₙ • bernstein n k /-! We now set up some of the basic machinery of the proof that the Bernstein approximations converge uniformly. A key player is the set `S f ε h n x`, for some function `f : C(I, ℝ)`, `h : 0 < ε`, `n : ℕ` and `x : I`. This is the set of points `k` in `fin (n+1)` such that `k/n` is within `δ` of `x`, where `δ` is the modulus of uniform continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. We show that if `k ∉ S`, then `1 ≤ δ^-2 * (x - k/n)^2`. -/ namespace bernstein_approximation @[simp] lemma apply (n : ℕ) (f : C(I, ℝ)) (x : I) : bernstein_approximation n f x = ∑ k : fin (n+1), f k/ₙ * bernstein n k x := by simp [bernstein_approximation] /-- The modulus of (uniform) continuity for `f`, chosen so `|f x - f y| < ε/2` when `|x - y| < δ`. -/ def δ (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) : ℝ := f.modulus (ε/2) (half_pos h) lemma δ_pos {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} : 0 < δ f ε h := f.modulus_pos /-- The set of points `k` so `k/n` is within `δ` of `x`. -/ def S (f : C(I, ℝ)) (ε : ℝ) (h : 0 < ε) (n : ℕ) (x : I) : finset (fin (n+1)) := { k : fin (n+1) | dist k/ₙ x < δ f ε h }.to_finset /-- If `k ∈ S`, then `f(k/n)` is close to `f x`. -/ lemma lt_of_mem_S {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ S f ε h n x) : |f k/ₙ - f x| < ε/2 := begin apply f.dist_lt_of_dist_lt_modulus (ε/2) (half_pos h), simpa [S] using m, end /-- If `k ∉ S`, then as `δ ≤ |x - k/n|`, we have the inequality `1 ≤ δ^-2 * (x - k/n)^2`. This particular formulation will be helpful later. -/ lemma le_of_mem_S_compl {f : C(I, ℝ)} {ε : ℝ} {h : 0 < ε} {n : ℕ} {x : I} {k : fin (n+1)} (m : k ∈ (S f ε h n x)ᶜ) : (1 : ℝ) ≤ (δ f ε h)^(-2 : ℤ) * (x - k/ₙ) ^ 2 := begin simp only [finset.mem_compl, not_lt, set.mem_to_finset, set.mem_set_of_eq, S] at m, rw [zpow_neg, ← div_eq_inv_mul, zpow_two, ←pow_two, one_le_div (pow_pos δ_pos 2), sq_le_sq, abs_of_pos δ_pos], rwa [dist_comm] at m end end bernstein_approximation open bernstein_approximation open bounded_continuous_function open filter open_locale topology /-- The Bernstein approximations ``` ∑ k : fin (n+1), f (k/n : ℝ) * n.choose k * x^k * (1-x)^(n-k) ``` for a continuous function `f : C([0,1], ℝ)` converge uniformly to `f` as `n` tends to infinity. This is the proof given in [Richard Beals' *Analysis, an introduction*][beals-analysis], §7D, and reproduced on wikipedia. -/ theorem bernstein_approximation_uniform (f : C(I, ℝ)) : tendsto (λ n : ℕ, bernstein_approximation n f) at_top (𝓝 f) := begin simp only [metric.nhds_basis_ball.tendsto_right_iff, metric.mem_ball, dist_eq_norm], intros ε h, let δ := δ f ε h, have nhds_zero := tendsto_const_div_at_top_nhds_0_nat (2 * ‖f‖ * δ ^ (-2 : ℤ)), filter_upwards [nhds_zero.eventually (gt_mem_nhds (half_pos h)), eventually_gt_at_top 0] with n nh npos', have npos : 0 < (n:ℝ) := by exact_mod_cast npos', -- Two easy inequalities we'll need later: have w₁ : 0 ≤ 2 * ‖f‖ := mul_nonneg (by norm_num) (norm_nonneg f), have w₂ : 0 ≤ 2 * ‖f‖ * δ^(-2 : ℤ) := mul_nonneg w₁ (zpow_neg_two_nonneg _), -- As `[0,1]` is compact, it suffices to check the inequality pointwise. rw (continuous_map.norm_lt_iff _ h), intro x, -- The idea is to split up the sum over `k` into two sets, -- `S`, where `x - k/n < δ`, and its complement. let S := S f ε h n x, calc |(bernstein_approximation n f - f) x| = |bernstein_approximation n f x - f x| : rfl ... = |bernstein_approximation n f x - f x * 1| : by rw mul_one ... = |bernstein_approximation n f x - f x * (∑ k : fin (n+1), bernstein n k x)| : by rw bernstein.probability ... = |∑ k : fin (n+1), (f k/ₙ - f x) * bernstein n k x| : by simp [bernstein_approximation, finset.mul_sum, sub_mul] ... ≤ ∑ k : fin (n+1), |(f k/ₙ - f x) * bernstein n k x| : finset.abs_sum_le_sum_abs _ _ ... = ∑ k : fin (n+1), |f k/ₙ - f x| * bernstein n k x : by simp_rw [abs_mul, abs_eq_self.mpr bernstein_nonneg] ... = ∑ k in S, |f k/ₙ - f x| * bernstein n k x + ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x : (S.sum_add_sum_compl _).symm -- We'll now deal with the terms in `S` and the terms in `Sᶜ` in separate calc blocks. ... < ε/2 + ε/2 : add_lt_add_of_le_of_lt _ _ ... = ε : add_halves ε, { -- We now work on the terms in `S`: uniform continuity and `bernstein.probability` -- quickly give us a bound. calc ∑ k in S, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in S, ε/2 * bernstein n k x : finset.sum_le_sum (λ k m, (mul_le_mul_of_nonneg_right (le_of_lt (lt_of_mem_S m)) bernstein_nonneg)) ... = ε/2 * ∑ k in S, bernstein n k x : by rw finset.mul_sum -- In this step we increase the sum over `S` back to a sum over all of `fin (n+1)`, -- so that we can use `bernstein.probability`. ... ≤ ε/2 * ∑ k : fin (n+1), bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, bernstein_nonneg)) (le_of_lt (half_pos h)) ... = ε/2 : by rw [bernstein.probability, mul_one] }, { -- We now turn to working on `Sᶜ`: we control the difference term just using `‖f‖`, -- and then insert a `δ^(-2) * (x - k/n)^2` factor -- (which is at least one because we are not in `S`). calc ∑ k in Sᶜ, |f k/ₙ - f x| * bernstein n k x ≤ ∑ k in Sᶜ, (2 * ‖f‖) * bernstein n k x : finset.sum_le_sum (λ k m, mul_le_mul_of_nonneg_right (f.dist_le_two_norm _ _) bernstein_nonneg) ... = (2 * ‖f‖) * ∑ k in Sᶜ, bernstein n k x : by rw finset.mul_sum ... ≤ (2 * ‖f‖) * ∑ k in Sᶜ, δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_sum (λ k m, begin conv_lhs { rw ←one_mul (bernstein _ _ _), }, exact mul_le_mul_of_nonneg_right (le_of_mem_S_compl m) bernstein_nonneg, end)) w₁ -- Again enlarging the sum from `Sᶜ` to all of `fin (n+1)` ... ≤ (2 * ‖f‖) * ∑ k : fin (n+1), δ^(-2 : ℤ) * (x - k/ₙ)^2 * bernstein n k x : mul_le_mul_of_nonneg_left (finset.sum_le_univ_sum_of_nonneg (λ k, mul_nonneg (mul_nonneg (zpow_neg_two_nonneg _) (sq_nonneg _)) bernstein_nonneg)) w₁ ... = (2 * ‖f‖) * δ^(-2 : ℤ) * ∑ k : fin (n+1), (x - k/ₙ)^2 * bernstein n k x : by conv_rhs { rw [mul_assoc, finset.mul_sum], simp only [←mul_assoc], } -- `bernstein.variance` and `x ∈ [0,1]` gives the uniform bound ... = (2 * ‖f‖) * δ^(-2 : ℤ) * x * (1-x) / n : by { rw variance npos, ring, } ... ≤ (2 * ‖f‖) * δ^(-2 : ℤ) / n : (div_le_div_right npos).mpr $ by refine mul_le_of_le_of_le_one' (mul_le_of_le_one_right w₂ _) _ _ w₂; unit_interval ... < ε/2 : nh, } end
d56f4d5171d2d1898fc724467b2930f3fd470678
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/982.lean
1f1271ecf0e878415759c9abe803348bb6d6666b
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
298
lean
import data.nat open nat constant P : nat → Prop example (Hex : ∃ n, P n) : true := obtain n Hn, from Hex, begin+ note Hn2 := Hn, exact trivial end example (Hex : ∃ n, P n) : true := obtain n Hn, from Hex, begin+ have H : n ≥ 0, from sorry, exact trivial end
37d6b51a57fbfc1ad703864c752c6478b6fe85ef
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/category/Kleisli.lean
b93a59c63de4db852eba300760cd9a00cd425734
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,244
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon The Kleisli construction on the Type category TODO: generalise this to work with category_theory.monad -/ import category_theory.category universes u v namespace category_theory def Kleisli (m) [monad.{u v} m] := Type u def Kleisli.mk (m) [monad.{u v} m] (α : Type u) : Kleisli m := α instance Kleisli.category_struct {m} [monad m] : category_struct (Kleisli m) := { hom := λ α β, α → m β, id := λ α x, (pure x : m α), comp := λ X Y Z f g, f >=> g } instance Kleisli.category {m} [monad m] [is_lawful_monad m] : category (Kleisli m) := by refine { hom := λ α β, α → m β, id := λ α x, (pure x : m α), comp := λ X Y Z f g, f >=> g, id_comp' := _, comp_id' := _, assoc' := _ }; intros; ext; simp only [(>=>)] with functor_norm @[simp] lemma Kleisli.id_def {m} [monad m] [is_lawful_monad m] (α : Kleisli m) : 𝟙 α = @pure m _ α := rfl lemma Kleisli.comp_def {m} [monad m] [is_lawful_monad m] (α β γ : Kleisli m) (xs : α ⟶ β) (ys : β ⟶ γ) (a : α) : (xs ≫ ys) a = xs a >>= ys := rfl end category_theory
f9cfad1ec5f1cd3a23c11289b69ce700062f7e2f
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/finsupp.lean
533caf150664dc1005b11a8a200f946800191792
[ "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
41,062
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finsupp.defs import linear_algebra.pi import linear_algebra.span /-! # Properties of the module `α →₀ M` Given an `R`-module `M`, the `R`-module structure on `α →₀ M` is defined in `data.finsupp.basic`. In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}` interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps: * `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map; * `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map; * `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a linear map; * `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`; * `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`; * `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with coefficients `l i`; * `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s` and codomain `submodule.span R (v '' s)`; * `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported on `s` and the functions `s →₀ M`; * `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`; * `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`; * `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to `supported M R t`; * `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃ β` and `e' : M ≃ₗ[R] N`. ## Tags function with finite support, module, linear algebra -/ noncomputable theory open set linear_map submodule open_locale classical big_operators namespace finsupp variables {α : Type*} {M : Type*} {N : Type*} {P : Type*} {R : Type*} {S : Type*} variables [semiring R] [semiring S] [add_comm_monoid M] [module R M] variables [add_comm_monoid N] [module R N] variables [add_comm_monoid P] [module R P] /-- Interpret `finsupp.single a` as a linear map. -/ def lsingle (a : α) : M →ₗ[R] (α →₀ M) := { map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a } /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) : φ = ψ := lhom_ext $ λ a, linear_map.congr_fun (h a) /-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/ def lapply (a : α) : (α →₀ M) →ₗ[R] M := { map_smul' := assume a b, rfl, ..finsupp.apply_add_hom a } section lsubtype_domain variables (s : set α) /-- Interpret `finsupp.subtype_domain s` as a linear map. -/ def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := { to_fun := subtype_domain (λx, x ∈ s), map_add' := λ a b, subtype_domain_add, map_smul' := λ c a, ext $ λ 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 : (α →₀ M) →ₗ[R] M)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, set_like.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 [set_like.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 $ set_like.le_def.2 $ assume f _, _), rw [← sum_single f], exact sum_mem (assume a ha, submodule.mem_supr_of_mem a ⟨_, rfl⟩), 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 : M →ₗ[R] (α →₀ M)).range) := begin refine disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (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_of_right_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_of_left_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 : M →ₗ[R] (α →₀ M)) := 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 }, _, _, _ ⟩, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { 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 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 mem_supported_support (p : α →₀ M) : p ∈ finsupp.supported M R (p.support : set α) := by rw finsupp.mem_supported 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 _ _ (set_like.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) →ₗ[R] 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) →ₗ[R] 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 = ⊤ := range_eq_top.2 $ function.right_inverse.surjective $ linear_map.congr_fun (restrict_dom_comp_subtype s) theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, apply finsupp.induction l, { exact zero_mem _ }, refine λ x a l hl a0, add_mem _, by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff] theorem supported_inter (s t : set α) : supported M R (s ∩ t) = supported M R s ⊓ supported M R t := by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) : disjoint (supported M R s) (supported M R t) := disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty] theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} : disjoint (supported M R s) (supported M R t) ↔ disjoint s t := begin refine ⟨λ h x hx, _, disjoint_supported_supported⟩, rcases exists_ne (0 : M) with ⟨y, hy⟩, have := h ⟨single_mem_supported R y hx.1, single_mem_supported R y hx.2⟩, rw [mem_bot, single_eq_zero] at this, exact hy this end /-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between `supported M R s` and `s →₀ M`. -/ def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := begin let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M, refine F.to_linear_equiv _, have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))) := rfl, rw this, exact linear_map.is_linear _ end section lsum variables (S) [module S N] [smul_comm_class R S N] /-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to `N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ def lsum : (α → M →ₗ[R] N) ≃ₗ[S] ((α →₀ M) →ₗ[R] N) := { to_fun := λ F, { to_fun := λ d, d.sum (λ i, F i), map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add, map_smul' := λ c f, by simp [sum_smul_index', smul_sum] }, inv_fun := λ F x, F.comp (lsingle x), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp }, map_smul' := λ F G, by { ext x y, simp } } @[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum S f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) : finsupp.lsum S f l = l.sum (λ b, f b) := rfl theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) : finsupp.lsum S f (finsupp.single i m) = f i m := finsupp.sum_single_index (f i).map_zero theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) : (lsum S).symm f x = f.comp (lsingle x) := rfl end lsum section variables (M) (R) (X : Type*) /-- A slight rearrangement from `lsum` gives us the bijection underlying the free-forgetful adjunction for R-modules. -/ noncomputable def lift : (X → M) ≃+ ((X →₀ R) →ₗ[R] M) := (add_equiv.arrow_congr (equiv.refl X) (ring_lmap_equiv_self R ℕ M).to_add_equiv.symm).trans (lsum _ : _ ≃ₗ[ℕ] _).to_add_equiv @[simp] lemma lift_symm_apply (f) (x) : ((lift M R X).symm f) x = f (single x 1) := rfl @[simp] lemma lift_apply (f) (g) : ((lift M R X) f) g = g.sum (λ x r, r • f x) := rfl end section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) /-- Interpret `finsupp.map_domain` as a linear map. -/ def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := { to_fun := map_domain f, map_add' := λ a b, map_domain_add, map_smul' := 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) →ₗ[R] α →₀ 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 [set_like.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'] [module 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) →ₗ[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 apply_total (f : M →ₗ[R] M') (v) (l : α →₀ R) : f (finsupp.total α M R v l) = finsupp.total α M' R (f ∘ v) l := by apply finsupp.induction_linear l; simp { contextual := tt, } theorem total_unique [unique α] (l : α →₀ R) (v) : finsupp.total α M R v l = l default • v default := by rw [← total_single, ← unique_single l] lemma total_surjective (h : function.surjective v) : function.surjective (finsupp.total α M R v) := begin intro x, obtain ⟨y, hy⟩ := h x, exact ⟨finsupp.single y 1, by simp [hy]⟩ end theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := range_eq_top.2 $ total_surjective R h /-- Any module is a quotient of a free module. This is stated as surjectivity of `finsupp.total M M R id : (M →₀ R) →ₗ[R] M`. -/ lemma total_id_surjective (M) [add_comm_monoid M] [module R M] : function.surjective (finsupp.total M M R id) := total_surjective R function.surjective_id 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, exact sum_mem (λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i))) }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [set_like.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] @[simp] 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 @[simp] theorem total_equiv_map_domain (f : α ≃ α') (l : α →₀ R) : (finsupp.total α' M' R v') (equiv_map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by rw [equiv_map_domain_eq_map_domain, total_map_domain _ _ f.injective] /-- A version of `finsupp.range_total` which is useful for going in the other direction -/ theorem span_eq_range_total (s : set M) : span R s = (finsupp.total s M R coe).range := by rw [range_total, subtype.range_coe_subtype, set.set_of_mem_eq] theorem mem_span_iff_total (s : set M) (x : M) : x ∈ span R s ↔ ∃ l : s →₀ R, finsupp.total s M R coe l = x := (set_like.ext_iff.1 $ span_eq_range_total _ _) x theorem span_image_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_image_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_image_eq_map_total, simp, } lemma total_option (v : option α → M) (f : option α →₀ R) : finsupp.total (option α) M R v f = f none • v none + finsupp.total α M R (v ∘ option.some) f.some := by rw [total_apply, sum_option_index_smul, total_apply] lemma total_total {α β : Type*} (A : α → M) (B : β → (α →₀ R)) (f : β →₀ R) : finsupp.total α M R A (finsupp.total β (α →₀ R) R B f) = finsupp.total β M R (λ b, finsupp.total α M R A (B b)) f := begin simp only [total_apply], apply induction_linear f, { simp only [sum_zero_index], }, { intros f₁ f₂ h₁ h₂, simp [sum_add_index, h₁, h₂, add_smul], }, { simp [sum_single_index, sum_smul_index, smul_sum, mul_smul], } end @[simp] lemma total_fin_zero (f : fin 0 → M) : finsupp.total (fin 0) M R f = 0 := by { ext i, apply fin_zero_elim i } 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_image_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := begin rw [finsupp.total_on, linear_map.range_eq_map, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype], exact (span_image_eq_map_total _ _).le end theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := by { ext, simp [total_apply] } 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. This is `finsupp.dom_congr` as a `linear_equiv`. See also `linear_map.fun_congr_left` for the case of arbitrary functions. -/ protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv $ by simpa only [equiv_map_domain_eq_map_domain, dom_congr_apply] using (lmap_domain M R e).map_smul @[simp] lemma dom_lcongr_apply {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (v : α₁ →₀ M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) v = finsupp.dom_congr e v := rfl @[simp] lemma dom_lcongr_refl : finsupp.dom_lcongr (equiv.refl α) = linear_equiv.refl R (α →₀ M) := linear_equiv.ext $ λ _, equiv_map_domain_refl _ lemma dom_lcongr_trans {α₁ α₂ α₃ : Type*} (f : α₁ ≃ α₂) (f₂ : α₂ ≃ α₃) : (finsupp.dom_lcongr f).trans (finsupp.dom_lcongr f₂) = (finsupp.dom_lcongr (f.trans f₂) : (_ →₀ M) ≃ₗ[R] _) := linear_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm @[simp] lemma dom_lcongr_symm {α₁ α₂ : Type*} (f : α₁ ≃ α₂) : ((finsupp.dom_lcongr f).symm : (_ →₀ M) ≃ₗ[R] _) = finsupp.dom_lcongr f.symm := linear_equiv.ext $ λ x, rfl @[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, equiv_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 (finsupp.supported_equiv_finsupp s) ≪≫ₗ (_ ≪≫ₗ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end /-- `finsupp.map_range` as a `linear_map`. -/ @[simps] def map_range.linear_map (f : M →ₗ[R] N) : (α →₀ M) →ₗ[R] (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_smul' := λ c v, map_range_smul c v (f.map_smul c), ..map_range.add_monoid_hom f.to_add_monoid_hom } @[simp] lemma map_range.linear_map_id : map_range.linear_map linear_map.id = (linear_map.id : (α →₀ M) →ₗ[R] _):= linear_map.ext map_range_id lemma map_range.linear_map_comp (f : N →ₗ[R] P) (f₂ : M →ₗ[R] N) : (map_range.linear_map (f.comp f₂) : (α →₀ _) →ₗ[R] _) = (map_range.linear_map f).comp (map_range.linear_map f₂) := linear_map.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.linear_map_to_add_monoid_hom (f : M →ₗ[R] N) : (map_range.linear_map f).to_add_monoid_hom = (map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ M) →+ _):= add_monoid_hom.ext $ λ _, rfl /-- `finsupp.map_range` as a `linear_equiv`. -/ @[simps apply] def map_range.linear_equiv (e : M ≃ₗ[R] N) : (α →₀ M) ≃ₗ[R] (α →₀ N) := { to_fun := map_range e e.map_zero, inv_fun := map_range e.symm e.symm.map_zero, ..map_range.linear_map e.to_linear_map, ..map_range.add_equiv e.to_add_equiv} @[simp] lemma map_range.linear_equiv_refl : map_range.linear_equiv (linear_equiv.refl R M) = linear_equiv.refl R (α →₀ M) := linear_equiv.ext map_range_id lemma map_range.linear_equiv_trans (f : M ≃ₗ[R] N) (f₂ : N ≃ₗ[R] P) : (map_range.linear_equiv (f.trans f₂) : (α →₀ _) ≃ₗ[R] _) = (map_range.linear_equiv f).trans (map_range.linear_equiv f₂) := linear_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.linear_equiv_symm (f : M ≃ₗ[R] N) : ((map_range.linear_equiv f).symm : (α →₀ _) ≃ₗ[R] _) = map_range.linear_equiv f.symm := linear_equiv.ext $ λ x, rfl @[simp] lemma map_range.linear_equiv_to_add_equiv (f : M ≃ₗ[R] N) : (map_range.linear_equiv f).to_add_equiv = (map_range.add_equiv f.to_add_equiv : (α →₀ M) ≃+ _):= add_equiv.ext $ λ _, rfl @[simp] lemma map_range.linear_equiv_to_linear_map (f : M ≃ₗ[R] N) : (map_range.linear_equiv f).to_linear_map = (map_range.linear_map f.to_linear_map : (α →₀ M) →ₗ[R] _):= linear_map.ext $ λ _, rfl /-- 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 (map_range.linear_equiv e₂) @[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] @[simp] lemma lcongr_apply_apply {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (f : ι →₀ M) (k : κ) : lcongr e₁ e₂ f k = e₂ (f (e₁.symm k)) := rfl theorem lcongr_symm_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (k : κ) (n : N) : (lcongr e₁ e₂).symm (finsupp.single k n) = finsupp.single (e₁.symm k) (e₂.symm n) := begin apply_fun lcongr e₁ e₂ using (lcongr e₁ e₂).injective, simp, end @[simp] lemma lcongr_symm {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (lcongr e₁ e₂).symm = lcongr e₁.symm e₂.symm := begin ext f i, simp only [equiv.symm_symm, finsupp.lcongr_apply_apply], apply finsupp.induction_linear f, { simp, }, { intros f g hf hg, simp [map_add, hf, hg], }, { intros k m, simp only [finsupp.lcongr_symm_single], simp only [finsupp.single, equiv.symm_apply_eq, finsupp.coe_mk], split_ifs; simp, }, end section sum variables (R) /-- The linear equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `linear_equiv` version of `finsupp.sum_finsupp_equiv_prod_finsupp`. -/ @[simps apply symm_apply] def sum_finsupp_lequiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃ₗ[R] (α →₀ M) × (β →₀ M) := { map_smul' := by { intros, ext; simp only [add_equiv.to_fun_eq_coe, prod.smul_fst, prod.smul_snd, smul_apply, snd_sum_finsupp_add_equiv_prod_finsupp, fst_sum_finsupp_add_equiv_prod_finsupp, ring_hom.id_apply] }, .. sum_finsupp_add_equiv_prod_finsupp } lemma fst_sum_finsupp_lequiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_lequiv_prod_finsupp R f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_lequiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_lequiv_prod_finsupp R f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_lequiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : ((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_lequiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : ((sum_finsupp_lequiv_prod_finsupp R).symm fg) (sum.inr y) = fg.2 y := rfl end sum section sigma variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] variables (R) /-- On a `fintype η`, `finsupp.split` is a linear equivalence between `(Σ (j : η), ιs j) →₀ M` and `Π j, (ιs j →₀ M)`. This is the `linear_equiv` version of `finsupp.sigma_finsupp_add_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_lequiv_pi_finsupp {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] : ((Σ j, ιs j) →₀ M) ≃ₗ[R] Π j, (ιs j →₀ M) := { map_smul' := λ c f, by { ext, simp }, .. sigma_finsupp_add_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_lequiv_pi_finsupp_apply {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] (f : (Σ j, ιs j) →₀ M) (j i) : sigma_finsupp_lequiv_pi_finsupp R f j i = f ⟨j, i⟩ := rfl @[simp] lemma sigma_finsupp_lequiv_pi_finsupp_symm_apply {M : Type*} {ιs : η → Type*} [add_comm_monoid M] [module R M] (f : Π j, (ιs j →₀ M)) (ji) : (finsupp.sigma_finsupp_lequiv_pi_finsupp R).symm f ji = f ji.1 ji.2 := rfl end sigma section prod /-- The linear equivalence between `α × β →₀ M` and `α →₀ β →₀ M`. This is the `linear_equiv` version of `finsupp.finsupp_prod_equiv`. -/ noncomputable def finsupp_prod_lequiv {α β : Type*} (R : Type*) {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : (α × β →₀ M) ≃ₗ[R] (α →₀ β →₀ M) := { map_add' := λ f g, by { ext, simp [finsupp_prod_equiv, curry_apply] }, map_smul' := λ c f, by { ext, simp [finsupp_prod_equiv, curry_apply] }, .. finsupp_prod_equiv } @[simp] lemma finsupp_prod_lequiv_apply {α β R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (f : α × β →₀ M) (x y) : finsupp_prod_lequiv R f x y = f (x, y) := by rw [finsupp_prod_lequiv, linear_equiv.coe_mk, finsupp_prod_equiv, finsupp.curry_apply] @[simp] lemma finsupp_prod_lequiv_symm_apply {α β R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (f : α →₀ β →₀ M) (xy) : (finsupp_prod_lequiv R).symm f xy = f xy.1 xy.2 := by conv_rhs { rw [← (finsupp_prod_lequiv R).apply_symm_apply f, finsupp_prod_lequiv_apply, prod.mk.eta] } end prod end finsupp section fintype variables {α M : Type*} (R : Type*) [fintype α] [semiring R] [add_comm_monoid M] [module R M] variables (S : Type*) [semiring S] [module S M] [smul_comm_class R S M] variable (v : α → M) /-- `fintype.total R S v f` is the linear combination of vectors in `v` with weights in `f`. This variant of `finsupp.total` is defined on fintype indexed vectors. This map is linear in `v` if `R` is commutative, and always linear in `f`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ protected def fintype.total : (α → M) →ₗ[S] (α → R) →ₗ[R] M := { to_fun := λ v, { to_fun := λ f, ∑ i, f i • v i, map_add' := λ f g, by { simp_rw [← finset.sum_add_distrib, ← add_smul], refl }, map_smul' := λ r f, by { simp_rw [finset.smul_sum, smul_smul], refl } }, map_add' := λ u v, by { ext, simp [finset.sum_add_distrib, pi.add_apply, smul_add] }, map_smul' := λ r v, by { ext, simp [finset.smul_sum, smul_comm _ r] } } variables {S} lemma fintype.total_apply (f) : fintype.total R S v f = ∑ i, f i • v i := rfl @[simp] lemma fintype.total_apply_single (i : α) (r : R) : fintype.total R S v (pi.single i r) = r • v i := begin simp_rw [fintype.total_apply, pi.single_apply, ite_smul, zero_smul], rw [finset.sum_ite_eq', if_pos (finset.mem_univ _)] end variables (S) lemma finsupp.total_eq_fintype_total_apply (x : α → R) : finsupp.total α M R v ((finsupp.linear_equiv_fun_on_fintype R R α).symm x) = fintype.total R S v x := begin apply finset.sum_subset, { exact finset.subset_univ _ }, { intros x _ hx, rw finsupp.not_mem_support_iff.mp hx, exact zero_smul _ _ } end lemma finsupp.total_eq_fintype_total : (finsupp.total α M R v).comp (finsupp.linear_equiv_fun_on_fintype R R α).symm.to_linear_map = fintype.total R S v := linear_map.ext $ finsupp.total_eq_fintype_total_apply R S v variables {S} @[simp] lemma fintype.range_total : (fintype.total R S v).range = submodule.span R (set.range v) := by rw [← finsupp.total_eq_fintype_total, linear_map.range_comp, linear_equiv.to_linear_map_eq_coe, linear_equiv.range, submodule.map_top, finsupp.range_total] end fintype variables {R : Type*} {M : Type*} {N : Type*} variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] section variables (R) /-- Pick some representation of `x : span R w` as a linear combination in `w`, using the axiom of choice. -/ def span.repr (w : set M) (x : span R w) : w →₀ R := ((finsupp.mem_span_iff_total _ _ _).mp x.2).some @[simp] lemma span.finsupp_total_repr {w : set M} (x : span R w) : finsupp.total w M R coe (span.repr R w x) = x := ((finsupp.mem_span_iff_total _ _ _).mp x.2).some_spec attribute [irreducible] span.repr end protected lemma submodule.finsupp_sum_mem {ι β : Type*} [has_zero β] (S : submodule R M) (f : ι →₀ β) (g : ι → β → M) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.sum g ∈ S := add_submonoid_class.finsupp_sum_mem S f g h 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 have := complete_lattice.is_compact_element.exists_finset_of_le_supr (submodule R M) (submodule.singleton_span_is_compact_element m) p, simp only [submodule.span_singleton_le_iff_mem] at this, exact this hm, end /-- `submodule.exists_finset_of_mem_supr` as an `iff` -/ lemma submodule.mem_supr_iff_exists_finset {ι : Sort*} {p : ι → submodule R M} {m : M} : (m ∈ ⨆ i, p i) ↔ ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := ⟨submodule.exists_finset_of_mem_supr p, λ ⟨_, hs⟩, supr_mono (λ i, (supr_const_le : _ ≤ p i)) hs⟩ 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_image_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)⟩ /-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if `m` can be written as a finite `R`-linear combination of elements of `s`. The implementation uses `finsupp.sum`. -/ lemma mem_span_set {m : M} {s : set M} : m ∈ submodule.span R s ↔ ∃ c : M →₀ R, (c.support : set M) ⊆ s ∧ c.sum (λ mi r, r • mi) = m := begin conv_lhs { rw ←set.image_id s }, simp_rw ←exists_prop, exact finsupp.mem_span_image_iff_total R, end /-- If `subsingleton R`, then `M ≃ₗ[R] ι →₀ R` for any type `ι`. -/ @[simps] def module.subsingleton_equiv (R M ι: Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [module R M] : M ≃ₗ[R] ι →₀ R := { to_fun := λ m, 0, inv_fun := λ f, 0, left_inv := λ m, by { letI := module.subsingleton R M, simp only [eq_iff_true_of_subsingleton] }, right_inv := λ f, by simp only [eq_iff_true_of_subsingleton], map_add' := λ m n, (add_zero 0).symm, map_smul' := λ r m, (smul_zero r).symm } namespace linear_map variables {R M} {α : Type*} open finsupp function /-- A surjective linear map to finitely supported functions has a splitting. -/ -- See also `linear_map.splitting_of_fun_on_fintype_surjective` def splitting_of_finsupp_surjective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : (α →₀ R) →ₗ[R] M := finsupp.lift _ _ _ (λ x : α, (s (finsupp.single x 1)).some) lemma splitting_of_finsupp_surjective_splits (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : f.comp (splitting_of_finsupp_surjective f s) = linear_map.id := begin ext x y, dsimp [splitting_of_finsupp_surjective], congr, rw [sum_single_index, one_smul], { exact (s (finsupp.single x 1)).some_spec, }, { rw zero_smul, }, end lemma left_inverse_splitting_of_finsupp_surjective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : left_inverse f (splitting_of_finsupp_surjective f s) := λ g, linear_map.congr_fun (splitting_of_finsupp_surjective_splits f s) g lemma splitting_of_finsupp_surjective_injective (f : M →ₗ[R] (α →₀ R)) (s : surjective f) : injective (splitting_of_finsupp_surjective f s) := (left_inverse_splitting_of_finsupp_surjective f s).injective /-- A surjective linear map to functions on a finite type has a splitting. -/ -- See also `linear_map.splitting_of_finsupp_surjective` def splitting_of_fun_on_fintype_surjective [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) : (α → R) →ₗ[R] M := (finsupp.lift _ _ _ (λ x : α, (s (finsupp.single x 1)).some)).comp (linear_equiv_fun_on_fintype R R α).symm.to_linear_map lemma splitting_of_fun_on_fintype_surjective_splits [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) : f.comp (splitting_of_fun_on_fintype_surjective f s) = linear_map.id := begin ext x y, dsimp [splitting_of_fun_on_fintype_surjective], rw [linear_equiv_fun_on_fintype_symm_single, finsupp.sum_single_index, one_smul, (s (finsupp.single x 1)).some_spec, finsupp.single_eq_pi_single], rw [zero_smul], end lemma left_inverse_splitting_of_fun_on_fintype_surjective [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) : left_inverse f (splitting_of_fun_on_fintype_surjective f s) := λ g, linear_map.congr_fun (splitting_of_fun_on_fintype_surjective_splits f s) g lemma splitting_of_fun_on_fintype_surjective_injective [fintype α] (f : M →ₗ[R] (α → R)) (s : surjective f) : injective (splitting_of_fun_on_fintype_surjective f s) := (left_inverse_splitting_of_fun_on_fintype_surjective f s).injective end linear_map
c41f86c17fd0ff326ca67f0d0697613d6c18ca9a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/power_series/well_known_auto.lean
eb49c36e416f7ab04eceedc22e4969003f8273f0
[]
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,236
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.power_series.basic import Mathlib.data.nat.parity import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Definition of well-known power series In this file we define the following power series: * `power_series.inv_units_sub`: given `u : units R`, this is the series for `1 / (u - x)`. It is given by `∑ n, x ^ n /ₚ u ^ (n + 1)`. * `power_series.sin`, `power_series.cos`, `power_series.exp` : power series for sin, cosine, and exponential functions. -/ namespace power_series /-- The power series for `1 / (u - x)`. -/ def inv_units_sub {R : Type u_1} [ring R] (u : units R) : power_series R := mk fun (n : ℕ) => 1 /ₚ u ^ (n + 1) @[simp] theorem coeff_inv_units_sub {R : Type u_1} [ring R] (u : units R) (n : ℕ) : coe_fn (coeff R n) (inv_units_sub u) = 1 /ₚ u ^ (n + 1) := coeff_mk n fun (n : ℕ) => 1 /ₚ u ^ (n + 1) @[simp] theorem constant_coeff_inv_units_sub {R : Type u_1} [ring R] (u : units R) : coe_fn (constant_coeff R) (inv_units_sub u) = 1 /ₚ u := sorry @[simp] theorem inv_units_sub_mul_X {R : Type u_1} [ring R] (u : units R) : inv_units_sub u * X = inv_units_sub u * coe_fn (C R) ↑u - 1 := sorry @[simp] theorem inv_units_sub_mul_sub {R : Type u_1} [ring R] (u : units R) : inv_units_sub u * (coe_fn (C R) ↑u - X) = 1 := sorry theorem map_inv_units_sub {R : Type u_1} {S : Type u_2} [ring R] [ring S] (f : R →+* S) (u : units R) : coe_fn (map f) (inv_units_sub u) = inv_units_sub (coe_fn (units.map ↑f) u) := sorry /-- Power series for the exponential function at zero. -/ def exp (A : Type u_1) [ring A] [algebra ℚ A] : power_series A := mk fun (n : ℕ) => coe_fn (algebra_map ℚ A) (1 / ↑(nat.factorial n)) /-- Power series for the sine function at zero. -/ def sin (A : Type u_1) [ring A] [algebra ℚ A] : power_series A := mk fun (n : ℕ) => ite (even n) 0 (coe_fn (algebra_map ℚ A) ((-1) ^ (n / bit0 1) / ↑(nat.factorial n))) /-- Power series for the cosine function at zero. -/ def cos (A : Type u_1) [ring A] [algebra ℚ A] : power_series A := mk fun (n : ℕ) => ite (even n) (coe_fn (algebra_map ℚ A) ((-1) ^ (n / bit0 1) / ↑(nat.factorial n))) 0 @[simp] theorem coeff_exp {A : Type u_1} [ring A] [algebra ℚ A] (n : ℕ) : coe_fn (coeff A n) (exp A) = coe_fn (algebra_map ℚ A) (1 / ↑(nat.factorial n)) := coeff_mk n fun (n : ℕ) => coe_fn (algebra_map ℚ A) (1 / ↑(nat.factorial n)) @[simp] theorem map_exp {A : Type u_1} {A' : Type u_2} [ring A] [ring A'] [algebra ℚ A] [algebra ℚ A'] (f : A →+* A') : coe_fn (map f) (exp A) = exp A' := sorry @[simp] theorem map_sin {A : Type u_1} {A' : Type u_2} [ring A] [ring A'] [algebra ℚ A] [algebra ℚ A'] (f : A →+* A') : coe_fn (map f) (sin A) = sin A' := sorry @[simp] theorem map_cos {A : Type u_1} {A' : Type u_2} [ring A] [ring A'] [algebra ℚ A] [algebra ℚ A'] (f : A →+* A') : coe_fn (map f) (cos A) = cos A' := sorry end Mathlib
d22d1b9d33e4e9f7cfdbe1460195d7094594bec3
1437b3495ef9020d5413178aa33c0a625f15f15f
/order/basic.lean
c6e10df532c71ab290f2ffccb215842a21e12665
[ "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
20,776
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import tactic.interactive logic.basic data.sum data.set.basic algebra.order open function /- TODO: automatic construction of dual definitions / theorems -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩ theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) := ⟨λ a b h₁ h₂, antisymm h₂ h₁⟩ theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) := ⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩ theorem is_total.swap (r) [is_total α r] : is_total α (swap r) := ⟨λ a b, (total_of r a b).swap⟩ theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩ theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) := {..@is_refl.swap α r _, ..@is_trans.swap α r _} theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..@is_irrefl.swap α r _, ..@is_trans.swap α r _} theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) := {..@is_preorder.swap α r _, ..@is_antisymm.swap α r _} theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) := {..@is_preorder.swap α r _, ..@is_total.swap α r _} theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) := {..@is_partial_order.swap α r _, ..@is_total.swap α r _} def antisymm_of_asymm (r) [is_asymm α r] : is_antisymm α r := ⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩ /- Convert algebraic structure style to explicit relation style typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ instance [preorder α] : is_refl α (≥) := is_refl.swap _ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ instance [preorder α] : is_trans α (≥) := is_trans.swap _ instance [preorder α] : is_preorder α (≤) := {} instance [preorder α] : is_preorder α (≥) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ instance [preorder α] : is_trans α (>) := is_trans.swap _ instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ instance [preorder α] : is_asymm α (>) := is_asymm.swap _ instance [preorder α] : is_antisymm α (<) := antisymm_of_asymm _ instance [preorder α] : is_antisymm α (>) := antisymm_of_asymm _ instance [preorder α] : is_strict_order α (<) := {} instance [preorder α] : is_strict_order α (>) := {} instance preorder.is_total_preorder [preorder α] [is_total α (≤)] : is_total_preorder α (≤) := {} instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _ instance [partial_order α] : is_partial_order α (≤) := {} instance [partial_order α] : is_partial_order α (≥) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ instance [linear_order α] : is_total α (≥) := is_total.swap _ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance instance [linear_order α] : is_total_preorder α (≥) := {} instance [linear_order α] : is_linear_order α (≤) := {} instance [linear_order α] : is_linear_order α (≥) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _ theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin resetI, cases A, cases B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := preorder.ext H; cases A; cases B; injection this; congr' theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := partial_order.ext H; cases A; cases B; injection this; congr' /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b theorem monotone_comp {f : α → β} {g : β → γ} (m_f : monotone f) (m_g : monotone g) : monotone (g ∘ f) := assume a b h, m_g (m_f h) end monotone def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, .. order_dual.has_le α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] [preorder γ] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f } def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj } def decidable_linear_order.lift {α β} [decidable_linear_order β] (f : α → β) (inj : injective f) : decidable_linear_order α := { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj } instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val $ λ x y, subtype.eq' instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val $ λ x y, subtype.eq' /- additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] {a₁ a₂ : α} (h : a₁ < a₂) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) := classical.or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ section variables {s : β → β → Prop} {t : γ → γ → Prop} theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ /-- Construct a partial order from a `is_strict_order` relation -/ def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } /-- This is basically the same as `is_strict_total_order`, but that definition is in Type (probably by mistake) and also has redundant assumptions. -/ @[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop. /-- Construct a linear order from a `is_strict_total_order'` relation -/ def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, ..partial_order_of_SO r } /-- Construct a decidable linear order from a `is_strict_total_order'` relation -/ def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α := by letI LO := linear_order_of_STO' r; exact { decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x), ..LO } noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO } theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} instance [linear_order α] : is_strict_total_order' α (<) := {} /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_irrefl_of_is_asymm α r _ } instance is_order_connected_of_is_strict_total_order' [is_strict_total_order' α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ instance is_strict_total_order_of_is_strict_total_order' [is_strict_total_order' α r] : is_strict_total_order α r := {..is_strict_weak_order_of_is_order_connected} instance [linear_order α] : is_strict_total_order α (<) := by apply_instance instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance /-- An extensional relation is one in which an element is determined by its set of predecessors. It is named for the `x ∈ y` relation in set theory, whose extensionality is one of the first axioms of ZFC. -/ @[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop := (ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b) instance is_extensional_of_is_strict_total_order' [is_strict_total_order' α r] : is_extensional α r := ⟨λ a b H, ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 (irrefl a)) .resolve_right $ mt (H _).1 (irrefl b)⟩ /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop := (wf : well_founded r) instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _, irrefl := λ a, id, trans := λ a b c, false.elim, wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ } instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩ instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous, irrefl := λ a, by cases a; simp; apply irrefl, trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans, wf := sum.lex_wf (is_well_order.wf r) (is_well_order.wf s) } instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h; [exact irrefl _ h, exact irrefl _ h], trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ _ (trans ab bc) }, { exact prod.lex.left _ _ _ ab }, { exact prod.lex.left _ _ _ bc }, { exact prod.lex.right _ _ (trans ab bc) } end, wf := prod.lex_wf (is_well_order.wf r) (is_well_order.wf s) } theorem well_founded.has_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) : p ≠ ∅ → ∃ a ∈ p, ∀ x ∈ p, ¬ r x a := by haveI := classical.prop_decidable; exact not_imp_comm.1 (λ he, set.eq_empty_iff_forall_not_mem.2 $ λ a, acc.rec_on (H.apply a) $ λ a H IH h, he ⟨_, h, λ y, imp_not_comm.1 (IH y)⟩) /-- The minimum element of a nonempty set in a well-founded order -/ noncomputable def well_founded.min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) : α := classical.some (H.has_min p h) theorem well_founded.min_mem {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) : H.min p h ∈ p := let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h theorem well_founded.not_lt_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p ≠ ∅) {x} (xp : x ∈ p) : ¬ r x (H.min p h) := let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp variable (r) local infix `≼` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) theorem directed_comp {ι} (f : ι → β) (g : β → α) : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl theorem directed_mono {s : α → α → Prop} {ι} (f : ι → α) (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ end
37be633d298b2911b3d4b212983c45c73e0dade4
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/gcd_monoid/multiset.lean
a5979fe6249a23b9a6d0d6662d4480882ace76b8
[ "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
6,746
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.gcd_monoid.basic import data.multiset.finset_ops import data.multiset.fold /-! # GCD and LCM operations on multisets ## Main definitions - `multiset.gcd` - the greatest common denominator of a `multiset` of elements of a `gcd_monoid` - `multiset.lcm` - the least common multiple of a `multiset` of elements of a `gcd_monoid` ## Implementation notes TODO: simplify with a tactic and `data.multiset.lattice` ## Tags multiset, gcd -/ namespace multiset variables {α : Type*} [cancel_comm_monoid_with_zero α] [normalized_gcd_monoid α] /-! ### lcm -/ section lcm /-- Least common multiple of a multiset -/ def lcm (s : multiset α) : α := s.fold gcd_monoid.lcm 1 @[simp] lemma lcm_zero : (0 : multiset α).lcm = 1 := fold_zero _ _ @[simp] lemma lcm_cons (a : α) (s : multiset α) : (a ::ₘ s).lcm = gcd_monoid.lcm a s.lcm := fold_cons_left _ _ _ _ @[simp] lemma lcm_singleton {a : α} : ({a} : multiset α).lcm = normalize a := (fold_singleton _ _ _).trans $ lcm_one_right _ @[simp] lemma lcm_add (s₁ s₂ : multiset α) : (s₁ + s₂).lcm = gcd_monoid.lcm s₁.lcm s₂.lcm := eq.trans (by simp [lcm]) (fold_add _ _ _ _ _) lemma lcm_dvd {s : multiset α} {a : α} : s.lcm ∣ a ↔ (∀ b ∈ s, b ∣ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib, lcm_dvd_iff] {contextual := tt}) lemma dvd_lcm {s : multiset α} {a : α} (h : a ∈ s) : a ∣ s.lcm := lcm_dvd.1 dvd_rfl _ h lemma lcm_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.lcm ∣ s₂.lcm := lcm_dvd.2 $ assume b hb, dvd_lcm (h hb) @[simp] lemma normalize_lcm (s : multiset α) : normalize (s.lcm) = s.lcm := multiset.induction_on s (by simp) $ λ a s IH, by simp @[simp] theorem lcm_eq_zero_iff [nontrivial α] (s : multiset α) : s.lcm = 0 ↔ (0 : α) ∈ s := begin induction s using multiset.induction_on with a s ihs, { simp only [lcm_zero, one_ne_zero, not_mem_zero] }, { simp only [mem_cons, lcm_cons, lcm_eq_zero_iff, ihs, @eq_comm _ a] }, end variables [decidable_eq α] @[simp] lemma lcm_dedup (s : multiset α) : (dedup s).lcm = s.lcm := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], unfold lcm, rw [← cons_erase h, fold_cons_left, ← lcm_assoc, lcm_same], apply lcm_eq_of_associated_left (associated_normalize _), end @[simp] lemma lcm_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).lcm = gcd_monoid.lcm s₁.lcm s₂.lcm := by { rw [← lcm_dedup, dedup_ext.2, lcm_dedup, lcm_add], simp } @[simp] lemma lcm_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).lcm = gcd_monoid.lcm s₁.lcm s₂.lcm := by { rw [← lcm_dedup, dedup_ext.2, lcm_dedup, lcm_add], simp } @[simp] lemma lcm_ndinsert (a : α) (s : multiset α) : (ndinsert a s).lcm = gcd_monoid.lcm a s.lcm := by { rw [← lcm_dedup, dedup_ext.2, lcm_dedup, lcm_cons], simp } end lcm /-! ### gcd -/ section gcd /-- Greatest common divisor of a multiset -/ def gcd (s : multiset α) : α := s.fold gcd_monoid.gcd 0 @[simp] lemma gcd_zero : (0 : multiset α).gcd = 0 := fold_zero _ _ @[simp] lemma gcd_cons (a : α) (s : multiset α) : (a ::ₘ s).gcd = gcd_monoid.gcd a s.gcd := fold_cons_left _ _ _ _ @[simp] lemma gcd_singleton {a : α} : ({a} : multiset α).gcd = normalize a := (fold_singleton _ _ _).trans $ gcd_zero_right _ @[simp] lemma gcd_add (s₁ s₂ : multiset α) : (s₁ + s₂).gcd = gcd_monoid.gcd s₁.gcd s₂.gcd := eq.trans (by simp [gcd]) (fold_add _ _ _ _ _) lemma dvd_gcd {s : multiset α} {a : α} : a ∣ s.gcd ↔ (∀ b ∈ s, a ∣ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib, dvd_gcd_iff] {contextual := tt}) lemma gcd_dvd {s : multiset α} {a : α} (h : a ∈ s) : s.gcd ∣ a := dvd_gcd.1 dvd_rfl _ h lemma gcd_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.gcd ∣ s₁.gcd := dvd_gcd.2 $ assume b hb, gcd_dvd (h hb) @[simp] lemma normalize_gcd (s : multiset α) : normalize (s.gcd) = s.gcd := multiset.induction_on s (by simp) $ λ a s IH, by simp theorem gcd_eq_zero_iff (s : multiset α) : s.gcd = 0 ↔ ∀ (x : α), x ∈ s → x = 0 := begin split, { intros h x hx, apply eq_zero_of_zero_dvd, rw ← h, apply gcd_dvd hx }, { apply s.induction_on, { simp }, intros a s sgcd h, simp [h a (mem_cons_self a s), sgcd (λ x hx, h x (mem_cons_of_mem hx))] } end lemma gcd_map_mul (a : α) (s : multiset α) : (s.map ((*) a)).gcd = normalize a * s.gcd := begin refine s.induction_on _ (λ b s ih, _), { simp_rw [map_zero, gcd_zero, mul_zero] }, { simp_rw [map_cons, gcd_cons, ← gcd_mul_left], rw ih, apply ((normalize_associated a).mul_right _).gcd_eq_right }, end section variables [decidable_eq α] @[simp] lemma gcd_dedup (s : multiset α) : (dedup s).gcd = s.gcd := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], unfold gcd, rw [← cons_erase h, fold_cons_left, ← gcd_assoc, gcd_same], apply (associated_normalize _).gcd_eq_left, end @[simp] lemma gcd_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).gcd = gcd_monoid.gcd s₁.gcd s₂.gcd := by { rw [← gcd_dedup, dedup_ext.2, gcd_dedup, gcd_add], simp } @[simp] lemma gcd_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).gcd = gcd_monoid.gcd s₁.gcd s₂.gcd := by { rw [← gcd_dedup, dedup_ext.2, gcd_dedup, gcd_add], simp } @[simp] lemma gcd_ndinsert (a : α) (s : multiset α) : (ndinsert a s).gcd = gcd_monoid.gcd a s.gcd := by { rw [← gcd_dedup, dedup_ext.2, gcd_dedup, gcd_cons], simp } end lemma extract_gcd' (s t : multiset α) (hs : ∃ x, x ∈ s ∧ x ≠ (0 : α)) (ht : s = t.map ((*) s.gcd)) : t.gcd = 1 := ((@mul_right_eq_self₀ _ _ s.gcd _).1 $ by conv_lhs { rw [← normalize_gcd, ← gcd_map_mul, ← ht] }) .resolve_right $ by { contrapose! hs, exact s.gcd_eq_zero_iff.1 hs } lemma extract_gcd (s : multiset α) (hs : s ≠ 0) : ∃ t : multiset α, s = t.map ((*) s.gcd) ∧ t.gcd = 1 := begin classical, by_cases h : ∀ x ∈ s, x = (0 : α), { use repeat 1 s.card, rw [map_repeat, eq_repeat, mul_one, s.gcd_eq_zero_iff.2 h, ←nsmul_singleton, ←gcd_dedup], rw [dedup_nsmul (card_pos.2 hs).ne', dedup_singleton, gcd_singleton], exact ⟨⟨rfl, h⟩, normalize_one⟩ }, { choose f hf using @gcd_dvd _ _ _ s, have := _, push_neg at h, refine ⟨s.pmap @f (λ _, id), this, extract_gcd' s _ h this⟩, rw map_pmap, conv_lhs { rw [← s.map_id, ← s.pmap_eq_map _ _ (λ _, id)] }, congr' with x hx, rw [id, ← hf hx] }, end end gcd end multiset
144d7c9f3cce1e1e1589a6d04ed841992e4c6e3f
2fb7334a212c3858db44039b5fa6cd57fd5d1443
/experiments/finite_prod_of_binary_prod.lean
fc6f79052f7e0b0096507a6fc967dd25c1e531bd
[]
no_license
ImperialCollegeLondon/condensed-sets
24514be041533b07fd62d337b1d6a5ce2b09c78c
e308291646396003dbed3896e5fbb40cb57c7050
refs/heads/master
1,628,397,992,041
1,601,549,576,000
1,601,549,576,000
224,198,323
3
1
null
1,601,549,578,000
1,574,774,780,000
Lean
UTF-8
Lean
false
false
2,681
lean
import category_theory.limits.limits import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal import data.fintype variable (α : Type*) open category_theory namespace category_theory.limits namespace is_limit universes v u variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 open_locale classical /- cheat sheet /-- `has_limit F` represents a particular chosen limit of the diagram `F`. -/ class has_limit (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone . tactic.apply_instance) -/ #check limits.has_limit #check category_theory.functor instance finite_prod_of_binary_prod [has_binary_products.{v} C] [has_terminal.{v} C ] : has_finite_products.{v} C := ⟨begin intros J fJ dJ, resetI, suffices : ∀ n : ℕ, fintype.card J = n → limits.has_limits_of_shape (discrete J) C, apply this (fintype.card J), refl, intro n, apply nat.rec_on n, { intro h, constructor, intro F, exact { cone := { X := ⊤_ C, π := { app := λ X, false.elim ((fintype.card_eq_zero_iff.1 h) X), } }, is_limit := {lift := λ s, terminal.from s.X, fac' := sorry, uniq' := sorry}}, }, sorry end⟩ #exit -- end of KB trying to catch up -- Calle stuff below ⟨begin intro J, let x := classical.choice h in have card_lt : fintype.card J' < fintype.card J, refine fintype.card_subtype_lt J _, exact x, simp, have J'_lims : limits.has_limits_of_shape (discrete J') C, refine finite_prod_of_binary_prod J', refine ⟨_⟩, intro, let F' := (discrete.lift (subtype.val : J' -> J)) ⋙ F, have F'_has_lim : has_limit F', refine (has_limits_of_shape.has_limit F'), let P := prod (limit F') (F.obj x), refine {cone := _, is_limit := _}, { refine {X := P, π := _}, { refine {app := _, naturality' := _}, { intro A, dsimp, exact ( if H1 : A = x then by {rw H1, exact prod.snd} else prod.fst ≫ limit.π F' (⟨A, H1⟩)) }, dsimp [x, J'] at *, dsimp [x, J'], intros, split_ifs, substs h_1 h_2, dsimp [eq.mpr], simp, exfalso, apply h_2, rw ←h_1, rcases f, rcases f, exact f, exfalso, apply h_1, rw ←h_2, rcases f, rcases f, exact f.symm, simp, rcases f, rcases f, cases f, simp, }, }, { refine {lift := _, fac' := _, uniq' := _}, { exact ( λ s, _ ) }, { }, { }, }, end else _ using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, @fintype.card x.1 x.2)⟩]} /- let MAP : (P ⟶ F'.obj ⟨A, H1⟩) := prod.fst ≫ limit.π F' (⟨A, H1⟩) in MAP) -/ #check subtype.val end is_limit end category_theory.limits
11e30e7dee9634b8828f46cf843d83fa02ede5f8
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/inline_issue.lean
6e8b4916cb0134df6f15900ee263bb9df2ab77e4
[ "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
373
lean
open tactic meta def f (n : nat) : tactic unit := trace "hello" >> trace "------------" >> trace_call_stack meta def g (n : nat) : tactic unit := trace "world" >> f n run_command (do x ← return 5, x ← return 5, x ← return 5, x ← return 5, x ← return 5, x ← return 5, x ← return 5, x ← return 5, x ← return 5, x ← return 5, g 1)
e696b2cd166dd2439f54c1118eed6906cd9910b9
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/order/omega_complete_partial_order.lean
5cb19bfece28ecd197b259b3e716a501718ac891
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
30,593
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.pfun import order.preorder_hom import tactic.wlog import tactic.monotonicity /-! # Omega Complete Partial Orders An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. The concept of an omega-complete partial order (ωCPO) is useful for the formalization of the semantics of programming languages. Its notion of supremum helps define the meaning of recursive procedures. ## Main definitions * class `omega_complete_partial_order` * `ite`, `map`, `bind`, `seq` as continuous morphisms ## Instances of `omega_complete_partial_order` * `roption` * every `complete_lattice` * pi-types * product types * `monotone_hom` * `continuous_hom` (with notation →𝒄) * an instance of `omega_complete_partial_order (α →𝒄 β)` * `continuous_hom.of_fun` * `continuous_hom.of_mono` * continuous functions: * `id` * `ite` * `const` * `roption.bind` * `roption.map` * `roption.seq` ## References * [G. Markowsky, *Chain-complete posets and directed sets with applications*, https://doi.org/10.1007/BF02485815][markowsky] * [J. M. Cadiou and Zohar Manna, *Recursive definitions of partial functions and their computations.*, https://doi.org/10.1145/942580.807072][cadiou] * [Carl A. Gunter, *Semantics of Programming Languages: Structures and Techniques*, ISBN: 0262570955][gunter] -/ universes u v local attribute [-simp] roption.bind_eq_bind roption.map_eq_map open_locale classical namespace preorder_hom variables (α : Type*) (β : Type*) {γ : Type*} {φ : Type*} variables [preorder α] [preorder β] [preorder γ] [preorder φ] variables {β γ} /-- The constant function, as a monotone function. -/ @[simps] def const (f : β) : α →ₘ β := { to_fun := function.const _ f, monotone' := assume x y h, le_refl _} variables {α} {α' : Type*} {β' : Type*} [preorder α'] [preorder β'] /-- The diagonal function, as a monotone function. -/ @[simps] def prod.diag : α →ₘ (α × α) := { to_fun := λ x, (x,x), monotone' := λ x y h, ⟨h,h⟩ } /-- The `prod.map` function, as a monotone function. -/ @[simps] def prod.map (f : α →ₘ β) (f' : α' →ₘ β') : (α × α') →ₘ (β × β') := { to_fun := prod.map f f', monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, ⟨f.monotone h,f'.monotone h'⟩ } /-- The `prod.fst` projection, as a monotone function. -/ @[simps] def prod.fst : (α × β) →ₘ α := { to_fun := prod.fst, monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, h } /-- The `prod.snd` projection, as a monotone function. -/ @[simps] def prod.snd : (α × β) →ₘ β := { to_fun := prod.snd, monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, h' } /-- The `prod` constructor, as a monotone function. -/ @[simps] def prod.zip (f : α →ₘ β) (g : α →ₘ γ) : α →ₘ (β × γ) := (prod.map f g).comp prod.diag /-- `roption.bind` as a monotone function -/ @[simps] def bind {β γ} (f : α →ₘ roption β) (g : α →ₘ β → roption γ) : α →ₘ roption γ := { to_fun := λ x, f x >>= g x, monotone' := begin intros x y h a, simp only [and_imp, exists_prop, roption.bind_eq_bind, roption.mem_bind_iff, exists_imp_distrib], intros b hb ha, refine ⟨b, f.monotone h _ hb, g.monotone h _ _ ha⟩, end } end preorder_hom namespace omega_complete_partial_order /-- A chain is a monotonically increasing sequence. See the definition on page 114 of [gunter]. -/ def chain (α : Type u) [preorder α] := ℕ →ₘ α namespace chain variables {α : Type u} {β : Type v} {γ : Type*} variables [preorder α] [preorder β] [preorder γ] instance : has_coe_to_fun (chain α) := @infer_instance (has_coe_to_fun $ ℕ →ₘ α) _ instance [inhabited α] : inhabited (chain α) := ⟨ ⟨ λ _, default _, λ _ _ _, le_refl _ ⟩ ⟩ instance : has_mem α (chain α) := ⟨λa (c : ℕ →ₘ α), ∃ i, a = c i⟩ variables (c c' : chain α) variables (f : α →ₘ β) variables (g : β →ₘ γ) instance : has_le (chain α) := { le := λ x y, ∀ i, ∃ j, x i ≤ y j } /-- `map` function for `chain` -/ @[simps] def map : chain β := f.comp c variables {f} lemma mem_map (x : α) : x ∈ c → f x ∈ chain.map c f := λ ⟨i,h⟩, ⟨i, h.symm ▸ rfl⟩ lemma exists_of_mem_map {b : β} : b ∈ c.map f → ∃ a, a ∈ c ∧ f a = b := λ ⟨i,h⟩, ⟨c i, ⟨i, rfl⟩, h.symm⟩ lemma mem_map_iff {b : β} : b ∈ c.map f ↔ ∃ a, a ∈ c ∧ f a = b := ⟨ exists_of_mem_map _, λ h, by { rcases h with ⟨w,h,h'⟩, subst b, apply mem_map c _ h, } ⟩ @[simp] lemma map_id : c.map preorder_hom.id = c := preorder_hom.comp_id _ lemma map_comp : (c.map f).map g = c.map (g.comp f) := rfl @[mono] lemma map_le_map {g : α →ₘ β} (h : f ≤ g) : c.map f ≤ c.map g := λ i, by simp [mem_map_iff]; intros; existsi i; apply h /-- `chain.zip` pairs up the elements of two chains that have the same index -/ @[simps] def zip (c₀ : chain α) (c₁ : chain β) : chain (α × β) := preorder_hom.prod.zip c₀ c₁ end chain end omega_complete_partial_order open omega_complete_partial_order section prio set_option extends_priority 50 /-- An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. See the definition on page 114 of [gunter]. -/ class omega_complete_partial_order (α : Type*) extends partial_order α := (ωSup : chain α → α) (le_ωSup : ∀(c:chain α), ∀ i, c i ≤ ωSup c) (ωSup_le : ∀(c:chain α) x, (∀ i, c i ≤ x) → ωSup c ≤ x) end prio namespace omega_complete_partial_order variables {α : Type u} {β : Type v} {γ : Type*} variables [omega_complete_partial_order α] /-- Transfer a `omega_complete_partial_order` on `β` to a `omega_complete_partial_order` on `α` using a strictly monotone function `f : β →ₘ α`, a definition of ωSup and a proof that `f` is continuous with regard to the provided `ωSup` and the ωCPO on `α`. -/ @[reducible] protected def lift [partial_order β] (f : β →ₘ α) (ωSup₀ : chain β → β) (h : ∀ x y, f x ≤ f y → x ≤ y) (h' : ∀ c, f (ωSup₀ c) = ωSup (c.map f)) : omega_complete_partial_order β := { ωSup := ωSup₀, ωSup_le := λ c x hx, h _ _ (by rw h'; apply ωSup_le; intro; apply f.monotone (hx i)), le_ωSup := λ c i, h _ _ (by rw h'; apply le_ωSup (c.map f)) } lemma le_ωSup_of_le {c : chain α} {x : α} (i : ℕ) (h : x ≤ c i) : x ≤ ωSup c := le_trans h (le_ωSup c _) lemma ωSup_total {c : chain α} {x : α} (h : ∀ i, c i ≤ x ∨ x ≤ c i) : ωSup c ≤ x ∨ x ≤ ωSup c := classical.by_cases (assume : ∀ i, c i ≤ x, or.inl (ωSup_le _ _ this)) (assume : ¬ ∀ i, c i ≤ x, have ∃ i, ¬ c i ≤ x, by simp only [not_forall] at this ⊢; assumption, let ⟨i, hx⟩ := this in have x ≤ c i, from (h i).resolve_left hx, or.inr $ le_ωSup_of_le _ this) @[mono] lemma ωSup_le_ωSup_of_le {c₀ c₁ : chain α} (h : c₀ ≤ c₁) : ωSup c₀ ≤ ωSup c₁ := ωSup_le _ _ $ λ i, Exists.rec_on (h i) $ λ j h, le_trans h (le_ωSup _ _) lemma ωSup_le_iff (c : chain α) (x : α) : ωSup c ≤ x ↔ (∀ i, c i ≤ x) := begin split; intros, { transitivity ωSup c, exact le_ωSup _ _, assumption }, exact ωSup_le _ _ ‹_›, end /-- A subset `p : α → Prop` of the type closed under `ωSup` induces an `omega_complete_partial_order` on the subtype `{a : α // p a}`. -/ def subtype {α : Type*} [omega_complete_partial_order α] (p : α → Prop) (hp : ∀ (c : chain α), (∀ i ∈ c, p i) → p (ωSup c)) : omega_complete_partial_order (subtype p) := omega_complete_partial_order.lift (preorder_hom.subtype.val p) (λ c, ⟨ωSup _, hp (c.map (preorder_hom.subtype.val p)) (λ i ⟨n, q⟩, q.symm ▸ (c n).2)⟩) (λ x y h, h) (λ c, rfl) section continuity open chain variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- A monotone function `f : α →ₘ β` is continuous if it distributes over ωSup. In order to distinguish it from the (more commonly used) continuity from topology (see topology/basic.lean), the present definition is often referred to as "Scott-continuity" (referring to Dana Scott). It corresponds to continuity in Scott topological spaces (not defined here). -/ def continuous (f : α →ₘ β) : Prop := ∀ c : chain α, f (ωSup c) = ωSup (c.map f) /-- `continuous' f` asserts that `f` is both monotone and continuous. -/ def continuous' (f : α → β) : Prop := ∃ hf : monotone f, continuous ⟨f, hf⟩ lemma continuous.to_monotone {f : α → β} (hf : continuous' f) : monotone f := hf.fst lemma continuous.of_bundled (f : α → β) (hf : monotone f) (hf' : continuous ⟨f, hf⟩) : continuous' f := ⟨hf, hf'⟩ lemma continuous.of_bundled' (f : α →ₘ β) (hf' : continuous f) : continuous' f := ⟨f.monotone, hf'⟩ lemma continuous.to_bundled (f : α → β) (hf : continuous' f) : continuous ⟨f, continuous.to_monotone hf⟩ := hf.snd variables (f : α →ₘ β) (g : β →ₘ γ) lemma continuous_id : continuous (@preorder_hom.id α _) := by intro; rw c.map_id; refl lemma continuous_comp (hfc : continuous f) (hgc : continuous g) : continuous (g.comp f):= begin dsimp [continuous] at *, intro, rw [hfc,hgc,chain.map_comp] end lemma id_continuous' : continuous' (@id α) := continuous.of_bundled _ (λ a b h, h) begin intro c, apply eq_of_forall_ge_iff, intro z, simp [ωSup_le_iff,function.const], end lemma const_continuous' (x: β) : continuous' (function.const α x) := continuous.of_bundled _ (λ a b h, le_refl _) begin intro c, apply eq_of_forall_ge_iff, intro z, simp [ωSup_le_iff,function.const], end end continuity end omega_complete_partial_order namespace roption variables {α : Type u} {β : Type v} {γ : Type*} open omega_complete_partial_order lemma eq_of_chain {c : chain (roption α)} {a b : α} (ha : some a ∈ c) (hb : some b ∈ c) : a = b := begin cases ha with i ha, replace ha := ha.symm, cases hb with j hb, replace hb := hb.symm, wlog h : i ≤ j := le_total i j using [a b i j, b a j i], rw [eq_some_iff] at ha hb, have := c.monotone h _ ha, apply mem_unique this hb end /-- The (noncomputable) `ωSup` definition for the `ω`-CPO structure on `roption α`. -/ protected noncomputable def ωSup (c : chain (roption α)) : roption α := if h : ∃a, some a ∈ c then some (classical.some h) else none lemma ωSup_eq_some {c : chain (roption α)} {a : α} (h : some a ∈ c) : roption.ωSup c = some a := have ∃a, some a ∈ c, from ⟨a, h⟩, have a' : some (classical.some this) ∈ c, from classical.some_spec this, calc roption.ωSup c = some (classical.some this) : dif_pos this ... = some a : congr_arg _ (eq_of_chain a' h) lemma ωSup_eq_none {c : chain (roption α)} (h : ¬∃a, some a ∈ c) : roption.ωSup c = none := dif_neg h lemma mem_chain_of_mem_ωSup {c : chain (roption α)} {a : α} (h : a ∈ roption.ωSup c) : some a ∈ c := begin simp [roption.ωSup] at h, split_ifs at h, { have h' := classical.some_spec h_1, rw ← eq_some_iff at h, rw ← h, exact h' }, { rcases h with ⟨ ⟨ ⟩ ⟩ } end noncomputable instance omega_complete_partial_order : omega_complete_partial_order (roption α) := { ωSup := roption.ωSup, le_ωSup := λ c i, by { intros x hx, rw ← eq_some_iff at hx ⊢, rw [ωSup_eq_some, ← hx], rw ← hx, exact ⟨i,rfl⟩ }, ωSup_le := by { rintros c x hx a ha, replace ha := mem_chain_of_mem_ωSup ha, cases ha with i ha, apply hx i, rw ← ha, apply mem_some } } section inst lemma mem_ωSup (x : α) (c : chain (roption α)) : x ∈ ωSup c ↔ some x ∈ c := begin simp [omega_complete_partial_order.ωSup,roption.ωSup], split, { split_ifs, swap, rintro ⟨⟨⟩⟩, intro h', have hh := classical.some_spec h, simp at h', subst x, exact hh }, { intro h, have h' : ∃ (a : α), some a ∈ c := ⟨_,h⟩, rw dif_pos h', have hh := classical.some_spec h', rw eq_of_chain hh h, simp } end end inst end roption namespace pi variables {α : Type*} {β : α → Type*} {γ : Type*} /-- Function application `λ f, f a` is monotone with respect to `f` for fixed `a`. -/ @[simps] def monotone_apply [∀a, partial_order (β a)] (a : α) : (Πa, β a) →ₘ β a := { to_fun := (λf:Πa, β a, f a), monotone' := assume f g hfg, hfg a } open omega_complete_partial_order omega_complete_partial_order.chain instance [∀a, omega_complete_partial_order (β a)] : omega_complete_partial_order (Πa, β a) := { ωSup := λc a, ωSup (c.map (monotone_apply a)), ωSup_le := assume c f hf a, ωSup_le _ _ $ by { rintro i, apply hf }, le_ωSup := assume c i x, le_ωSup_of_le _ $ le_refl _ } namespace omega_complete_partial_order variables [∀ x, omega_complete_partial_order $ β x] variables [omega_complete_partial_order γ] lemma flip₁_continuous' (f : ∀ x : α, γ → β x) (a : α) (hf : continuous' (λ x y, f y x)) : continuous' (f a) := continuous.of_bundled _ (λ x y h, continuous.to_monotone hf h a) (λ c, congr_fun (continuous.to_bundled _ hf c) a) lemma flip₂_continuous' (f : γ → Π x, β x) (hf : ∀ x, continuous' (λ g, f g x)) : continuous' f := continuous.of_bundled _ (λ x y h a, continuous.to_monotone (hf a) h) (by intro c; ext a; apply continuous.to_bundled _ (hf a) c) end omega_complete_partial_order end pi namespace prod open omega_complete_partial_order variables {α : Type*} {β : Type*} {γ : Type*} variables [omega_complete_partial_order α] variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- The supremum of a chain in the product `ω`-CPO. -/ @[simps] protected def ωSup (c : chain (α × β)) : α × β := (ωSup (c.map preorder_hom.prod.fst), ωSup (c.map preorder_hom.prod.snd)) @[simps ωSup_fst ωSup_snd] instance : omega_complete_partial_order (α × β) := { ωSup := prod.ωSup, ωSup_le := λ c ⟨x,x'⟩ h, ⟨ωSup_le _ _ $ λ i, (h i).1, ωSup_le _ _ $ λ i, (h i).2⟩, le_ωSup := λ c i, ⟨le_ωSup (c.map preorder_hom.prod.fst) i, le_ωSup (c.map preorder_hom.prod.snd) i⟩ } end prod namespace complete_lattice variables (α : Type u) /-- Any complete lattice has an `ω`-CPO structure where the countable supremum is a special case of arbitrary suprema. -/ @[priority 100] -- see Note [lower instance priority] instance [complete_lattice α] : omega_complete_partial_order α := { ωSup := λc, ⨆ i, c i, ωSup_le := λ ⟨c, _⟩ s hs, by simp only [supr_le_iff, preorder_hom.coe_fun_mk] at ⊢ hs; intros i; apply hs i, le_ωSup := assume ⟨c, _⟩ i, by simp only [preorder_hom.coe_fun_mk]; apply le_supr_of_le i; refl } variables {α} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] open omega_complete_partial_order lemma inf_continuous [is_total β (≤)] (f g : α →ₘ β) (hf : continuous f) (hg : continuous g) : continuous (f ⊓ g) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [inf_le_iff, hf c, hg c, ωSup_le_iff, ←forall_or_distrib_left, ←forall_or_distrib_right, chain.map_to_fun, function.comp_app, preorder_hom.has_inf_inf_to_fun], split, { introv h, apply h }, { intros h i j, apply or.imp _ _ (h (max i j)); apply le_trans; mono*, { apply le_max_left }, { apply le_max_right }, }, end lemma Sup_continuous (s : set $ α →ₘ β) (hs : ∀ f ∈ s, continuous f) : continuous (Sup s) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, and_imp, preorder_hom.complete_lattice_Sup, set.mem_image, chain.map_to_fun, function.comp_app, Sup_le_iff, preorder_hom.has_Sup_Sup_to_fun, exists_imp_distrib], split; introv h hx hb; subst b, { apply le_trans _ (h _ _ hx rfl), mono, apply le_ωSup }, { rw [hs _ hx c, ωSup_le_iff], intro, apply h i _ x hx rfl, } end theorem Sup_continuous' : ∀s : set (α → β), (∀t∈s, omega_complete_partial_order.continuous' t) → omega_complete_partial_order.continuous' (Sup s) := begin introv ht, dsimp [continuous'], have : monotone (Sup s), { intros x y h, apply Sup_le_Sup_of_forall_exists_le, intro, simp only [and_imp, exists_prop, set.mem_range, set_coe.exists, subtype.coe_mk, exists_imp_distrib], intros f hfs hfx, subst hfx, refine ⟨f y, ⟨f, hfs, rfl⟩, _⟩, cases ht _ hfs with hf, apply hf h }, existsi this, let s' : set (α →ₘ β) := { f | ⇑f ∈ s }, suffices : omega_complete_partial_order.continuous (Sup s'), { convert this, ext, simp only [supr, has_Sup.Sup, Sup, set.image, set.mem_set_of_eq], congr, ext, simp only [exists_prop, set.mem_range, set_coe.exists, set.mem_set_of_eq, subtype.coe_mk], split, { rintro ⟨y,hy,hy'⟩, cases ht _ hy, refine ⟨⟨_, w⟩, hy, hy'⟩ }, tauto }, apply complete_lattice.Sup_continuous, intros f hf, specialize ht f hf, cases ht, exact ht_h, end lemma sup_continuous {f g : α →ₘ β} (hf : continuous f) (hg : continuous g) : continuous (f ⊔ g) := begin rw ← Sup_pair, apply Sup_continuous, simp only [or_imp_distrib, forall_and_distrib, set.mem_insert_iff, set.mem_singleton_iff, forall_eq], split; assumption, end lemma top_continuous : continuous (⊤ : α →ₘ β) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, forall_const, chain.map_to_fun, function.comp_app, preorder_hom.has_top_top_to_fun], end lemma bot_continuous : continuous (⊥ : α →ₘ β) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, forall_const, chain.map_to_fun, function.comp_app, preorder_hom.has_bot_bot_to_fun], end end complete_lattice namespace omega_complete_partial_order variables {α : Type u} {α' : Type*} {β : Type v} {β' : Type*} {γ : Type*} {φ : Type*} variables [omega_complete_partial_order α] [omega_complete_partial_order β] variables [omega_complete_partial_order γ] [omega_complete_partial_order φ] variables [omega_complete_partial_order α'] [omega_complete_partial_order β'] namespace preorder_hom /-- Function application `λ f, f a` (for fixed `a`) is a monotone function from the monotone function space `α →ₘ β` to `β`. -/ @[simps] def monotone_apply (a : α) : (α →ₘ β) →ₘ β := { to_fun := (λf : α →ₘ β, f a), monotone' := assume f g hfg, hfg a } /-- The "forgetful functor" from `α →ₘ β` to `α → β` that takes the underlying function, is monotone. -/ def to_fun_hom : (α →ₘ β) →ₘ (α → β) := { to_fun := λ f, f.to_fun, monotone' := λ x y h, h } /-- The `ωSup` operator for monotone functions. -/ @[simps] protected def ωSup (c : chain (α →ₘ β)) : α →ₘ β := { to_fun := λ a, ωSup (c.map (monotone_apply a)), monotone' := λ x y h, ωSup_le_ωSup_of_le (chain.map_le_map _ $ λ a, a.monotone h) } @[simps ωSup_to_fun] instance omega_complete_partial_order : omega_complete_partial_order (α →ₘ β) := omega_complete_partial_order.lift preorder_hom.to_fun_hom preorder_hom.ωSup (λ x y h, h) (λ c, rfl) end preorder_hom section old_struct set_option old_structure_cmd true variables (α β) /-- A monotone function on `ω`-continuous partial orders is said to be continuous if for every chain `c : chain α`, `f (⊔ i, c i) = ⊔ i, f (c i)`. This is just the bundled version of `preorder_hom.continuous`. -/ structure continuous_hom extends preorder_hom α β := (cont : continuous (preorder_hom.mk to_fun monotone')) attribute [nolint doc_blame] continuous_hom.to_preorder_hom infixr ` →𝒄 `:25 := continuous_hom -- Input: \r\MIc instance : has_coe_to_fun (α →𝒄 β) := { F := λ _, α → β, coe := continuous_hom.to_fun } instance : has_coe (α →𝒄 β) (α →ₘ β) := { coe := continuous_hom.to_preorder_hom } instance : partial_order (α →𝒄 β) := partial_order.lift continuous_hom.to_fun $ by rintro ⟨⟩ ⟨⟩ h; congr; exact h end old_struct namespace continuous_hom theorem congr_fun {f g : α →𝒄 β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →𝒄 β, h x) h theorem congr_arg (f : α →𝒄 β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h @[mono] lemma monotone (f : α →𝒄 β) : monotone f := continuous_hom.monotone' f lemma ite_continuous' {p : Prop} [hp : decidable p] (f g : α → β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, if p then f x else g x) := by split_ifs; simp * lemma ωSup_bind {β γ : Type v} (c : chain α) (f : α →ₘ roption β) (g : α →ₘ β → roption γ) : ωSup (c.map (f.bind g)) = ωSup (c.map f) >>= ωSup (c.map g) := begin apply eq_of_forall_ge_iff, intro x, simp only [ωSup_le_iff, roption.bind_le, chain.mem_map_iff, and_imp, preorder_hom.bind_to_fun, exists_imp_distrib], split; intro h''', { intros b hb, apply ωSup_le _ _ _, rintros i y hy, simp only [roption.mem_ωSup] at hb, rcases hb with ⟨j,hb⟩, replace hb := hb.symm, simp only [roption.eq_some_iff, chain.map_to_fun, function.comp_app, pi.monotone_apply_to_fun] at hy hb, replace hb : b ∈ f (c (max i j)) := f.monotone (c.monotone (le_max_right i j)) _ hb, replace hy : y ∈ g (c (max i j)) b := g.monotone (c.monotone (le_max_left i j)) _ _ hy, apply h''' (max i j), simp only [exists_prop, roption.bind_eq_bind, roption.mem_bind_iff, chain.map_to_fun, function.comp_app, preorder_hom.bind_to_fun], exact ⟨_,hb,hy⟩, }, { intros i, intros y hy, simp only [exists_prop, roption.bind_eq_bind, roption.mem_bind_iff, chain.map_to_fun, function.comp_app, preorder_hom.bind_to_fun] at hy, rcases hy with ⟨b,hb₀,hb₁⟩, apply h''' b _, { apply le_ωSup (c.map g) _ _ _ hb₁ }, { apply le_ωSup (c.map f) i _ hb₀ } }, end lemma bind_continuous' {β γ : Type v} (f : α → roption β) (g : α → β → roption γ) : continuous' f → continuous' g → continuous' (λ x, f x >>= g x) | ⟨hf,hf'⟩ ⟨hg,hg'⟩ := continuous.of_bundled' (preorder_hom.bind ⟨f,hf⟩ ⟨g,hg⟩) (by intro c; rw [ωSup_bind, ← hf', ← hg']; refl) lemma map_continuous' {β γ : Type v} (f : β → γ) (g : α → roption β) (hg : continuous' g) : continuous' (λ x, f <$> g x) := by simp only [map_eq_bind_pure_comp]; apply bind_continuous' _ _ hg; apply const_continuous' lemma seq_continuous' {β γ : Type v} (f : α → roption (β → γ)) (g : α → roption β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, f x <*> g x) := by simp only [seq_eq_bind_map]; apply bind_continuous' _ _ hf; apply pi.omega_complete_partial_order.flip₂_continuous'; intro; apply map_continuous' _ _ hg lemma continuous (F : α →𝒄 β) (C : chain α) : F (ωSup C) = ωSup (C.map F) := continuous_hom.cont _ _ /-- Construct a continuous function from a bare function, a continuous function, and a proof that they are equal. -/ @[simps, reducible] def of_fun (f : α → β) (g : α →𝒄 β) (h : f = g) : α →𝒄 β := by refine {to_fun := f, ..}; subst h; cases g; assumption /-- Construct a continuous function from a monotone function with a proof of continuity. -/ @[simps, reducible] def of_mono (f : α →ₘ β) (h : ∀ c : chain α, f (ωSup c) = ωSup (c.map f)) : α →𝒄 β := { to_fun := f, monotone' := f.monotone, cont := h } /-- The identity as a continuous function. -/ @[simps] def id : α →𝒄 α := of_mono preorder_hom.id (by intro; rw [chain.map_id]; refl) /-- The composition of continuous functions. -/ @[simps] def comp (f : β →𝒄 γ) (g : α →𝒄 β) : α →𝒄 γ := of_mono (preorder_hom.comp (↑f) (↑g)) (by intro; rw [preorder_hom.comp, ← preorder_hom.comp, ← chain.map_comp, ← f.continuous, ← g.continuous]; refl) @[ext] protected lemma ext (f g : α →𝒄 β) (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr; ext; apply h protected lemma coe_inj (f g : α →𝒄 β) (h : (f : α → β) = g) : f = g := continuous_hom.ext _ _ $ _root_.congr_fun h @[simp] lemma comp_id (f : β →𝒄 γ) : f.comp id = f := by ext; refl @[simp] lemma id_comp (f : β →𝒄 γ) : id.comp f = f := by ext; refl @[simp] lemma comp_assoc (f : γ →𝒄 φ) (g : β →𝒄 γ) (h : α →𝒄 β) : f.comp (g.comp h) = (f.comp g).comp h := by ext; refl @[simp] lemma coe_apply (a : α) (f : α →𝒄 β) : (f : α →ₘ β) a = f a := rfl /-- `function.const` is a continuous function. -/ def const (f : β) : α →𝒄 β := of_mono (preorder_hom.const _ f) begin intro c, apply le_antisymm, { simp only [function.const, preorder_hom.const_to_fun], apply le_ωSup_of_le 0, refl }, { apply ωSup_le, simp only [preorder_hom.const_to_fun, chain.map_to_fun, function.comp_app], intros, refl }, end @[simp] theorem const_apply (f : β) (a : α) : const f a = f := rfl instance [inhabited β] : inhabited (α →𝒄 β) := ⟨ const (default β) ⟩ namespace prod /-- The application of continuous functions as a monotone function. (It would make sense to make it a continuous function, but we are currently constructing a `omega_complete_partial_order` instance for `α →𝒄 β`, and we cannot use it as the domain or image of a continuous function before we do.) -/ @[simps] def apply : (α →𝒄 β) × α →ₘ β := { to_fun := λ f, f.1 f.2, monotone' := λ x y h, by dsimp; transitivity y.fst x.snd; [apply h.1, apply y.1.monotone h.2] } end prod /-- The map from continuous functions to monotone functions is itself a monotone function. -/ @[simps] def to_mono : (α →𝒄 β) →ₘ (α →ₘ β) := { to_fun := λ f, f, monotone' := λ x y h, h } /-- When proving that a chain of applications is below a bound `z`, it suffices to consider the functions and values being selected from the same index in the chains. This lemma is more specific than necessary, i.e. `c₀` only needs to be a chain of monotone functions, but it is only used with continuous functions. -/ @[simp] lemma forall_forall_merge (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (i j : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := begin split; introv h, { apply h }, { apply le_trans _ (h (max i j)), transitivity c₀ i (c₁ (max i j)), { apply (c₀ i).monotone, apply c₁.monotone, apply le_max_right }, { apply c₀.monotone, apply le_max_left } } end @[simp] lemma forall_forall_merge' (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (j i : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := by rw [forall_swap,forall_forall_merge] /-- The `ωSup` operator for continuous functions, which takes the pointwise countable supremum of the functions in the `ω`-chain. -/ @[simps] protected def ωSup (c : chain (α →𝒄 β)) : α →𝒄 β := continuous_hom.of_mono (ωSup $ c.map to_mono) begin intro c', apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c _).continuous, chain.map_to_fun, preorder_hom.monotone_apply_to_fun, to_mono_to_fun, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_to_fun, forall_forall_merge, forall_forall_merge', function.comp_app], end @[simps ωSup] instance : omega_complete_partial_order (α →𝒄 β) := omega_complete_partial_order.lift continuous_hom.to_mono continuous_hom.ωSup (λ x y h, h) (λ c, rfl) lemma ωSup_def (c : chain (α →𝒄 β)) (x : α) : ωSup c x = continuous_hom.ωSup c x := rfl lemma ωSup_ωSup (c₀ : chain (α →𝒄 β)) (c₁ : chain α) : ωSup c₀ (ωSup c₁) = ωSup (continuous_hom.prod.apply.comp $ c₀.zip c₁) := begin apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c₀ _).continuous, chain.map_to_fun, to_mono_to_fun, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_to_fun, ωSup_def, forall_forall_merge, chain.zip_to_fun, preorder_hom.prod.map_to_fun, preorder_hom.prod.diag_to_fun, prod.map_mk, preorder_hom.monotone_apply_to_fun, function.comp_app, prod.apply_to_fun, preorder_hom.comp_to_fun, ωSup_to_fun], end /-- A family of continuous functions yields a continuous family of functions. -/ @[simps] def flip {α : Type*} (f : α → β →𝒄 γ) : β →𝒄 α → γ := { to_fun := λ x y, f y x, monotone' := λ x y h a, (f a).monotone h, cont := by intro; ext; change f x _ = _; rw [(f x).continuous ]; refl, } /-- `roption.bind` as a continuous function. -/ @[simps { rhs_md := reducible }] noncomputable def bind {β γ : Type v} (f : α →𝒄 roption β) (g : α →𝒄 β → roption γ) : α →𝒄 roption γ := of_mono (preorder_hom.bind (↑f) (↑g)) $ λ c, begin rw [preorder_hom.bind, ← preorder_hom.bind, ωSup_bind, ← f.continuous, ← g.continuous], refl end /-- `roption.map` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def map {β γ : Type v} (f : β → γ) (g : α →𝒄 roption β) : α →𝒄 roption γ := of_fun (λ x, f <$> g x) (bind g (const (pure ∘ f))) $ by ext; simp only [map_eq_bind_pure_comp, bind_to_fun, preorder_hom.bind_to_fun, const_apply, preorder_hom.const_to_fun, coe_apply] /-- `roption.seq` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def seq {β γ : Type v} (f : α →𝒄 roption (β → γ)) (g : α →𝒄 roption β) : α →𝒄 roption γ := of_fun (λ x, f x <*> g x) (bind f $ (flip $ _root_.flip map g)) (by ext; simp only [seq_eq_bind_map, flip, roption.bind_eq_bind, map_to_fun, roption.mem_bind_iff, bind_to_fun, preorder_hom.bind_to_fun, coe_apply, flip_to_fun]; refl) end continuous_hom end omega_complete_partial_order
2b9b86b393f337444d4991eb7b8fda50cc83fcca
fe25de614feb5587799621c41487aaee0d083b08
/src/Lean/Server/InfoUtils.lean
03452a8066a1f6f9fea31dce86c5251400f7e5e6
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,119
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.DocString import Lean.Elab.InfoTree import Lean.Util.Sorry protected structure String.Range where start : String.Pos stop : String.Pos deriving Inhabited, Repr def String.Range.contains (r : String.Range) (pos : String.Pos) : Bool := r.start <= pos && pos < r.stop def Lean.Syntax.getRange? (stx : Syntax) (originalOnly := false) : Option String.Range := match stx.getPos? originalOnly, stx.getTailPos? originalOnly with | some start, some stop => some { start, stop } | _, _ => none namespace Lean.Elab /-- For every branch, find the deepest node in that branch matching `p` with a surrounding context (the innermost one) and return all of them. -/ partial def InfoTree.deepestNodes (p : ContextInfo → Info → Std.PersistentArray InfoTree → Option α) : InfoTree → List α := go none where go ctx? | context ctx t => go ctx t | n@(node i cs) => let ccs := cs.toList.map (go <| i.updateContext? ctx?) let cs' := ccs.join if !cs'.isEmpty then cs' else match ctx? with | some ctx => match p ctx i cs with | some a => [a] | _ => [] | _ => [] | _ => [] partial def InfoTree.foldInfo (f : ContextInfo → Info → α → α) (init : α) : InfoTree → α := go none init where go ctx? a | context ctx t => go ctx a t | node i ts => let a := match ctx? with | none => a | some ctx => f ctx i a ts.foldl (init := a) (go <| i.updateContext? ctx?) | _ => a def Info.isTerm : Info → Bool | ofTermInfo _ => true | _ => false def Info.isCompletion : Info → Bool | ofCompletionInfo .. => true | _ => false def InfoTree.getCompletionInfos (infoTree : InfoTree) : Array (ContextInfo × CompletionInfo) := infoTree.foldInfo (init := #[]) fun ctx info result => match info with | Info.ofCompletionInfo info => result.push (ctx, info) | _ => result def Info.stx : Info → Syntax | ofTacticInfo i => i.stx | ofTermInfo i => i.stx | ofCommandInfo i => i.stx | ofMacroExpansionInfo i => i.stx | ofFieldInfo i => i.stx | ofCompletionInfo i => i.stx def Info.lctx : Info → LocalContext | Info.ofTermInfo i => i.lctx | Info.ofFieldInfo i => i.lctx | _ => LocalContext.empty def Info.pos? (i : Info) : Option String.Pos := i.stx.getPos? (originalOnly := true) def Info.tailPos? (i : Info) : Option String.Pos := i.stx.getTailPos? (originalOnly := true) def Info.range? (i : Info) : Option String.Range := i.stx.getRange? (originalOnly := true) def Info.contains (i : Info) (pos : String.Pos) : Bool := i.range?.any (·.contains pos) def Info.size? (i : Info) : Option Nat := OptionM.run do let pos ← i.pos? let tailPos ← i.tailPos? return tailPos - pos -- `Info` without position information are considered to have "infinite" size def Info.isSmaller (i₁ i₂ : Info) : Bool := match i₁.size?, i₂.pos? with | some sz₁, some sz₂ => sz₁ < sz₂ | some _, none => true | _, _ => false def Info.occursBefore? (i : Info) (hoverPos : String.Pos) : Option Nat := OptionM.run do let tailPos ← i.tailPos? guard (tailPos ≤ hoverPos) return hoverPos - tailPos def InfoTree.smallestInfo? (p : Info → Bool) (t : InfoTree) : Option (ContextInfo × Info) := let ts := t.deepestNodes fun ctx i _ => if p i then some (ctx, i) else none let infos := ts.map fun (ci, i) => let diff := i.tailPos?.get! - i.pos?.get! (diff, ci, i) infos.toArray.getMax? (fun a b => a.1 > b.1) |>.map fun (_, ci, i) => (ci, i) /-- Find an info node, if any, which should be shown on hover/cursor at position `hoverPos`. -/ partial def InfoTree.hoverableInfoAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) := t.smallestInfo? fun i => do if let Info.ofTermInfo ti := i then if ti.expr.isSyntheticSorry then return false if i matches Info.ofFieldInfo _ || i.toElabInfo?.isSome then return i.contains hoverPos return false /-- Construct a hover popup, if any, from an info node in a context.-/ def Info.fmtHover? (ci : ContextInfo) (i : Info) : IO (Option Format) := do ci.runMetaM i.lctx do let mut fmts := #[] try if let some f ← fmtTerm? then fmts := fmts.push f catch _ => pure () if let some f ← fmtDoc? then fmts := fmts.push f if fmts.isEmpty then none else f!"\n***\n".joinSep fmts.toList where fmtTerm? := do match i with | Info.ofTermInfo ti => let tp ← Meta.inferType ti.expr let eFmt ← Meta.ppExpr ti.expr let tpFmt ← Meta.ppExpr tp -- try not to show too scary internals let fmt := if isAtomicFormat eFmt then f!"{eFmt} : {tpFmt}" else tpFmt return some f!"```lean {fmt} ```" | Info.ofFieldInfo fi => let tp ← Meta.inferType fi.val let tpFmt ← Meta.ppExpr tp return some f!"```lean {fi.fieldName} : {tpFmt} ```" | _ => return none fmtDoc? := do if let Info.ofTermInfo ti := i then if let some n := ti.expr.constName? then return ← findDocString? n if let Info.ofFieldInfo fi := i then return ← findDocString? fi.projName if let some ei := i.toElabInfo? then return ← findDocString? ei.elaborator <||> findDocString? ei.stx.getKind return none isAtomicFormat : Format → Bool | Std.Format.text _ => true | Std.Format.group f _ => isAtomicFormat f | Std.Format.nest _ f => isAtomicFormat f | Std.Format.tag _ f => isAtomicFormat f | _ => false structure GoalsAtResult where ctxInfo : ContextInfo tacticInfo : TacticInfo useAfter : Bool /- Try to retrieve `TacticInfo` for `hoverPos`. We retrieve the `TacticInfo` `info`, if there is a node of the form `node (ofTacticInfo info) children` s.t. - `hoverPos` is sufficiently inside `info`'s range (see code), and - None of the `children` satisfy the condition above. That is, for composite tactics such as `induction`, we always give preference for information stored in nested (children) tactics. Moreover, we instruct the LSP server to use the state after the tactic execution if the hover is inside the info *and* there is no nested tactic info (i.e. it is a leaf tactic; tactic combinators should decide for themselves where to show intermediate/final states) -/ partial def InfoTree.goalsAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List GoalsAtResult := do t.deepestNodes fun | ctx, i@(Info.ofTacticInfo ti), cs => OptionM.run do let (some pos, some tailPos) ← pure (i.pos?, i.tailPos?) | failure let trailSize := i.stx.getTrailingSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos == text.source.bsize guard <| pos ≤ hoverPos ∧ (hoverPos < tailPos + trailSize || atEOF) return { ctxInfo := ctx, tacticInfo := ti, useAfter := hoverPos > pos && (hoverPos >= tailPos || !cs.any (hasNestedTactic pos tailPos)) } | _, _, _ => none where hasNestedTactic (pos tailPos) : InfoTree → Bool | InfoTree.node i@(Info.ofTacticInfo _) cs => do if let `(by $t) := i.stx then return false -- ignore term-nested proofs such as in `simp [show p by ...]` if let (some pos', some tailPos') := (i.pos?, i.tailPos?) then -- ignore nested infos of the same tactic, e.g. from expansion if (pos', tailPos') != (pos, tailPos) then return true cs.any (hasNestedTactic pos tailPos) | InfoTree.node (Info.ofMacroExpansionInfo _) cs => cs.any (hasNestedTactic pos tailPos) | _ => false /-- Find info nodes that should be used for the term goal feature. The main complication concerns applications like `f a b` where `f` is an identifier. In this case, the term goal at `f` should be the goal for the full application `f a b`. Therefore we first gather the position of these head function symbols such as `f`, and later ignore identifiers at these positions. -/ partial def InfoTree.termGoalAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) := let headFns : Std.HashSet String.Pos := t.foldInfo (init := {}) fun ctx i headFns => do if let some pos := getHeadFnPos? i.stx then headFns.insert pos else headFns t.smallestInfo? fun i => do if i.contains hoverPos then if let Info.ofTermInfo ti := i then return !ti.stx.isIdent || !headFns.contains i.pos?.get! false where /- Returns the position of the head function symbol, if it is an identifier. -/ getHeadFnPos? (s : Syntax) (foundArgs := false) : Option String.Pos := match s with | `(($s)) => getHeadFnPos? s foundArgs | `($f $as*) => getHeadFnPos? f (foundArgs := foundArgs || !as.isEmpty) | stx => if foundArgs && stx.isIdent then stx.getPos? else none end Lean.Elab
1dbcfbe54c95bdd3703d9bd30554947d00b21198
1dd482be3f611941db7801003235dc84147ec60a
/src/data/multiset.lean
ca71d66ce334364407b1e3dfe5a1a4e1617a27bd
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
126,119
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.list.basic data.list.perm data.list.sort data.quot data.string algebra.order_functions algebra.group_power algebra.ordered_group category.traversable.lemmas tactic.interactive category.traversable.instances category.basic open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} local infix ` • ` := add_monoid.smul instance list.perm.setoid (α : Type*) : setoid (list α) := setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩ /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.perm.setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_of_forall_not_mem H; refl theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by induction n; simp [succ_smul, *, nat.succ_mul] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl @[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := by refine_struct {..}; simp @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ @[simp] theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive multiset.sum_singleton] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive multiset.sum_add] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := by refine_struct {..}; simp @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive multiset.sum_repeat] prod_repeat @[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := multiset.induction_on m (by simp) (by simp) @[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := multiset.induction_on m (by simp) (by simp) attribute [to_additive multiset.sum_map_zero] prod_map_one @[simp, to_additive multiset.sum_map_add] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive multiset.sum_map_sum_map] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) lemma prod_hom [comm_monoid α] [comm_monoid β] (f : α → β) [is_monoid_hom f] (s : multiset α) : (s.map f).prod = f s.prod := multiset.induction_on s (by simp [is_monoid_hom.map_one f]) (by simp [is_monoid_hom.map_mul f] {contextual := tt}) lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma sum_hom [add_comm_monoid α] [add_comm_monoid β] (f : α → β) [is_add_monoid_hom f] (s : multiset α) : (s.map f).sum = f s.sum := multiset.induction_on s (by simp [is_add_monoid_hom.map_zero f]) (by simp [is_add_monoid_hom.map_add f] {contextual := tt}) attribute [to_additive multiset.sum_hom] multiset.prod_hom /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, -map_const, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive multiset.sum_bind] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _ @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- diagonal -/ theorem revzip_powerset_aux {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux l)) : s + t = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux' l)) : s + t = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃s t⦄, (s, t) ∈ revzip l' → s + t = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact perm_map _ powerset_aux_perm_powerset_aux', end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact perm_map _ (powerset_aux_perm p) end def diagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem diagonal_coe (l : list α) : @diagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem diagonal_coe' (l : list α) : @diagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' @[simp] theorem mem_diagonal {s₁ s₂ t : multiset α} : (s₁, s₂) ∈ diagonal t ↔ s₁ + s₂ = t := quotient.induction_on t $ λ l, begin simp [diagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], exact ⟨_, le_add_right _ _, rfl, add_sub_cancel_left _ _⟩ end @[simp] theorem diagonal_map_fst (s : multiset α) : (diagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_map_snd (s : multiset α) : (diagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_zero : @diagonal α 0 = (0, 0)::0 := rfl @[simp] theorem diagonal_cons (a : α) (s) : diagonal (a::s) = map (prod.map id (cons a)) (diagonal s) + map (prod.map (cons a) id) (diagonal s) := quotient.induction_on s $ λ l, begin simp [revzip, reverse_append], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_diagonal (s : multiset α) : card (diagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← diagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((diagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] }, end /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := by refine_struct {..}; simp theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom @[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[extensionality] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp [max_min_distrib_left], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero {} : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono (assume a b, h) lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem injective_map {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sup variables [semilattice_sup_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a :: s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup := fold_erase_dup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 (le_refl _) _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) end sup section inf variables [semilattice_inf_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a :: s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf := fold_erase_dup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 (le_refl _) _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) end inf section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp, split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset namespace multiset instance : functor multiset := { map := @map } instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F] variables {α' β' : Type u_1} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.skip { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end open functor open traversable is_lawful_traversable @[simp] lemma lift_beta {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_beta _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x (by { intro, rw [traverse,quotient.lift_beta,function.comp], simp, congr }) lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [comp_map,map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose /- Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := congr_arg coe $ list.Ico.filter_ge_of_le_bot hln lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = ∅ := congr_arg coe $ list.Ico.filter_ge_of_top_le hml lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := congr_arg coe $ list.Ico.filter_ge_of_ge hnl @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_ge n m l end Ico end multiset
a74b2f8b41b5aa46b289faed03d276f1ee869915
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/algebra/field.lean
548ff4f450d87eba600c928bce8465cc1065592b
[ "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
8,777
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 algebra.ring logic.basic open set universe u variables {α : Type u} -- Default priority sufficient as core version has custom-set lower priority (100) /-- Core version `division_ring_has_div` erratically requires two instances of `division_ring` -/ instance division_ring_has_div' [division_ring α] : has_div α := ⟨algebra.div⟩ instance division_ring.to_domain [s : division_ring α] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, classical.by_contradiction $ λ hn, division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h ..s } namespace units variables [division_ring α] {a b : α} /-- Embed an element of a division ring into the unit group. By combining this function with the operations on units, or the `/ₚ` operation, it is possible to write a division as a partial function with three arguments. -/ def mk0 (a : α) (ha : a ≠ 0) : units α := ⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩ @[simp] theorem inv_eq_inv (u : units α) : (↑u⁻¹ : α) = u⁻¹ := (mul_left_inj u).1 $ by rw [units.mul_inv, mul_inv_cancel]; apply units.ne_zero @[simp] theorem mk0_val (ha : a ≠ 0) : (mk0 a ha : α) = a := rfl @[simp] theorem mk0_inv (ha : a ≠ 0) : ((mk0 a ha)⁻¹ : α) = a⁻¹ := rfl @[simp] lemma mk0_coe (u : units α) (h : (u : α) ≠ 0) : mk0 (u : α) h = u := units.ext rfl @[simp] lemma units.mk0_inj [field α] {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : units.mk0 a ha = units.mk0 b hb ↔ a = b := ⟨λ h, by injection h, λ h, units.ext h⟩ end units section division_ring variables [s : division_ring α] {a b c : α} include s lemma div_eq_mul_inv : a / b = a * b⁻¹ := rfl attribute [simp] div_one zero_div div_self theorem divp_eq_div (a : α) (u : units α) : a /ₚ u = a / u := congr_arg _ $ units.inv_eq_inv _ @[simp] theorem divp_mk0 (a : α) {b : α} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div _ _ lemma inv_div (ha : a ≠ 0) (hb : b ≠ 0) : (a / b)⁻¹ = b / a := (mul_inv_eq (inv_ne_zero hb) ha).trans $ by rw division_ring.inv_inv hb; refl lemma inv_div_left (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ / b = (b * a)⁻¹ := (mul_inv_eq ha hb).symm lemma neg_inv (h : a ≠ 0) : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div _ h] lemma division_ring.inv_comm_of_comm (h : a ≠ 0) (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm, rwa [mul_assoc, mul_assoc, mul_inv_cancel, mul_one, ← mul_assoc, inv_mul_cancel, one_mul] at this; exact h end lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := division_ring.mul_ne_zero ha (inv_ne_zero hb) lemma div_ne_zero_iff (hb : b ≠ 0) : a / b ≠ 0 ↔ a ≠ 0 := ⟨mt (λ h, by rw [h, zero_div]), λ ha, div_ne_zero ha hb⟩ lemma div_eq_zero_iff (hb : b ≠ 0) : a / b = 0 ↔ a = 0 := by haveI := classical.prop_decidable; exact not_iff_not.1 (div_ne_zero_iff hb) lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma div_right_inj (hc : c ≠ 0) : a / c = b / c ↔ a = b := by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_right_inj] lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma division_ring.inv_inj (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b⁻¹ ↔ a = b := ⟨λ h, by rw [← division_ring.inv_inv ha, ← division_ring.inv_inv hb, h], congr_arg (λx,x⁻¹)⟩ lemma division_ring.inv_eq_iff (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b ↔ b⁻¹ = a := by rw [← division_ring.inv_inj (inv_ne_zero ha) hb, eq_comm, division_ring.inv_inv ha] lemma div_neg (a : α) (hb : b ≠ 0) : a / -b = -(a / b) := by rw [← division_ring.neg_div_neg_eq _ (neg_ne_zero.2 hb), neg_neg, neg_div] lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a := ⟨λ h, by rw [← h, div_mul_cancel _ hb], λ h, by rw [← h, mul_div_cancel _ hb]⟩ end division_ring instance field.to_integral_domain [F : field α] : integral_domain α := { ..F, ..division_ring.to_domain } section variables [field α] {a b c d : α} lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _ lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] lemma mul_div_right_comm (a b c : α) : (a * b) / c = (a / c) * b := (div_mul_eq_mul_div _ _ _).symm lemma mul_comm_div (a b c : α) : (a / b) * c = a * (c / b) := by rw [← mul_div_assoc, mul_div_right_comm] lemma div_mul_comm (a b c : α) : (a / b) * c = (c / b) * a := by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm] lemma mul_div_comm (a b c : α) : a * (b / c) = b * (a / c) := by rw [← mul_div_assoc, mul_comm, mul_div_assoc] lemma field.div_right_comm (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = (a / c) / b := by rw [field.div_div_eq_div_mul _ hb hc, field.div_div_eq_div_mul _ hc hb, mul_comm] lemma field.div_div_div_cancel_right (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := by rw [field.div_div_eq_mul_div _ hb hc, div_mul_cancel _ hc] lemma field.div_mul_div_cancel (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := by rw [← mul_div_assoc, div_mul_cancel _ hc] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := (domain.mul_right_inj (mul_ne_zero' hb hd)).symm.trans $ by rw [← mul_assoc, div_mul_cancel _ hb, ← mul_assoc, mul_right_comm, div_mul_cancel _ hd] lemma field.div_div_cancel (ha : a ≠ 0) (hb : b ≠ 0) : a / (a / b) = b := by rw [div_eq_mul_inv, inv_div ha hb, mul_div_cancel' _ ha] end section variables [discrete_field α] {a b c : α} attribute [simp] inv_zero div_zero lemma div_right_comm (a b c : α) : (a / b) / c = (a / c) / b := if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else if c0 : c = 0 then by simp only [c0, div_zero, zero_div] else field.div_right_comm _ b0 c0 lemma div_div_div_cancel_right (a b : α) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else field.div_div_div_cancel_right _ b0 hc lemma div_mul_div_cancel (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := if b0 : b = 0 then by simp only [b0, div_zero, mul_zero] else field.div_mul_div_cancel _ b0 hc lemma div_div_cancel (ha : a ≠ 0) : a / (a / b) = b := if b0 : b = 0 then by simp only [b0, div_zero] else field.div_div_cancel ha b0 @[simp] lemma inv_eq_zero (a : α) : a⁻¹ = 0 ↔ a = 0 := classical.by_cases (assume : a = 0, by simp [*])(assume : a ≠ 0, by simp [*, inv_ne_zero]) lemma neg_inv' (a : α) : (-a)⁻¹ = - a⁻¹ := begin by_cases a = 0, { rw [h, neg_zero, inv_zero, neg_zero] }, { rw [neg_inv h] } end end @[reducible] def is_field_hom {α β} [division_ring α] [division_ring β] (f : α → β) := is_ring_hom f namespace is_field_hom open is_ring_hom section variables {β : Type*} [division_ring α] [division_ring β] variables (f : α → β) [is_field_hom f] {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := ⟨mt $ λ h, h.symm ▸ map_zero f, λ x0 h, one_ne_zero $ calc 1 = f (x * x⁻¹) : by rw [mul_inv_cancel x0, map_one f] ... = 0 : by rw [map_mul f, h, zero_mul]⟩ lemma map_eq_zero : f x = 0 ↔ x = 0 := by haveI := classical.dec; exact not_iff_not.1 (map_ne_zero f) lemma map_inv' (h : x ≠ 0) : f x⁻¹ = (f x)⁻¹ := (domain.mul_left_inj ((map_ne_zero f).2 h)).1 $ by rw [mul_inv_cancel ((map_ne_zero f).2 h), ← map_mul f, mul_inv_cancel h, map_one f] lemma map_div' (h : y ≠ 0) : f (x / y) = f x / f y := (map_mul f).trans $ congr_arg _ $ map_inv' f h lemma injective : function.injective f := (is_add_group_hom.injective_iff _).2 (λ a ha, classical.by_contradiction $ λ ha0, by simpa [ha, is_ring_hom.map_mul f, is_ring_hom.map_one f, zero_ne_one] using congr_arg f (mul_inv_cancel ha0)) end section variables {β : Type*} [discrete_field α] [discrete_field β] variables (f : α → β) [is_field_hom f] {x y : α} lemma map_inv : f x⁻¹ = (f x)⁻¹ := classical.by_cases (by rintro rfl; simp only [map_zero f, inv_zero]) (map_inv' f) lemma map_div : f (x / y) = f x / f y := (map_mul f).trans $ congr_arg _ $ map_inv f end end is_field_hom
0a661574e68765c17846f8d7a880953a71a1b6ca
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/big_operators/order.lean
a9763dc15587915b7d800b0bd792e1d7d3611f87
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
16,644
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 algebra.big_operators.basic /-! # Results about big operators with values in an ordered algebraic structure. Mostly monotonicity results for the `∑` operation. -/ universes u v w open_locale big_operators variables {α : Type u} {β : Type v} {γ : Type w} namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive le_sum_nonempty_of_subadditive_on_pred] lemma le_prod_nonempty_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_mul : ∀ x y, p x → p y → f (x * y) ≤ f x * f y) (hp_mul : ∀ x y, p x → p y → p (x * y)) (g : γ → α) (s : finset γ) (hs_nonempty : s.nonempty) (hs : ∀ x, x ∈ s → p (g x)) : f (∏ x in s, g x) ≤ ∏ x in s, f (g x) := begin refine le_trans (multiset.le_prod_nonempty_of_submultiplicative_on_pred f p h_mul hp_mul _ _ _) _, { simp [nonempty_iff_ne_empty.mp hs_nonempty], }, { exact multiset.forall_mem_map_iff.mpr hs, }, rw multiset.map_map, refl, end @[to_additive le_sum_nonempty_of_subadditive] lemma le_prod_nonempty_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_mul : ∀ x y, f (x * y) ≤ f x * f y) {s : finset γ} (hs : s.nonempty) (g : γ → α) : f (∏ x in s, g x) ≤ ∏ x in s, f (g x) := le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (by simp [h_mul]) (by simp) g s hs (by simp) @[to_additive le_sum_of_subadditive_on_pred] lemma le_prod_of_submultiplicative_on_pred [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (p : α → Prop) (h_one : f 1 = 1) (h_mul : ∀ x y, p x → p y → f (x * y) ≤ f x * f y) (hp_mul : ∀ x y, p x → p y → p (x * y)) (g : γ → α) {s : finset γ} (hs : ∀ x, x ∈ s → p (g x)) : f (∏ x in s, g x) ≤ ∏ x in s, f (g x) := begin by_cases hs_nonempty : s.nonempty, { exact le_prod_nonempty_of_submultiplicative_on_pred f p h_mul hp_mul g s hs_nonempty hs, }, { simp [not_nonempty_iff_eq_empty.mp hs_nonempty, h_one], }, end @[to_additive le_sum_of_subadditive] lemma le_prod_of_submultiplicative [comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_one : f 1 = 1) (h_mul : ∀ x y, f (x * y) ≤ f x * f y) (s : finset γ) (g : γ → α) : f (∏ x in s, g x) ≤ ∏ x in s, f (g x) := begin refine le_trans (multiset.le_prod_of_submultiplicative f h_one h_mul _) _, rw multiset.map_map, refl, end lemma abs_sum_le_sum_abs [linear_ordered_field α] {f : β → α} {s : finset β} : abs (∑ x in s, f x) ≤ ∑ x in s, abs (f x) := le_sum_of_subadditive _ abs_zero abs_add s f lemma abs_prod [linear_ordered_comm_ring α] {f : β → α} {s : finset β} : abs (∏ x in s, f x) = ∏ x in s, abs (f x) := (abs_hom.to_monoid_hom : α →* α).map_prod _ _ section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → (∑ x in s, f x) ≤ (∑ x in s, g x) := begin classical, apply finset.induction_on s, exact (λ _, le_refl _), assume a s ha ih h, have : f a + (∑ x in s, f x) ≤ g a + (∑ x in s, g x), from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] end theorem card_le_mul_card_image_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * t.card := calc s.card = (∑ a in t, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_fiberwise Hf ... ≤ (∑ _ in t, n) : sum_le_sum hn ... = _ : by simp [mul_comm] theorem card_le_mul_card_image [decidable_eq γ] {f : α → γ} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := card_le_mul_card_image_of_maps_to (λ x, mem_image_of_mem _) n hn theorem mul_card_image_le_card_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, n ≤ (s.filter (λ x, f x = a)).card) : n * t.card ≤ s.card := calc n * t.card = (∑ _ in t, n) : by simp [mul_comm] ... ≤ (∑ a in t, (s.filter (λ x, f x = a)).card) : sum_le_sum hn ... = s.card : by rw ← card_eq_sum_card_fiberwise Hf theorem mul_card_image_le_card [decidable_eq γ] {f : α → γ} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, n ≤ (s.filter (λ x, f x = a)).card) : n * (s.image f).card ≤ s.card := mul_card_image_le_card_of_maps_to (λ x, mem_image_of_mem _) n hn lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ (∑ x in s, f x) := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : (∑ x in s, f x) ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := by classical; calc (∑ x in s₁, f x) ≤ (∑ x in s₂ \ s₁, f x) + (∑ x in s₁, f x) : le_add_of_nonneg_left $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = ∑ x in s₂ \ s₁ ∪ s₁, f x : (sum_union sdiff_disjoint).symm ... = (∑ x in s₂, f x) : by rw [sdiff_union_of_subset h] lemma sum_mono_set_of_nonneg (hf : ∀ x, 0 ≤ f x) : monotone (λ s, ∑ x in s, f x) := λ s₁ s₂ hs, sum_le_sum_of_subset_of_nonneg hs $ λ x _ _, hf x lemma sum_fiberwise_le_sum_of_sum_fiber_nonneg [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} {f : α → β} (h : ∀ y ∉ t, (0 : β) ≤ ∑ x in s.filter (λ x, g x = y), f x) : (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ ∑ x in s, f x := calc (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ (∑ y in t ∪ s.image g, ∑ x in s.filter (λ x, g x = y), f x) : sum_le_sum_of_subset_of_nonneg (subset_union_left _ _) $ λ y hyts, h y ... = ∑ x in s, f x : sum_fiberwise_of_maps_to (λ x hx, mem_union.2 $ or.inr $ mem_image_of_mem _ hx) _ lemma sum_le_sum_fiberwise_of_sum_fiber_nonpos [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} {f : α → β} (h : ∀ y ∉ t, (∑ x in s.filter (λ x, g x = y), f x) ≤ 0) : (∑ x in s, f x) ≤ ∑ y in t, ∑ x in s.filter (λ x, g x = y), f x := @sum_fiberwise_le_sum_of_sum_fiber_nonneg α (order_dual β) _ _ _ _ _ _ _ h lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) := begin classical, apply finset.induction_on s, exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩, assume a s ha ih H, have : ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] end lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ (∑ x in s, f x) := have ∑ x in {a}, f x ≤ (∑ x in s, f x), from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_add_comm_monoid section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid β] @[simp] lemma sum_eq_zero_iff : ∑ x in s, f x = 0 ↔ ∀ x ∈ s, f x = 0 := sum_eq_zero_iff_of_nonneg $ λ x hx, zero_le (f x) lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_mono_set (f : α → β) : monotone (λ s, ∑ x in s, f x) := λ s₁ s₂ hs, sum_le_sum_of_subset hs lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := by classical; calc (∑ x in s₁, f x) = ∑ x in s₁.filter (λx, f x = 0), f x + ∑ x in s₁.filter (λx, f x ≠ 0), f x : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ (∑ x in s₂, f x) : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_add_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_add_comm_monoid β] theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : (∑ x in s, f x) < (∑ x in s, g x) := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)], exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj) end lemma sum_lt_sum_of_nonempty (hs : s.nonempty) (Hlt : ∀ x ∈ s, f x < g x) : (∑ x in s, f x) < (∑ x in s, g x) := begin apply sum_lt_sum, { intros i hi, apply le_of_lt (Hlt i hi) }, cases hs with i hi, exact ⟨i, hi, Hlt i hi⟩, end lemma sum_lt_sum_of_subset [decidable_eq α] (h : s₁ ⊆ s₂) {i : α} (hi : i ∈ s₂ \ s₁) (hpos : 0 < f i) (hnonneg : ∀ j ∈ s₂ \ s₁, 0 ≤ f j) : (∑ x in s₁, f x) < (∑ x in s₂, f x) := calc (∑ x in s₁, f x) < (∑ x in insert i s₁, f x) : begin simp only [mem_sdiff] at hi, rw sum_insert hi.2, exact lt_add_of_pos_left (∑ x in s₁, f x) hpos, end ... ≤ (∑ x in s₂, f x) : begin simp only [mem_sdiff] at hi, apply sum_le_sum_of_subset_of_nonneg, { simp [finset.insert_subset, h, hi.1] }, { assume x hx h'x, apply hnonneg x, simp [mem_insert, not_or_distrib] at h'x, rw mem_sdiff, simp [hx, h'x] } end end ordered_cancel_comm_monoid section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_add_comm_monoid β] theorem exists_lt_of_sum_lt (Hlt : (∑ x in s, f x) < ∑ x in s, g x) : ∃ i ∈ s, f i < g i := begin contrapose! Hlt with Hle, exact sum_le_sum Hle end theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : (∑ x in s, f x) ≤ ∑ x in s, g x) : ∃ i ∈ s, f i ≤ g i := begin contrapose! Hle with Hlt, rcases hs with ⟨i, hi⟩, exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩ end lemma exists_pos_of_sum_zero_of_exists_nonzero (f : α → β) (h₁ : ∑ e in s, f e = 0) (h₂ : ∃ x ∈ s, f x ≠ 0) : ∃ x ∈ s, 0 < f x := begin contrapose! h₁, obtain ⟨x, m, x_nz⟩ : ∃ x ∈ s, f x ≠ 0 := h₂, apply ne_of_lt, calc ∑ e in s, f e < ∑ e in s, 0 : sum_lt_sum h₁ ⟨x, m, lt_of_le_of_ne (h₁ x m) x_nz⟩ ... = 0 : by rw [finset.sum_const, nsmul_zero], end end linear_ordered_cancel_comm_monoid section ordered_comm_ring variables [ordered_comm_ring β] open_locale classical /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ (∏ x in s, f x) := prod_induction f (λ x, 0 ≤ x) (λ _ _ ha hb, mul_nonneg ha hb) zero_le_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos [nontrivial β] {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < (∏ x in s, f x) := prod_induction f (λ x, 0 < x) (λ _ _ ha hb, mul_pos ha hb) zero_lt_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : (∏ x in s, f x) ≤ (∏ x in s, g x) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end lemma prod_le_one {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ 1) : (∏ x in s, f x) ≤ 1 := begin convert ← prod_le_prod h0 h1, exact finset.prod_const_one end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `linear_ordered_comm_ring`. -/ lemma prod_add_prod_le {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) (hg : ∀ i ∈ s, 0 ≤ g i) (hh : ∀ i ∈ s, 0 ≤ h i) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin simp_rw [← mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_of_nonneg_right h2i _), { rw [right_distrib], apply add_le_add; apply mul_le_mul_of_nonneg_left; try { apply prod_le_prod }; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption }, { apply prod_nonneg, simp only [and_imp, mem_sdiff, mem_singleton], intros j h1j h2j, refine le_trans (hg j h1j) (hgf j h1j h2j) } end end ordered_comm_ring section canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring β] lemma prod_le_prod' {s : finset α} {f g : α → β} (h : ∀ i ∈ s, f i ≤ g i) : (∏ x in s, f x) ≤ (∏ x in s, g x) := begin classical, induction s using finset.induction with a s has ih h, { simp }, { rw [finset.prod_insert has, finset.prod_insert has], apply canonically_ordered_semiring.mul_le_mul, { exact h _ (finset.mem_insert_self a s) }, { exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } } end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `canonically_ordered_comm_semiring`. -/ lemma prod_add_prod_le' {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin classical, simp_rw [← mul_prod_diff_singleton hi], refine le_trans _ (canonically_ordered_semiring.mul_le_mul_right' h2i _), rw [right_distrib], apply add_le_add; apply canonically_ordered_semiring.mul_le_mul_left'; apply prod_le_prod'; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption end end canonically_ordered_comm_semiring end finset namespace fintype variables [fintype α] @[mono] lemma sum_mono [ordered_add_comm_monoid β] : monotone (λ f : α → β, ∑ x, f x) := λ f g hfg, finset.sum_le_sum $ λ x _, hfg x lemma sum_strict_mono [ordered_cancel_add_comm_monoid β] : strict_mono (λ f : α → β, ∑ x, f x) := λ f g hfg, let ⟨hle, i, hlt⟩ := pi.lt_def.mp hfg in finset.sum_lt_sum (λ i _, hle i) ⟨i, finset.mem_univ i, hlt⟩ end fintype namespace with_top open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top [canonically_ordered_comm_semiring β] [nontrivial β] [decidable_eq β] {s : finset α} {f : α → with_top β} (h : ∀ a ∈ s, f a < ⊤) : (∏ x in s, f x) < ⊤ := prod_induction f (λ a, a < ⊤) (λ a b, mul_lt_top) (coe_lt_top 1) h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_add_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → (∑ x in s, f x) < ⊤ := λ h, sum_induction f (λ a, a < ⊤) (by { simp_rw add_lt_top, tauto }) zero_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : (∑ x in s, f x) < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : (∑ x in s, f x) = ⊤ ↔ (∃a∈s, f a = ⊤) := begin rw ← not_iff_not, push_neg, simp only [← lt_top_iff_ne_top], exact sum_lt_top_iff end end with_top
4b72fb4719f61fa92f9e708f5a809557fe7f0628
ca1ad81c8733787aba30f7a8d63f418508e12812
/clfrags/src/hilbert/wr/proofs/dc_pt.lean
88a5f31e31d7bc12812668085db07e0272b0030b
[]
no_license
greati/hilbert-classical-fragments
5cdbe07851e979c8a03c621a5efd4d24bbfa333a
18a21ac6b2e890060eb4ae65752fc0245394d226
refs/heads/master
1,591,973,117,184
1,573,822,710,000
1,573,822,710,000
194,334,439
2
0
null
null
null
null
UTF-8
Lean
false
false
28,545
lean
import hilbert.wr.dc_pt namespace clfrags namespace hilbert namespace wr namespace dc_pt theorem dc₁_pt {a b c d e : Prop} (h₁ : pt d e a) (h₂ : pt d e b) : pt d e (dc a b c) := have h₃ : dc (pt d e a) (pt d e b) (pt d e c), from dc.dc₁ h₁ h₂, show pt d e (dc a b c), from dcpt₄ h₃ theorem dc₂_pt {a b c d : Prop} (h₁ : pt c d (dc b a a)) : pt c d a := dc.dc₂ (dcpt₃ h₁) theorem dc₃_pt {a b c d: Prop} (h₁ : pt c d a) : pt c d (dc b a a) := dcpt₄ (dc.dc₃ h₁) theorem dc₄_pt {a b c d e f g : Prop} (h₁ : pt f g (dc d e (dc a b c))) : pt f g (dc e d (dc b a c)) := have h₂ : dc (pt f g d) (pt f g e) (pt f g (dc a b c)), from dcpt₃ h₁, have h₃ : dc (pt f g d) (pt f g e) (dc (pt f g a) (pt f g b) (pt f g c)), from dcpt₅ h₂, have h₄ : dc (pt f g e) (pt f g d) (dc (pt f g b) (pt f g a) (pt f g c)), from dc.dc₄ h₃, have h₅ : dc (pt f g e) (pt f g d) (pt f g (dc b a c)), from dcpt₆ h₄, show pt f g (dc e d (dc b a c)), from dcpt₄ h₅ theorem dc₅_pt {a b c d e f g : Prop} (h₁ : pt f g (dc d e (dc a b c))) : pt f g (dc e d (dc a c b)) := have h₂ : dc (pt f g d) (pt f g e) (pt f g (dc a b c)), from dcpt₃ h₁, have h₃ : dc (pt f g d) (pt f g e) (dc (pt f g a) (pt f g b) (pt f g c)), from dcpt₅ h₂, have h₄ : dc (pt f g e) (pt f g d) (dc (pt f g a) (pt f g c) (pt f g b)), from dc.dc₅ h₃, have h₅ : dc (pt f g e) (pt f g d) (pt f g (dc a c b)), from dcpt₆ h₄, show pt f g (dc e d (dc a c b)), from dcpt₄ h₅ theorem dcpt₅_dc {a b c d e f g h i : Prop} (h₁ : dc h i (dc f g (pt a b (dc c d e)))) : dc h i (dc f g (dc (pt a b c) (pt a b d) (pt a b e))) := dc.dc₇' (dcpt₅ (dc.dc₆' h₁)) theorem dcpt₆_dc {a b c d e f g h i : Prop} (h₁ : dc h i (dc f g (dc (pt a b c) (pt a b d) (pt a b e)))) : dc h i (dc f g (pt a b (dc c d e))) := dc.dc₇' (dcpt₆ (dc.dc₆' h₁)) theorem dc₆_pt {a b c d e f g h i : Prop} (h₁ : pt h i (dc f g (dc d e (dc a b c)))) : pt h i (dc f g (dc (dc d e a) (dc d e b) c)) := let f' := pt h i f, g' := pt h i g, d' := pt h i d, e' := pt h i e in have h₂ : dc f' g' (pt h i (dc d e (dc a b c))), from dcpt₃ h₁, have h₃ : dc f' g' (dc d' e' (pt h i (dc a b c))), from dcpt₅ h₂, have h₄ : dc (dc f' g' d') (dc f' g' e') ((pt h i (dc a b c))), from dc.dc₆' h₃, have h₅ : dc (dc f' g' d') (dc f' g' e') (dc (pt h i a) (pt h i b) (pt h i c)), from dcpt₅ h₄, have h₆ : dc f' g' (dc d' e' (dc (pt h i a) (pt h i b) (pt h i c))), from dc.dc₇' h₅, have h₇ : dc f' g' (dc (dc d' e' (pt h i a)) (dc d' e' (pt h i b)) (pt h i c)), from dc.dc₆ h₆, have h₈ : dc g' f' (dc (dc d' e' (pt h i a)) (pt h i c) (dc d' e' (pt h i b))), from dc.dc₅ h₇, have h₉ : dc g' f' (dc (dc d' e' (pt h i a)) (pt h i c) (pt h i (dc d e b))), from dcpt₆_dc h₈, have h₁₀ : dc g' f' (dc (pt h i c) (pt h i (dc d e b)) (dc d' e' (pt h i a))), from dc.dc₅ (dc.dc₄ h₉), have h₁₁ : dc g' f' (dc (pt h i c) (pt h i (dc d e b)) (pt h i (dc d e a))), from dcpt₆_dc h₁₀, have h₁₂ : dc f' g' (dc (pt h i (dc d e a)) (pt h i (dc d e b)) (pt h i c)), from dc.dc₅ (dc.dc₄ (dc.dc₅ h₁₁)), have h₁₃ : dc f' g' (pt h i (dc (dc d e a) (dc d e b) c)), from dcpt₆ h₁₂, show pt h i (dc f g (dc (dc d e a) (dc d e b) c)), from dcpt₄ h₁₃ theorem dc₇_pt {a b c d e f g h i: Prop} (h₁ : pt h i (dc f g (dc (dc d e a) (dc d e b) c))) : pt h i (dc f g (dc d e (dc a b c))) := let f' := pt h i f, g' := pt h i g, d' := pt h i d, e' := pt h i e in have h₂ : dc f' g' (pt h i (dc (dc d e a) (dc d e b) c)), from dcpt₃ h₁, have h₃ : dc f' g' (dc (pt h i (dc d e a)) (pt h i (dc d e b)) (pt h i c)), from dcpt₅ h₂, have h₄ : dc g' f' (dc (pt h i (dc d e a)) (pt h i c) (pt h i (dc d e b))), from dc.dc₅ h₃, have h₅ : dc g' f' (dc (pt h i (dc d e a)) (pt h i c) (dc d' e' (pt h i b))), from dcpt₅_dc h₄, have h₆ : dc g' f' (dc (pt h i c) (dc d' e' (pt h i b)) (pt h i (dc d e a))), from dc.dc₅ (dc.dc₄ h₅), have h₇ : dc g' f' (dc (pt h i c) (dc d' e' (pt h i b)) (dc d' e' (pt h i a))), from dcpt₅_dc h₆, have h₈ : dc f' g' (dc (dc d' e' (pt h i a)) (dc d' e' (pt h i b)) (pt h i c)), from dc.dc₅ (dc.dc₄ (dc.dc₅ h₇)), have h₉ : dc f' g' (dc d' e' (dc (pt h i a) (pt h i b) (pt h i c))), from dc.dc₇ h₈, have h₁₀ : dc f' g' (dc d' e' (pt h i (dc a b c))), from dcpt₆_dc h₉, have h₁₁ : dc f' g' (pt h i (dc d e (dc a b c))), from dcpt₆ h₁₀, show pt h i (dc f g (dc d e (dc a b c))), from dcpt₄ h₁₁ theorem dc₄'_pt {a b c d e : Prop} (h₁ : pt d e (dc a b c)) : pt d e (dc b a c) := have h₂ : pt d e (dc (dc b a c) (dc a b c) (dc a b c)), from dc₃_pt h₁, have h₃ : pt d e (dc (dc a b c) (dc b a c) (dc b a c)), from dc₄_pt h₂, show pt d e (dc b a c), from dc₂_pt h₃ theorem dc₅'_pt {a b c d e : Prop} (h₁ : pt d e (dc a b c)) : pt d e (dc a c b) := have h₂ : pt d e (dc (dc a c b) (dc a b c) (dc a b c)), from dc₃_pt h₁, have h₃ : pt d e (dc (dc a b c) (dc a c b) (dc a c b)), from dc₅_pt h₂, show pt d e (dc a c b), from dc₂_pt h₃ theorem dc₆'_pt {a b c d e f g : Prop} (h₁ : pt f g (dc d e (dc a b c))) : pt f g (dc (dc d e a) (dc d e b) c) := let h := dc d e (dc a b c), i := dc (dc d e a) (dc d e b) c in have h₂ : pt f g (dc i h h), from dc₃_pt h₁, have h₃ : pt f g (dc i h i), from dc₆_pt h₂, have h₄ : pt f g (dc h i i), from dc₄'_pt h₃, show pt f g i, from dc₂_pt h₄ theorem dc₇'_pt {a b c d e f g : Prop} (h₁ : pt f g (dc (dc d e a) (dc d e b) c)) : pt f g (dc d e (dc a b c)) := let h := dc d e (dc a b c), i := dc (dc d e a) (dc d e b) c in have h₂ : pt f g (dc h i i), from dc₃_pt h₁, have h₃ : pt f g (dc h i h), from dc₇_pt h₂, have h₄ : pt f g (dc i h h), from dc₄'_pt h₃, show pt f g h, from dc₂_pt h₄ theorem pt₁_dc {a b c d e : Prop} (h₁ : dc d e a) (h₂ : dc d e b) (h₃ : dc d e c) : dc d e (pt a b c) := dcpt₂ (pt.pt₁ h₁ h₂ h₃) theorem pt₂_dc {a b c d e : Prop} (h₁ : dc d e (pt a b c)) : dc d e (pt b a c) := dcpt₂ (pt.pt₂ (dcpt₁ h₁)) theorem pt₃_dc {a b c d e : Prop} (h₁ : dc d e (pt a b c)) : dc d e (pt a c b) := dcpt₂ (pt.pt₃ (dcpt₁ h₁)) theorem pt₄_dc {a b c d : Prop} (h₁ : dc c d a) : dc c d (pt a b b) := dcpt₂ (pt.pt₄ h₁) theorem pt₅_dc {a b c d : Prop} (h₁ : dc c d (pt a b b)) : dc c d a := pt.pt₅ (dcpt₁ h₁) theorem pt₆_dc {a b c d e f g : Prop} (h₁ : dc f g (pt a b (pt c d e))) : dc f g (pt (pt a b c) d e) := have h₂ : pt (dc f g a) (dc f g b) (dc f g (pt c d e)), from dcpt₁ h₁, have h₃ : pt (dc f g a) (dc f g b) (pt (dc f g c) (dc f g d) (dc f g e)), from dcpt₇ h₂, have h₄ : pt (pt (dc f g a) (dc f g b) (dc f g c)) (dc f g d) (dc f g e), from pt.pt₆ h₃, have h₅ : pt (dc f g d) (dc f g e) (pt (dc f g a) (dc f g b) (dc f g c)), from pt.pt₃ (pt.pt₂ h₄), have h₆ : pt (dc f g d) (dc f g e) (dc f g (pt a b c)), from dcpt₈ h₅, have h₇ : pt (dc f g (pt a b c)) (dc f g d) (dc f g e) , from pt.pt₂ (pt.pt₃ h₆), show dc f g (pt (pt a b c) d e), from dcpt₂ h₇ theorem dcpt₁_dc {a b c d e f g : Prop} (h₁ : dc f g (dc a b (pt c d e))) : dc f g (pt (dc a b c) (dc a b d) (dc a b e)) := let a' := dc f g a, b' := dc f g b, d' := dc a b d, e' := dc a b e in have h₁ : dc a' b' (pt c d e), from dc.dc₆' h₁, have h₂ : pt (dc a' b' c) (dc a' b' d) (dc a' b' e), from dcpt₁ h₁, have h₃ : pt (dc a' b' c) (dc a' b' d) (dc f g e'), from dc₇'_pt h₂, have h₄ : pt (dc a' b' c) (dc f g e') (dc a' b' d), from pt.pt₃ h₃, have h₅ : pt (dc a' b' c) (dc f g e') (dc f g d'), from dc₇'_pt h₄, have h₆ : pt (dc f g e') (dc f g d') (dc a' b' c), from pt.pt₃ (pt.pt₂ h₅), have h₇ : pt (dc f g e') (dc f g d') (dc f g (dc a b c)), from dc₇'_pt h₆, have h₈ : pt (dc f g (dc a b c)) (dc f g d') (dc f g e'), from pt.pt₂ (pt.pt₃ (pt.pt₂ h₇)), show dc f g (pt (dc a b c) d' e'), from dcpt₂ h₈ theorem dcpt₂_dc {a b c d e f g : Prop} (h₁ : dc f g (pt (dc a b c) (dc a b d) (dc a b e))) : dc f g (dc a b (pt c d e)) := let a' := dc f g a, b' := dc f g b, d' := dc a b d, e' := dc a b e in have h₂ : pt (dc f g (dc a b c)) (dc f g d') (dc f g e'), from dcpt₁ h₁, have h₃ : pt (dc f g (dc a b c)) (dc f g d') (dc a' b' e), from dc₆'_pt h₂, have h₄ : pt (dc f g (dc a b c)) (dc a' b' e) (dc f g d'), from pt.pt₃ h₃, have h₅ : pt (dc f g (dc a b c)) (dc a' b' e) (dc a' b' d), from dc₆'_pt h₄, have h₆ : pt (dc a' b' e) (dc a' b' d) (dc f g (dc a b c)), from pt.pt₃ (pt.pt₂ h₅), have h₇ : pt (dc a' b' e) (dc a' b' d) (dc a' b' c), from dc₆'_pt h₆, have h₈ : pt (dc a' b' c) (dc a' b' d) (dc a' b' e), from pt.pt₂ (pt.pt₃ (pt.pt₂ h₇)), have h₉ : dc a' b' (pt c d e), from dcpt₂ h₈, show dc f g (dc a b (pt c d e)), from dc.dc₇' h₉ theorem dcpt₃_dc {a b c d e f g : Prop} (h₁ : dc f g (pt a b (dc c d e))) : dc f g (dc (pt a b c) (pt a b d) (pt a b e)) := dcpt₅ h₁ theorem dcpt₄_dc {a b c d e f g : Prop} (h₁ : dc f g (dc (pt a b c) (pt a b d) (pt a b e))) : dc f g (pt a b (dc c d e)) := dcpt₆ h₁ -- dcpt₅_dc : done above -- dcpt₆_dc : done above theorem dcpt₇_dc {a b c d e f g h i : Prop} (h₁ : dc h i (pt f g (dc a b (pt c d e)))) : dc h i (pt f g (pt (dc a b c) (dc a b d) (dc a b e))) := let f' := dc h i f, g' := dc h i g, a' := dc h i a, b' := dc h i b in have h₂ : pt f' g' (dc h i (dc a b (pt c d e))), from dcpt₁ h₁, have h₃ : pt f' g' (dc a' b' (pt c d e)), from dc₆'_pt h₂, have h₄ : pt f' g' (pt (dc a' b' c) (dc a' b' d) (dc a' b' e)), from dcpt₇ h₃, have h₅ : pt (pt f' g' (dc a' b' c)) (dc a' b' d) (dc a' b' e), from pt.pt₆ h₄, have h₆ : pt (pt f' g' (dc a' b' c)) (dc a' b' d) (dc h i (dc a b e)), from dc₇'_pt h₅, have h₇ : pt (pt f' g' (dc a' b' c)) (dc h i (dc a b e)) (dc a' b' d), from pt.pt₃ h₆, have h₈ : pt (pt f' g' (dc a' b' c)) (dc h i (dc a b e)) (dc h i (dc a b d)), from dc₇'_pt h₇, have h₉ : pt f' g' (pt (dc a' b' c) (dc h i (dc a b e)) (dc h i (dc a b d))), from pt.pt₇ h₈, have h₁₀ : pt f' g' (pt (dc h i (dc a b e)) (dc h i (dc a b d)) (dc a' b' c)), from pt.pt₃_pt (pt.pt₂_pt h₉), have h₁₁ : pt (pt f' g' (dc h i (dc a b e))) (dc h i (dc a b d)) (dc a' b' c), from pt.pt₆ h₁₀, have h₁₂ : pt (pt f' g' (dc h i (dc a b e))) (dc h i (dc a b d)) (dc h i (dc a b c)), from dc₇'_pt h₁₁, have h₁₃ : pt f' g' (pt (dc h i (dc a b e)) (dc h i (dc a b d)) (dc h i (dc a b c))), from pt.pt₇ h₁₂, have h₁₄ : pt f' g' (pt (dc h i (dc a b c)) (dc h i (dc a b d)) (dc h i (dc a b e))), from pt.pt₂_pt (pt.pt₃_pt (pt.pt₂_pt h₁₃)), have h₁₅ : pt f' g' (dc h i (pt (dc a b c) (dc a b d) (dc a b e))), from dcpt₈ h₁₄, show dc h i (pt f g (pt (dc a b c) (dc a b d) (dc a b e))), from dcpt₂ h₁₅ theorem dcpt₈_dc {a b c d e f g h i : Prop} (h₁ : dc h i (pt f g (pt (dc a b c) (dc a b d) (dc a b e)))) : dc h i (pt f g (dc a b (pt c d e))) := let f' := dc h i f, g' := dc h i g, a' := dc h i a, b' := dc h i b in have h₂ : pt f' g' (dc h i (pt (dc a b c) (dc a b d) (dc a b e))), from dcpt₁ h₁, have h₃ : pt f' g' (pt (dc h i (dc a b c)) (dc h i (dc a b d)) (dc h i (dc a b e))), from dcpt₇ h₂, have h₄ : pt (pt f' g' (dc h i (dc a b c))) (dc h i (dc a b d)) (dc h i (dc a b e)), from pt.pt₆ h₃, have h₅ : pt (pt f' g' (dc h i (dc a b c))) (dc h i (dc a b d)) (dc a' b' e), from dc₆'_pt h₄, have h₆ : pt (pt f' g' (dc h i (dc a b c))) (dc a' b' e) (dc h i (dc a b d)), from pt.pt₃ h₅, have h₇ : pt (pt f' g' (dc h i (dc a b c))) (dc a' b' e) (dc a' b' d), from dc₆'_pt h₆, have h₈ : pt f' g' (pt (dc h i (dc a b c)) (dc a' b' e) (dc a' b' d)), from pt.pt₇ h₇, have h₉ : pt f' g' (pt (dc a' b' e) (dc a' b' d) (dc h i (dc a b c))), from pt.pt₃_pt (pt.pt₂_pt h₈), have h₁₀ : pt (pt f' g' (dc a' b' e)) (dc a' b' d) (dc h i (dc a b c)), from pt.pt₆ h₉, have h₁₁ : pt (pt f' g' (dc a' b' e)) (dc a' b' d) (dc a' b' c), from dc₆'_pt h₁₀, have h₁₂ : pt f' g' (pt (dc a' b' e) (dc a' b' d) (dc a' b' c)), from pt.pt₇ h₁₁, have h₁₃ : pt f' g' (pt (dc a' b' c) (dc a' b' d) (dc a' b' e)), from pt.pt₂_pt (pt.pt₃_pt (pt.pt₂_pt h₁₂)), have h₁₄ : pt f' g' (dc a' b' (pt c d e)), from dcpt₈ h₁₃, have h₁₅ : pt f' g' (dc h i (dc a b (pt c d e))), from dc₇'_pt h₁₄, show dc h i (pt f g (dc a b (pt c d e))), from dcpt₂ h₁₅ theorem pt₇_dc {a b c d e f g : Prop} (h₁ : dc f g (pt (pt a b c) d e)) : dc f g (pt a b (pt c d e)) := have h₂ : dc f g (pt d (pt a b c) e), from pt₂_dc h₁, have h₃ : dc f g (pt d e (pt a b c)), from pt₃_dc h₂, have h₄ : dc f g (pt (pt d e a) b c), from pt₆_dc h₃, have h₅ : dc f g (pt b (pt d e a) c), from pt₂_dc h₄, have h₆ : dc f g (pt b c (pt d e a)), from pt₃_dc h₅, have h₇ : dc f g (pt (pt b c d) e a), from pt₆_dc h₆, have h₈ : dc f g (pt e (pt b c d) a), from pt₂_dc h₇, have h₉ : dc f g (pt e a (pt b c d)), from pt₃_dc h₈, have h₁₀ : dc f g (pt (pt e a b) c d), from pt₆_dc h₉, have h₁₁ : dc f g (pt c (pt e a b) d), from pt₂_dc h₁₀, have h₁₂ : dc f g (pt c d (pt e a b)), from pt₃_dc h₁₁, have h₁₃ : dc f g (pt (pt c d e) a b), from pt₆_dc h₁₂, have h₁₄ : dc f g (pt a (pt c d e) b), from pt₂_dc h₁₃, show dc f g (pt a b (pt c d e)), from pt₃_dc h₁₄ theorem dcpt₁_pt {a b c d e f g : Prop} (h₁ : pt f g (dc a b (pt c d e))) : pt f g (pt (dc a b c) (dc a b d) (dc a b e)) := dcpt₇ h₁ theorem dcpt₂_pt {a b c d e f g : Prop} (h₁ : pt f g (pt (dc a b c) (dc a b d) (dc a b e))) : pt f g (dc a b (pt c d e)) := dcpt₈ h₁ theorem dcpt₃_pt {a b c d e f g : Prop} (h₁ : pt f g (pt a b (dc c d e))) : pt f g (dc (pt a b c) (pt a b d) (pt a b e)) := let a' := pt f g a, c' := pt a b c, d' := pt a b d, e' := pt a b e in have h₂ : pt a' b (dc c d e), from pt.pt₆ h₁, have h₃ : dc (pt a' b c) (pt a' b d) (pt a' b e), from dcpt₃ h₂, have h₄ : dc (pt a' b c) (pt a' b d) (pt f g e'), from pt₇_dc h₃, have h₅ : dc (pt a' b c) (pt f g e') (pt a' b d), from dc.dc₅' h₄, have h₆ : dc (pt a' b c) (pt f g e') (pt f g d'), from pt₇_dc h₅, have h₇ : dc (pt f g e') (pt f g d') (pt a' b c), from dc.dc₅' (dc.dc₄' h₆), have h₈ : dc (pt f g e') (pt f g d') (pt f g c'), from pt₇_dc h₇, have h₉ : dc (pt f g c') (pt f g d') (pt f g e'), from dc.dc₄' (dc.dc₅' (dc.dc₄' h₈)), show pt f g (dc c' d' e'), from dcpt₄ h₉ theorem dcpt₄_pt {a b c d e f g : Prop} (h₁ : pt f g (dc (pt a b c) (pt a b d) (pt a b e))) : pt f g (pt a b (dc c d e)) := let a' := pt f g a, c' := pt a b c, d' := pt a b d, e' := pt a b e in have h₂ : dc (pt f g c') (pt f g (pt a b d)) (pt f g e'), from dcpt₃ h₁, have h₃ : dc (pt f g c') (pt f g (pt a b d)) (pt a' b e), from pt₆_dc h₂, have h₄ : dc (pt f g c') (pt a' b e) (pt f g (pt a b d)), from dc.dc₅' h₃, have h₅ : dc (pt f g c') (pt a' b e) (pt a' b d), from pt₆_dc h₄, have h₆ : dc (pt a' b e) (pt a' b d) (pt f g c'), from dc.dc₅' (dc.dc₄' h₅), have h₇ : dc (pt a' b e) (pt a' b d) (pt a' b c), from pt₆_dc h₆, have h₈ : dc (pt a' b c) (pt a' b d) (pt a' b e), from dc.dc₄' (dc.dc₅' (dc.dc₄' h₇)), have h₉ : pt a' b (dc c d e), from dcpt₄ h₈, show pt f g (pt a b (dc c d e)), from pt.pt₇ h₉ theorem dcpt₅_pt {a b c d e f g h i : Prop} (h₁ : pt h i (dc f g (pt a b (dc c d e)))) : pt h i (dc f g (dc (pt a b c) (pt a b d) (pt a b e))) := let f' := pt h i f, g' := pt h i g, a' := pt h i a, d' := pt a b d, e' := pt a b e in have h₂ : dc f' g' (pt h i (pt a b (dc c d e))), from dcpt₃ h₁, have h₃ : dc f' g' (pt a' b (dc c d e)), from pt₆_dc h₂, have h₄ : dc f' g' (dc (pt a' b c) (pt a' b d) (pt a' b e)), from dcpt₅ h₃, have h₅ : dc (dc f' g' (pt a' b c)) (dc f' g' (pt a' b d)) (pt a' b e), from dc.dc₆' h₄, have h₆ : dc (dc f' g' (pt a' b c)) (dc f' g' (pt a' b d)) (pt h i e'), from pt₇_dc h₅, have h₇ : dc f' g' (dc (pt a' b c) (pt a' b d) (pt h i e')), from dc.dc₇' h₆, have h₈ : dc g' f' (dc (pt a' b c) (pt h i e') (pt a' b d)), from dc.dc₅ h₇, have h₉ : dc (dc g' f' (pt a' b c)) (dc g' f' (pt h i e')) (pt a' b d), from dc.dc₆' h₈, have h₁₀ : dc (dc g' f' (pt a' b c)) (dc g' f' (pt h i e')) (pt h i d'), from pt₇_dc h₉, have h₁₁ : dc g' f' (dc (pt a' b c) (pt h i e') (pt h i d')), from dc.dc₇' h₁₀, have h₁₂ : dc g' f' (dc (pt h i e') (pt h i d') (pt a' b c)), from dc.dc₅ (dc.dc₄ h₁₁), have h₁₃ : dc (dc g' f' (pt h i e')) (dc g' f' (pt h i d')) (pt a' b c), from dc.dc₆' h₁₂, have h₁₄ : dc (dc g' f' (pt h i e')) (dc g' f' (pt h i d')) (pt h i (pt a b c)), from pt₇_dc h₁₃, have h₁₅ : dc g' f' (dc (pt h i e') (pt h i d') (pt h i (pt a b c))), from dc.dc₇' h₁₄, have h₁₆ : dc f' g' (dc (pt h i (pt a b c)) (pt h i d') (pt h i e')), from dc.dc₄ (dc.dc₅ (dc.dc₄ h₁₅)), have h₁₇ : dc f' g' (pt h i (dc (pt a b c) d' e')), from dcpt₆ h₁₆, show pt h i (dc f g (dc (pt a b c) d' e')), from dcpt₄ h₁₇ theorem dcpt₆_pt {a b c d e f g h i : Prop} (h₁ : pt h i (dc f g (dc (pt a b c) (pt a b d) (pt a b e)))) : pt h i (dc f g (pt a b (dc c d e))) := let f' := pt h i f, g' := pt h i g, a' := pt h i a, d' := pt a b d, e' := pt a b e in have h₂ : dc f' g' (pt h i (dc (pt a b c) d' e')), from dcpt₃ h₁, have h₃ : dc f' g' (dc (pt h i (pt a b c)) (pt h i d') (pt h i e')), from dcpt₅ h₂, have h₄ : dc g' f' (dc (pt h i e') (pt h i d') (pt h i (pt a b c))), from dc.dc₄ (dc.dc₅ (dc.dc₄ h₃)), have h₅ : dc (dc g' f' (pt h i e')) (dc g' f' (pt h i d')) (pt h i (pt a b c)), from dc.dc₆' h₄, have h₆ : dc (dc g' f' (pt h i e')) (dc g' f' (pt h i d')) (pt a' b c), from pt₆_dc h₅, have h₇ : dc g' f' (dc (pt h i e') (pt h i d') (pt a' b c)), from dc.dc₇' h₆, have h₈ : dc g' f' (dc (pt a' b c) (pt h i e') (pt h i d')), from dc.dc₄ (dc.dc₅ h₇), have h₉ : dc (dc g' f' (pt a' b c)) (dc g' f' (pt h i e')) (pt h i d'), from dc.dc₆' h₈, have h₁₀ : dc (dc g' f' (pt a' b c)) (dc g' f' (pt h i e')) (pt a' b d), from pt₆_dc h₉, have h₁₁ : dc g' f' (dc (pt a' b c) (pt h i e') (pt a' b d)), from dc.dc₇' h₁₀, have h₁₂ : dc f' g' (dc (pt a' b c) (pt a' b d) (pt h i e')), from dc.dc₅ h₁₁, have h₁₃ : dc (dc f' g' (pt a' b c)) (dc f' g' (pt a' b d)) (pt h i e'), from dc.dc₆' h₁₂, have h₁₄ : dc (dc f' g' (pt a' b c)) (dc f' g' (pt a' b d)) (pt a' b e), from pt₆_dc h₁₃, have h₁₅ : dc f' g' (dc (pt a' b c) (pt a' b d) (pt a' b e)), from dc.dc₇' h₁₄, have h₁₆ : dc f' g' (pt a' b (dc c d e)), from dcpt₆ h₁₅, have h₁₇ : dc f' g' (pt h i (pt a b (dc c d e))), from pt₇_dc h₁₆, show pt h i (dc f g (pt a b (dc c d e))), from dcpt₄ h₁₇ theorem dcpt₇_pt {a b c d e f g h i : Prop} (h₁ : pt h i (pt f g (dc a b (pt c d e)))) : pt h i (pt f g (pt (dc a b c) (dc a b d) (dc a b e))) := have h₂ : pt (pt h i f) g (dc a b (pt c d e)), from pt.pt₆ h₁, have h₃ : pt (pt h i f) g (pt (dc a b c) (dc a b d) (dc a b e)), from dcpt₇ h₂, show pt h i (pt f g (pt (dc a b c) (dc a b d) (dc a b e))), from pt.pt₇ h₃ theorem dcpt₈_pt {a b c d e f g h i : Prop} (h₁ : pt h i (pt f g (pt (dc a b c) (dc a b d) (dc a b e)))) : pt h i (pt f g (dc a b (pt c d e))) := have h₂ : pt (pt h i f) g (pt (dc a b c) (dc a b d) (dc a b e)), from pt.pt₆ h₁, have h₃ : pt (pt h i f) g (dc a b (pt c d e)), from dcpt₈ h₂, show pt h i (pt f g (dc a b (pt c d e))), from pt.pt₇ h₃ end dc_pt end wr end hilbert end clfrags
05c8d548e05751e1e297d1f5161313a5ef20891d
a0379d42ba8100ac862416817046aeff59ae8da6
/library/init/algebra/order.lean
3d96241fbad4a8ef629bee3e6ee6519a1c543493
[ "Apache-2.0" ]
permissive
YJMD/lean
afa761162b3d9c835d1eb1139e48d2f8490a4d1b
96a1980a4c3aba1d09dd5423a1751f3248c9e92e
refs/heads/master
1,670,491,156,188
1,598,723,019,000
1,598,723,019,000
292,284,715
0
0
null
1,599,051,825,000
1,599,051,824,000
null
UTF-8
Lean
false
false
11,396
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.classical init.meta.name init.algebra.classes /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u variables {α : Type u} set_option auto_param.check_exists false /-- A preorder is a reflexive, transitive relation `≤` with `a < b` defined in the obvious way. -/ class preorder (α : Type u) extends has_le α, has_lt α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (lt := λ a b, a ≤ b ∧ ¬ b ≤ a) (lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) . order_laws_tac) /-- A partial order is a reflexive, transitive, antisymmetric relation `≤`. -/ class partial_order (α : Type u) extends preorder α := (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) /-- A linear order is reflexive, transitive, antisymmetric and total relation `≤`.-/ class linear_order (α : Type u) extends partial_order α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) @[refl] lemma le_refl [preorder α] : ∀ a : α, a ≤ a := preorder.le_refl @[trans] lemma le_trans [preorder α] : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := preorder.le_trans lemma lt_iff_le_not_le [preorder α] : ∀ {a b : α}, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := preorder.lt_iff_le_not_le lemma lt_of_le_not_le [preorder α] : ∀ {a b : α}, a ≤ b → ¬ b ≤ a → a < b | a b hab hba := lt_iff_le_not_le.mpr ⟨hab, hba⟩ lemma le_not_le_of_lt [preorder α] : ∀ {a b : α}, a < b → a ≤ b ∧ ¬ b ≤ a | a b hab := lt_iff_le_not_le.mp hab lemma le_antisymm [partial_order α] : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := partial_order.le_antisymm lemma le_of_eq [preorder α] {a b : α} : a = b → a ≤ b := λ h, h ▸ le_refl a lemma le_antisymm_iff [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ b ≤ a := ⟨λe, ⟨le_of_eq e, le_of_eq e.symm⟩, λ⟨h1, h2⟩, le_antisymm h1 h2⟩ @[trans] lemma ge_trans [preorder α] : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ a b c h₁ h₂, le_trans h₂ h₁ lemma le_total [linear_order α] : ∀ a b : α, a ≤ b ∨ b ≤ a := linear_order.le_total lemma le_of_not_ge [linear_order α] {a b : α} : ¬ a ≥ b → a ≤ b := or.resolve_left (le_total b a) lemma le_of_not_le [linear_order α] {a b : α} : ¬ a ≤ b → b ≤ a := or.resolve_left (le_total a b) lemma lt_irrefl [preorder α] : ∀ a : α, ¬ a < a | a haa := match le_not_le_of_lt haa with | ⟨h1, h2⟩ := false.rec _ (h2 h1) end lemma gt_irrefl [preorder α] : ∀ a : α, ¬ a > a := lt_irrefl @[trans] lemma lt_trans [preorder α] : ∀ {a b c : α}, a < b → b < c → a < c | a b c hab hbc := match le_not_le_of_lt hab, le_not_le_of_lt hbc with | ⟨hab, hba⟩, ⟨hbc, hcb⟩ := lt_of_le_not_le (le_trans hab hbc) (λ hca, hcb (le_trans hca hab)) end def lt.trans := @lt_trans @[trans] lemma gt_trans [preorder α] : ∀ {a b c : α}, a > b → b > c → a > c := λ a b c h₁ h₂, lt_trans h₂ h₁ def gt.trans := @gt_trans lemma ne_of_lt [preorder α] {a b : α} (h : a < b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma ne_of_gt [preorder α] {a b : α} (h : a > b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma lt_asymm [preorder α] {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a, lt_irrefl a (lt_trans h h1) lemma not_lt_of_gt [linear_order α] {a b : α} (h : a > b) : ¬ a < b := lt_asymm h lemma le_of_lt [preorder α] : ∀ {a b : α}, a < b → a ≤ b | a b hab := (le_not_le_of_lt hab).left @[trans] lemma lt_of_lt_of_le [preorder α] : ∀ {a b c : α}, a < b → b ≤ c → a < c | a b c hab hbc := let ⟨hab, hba⟩ := le_not_le_of_lt hab in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hba (le_trans hbc hca) @[trans] lemma lt_of_le_of_lt [preorder α] : ∀ {a b c : α}, a ≤ b → b < c → a < c | a b c hab hbc := let ⟨hbc, hcb⟩ := le_not_le_of_lt hbc in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hcb (le_trans hca hab) @[trans] lemma gt_of_gt_of_ge [preorder α] {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ @[trans] lemma gt_of_ge_of_gt [preorder α] {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ lemma not_le_of_gt [preorder α] {a b : α} (h : a > b) : ¬ a ≤ b := (le_not_le_of_lt h).right lemma not_lt_of_ge [preorder α] {a b : α} (h : a ≥ b) : ¬ a < b := λ hab, not_le_of_gt hab h lemma lt_or_eq_of_le [partial_order α] : ∀ {a b : α}, a ≤ b → a < b ∨ a = b | a b hab := classical.by_cases (λ hba : b ≤ a, or.inr (le_antisymm hab hba)) (λ hba, or.inl (lt_of_le_not_le hab hba)) lemma le_of_lt_or_eq [preorder α] : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b | a b (or.inl hab) := le_of_lt hab | a b (or.inr hab) := hab ▸ le_refl _ lemma le_iff_lt_or_eq [partial_order α] : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b | a b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma lt_of_le_of_ne [partial_order α] {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂, lt_of_le_not_le h₁ $ mt (le_antisymm h₁) h₂ lemma lt_trichotomy [linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := or.elim (le_total a b) (λ h : a ≤ b, or.elim (lt_or_eq_of_le h) (λ h : a < b, or.inl h) (λ h : a = b, or.inr (or.inl h))) (λ h : b ≤ a, or.elim (lt_or_eq_of_le h) (λ h : b < a, or.inr (or.inr h)) (λ h : b = a, or.inr (or.inl h.symm))) lemma le_of_not_gt [linear_order α] {a b : α} (h : ¬ a > b) : a ≤ b := match lt_trichotomy a b with | or.inl hlt := le_of_lt hlt | or.inr (or.inl heq) := heq ▸ le_refl a | or.inr (or.inr hgt) := absurd hgt h end lemma lt_of_not_ge [linear_order α] {a b : α} (h : ¬ a ≥ b) : a < b := lt_of_le_not_le ((le_total _ _).resolve_right h) h lemma lt_or_ge [linear_order α] (a b : α) : a < b ∨ a ≥ b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := or.inr (heq ▸ le_refl a) | or.inr (or.inr hgt) := or.inr (le_of_lt hgt) end lemma le_or_gt [linear_order α] (a b : α) : a ≤ b ∨ a > b := or.swap (lt_or_ge b a) lemma lt_or_gt_of_ne [linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := absurd heq h | or.inr (or.inr hgt) := or.inr hgt end lemma le_of_eq_or_lt [preorder α] {a b : α} (h : a = b ∨ a < b) : a ≤ b := or.elim h le_of_eq le_of_lt lemma ne_iff_lt_or_gt [linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ a > b := ⟨lt_or_gt_of_ne, λo, or.elim o ne_of_lt ne_of_gt⟩ lemma lt_iff_not_ge [linear_order α] (x y : α) : x < y ↔ ¬ x ≥ y := ⟨not_le_of_gt, lt_of_not_ge⟩ @[simp] lemma not_lt [linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_gt, not_lt_of_ge⟩ @[simp] lemma not_le [linear_order α] {a b : α} : ¬ a ≤ b ↔ b < a := (lt_iff_not_ge _ _).symm instance decidable_lt_of_decidable_le [preorder α] [decidable_rel ((≤) : α → α → Prop)] : decidable_rel ((<) : α → α → Prop) | a b := if hab : a ≤ b then if hba : b ≤ a then is_false $ λ hab', not_le_of_gt hab' hba else is_true $ lt_of_le_not_le hab hba else is_false $ λ hab', hab (le_of_lt hab') instance decidable_eq_of_decidable_le [partial_order α] [decidable_rel ((≤) : α → α → Prop)] : decidable_eq α | a b := if hab : a ≤ b then if hba : b ≤ a then is_true (le_antisymm hab hba) else is_false (λ heq, hba (heq ▸ le_refl _)) else is_false (λ heq, hab (heq ▸ le_refl _)) class decidable_linear_order (α : Type u) extends linear_order α := (decidable_le : decidable_rel (≤)) (decidable_eq : decidable_eq α := @decidable_eq_of_decidable_le _ _ decidable_le) (decidable_lt : decidable_rel ((<) : α → α → Prop) := @decidable_lt_of_decidable_le _ _ decidable_le) instance [decidable_linear_order α] (a b : α) : decidable (a < b) := decidable_linear_order.decidable_lt a b instance [decidable_linear_order α] (a b : α) : decidable (a ≤ b) := decidable_linear_order.decidable_le a b instance [decidable_linear_order α] (a b : α) : decidable (a = b) := decidable_linear_order.decidable_eq a b lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then or.inl h₁ else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁))) instance [decidable_linear_order α] : is_total_preorder α (≤) := {trans := @le_trans _ _, total := le_total} /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_weak_order_of_decidable_linear_order [decidable_linear_order α] : is_strict_weak_order α (<) := is_strict_weak_order_of_is_total_preorder lt_iff_not_ge /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_total_order_of_decidable_linear_order [decidable_linear_order α] : is_strict_total_order α (<) := { trichotomous := lt_trichotomy } namespace decidable lemma lt_or_eq_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a < b ∨ a = b := if hba : b ≤ a then or.inr (le_antisymm hab hba) else or.inl (lt_of_le_not_le hab hba) lemma eq_or_lt_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le hab).swap lemma le_iff_lt_or_eq [partial_order α] [@decidable_rel α (≤)] {a b : α} : a ≤ b ↔ a < b ∨ a = b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma le_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ b < a) : a ≤ b := decidable.by_contradiction $ λ h', h $ lt_of_le_not_le ((le_total _ _).resolve_right h') h' lemma not_lt [decidable_linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_lt, not_lt_of_ge⟩ lemma lt_or_le [decidable_linear_order α] (a b : α) : a < b ∨ b ≤ a := if hba : b ≤ a then or.inr hba else or.inl $ lt_of_not_ge hba lemma le_or_lt [decidable_linear_order α] (a b : α) : a ≤ b ∨ b < a := (lt_or_le b a).swap lemma lt_trichotomy [decidable_linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := (lt_or_le _ _).imp_right $ λ h, (eq_or_lt_of_le h).imp_left eq.symm lemma lt_or_gt_of_ne [decidable_linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ b < a := (lt_trichotomy a b).imp_right $ λ h', h'.resolve_left h /-- Perform a case-split on the ordering of `x` and `y` in a decidable linear order. -/ def lt_by_cases [decidable_linear_order α] (x y : α) {P : Sort*} (h₁ : x < y → P) (h₂ : x = y → P) (h₃ : y < x → P) : P := if h : x < y then h₁ h else if h' : y < x then h₃ h' else h₂ (le_antisymm (le_of_not_gt h') (le_of_not_gt h)) lemma ne_iff_lt_or_gt [decidable_linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ b < a := ⟨lt_or_gt_of_ne, λo, o.elim ne_of_lt ne_of_gt⟩ lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [decidable_linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_lt $ λ h', not_le_of_gt (H h') h end decidable
0ae0d06ec9b8af9c91d42d8c6bb8c46142fc83be
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/sec_param_pp2.lean
71828df578bc5fb1cb9432cb7a668547463c6d82
[ "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
225
lean
section parameters {A : Type} (a : A) section parameters {B : Type} (b : B) variable f : A → B → A definition id := f a b check id set_option pp.universes true check id end check id end check id
84bc203bfa5c8a3692d943c48134eb310fbd2d82
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/finset/basic.lean
0966010e09b207aa502344ef5b88e033bc812d65
[ "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
109,830
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, Minchao Wu, Mario Carneiro -/ import data.multiset.finset_ops import tactic.apply import tactic.nth_rewrite import tactic.monotonicity /-! # Finite sets Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib. Below, `finset α` is defined as a structure with 2 fields: 1. `val` is a `multiset α` of elements; 2. `nodup` is a proof that `val` has no duplicates. Finsets in Lean are constructive in that they have an underlying `list` that enumerates their elements. In particular, any function that uses the data of the underlying list cannot depend on its ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't worry about it explicitly. Finsets give a basic foundation for defining finite sums and products over types: 1. `∑ i in (s : finset α), f i`; 2. `∏ i in (s : finset α), f i`. Lean refers to these operations as `big_operator`s. More information can be found in `algebra.big_operators.basic`. Finsets are directly used to define fintypes in Lean. A `fintype α` instance for a type `α` consists of a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`. There is also `univ'`, the noncomputable partner to `univ`, which is defined to be `α` as a finset if `α` is finite, and the empty finset otherwise. See `data.fintype.basic`. `finset.card`, the size of a finset is defined in `data.finset.card`. This is then used to define `fintype.card`, the size of a type. ## Main declarations ### Main definitions * `finset`: Defines a type for the finite subsets of `α`. Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements, and `nodup`, a proof that `val` has no duplicates. * `finset.has_mem`: Defines membership `a ∈ (s : finset α)`. * `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`. * `finset.has_coe_to_sort`: Coerce `s : finset α` to the type of all `x ∈ s`. * `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`, then it holds for the finset obtained by inserting a new element. * `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate. ### Finset constructions * `singleton`: Denoted by `{a}`; the finset consisting of one element. * `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements. * `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`. This convention is consistent with other languages and normalizes `card (range n) = n`. Beware, `n` is not in `range n`. * `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype `{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set. ### Finsets from functions * `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is the finset consisting of those elements in `s` satisfying the predicate `p`. ### The lattice structure on subsets of finsets There is a natural lattice structure on the subsets of a set. In Lean, we use lattice notation to talk about things involving unions and intersections. See `order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is called `top` with `⊤ = univ`. * `finset.has_subset`: Lots of API about lattices, otherwise behaves exactly as one would expect. * `finset.has_union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`. See `finset.sup`/`finset.bUnion` for finite unions. * `finset.has_inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`. See `finset.inf` for finite intersections. * `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint, `s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does not require decidable equality on the type `α`. ### Operations on two or more finsets * `insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h` returns the same except that it requires a hypothesis stating that `a` is not already in `s`. This does not require decidable equality on the type `α`. * `finset.has_union`: see "The lattice structure on subsets of finsets" * `finset.has_inter`: see "The lattice structure on subsets of finsets" * `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed. * `finset.has_sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`. * `finset.product`: Given finsets of `α` and `β`, defines finsets of `α × β`. For arbitrary dependent products, see `data.finset.pi`. * `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a `s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`. * `finset.bInter`: TODO: Implemement finite intersections. ### Maps constructed using finsets * `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal to `f` on `s` and `g` on the complement. ### Predicates on finsets * `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their intersection is empty. * `finset.nonempty`: A finset is nonempty if it has elements. This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form. ### Equivalences between finsets * The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`. TODO: examples ## Tags finite sets, finset -/ open multiset subtype nat function universes u variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) instance multiset.can_lift_finset {α} : can_lift (multiset α) (finset α) finset.val multiset.nodup := ⟨λ m hm, ⟨⟨m, hm⟩, rfl⟩⟩ namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl theorem val_injective : injective (val : finset α → multiset α) := λ _ _, eq_of_veq @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := val_injective.eq_iff @[simp] theorem dedup_eq_self [decidable_eq α] (s : finset α) : dedup s.1 = s.1 := s.2.dedup instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /-! ### membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] lemma mem_val {a : α} {s : finset α} : a ∈ s.1 ↔ a ∈ s := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩ @[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl @[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2 @[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} : (⟨x, h⟩ : (s : set α)) = x := subtype.coe_eta _ _ instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ s₁.nodup.ext s₂.nodup @[ext] theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ := set.ext_iff.trans ext_iff.symm lemma coe_injective {α} : injective (coe : finset α → set α) := λ s t, coe_inj.1 /-! ### type coercion -/ /-- Coercion from a finset to the corresponding subtype. -/ instance {α : Type u} : has_coe_to_sort (finset α) (Type u) := ⟨λ s, {x // x ∈ s}⟩ @[simp] protected lemma forall_coe {α : Type*} (s : finset α) (p : s → Prop) : (∀ (x : s), p x) ↔ ∀ (x : α) (h : x ∈ s), p ⟨x, h⟩ := subtype.forall @[simp] protected lemma exists_coe {α : Type*} (s : finset α) (p : s → Prop) : (∃ (x : s), p x) ↔ ∃ (x : α) (h : x ∈ s), p ⟨x, h⟩ := subtype.exists instance pi_finset_coe.can_lift (ι : Type*) (α : Π i : ι, Type*) [ne : Π i, nonempty (α i)] (s : finset ι) : can_lift (Π i : s, α i) (Π i, α i) (λ f i, f i) (λ _, true) := pi_subtype.can_lift ι α (∈ s) instance pi_finset_coe.can_lift' (ι α : Type*) [ne : nonempty α] (s : finset ι) : can_lift (s → α) (ι → α) (λ f i, f i) (λ _, true) := pi_finset_coe.can_lift ι (λ _, α) s instance finset_coe.can_lift (s : finset α) : can_lift α s coe (λ a, a ∈ s) := { prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ } @[simp, norm_cast] lemma coe_sort_coe (s : finset α) : ((s : set α) : Sort*) = s := rfl /-! ### Subset and strict subset relations -/ section subset variables {s t : finset α} instance : has_subset (finset α) := ⟨λ s t, ∀ ⦃a⦄, a ∈ s → a ∈ t⟩ instance : has_ssubset (finset α) := ⟨λ s t, s ⊆ t ∧ ¬ t ⊆ s⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := λ s a, id, le_trans := λ s t u hst htu a ha, htu $ hst ha, le_antisymm := λ s t hst hts, ext $ λ a, ⟨@hst _, @hts _⟩ } instance : is_refl (finset α) (⊆) := has_le.le.is_refl instance : is_trans (finset α) (⊆) := has_le.le.is_trans instance : is_antisymm (finset α) (⊆) := has_le.le.is_antisymm instance : is_irrefl (finset α) (⊂) := has_lt.lt.is_irrefl instance : is_trans (finset α) (⊂) := has_lt.lt.is_trans instance : is_asymm (finset α) (⊂) := has_lt.lt.is_asymm instance : is_nonstrict_strict_order (finset α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩ lemma subset_def : s ⊆ t ↔ s.1 ⊆ t.1 := iff.rfl lemma ssubset_def : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ protected lemma subset.rfl {s :finset α} : s ⊆ s := subset.refl _ protected theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset lemma not_mem_mono {s t : finset α} (h : s ⊆ t) {a : α} : a ∉ t → a ∉ s := mt $ @h _ theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} : (s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff lemma not_subset : ¬ s ⊆ t ↔ ∃ x ∈ s, x ∉ t := by simp only [←coe_subset, set.not_subset, mem_coe] @[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl @[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff lemma ssubset_iff_subset_ne {s t : finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne _ _ s t theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := set.ssubset_iff_of_subset h lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃ lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃ lemma exists_of_ssubset {s₁ s₂ : finset α} (h : s₁ ⊂ s₂) : ∃ x ∈ s₂, x ∉ s₁ := set.exists_of_ssubset h instance is_well_founded_ssubset : is_well_founded (finset α) (⊂) := subrelation.is_well_founded (inv_image _ _) $ λ _ _, val_lt_iff.2 instance is_well_founded_lt : well_founded_lt (finset α) := finset.is_well_founded_ssubset end subset -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans /-! ### Order embedding from `finset α` to `set α` -/ /-- Coercion to `set α` as an `order_embedding`. -/ def coe_emb : finset α ↪o set α := ⟨⟨coe, coe_injective⟩, λ s t, coe_subset⟩ @[simp] lemma coe_coe_emb : ⇑(coe_emb : finset α ↪o set α) = coe := rfl /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x : α, x ∈ s instance decidable_nonempty {s : finset α} : decidable s.nonempty := decidable_of_iff (∃ a ∈ s, true) $ by simp_rw [exists_prop, and_true, finset.nonempty] @[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s : set α).nonempty ↔ s.nonempty := iff.rfl @[simp] lemma nonempty_coe_sort {s : finset α} : nonempty ↥s ↔ s.nonempty := nonempty_subtype alias coe_nonempty ↔ _ nonempty.to_set alias nonempty_coe_sort ↔ _ nonempty.coe_sort lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x : α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p := let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩ lemma nonempty.to_subtype {s : finset α} : s.nonempty → nonempty s := nonempty_coe_sort.2 lemma nonempty.to_type {s : finset α} : s.nonempty → nonempty α := λ ⟨x, hx⟩, ⟨x⟩ /-! ### empty -/ section empty variables {s : finset α} /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance inhabited_finset : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty := λ ⟨x, hx⟩, not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ := λ e, not_mem_empty a $ e ▸ h theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ := exists.elim h $ λ a, ne_empty_of_mem @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ lemma eq_empty_of_forall_not_mem {s : finset α} (H : ∀ x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero @[simp] lemma not_ssubset_empty (s : finset α) : ¬s ⊂ ∅ := λ h, let ⟨x, he, hs⟩ := exists_of_ssubset h in he theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨nonempty.ne_empty, nonempty_of_ne_empty⟩ @[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ := nonempty_iff_ne_empty.not.trans not_not theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_eq_empty {s : finset α} : (s : set α) = ∅ ↔ s = ∅ := by rw [← coe_empty, coe_inj] @[simp] lemma is_empty_coe_sort {s : finset α} : is_empty ↥s ↔ s = ∅ := by simpa using @set.is_empty_coe_sort α s instance : is_empty (∅ : finset α) := is_empty_coe_sort.2 rfl /-- A `finset` for an empty type is empty. -/ lemma eq_empty_of_is_empty [is_empty α] (s : finset α) : s = ∅ := finset.eq_empty_of_forall_not_mem is_empty_elim instance : order_bot (finset α) := { bot := ∅, bot_le := empty_subset } @[simp] lemma bot_eq_empty : (⊥ : finset α) = ∅ := rfl @[simp] lemma empty_ssubset : ∅ ⊂ s ↔ s.nonempty := (@bot_lt_iff_ne_bot (finset α) _ _ _).trans nonempty_iff_ne_empty.symm alias empty_ssubset ↔ _ nonempty.empty_ssubset end empty /-! ### singleton -/ section singleton variables {s : finset α} {a b : α} /-- `{a} : finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`. -/ instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = {a} := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton lemma eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : finset α)) : x = y := mem_singleton.1 h theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl lemma singleton_injective : injective (singleton : α → finset α) := λ a b h, mem_singleton.1 (h ▸ mem_singleton_self _) @[simp] lemma singleton_inj : ({a} : finset α) = {b} ↔ a = b := singleton_injective.eq_iff @[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty lemma empty_ssubset_singleton : (∅ : finset α) ⊂ {a} := (singleton_nonempty _).empty_ssubset @[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} := by { ext, simp } @[simp, norm_cast] lemma coe_eq_singleton {s : finset α} {a : α} : (s : set α) = {a} ↔ s = {a} := by rw [←coe_singleton, coe_inj] lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := begin split, { rintro rfl, simp }, { rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩, rw ← h_uniq hne.some hne.some_spec, exact hne.some_spec } end lemma nonempty_iff_eq_singleton_default [unique α] {s : finset α} : s.nonempty ↔ s = {default} := by simp [eq_singleton_iff_nonempty_unique_mem] alias nonempty_iff_eq_singleton_default ↔ nonempty.eq_singleton_default _ lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, set.singleton_subset_iff] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff @[simp] lemma subset_singleton_iff {s : finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} := by rw [←coe_subset, coe_singleton, set.subset_singleton_iff_eq, coe_eq_empty, coe_eq_singleton] lemma singleton_subset_singleton : ({a} : finset α) ⊆ {b} ↔ a = b := by simp protected lemma nonempty.subset_singleton_iff {s : finset α} {a : α} (h : s.nonempty) : s ⊆ {a} ↔ s = {a} := subset_singleton_iff.trans $ or_iff_right h.ne_empty lemma subset_singleton_iff' {s : finset α} {a : α} : s ⊆ {a} ↔ ∀ b ∈ s, b = a := forall₂_congr $ λ _ _, mem_singleton @[simp] lemma ssubset_singleton_iff {s : finset α} {a : α} : s ⊂ {a} ↔ s = ∅ := by rw [←coe_ssubset, coe_singleton, set.ssubset_singleton_iff, coe_eq_empty] lemma eq_empty_of_ssubset_singleton {s : finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs lemma eq_singleton_or_nontrivial (ha : a ∈ s) : s = {a} ∨ (s : set α).nontrivial := by { rw ←coe_eq_singleton, exact set.eq_singleton_or_nontrivial ha } lemma nonempty.exists_eq_singleton_or_nontrivial : s.nonempty → (∃ a, s = {a}) ∨ (s : set α).nontrivial := λ ⟨a, ha⟩, (eq_singleton_or_nontrivial ha).imp_left $ exists.intro a instance [nonempty α] : nontrivial (finset α) := ‹nonempty α›.elim $ λ a, ⟨⟨{a}, ∅, singleton_ne_empty _⟩⟩ instance [is_empty α] : unique (finset α) := { default := ∅, uniq := λ s, eq_empty_of_forall_not_mem is_empty_elim } end singleton /-! ### cons -/ section cons variables {s t : finset α} {a b : α} /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`, and the union is guaranteed to be disjoint. -/ def cons (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] lemma mem_cons {h} : b ∈ s.cons a h ↔ b = a ∨ b ∈ s := mem_cons @[simp] lemma mem_cons_self (a : α) (s : finset α) {h} : a ∈ cons a s h := mem_cons_self _ _ @[simp] lemma cons_val (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl lemma forall_mem_cons (h : a ∉ s) (p : α → Prop) : (∀ x, x ∈ cons a s h → p x) ↔ p a ∧ ∀ x, x ∈ s → p x := by simp only [mem_cons, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] lemma mk_cons {s : multiset α} (h : (a ::ₘ s).nodup) : (⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (nodup_cons.1 h).2⟩ (nodup_cons.1 h).1 := rfl @[simp] lemma nonempty_cons (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 $ or.inl rfl⟩ @[simp] lemma nonempty_mk {m : multiset α} {hm} : (⟨m, hm⟩ : finset α).nonempty ↔ m ≠ 0 := by induction m using multiset.induction_on; simp @[simp] lemma coe_cons {a s h} : (@cons α a s h : set α) = insert a s := by { ext, simp } lemma subset_cons (h : a ∉ s) : s ⊆ s.cons a h := subset_cons _ _ lemma ssubset_cons (h : a ∉ s) : s ⊂ s.cons a h := ssubset_cons h lemma cons_subset {h : a ∉ s} : s.cons a h ⊆ t ↔ a ∈ t ∧ s ⊆ t := cons_subset @[simp] lemma cons_subset_cons {hs ht} : s.cons a hs ⊆ t.cons a ht ↔ s ⊆ t := by rwa [← coe_subset, coe_cons, coe_cons, set.insert_subset_insert_iff, coe_subset] lemma ssubset_iff_exists_cons_subset : s ⊂ t ↔ ∃ a (h : a ∉ s), s.cons a h ⊆ t := begin refine ⟨λ h, _, λ ⟨a, ha, h⟩, ssubset_of_ssubset_of_subset (ssubset_cons _) h⟩, obtain ⟨a, hs, ht⟩ := not_subset.1 h.2, exact ⟨a, ht, cons_subset.2 ⟨hs, h.subset⟩⟩, end end cons /-! ### disjoint -/ section disjoint variables {f : α → β} {s t u : finset α} {a b : α} lemma disjoint_left : disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t := ⟨λ h a hs ht, singleton_subset_iff.mp (h (singleton_subset_iff.mpr hs) (singleton_subset_iff.mpr ht)), λ h x hs ht a ha, h (hs ha) (ht ha)⟩ lemma disjoint_right : disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] lemma disjoint_iff_ne : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] @[simp] lemma disjoint_val : s.1.disjoint t.1 ↔ disjoint s t := disjoint_left.symm lemma _root_.disjoint.forall_ne_finset (h : disjoint s t) (ha : a ∈ s) (hb : b ∈ t) : a ≠ b := disjoint_iff_ne.1 h _ ha _ hb lemma not_disjoint_iff : ¬ disjoint s t ↔ ∃ a, a ∈ s ∧ a ∈ t := disjoint_left.not.trans $ not_forall.trans $ exists_congr $ λ _, by rw [not_imp, not_not] lemma disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) lemma disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] lemma disjoint_singleton_left : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] lemma disjoint_singleton_right : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans disjoint_singleton_left @[simp] lemma disjoint_singleton : disjoint ({a} : finset α) {b} ↔ a ≠ b := by rw [disjoint_singleton_left, mem_singleton] lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self @[simp, norm_cast] lemma disjoint_coe : disjoint (s : set α) t ↔ disjoint s t := by { rw [finset.disjoint_left, set.disjoint_left], refl } @[simp, norm_cast] lemma pairwise_disjoint_coe {ι : Type*} {s : set ι} {f : ι → finset α} : s.pairwise_disjoint (λ i, f i : ι → set α) ↔ s.pairwise_disjoint f := forall₅_congr $ λ _ _ _ _ _, disjoint_coe end disjoint /-! ### disjoint union -/ /-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_union (s t : finset α) (h : disjoint s t) : finset α := ⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, disjoint_val.2 h⟩⟩ @[simp] theorem mem_disj_union {α s t h a} : a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append lemma disj_union_comm (s t : finset α) (h : disjoint s t) : disj_union s t h = disj_union t s h.symm := eq_of_veq $ add_comm _ _ @[simp] lemma empty_disj_union (t : finset α) (h : disjoint ∅ t := disjoint_bot_left) : disj_union ∅ t h = t := eq_of_veq $ zero_add _ @[simp] lemma disj_union_empty (s : finset α) (h : disjoint s ∅ := disjoint_bot_right) : disj_union s ∅ h = s := eq_of_veq $ add_zero _ lemma singleton_disj_union (a : α) (t : finset α) (h : disjoint {a} t) : disj_union {a} t h = cons a t (disjoint_singleton_left.mp h) := eq_of_veq $ multiset.singleton_add _ _ lemma disj_union_singleton (s : finset α) (a : α) (h : disjoint s {a}) : disj_union s {a} h = cons a s (disjoint_singleton_right.mp h) := by rw [disj_union_comm, singleton_disj_union] /-! ### insert -/ section insert variables [decidable_eq α] {s t u v : finset α} {a b : α} /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, s.2.ndinsert a⟩⟩ lemma insert_def (a : α) (s : finset α) : insert a s = ⟨_, s.2.ndinsert a⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = dedup (a ::ₘ s.1) := by rw [dedup_cons, dedup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] lemma mem_insert : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 lemma mem_insert_of_mem (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h lemma mem_of_mem_insert_of_ne (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left lemma eq_of_not_mem_of_mem_insert (ha : b ∈ insert a s) (hb : b ∉ s) : b = a := (mem_insert.1 ha).resolve_right hb @[simp] theorem cons_eq_insert (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp @[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) := by simp instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩ @[simp] lemma insert_eq_of_mem (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h @[simp] lemma insert_eq_self : insert a s = s ↔ a ∈ s := ⟨λ h, h ▸ mem_insert_self _ _, insert_eq_of_mem⟩ lemma insert_ne_self : insert a s ≠ s ↔ a ∉ s := insert_eq_self.not @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : finset α) = {a} := insert_eq_of_mem $ mem_singleton_self _ theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, by simp only [mem_insert, or.left_comm] @[simp, norm_cast] lemma coe_pair {a b : α} : (({a, b} : finset α) : set α) = {a, b} := by { ext, simp } @[simp, norm_cast] lemma coe_eq_pair {s : finset α} {a b : α} : (s : set α) = {a, b} ↔ s = {a, b} := by rw [←coe_pair, coe_inj] theorem pair_comm (a b : α) : ({a, b} : finset α) = {b, a} := insert.comm a b ∅ @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty /-! The universe annotation is required for the following instance, possibly this is a bug in Lean. See leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F) -/ instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) : nonempty.{u + 1} ((insert i s : finset α) : set α) := (finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } lemma insert_subset : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] lemma subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b := ⟨λ h, eq_of_not_mem_of_mem_insert (h.subst $ mem_insert_self _ _) ha, congr_arg _⟩ lemma insert_inj_on (s : finset α) : set.inj_on (λ a, insert a s) sᶜ := λ a h b _, (insert_inj h).1 lemma ssubset_iff : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := by exact_mod_cast @set.ssubset_iff_insert α s t lemma ssubset_insert (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.rfl⟩ @[elab_as_eliminator] lemma cons_induction {α : Type*} {p : finset α → Prop} (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : cons a (finset.mk s _) m = ⟨a ::ₘ s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [cons_val] } end) nd @[elab_as_eliminator] lemma cons_induction_on {α : Type*} {p : finset α → Prop} (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : p s := cons_induction h₁ h₂ s @[elab_as_eliminator] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s := cons_induction h₁ $ λ a s ha, (s.cons_eq_insert a ha).symm ▸ h₂ ha /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s /-- To prove a proposition about `S : finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α ⊆ S`, then it holds for the `finset` obtained by inserting a new element of `S`. -/ @[elab_as_eliminator] theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs, let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S) /-- To prove a proposition about a nonempty `s : finset α`, it suffices to show it holds for all singletons and that if it holds for nonempty `t : finset α`, then it also holds for the `finset` obtained by inserting an element in `t`. -/ @[elab_as_eliminator] lemma nonempty.cons_induction {α : Type*} {p : Π s : finset α, s.nonempty → Prop} (h₀ : ∀ a, p {a} (singleton_nonempty _)) (h₁ : ∀ ⦃a⦄ s (h : a ∉ s) hs, p s hs → p (finset.cons a s h) (nonempty_cons h)) {s : finset α} (hs : s.nonempty) : p s hs := begin induction s using finset.cons_induction with a t ha h, { exact (not_nonempty_empty hs).elim }, obtain rfl | ht := t.eq_empty_or_nonempty, { exact h₀ a }, { exact h₁ t ha ht (h ht) } end /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) : {i // i ∈ insert x t} ≃ option {i // i ∈ t} := begin refine { to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩, inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩, .. }, { intro y, by_cases h : ↑y = x, simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk], simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, { rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk], have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 }, simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, end @[simp] lemma disjoint_insert_left : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] lemma disjoint_insert_right : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] end insert /-! ### Lattice structure -/ section lattice variables [decidable_eq α] {s t u v : finset α} {a b : α} /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s t, ⟨_, t.2.ndunion s.1⟩⟩ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s t, ⟨_, s.2.ndinter t.1⟩⟩ instance : lattice (finset α) := { sup := (∪), sup_le := λ s t u hs ht a ha, (mem_ndunion.1 ha).elim (λ h, hs h) (λ h, ht h), le_sup_left := λ s t a h, mem_ndunion.2 $ or.inl h, le_sup_right := λ s t a h, mem_ndunion.2 $ or.inr h, inf := (∩), le_inf := λ s t u ht hu a h, mem_ndinter.2 ⟨ht h, hu h⟩, inf_le_left := λ s t a h, (mem_ndinter.1 h).1, inf_le_right := λ s t a h, (mem_ndinter.1 h).2, ..finset.partial_order } @[simp] lemma sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl @[simp] lemma inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl lemma disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := decidable_of_iff _ disjoint_left.symm /-! #### union -/ lemma union_val_nd (s t : finset α) : (s ∪ t).1 = ndunion s.1 t.1 := rfl @[simp] lemma union_val (s t : finset α) : (s ∪ t).1 = s.1 ∪ t.1 := ndunion_eq_union s.2 @[simp] lemma mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := mem_ndunion @[simp] lemma disj_union_eq_union (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp lemma mem_union_left (t : finset α) (h : a ∈ s) : a ∈ s ∪ t := mem_union.2 $ or.inl h lemma mem_union_right (s : finset α) (h : a ∈ t) : a ∈ s ∪ t := mem_union.2 $ or.inr h lemma forall_mem_union {p : α → Prop} : (∀ a ∈ s ∪ t, p a) ↔ (∀ a ∈ s, p a) ∧ ∀ a ∈ t, p a := ⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩, λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ lemma not_mem_union : a ∉ s ∪ t ↔ a ∉ s ∧ a ∉ t := by rw [mem_union, not_or_distrib] @[simp, norm_cast] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union lemma union_subset (hs : s ⊆ u) : t ⊆ u → s ∪ t ⊆ u := sup_le $ le_iff_subset.2 hs theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ lemma union_subset_union (hsu : s ⊆ u) (htv : t ⊆ v) : s ∪ t ⊆ u ∪ v := sup_le_sup (le_iff_subset.2 hsu) htv lemma union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := sup_comm instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] lemma union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := sup_assoc instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] lemma union_idempotent (s : finset α) : s ∪ s = s := sup_idem instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ lemma union_subset_left (h : s ∪ t ⊆ u) : s ⊆ u := (subset_union_left _ _).trans h lemma union_subset_right {s t u : finset α} (h : s ∪ t ⊆ u) : t ⊆ u := subset.trans (subset_union_right _ _) h lemma union_left_comm (s t u : finset α) : s ∪ (t ∪ u) = t ∪ (s ∪ u) := ext $ λ _, by simp only [mem_union, or.left_comm] lemma union_right_comm (s t u : finset α) : (s ∪ t) ∪ u = (s ∪ u) ∪ t := ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ t)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] lemma insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := sup_eq_left @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : s ∪ t = t ↔ s ⊆ t := sup_eq_right @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] lemma union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ⊔ u := sup_congr_left ht hu lemma union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u := sup_congr_right hs ht lemma union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t := sup_eq_sup_iff_left lemma union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u := sup_eq_sup_iff_right @[simp] lemma disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] lemma disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] /-- To prove a relation on pairs of `finset X`, it suffices to show that it is * symmetric, * it holds when one of the `finset`s is empty, * it holds for pairs of singletons, * if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`. -/ lemma induction_on_union (P : finset α → finset α → Prop) (symm : ∀ {a b}, P a b → P b a) (empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b}) (union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := begin intros a b, refine finset.induction_on b empty_right (λ x s xs hi, symm _), rw finset.insert_eq, apply union_of _ (symm hi), refine finset.induction_on a empty_right (λ a t ta hi, symm _), rw finset.insert_eq, exact union_of singletons (symm hi), end lemma _root_.directed.exists_mem_subset_of_finset_subset_bUnion {α ι : Type*} [hn : nonempty ι] {f : ι → set α} (h : directed (⊆) f) {s : finset α} (hs : (s : set α) ⊆ ⋃ i, f i) : ∃ i, (s : set α) ⊆ f i := begin classical, revert hs, apply s.induction_on, { refine λ _, ⟨hn.some, _⟩, simp only [coe_empty, set.empty_subset], }, { intros b t hbt htc hbtc, obtain ⟨i : ι , hti : (t : set α) ⊆ f i⟩ := htc (set.subset.trans (t.subset_insert b) hbtc), obtain ⟨j, hbj⟩ : ∃ j, b ∈ f j, by simpa [set.mem_Union₂] using hbtc (t.mem_insert_self b), rcases h j i with ⟨k, hk, hk'⟩, use k, rw [coe_insert, set.insert_subset], exact ⟨hk hbj, trans hti hk'⟩ } end lemma _root_.directed_on.exists_mem_subset_of_finset_subset_bUnion {α ι : Type*} {f : ι → set α} {c : set ι} (hn : c.nonempty) (hc : directed_on (λ i j, f i ⊆ f j) c) {s : finset α} (hs : (s : set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : set α) ⊆ f i := begin rw set.bUnion_eq_Union at hs, haveI := hn.coe_sort, obtain ⟨⟨i, hic⟩, hi⟩ := (directed_comp.2 hc.directed_coe).exists_mem_subset_of_finset_subset_bUnion hs, exact ⟨i, hic, hi⟩ end /-! #### inter -/ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] lemma inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right lemma subset_inter {s₁ s₂ u : finset α} : s₁ ⊆ s₂ → s₁ ⊆ u → s₁ ⊆ s₂ ∩ u := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp, norm_cast] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ _, by simp only [mem_inter, and.right_comm] @[simp] lemma inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _ @[simp] lemma inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _ @[simp] lemma empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _ @[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_left (h : t ⊆ u) : s ∩ t ⊆ s ∩ u := inter_subset_inter subset.rfl h lemma inter_subset_inter_right (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter h subset.rfl lemma inter_subset_union : s ∩ t ⊆ s ∪ t := le_iff_subset.1 inf_le_sup instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice } @[simp] theorem union_left_idem (s t : finset α) : s ∪ (s ∪ t) = s ∪ t := sup_left_idem @[simp] theorem union_right_idem (s t : finset α) : s ∪ t ∪ t = s ∪ t := sup_right_idem @[simp] theorem inter_left_idem (s t : finset α) : s ∩ (s ∩ t) = s ∩ t := inf_left_idem @[simp] theorem inter_right_idem (s t : finset α) : s ∩ t ∩ t = s ∩ t := inf_right_idem theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_union_distrib_left (s t u : finset α) : s ∪ (t ∪ u) = (s ∪ t) ∪ (s ∪ u) := sup_sup_distrib_left _ _ _ lemma union_union_distrib_right (s t u : finset α) : (s ∪ t) ∪ u = (s ∪ u) ∪ (t ∪ u) := sup_sup_distrib_right _ _ _ lemma inter_inter_distrib_left (s t u : finset α) : s ∩ (t ∩ u) = (s ∩ t) ∩ (s ∩ u) := inf_inf_distrib_left _ _ _ lemma inter_inter_distrib_right (s t u : finset α) : (s ∩ t) ∩ u = (s ∩ u) ∩ (t ∩ u) := inf_inf_distrib_right _ _ _ lemma union_union_union_comm (s t u v : finset α) : (s ∪ t) ∪ (u ∪ v) = (s ∪ u) ∪ (t ∪ v) := sup_sup_sup_comm _ _ _ _ lemma inter_inter_inter_comm (s t u v : finset α) : (s ∩ t) ∩ (u ∩ v) = (s ∩ u) ∩ (t ∩ v) := inf_inf_inf_comm _ _ _ _ lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff lemma union_subset_iff : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (sup_le_iff : s ⊔ t ≤ u ↔ s ≤ u ∧ t ≤ u) lemma subset_inter_iff : s ⊆ t ∩ u ↔ s ⊆ t ∧ s ⊆ u := (le_inf_iff : s ≤ t ⊓ u ↔ s ≤ t ∧ s ≤ u) @[simp] lemma inter_eq_left_iff_subset (s t : finset α) : s ∩ t = s ↔ s ⊆ t := inf_eq_left @[simp] lemma inter_eq_right_iff_subset (s t : finset α) : t ∩ s = s ↔ s ⊆ t := inf_eq_right lemma inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u := inf_congr_left ht hu lemma inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u := inf_congr_right hs ht lemma inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u := inf_eq_inf_iff_left lemma inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t := inf_eq_inf_iff_right lemma ite_subset_union (s s' : finset α) (P : Prop) [decidable P] : ite P s s' ⊆ s ∪ s' := ite_le_sup s s' P lemma inter_subset_ite (s s' : finset α) (P : Prop) [decidable P] : s ∩ s' ⊆ ite P s s' := inf_le_ite s s' P lemma not_disjoint_iff_nonempty_inter : ¬disjoint s t ↔ (s ∩ t).nonempty := not_disjoint_iff.trans $ by simp [finset.nonempty] alias not_disjoint_iff_nonempty_inter ↔ _ nonempty.not_disjoint lemma disjoint_or_nonempty_inter (s t : finset α) : disjoint s t ∨ (s ∩ t).nonempty := by { rw ←not_disjoint_iff_nonempty_inter, exact em _ } end lattice /-! ### erase -/ section erase variables [decidable_eq α] {s t u v : finset α} {a b : α} /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, s.2.erase a⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := s.2.mem_erase_iff lemma not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := s.2.not_mem_erase -- While this can be solved by `simp`, this lemma is eligible for `dsimp` @[nolint simp_nf, simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl @[simp] lemma erase_singleton (a : α) : ({a} : finset α).erase a = ∅ := begin ext x, rw [mem_erase, mem_singleton, not_and_self], refl, end lemma ne_of_mem_erase : b ∈ erase s a → b ≠ a := λ h, (mem_erase.1 h).1 lemma mem_of_mem_erase : b ∈ erase s a → b ∈ s := mem_of_mem_erase lemma mem_erase_of_ne_of_mem : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro /-- An element of `s` that is not an element of `erase s a` must be `a`. -/ lemma eq_of_mem_of_not_mem_erase (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := begin rw [mem_erase, not_and] at hsa, exact not_imp_not.mp hsa hs end @[simp] theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h @[simp] lemma erase_eq_self : s.erase a = s ↔ a ∉ s := ⟨λ h, h ▸ not_mem_erase _ _, erase_eq_of_not_mem⟩ @[simp] lemma erase_insert_eq_erase (s : finset α) (a : α) : (insert a s).erase a = s.erase a := ext $ λ x, by simp only [mem_erase, mem_insert, and.congr_right_iff, false_or, iff_self, implies_true_iff] { contextual := tt } theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := by rw [erase_insert_eq_erase, erase_eq_of_not_mem h] theorem erase_insert_of_ne {a b : α} {s : finset α} (h : a ≠ b) : erase (insert a s) b = insert a (erase s b) := ext $ λ x, have x ≠ b ∧ x = a ↔ x = a, from and_iff_right_of_imp (λ hx, hx.symm ▸ h), by simp only [mem_erase, mem_insert, and_or_distrib_left, this] theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ lemma subset_erase {a : α} {s t : finset α} : s ⊆ t.erase a ↔ s ⊆ t ∧ a ∉ s := ⟨λ h, ⟨h.trans (erase_subset _ _), λ ha, not_mem_erase _ _ (h ha)⟩, λ h b hb, mem_erase.2 ⟨ne_of_mem_of_not_mem hb h.2, h.1 hb⟩⟩ @[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h lemma ssubset_iff_exists_subset_erase {s t : finset α} : s ⊂ t ↔ ∃ a ∈ t, s ⊆ t.erase a := begin refine ⟨λ h, _, λ ⟨a, ha, h⟩, ssubset_of_subset_of_ssubset h $ erase_ssubset ha⟩, obtain ⟨a, ht, hs⟩ := not_subset.1 h.2, exact ⟨a, ht, subset_erase.2 ⟨h.1, hs⟩⟩, end lemma erase_ssubset_insert (s : finset α) (a : α) : s.erase a ⊂ insert a s := ssubset_iff_exists_subset_erase.2 ⟨a, mem_insert_self _ _, erase_subset_erase _ $ subset_insert _ _⟩ lemma erase_ne_self : s.erase a ≠ s ↔ a ∈ s := erase_eq_self.not_left lemma erase_cons {s : finset α} {a : α} (h : a ∉ s) : (s.cons a h).erase a = s := by rw [cons_eq_insert, erase_insert_eq_erase, erase_eq_of_not_mem h] lemma erase_idem {a : α} {s : finset α} : erase (erase s a) a = erase s a := by simp lemma erase_right_comm {a b : α} {s : finset α} : erase (erase s a) b = erase (erase s b) a := by { ext x, simp only [mem_erase, ←and_assoc], rw and_comm (x ≠ a) } theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.rfl theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.rfl lemma subset_insert_iff_of_not_mem (h : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t := by rw [subset_insert_iff, erase_eq_of_not_mem h] lemma erase_subset_iff_of_mem (h : a ∈ t) : s.erase a ⊆ t ↔ s ⊆ t := by rw [←subset_insert_iff, insert_eq_of_mem h] lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y := begin refine ⟨λ h, _, congr_arg _⟩, rw eq_of_mem_of_not_mem_erase hx, rw ←h, simp, end lemma erase_inj_on (s : finset α) : set.inj_on s.erase s := λ _ _ _ _, (erase_inj s ‹_›).mp lemma erase_inj_on' (a : α) : {s : finset α | a ∈ s}.inj_on (λ s, erase s a) := λ s hs t ht (h : s.erase a = _), by rw [←insert_erase hs, ←insert_erase ht, h] end erase /-! ### sdiff -/ section sdiff variables [decidable_eq α] {s t u v : finset α} {a b : α} /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le tsub_le_self s₁.2⟩⟩ @[simp] lemma sdiff_val (s₁ s₂ : finset α) : (s₁ \ s₂).val = s₁.val - s₂.val := rfl @[simp] theorem mem_sdiff : a ∈ s \ t ↔ a ∈ s ∧ a ∉ t := mem_sub_of_nodup s.2 @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h instance : generalized_boolean_algebra (finset α) := { sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union, mem_inter], tauto }, inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc, false_iff, inf_eq_inter, not_mem_empty], tauto }, ..finset.has_sdiff, ..finset.distrib_lattice, ..finset.order_bot } lemma not_mem_sdiff_of_mem_right (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false] lemma not_mem_sdiff_of_not_mem_left (h : a ∉ s) : a ∉ s \ t := by simpa lemma union_sdiff_of_subset (h : s ⊆ t) : s ∪ (t \ s) = t := sup_sdiff_cancel_right h theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := (union_comm _ _).trans (union_sdiff_of_subset h) lemma inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] lemma sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := inf_sdiff_self_left @[simp] lemma sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := sdiff_self lemma sdiff_inter_distrib_right (s t u : finset α) : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := sdiff_inf @[simp] lemma sdiff_inter_self_left (s t : finset α) : s \ (s ∩ t) = s \ t := sdiff_inf_self_left _ _ @[simp] lemma sdiff_inter_self_right (s t : finset α) : s \ (t ∩ s) = s \ t := sdiff_inf_self_right _ _ @[simp] lemma sdiff_empty : s \ ∅ = s := sdiff_bot @[mono] lemma sdiff_subset_sdiff (hst : s ⊆ t) (hvu : v ⊆ u) : s \ u ⊆ t \ v := sdiff_le_sdiff ‹s ≤ t› ‹v ≤ u› @[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] lemma union_sdiff_self_eq_union : s ∪ t \ s = s ∪ t := sup_sdiff_self_right _ _ @[simp] lemma sdiff_union_self_eq_union : s \ t ∪ t = s ∪ t := sup_sdiff_self_left _ _ lemma union_sdiff_left (s t : finset α) : (s ∪ t) \ s = t \ s := sup_sdiff_left_self lemma union_sdiff_right (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self lemma union_sdiff_symm : s ∪ (t \ s) = t ∪ (s \ t) := by simp [union_comm] lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := sup_sdiff_inf _ _ @[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := sdiff_idem lemma subset_sdiff : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := le_iff_subset.symm.trans le_sdiff @[simp] lemma sdiff_eq_empty_iff_subset : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff lemma sdiff_nonempty : (s \ t).nonempty ↔ ¬ s ⊆ t := nonempty_iff_ne_empty.trans sdiff_eq_empty_iff_subset.not @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := bot_sdiff lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem s h end lemma insert_sdiff_of_mem (s : finset α) {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem s h end @[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) : (insert x s) \ (insert x t) = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma sdiff_insert_of_not_mem {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t := begin refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _), simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢, exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩ end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le lemma sdiff_ssubset (h : t ⊆ s) (ht : t.nonempty) : s \ t ⊂ s := sdiff_lt ‹t ≤ s› ht.ne_empty lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sup_sdiff lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := sdiff_sup lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a := by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto } @[simp] lemma sdiff_singleton_not_mem_eq_self (s : finset α) {a : α} (ha : a ∉ s) : s \ {a} = s := by simp only [sdiff_singleton_eq_erase, ha, erase_eq_of_not_mem, not_false_iff] lemma sdiff_sdiff_left' (s t u : finset α) : (s \ t) \ u = (s \ t) ∩ (s \ u) := sdiff_sdiff_left' lemma sdiff_insert (s t : finset α) (x : α) : s \ insert x t = (s \ t).erase x := by simp_rw [← sdiff_singleton_eq_erase, insert_eq, sdiff_sdiff_left', sdiff_union_distrib, inter_comm] lemma sdiff_insert_insert_of_mem_of_not_mem {s t : finset α} {x : α} (hxs : x ∈ s) (hxt : x ∉ t) : insert x (s \ insert x t) = s \ t := by rw [sdiff_insert, insert_erase (mem_sdiff.mpr ⟨hxs, hxt⟩)] lemma sdiff_erase {x : α} (hx : x ∈ s) : s \ s.erase x = {x} := begin rw [← sdiff_singleton_eq_erase, sdiff_sdiff_right_self], exact inf_eq_right.2 (singleton_subset_iff.2 hx), end lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma sdiff_sdiff_eq_self (h : t ⊆ s) : s \ (s \ t) = t := sdiff_sdiff_eq_self h lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ := sdiff_eq_sdiff_iff_inf_eq_inf lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf lemma erase_eq_empty_iff (s : finset α) (a : α) : s.erase a = ∅ ↔ s = ∅ ∨ s = {a} := by rw [←sdiff_singleton_eq_erase, sdiff_eq_empty_iff_subset, subset_singleton_iff] --TODO@Yaël: Kill lemmas duplicate with `boolean_algebra` lemma sdiff_disjoint : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint lemma sdiff_eq_self_iff_disjoint : s \ t = s ↔ disjoint s t := sdiff_eq_self_iff_disjoint' lemma sdiff_eq_self_of_disjoint (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h end sdiff /-! ### Symmetric difference -/ section symm_diff variables [decidable_eq α] {s t : finset α} {a b : α} lemma mem_symm_diff : a ∈ s ∆ t ↔ a ∈ s ∧ a ∉ t ∨ a ∈ t ∧ a ∉ s := by simp_rw [symm_diff, sup_eq_union, mem_union, mem_sdiff] @[simp, norm_cast] lemma coe_symm_diff : (↑(s ∆ t) : set α) = s ∆ t := set.ext $ λ _, mem_symm_diff end symm_diff /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := by { cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof], apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx } @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl @[simp] lemma attach_nonempty_iff (s : finset α) : s.attach.nonempty ↔ s.nonempty := by simp [finset.nonempty] @[simp] lemma attach_eq_empty_iff (s : finset α) : s.attach = ∅ ↔ s = ∅ := by simpa [eq_empty_iff_forall_not_mem] /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Π i, δ i) [Π j, decidable (j ∈ s)] : Π i, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Π i, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀ i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [Π i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [Π j, decidable (j ∈ s)] -- TODO: fix this in norm_cast @[norm_cast move] lemma piecewise_coe [∀ j, decidable (j ∈ (s : set α))] : (s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i) @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀ i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀ i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := by { classical, simp only [← piecewise_coe, coe_insert, ← set.piecewise_insert] } lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s; simpa [hi] lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' := by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg } lemma piecewise_singleton [decidable_eq α] (i : α) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl) @[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi)) @[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : update f i v = piecewise (singleton i) (λj, v) f := (piecewise_singleton _ _ _).symm lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := begin ext j, rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp * end lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := begin rw update_piecewise, refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _), exact λ h, hj (h.symm ▸ hi) end lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := begin rw update_piecewise, refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl), exact λ h, hi (h ▸ hj) end lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h := λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x) lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g := λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x) lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' := λ x, by { by_cases hx : x ∈ s; simp [hx, *] } lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' := s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x) lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : s.piecewise f g ∈ set.Icc f₁ g₁ := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) : s.piecewise f g ∈ set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) : s.piecewise f g ∈ set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h) end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Π a ∈ s, Prop} [hp : ∀ a (h : a ∈ s), decidable (p a h)] : decidable (∀ a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀ a, decidable_eq (β a)] : decidable_eq (Π a ∈ s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Π a ∈ s, Prop} [hp : ∀ a (h : a ∈ s), decidable (p a h)] : decidable (∃ a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (s : finset α) : finset α := ⟨_, s.2.filter p⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter lemma mem_of_mem_filter {s : finset α} (x : α) (h : x ∈ s.filter p) : x ∈ s := mem_of_mem_filter h theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x := ⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩, λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext $ assume a, by simp only [mem_filter, and_false]; refl variables {p q} lemma filter_eq_self (s : finset α) : s.filter p = s ↔ ∀ x ∈ s, p x := by simp [finset.ext_iff] /-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ @[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s := (filter_eq_self s).mpr h /-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ := eq_empty_of_forall_not_mem (by simpa) lemma filter_eq_empty_iff (s : finset α) : (s.filter p = ∅) ↔ ∀ x ∈ s, ¬ p x := begin refine ⟨_, filter_false_of_mem⟩, intros hs, injection hs with hs', rwa filter_eq_nil at hs' end lemma filter_nonempty_iff {s : finset α} : (s.filter p).nonempty ↔ ∃ a ∈ s, p a := by simp only [nonempty_iff_ne_empty, ne.def, filter_eq_empty_iff, not_not, not_forall] lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H variables (p q) lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ lemma monotone_filter_left : monotone (filter p) := λ _ _, filter_subset_filter p lemma monotone_filter_right (s : finset α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : s.filter p ≤ s.filter q := multiset.subset_of_le (multiset.monotone_filter_right s.val h) @[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter lemma subset_coe_filter_of_subset_forall (s : finset α) {t : set α} (h₁ : t ⊆ s) (h₂ : ∀ x ∈ t, p x) : t ⊆ s.filter p := λ x hx, (s.coe_filter p).symm ▸ ⟨h₁ hx, h₂ x hx⟩ theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_cons_of_pos (a : α) (s : finset α) (ha : a ∉ s) (hp : p a): filter p (cons a s ha) = cons a (filter p s) (mem_filter.not.mpr $ mt and.left ha) := eq_of_veq $ multiset.filter_cons_of_pos s.val hp theorem filter_cons_of_neg (a : α) (s : finset α) (ha : a ∉ s) (hp : ¬p a): filter p (cons a s ha) = filter p s := eq_of_veq $ multiset.filter_cons_of_neg s.val hp lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ ∀ x ∈ s, p x → ¬ q x := by split; simp [disjoint_left] {contextual := tt} lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint s t → disjoint (s.filter p) (t.filter q) := disjoint.mono (filter_subset _ _) (filter_subset _ _) lemma disjoint_filter_filter' (s t : finset α) {p q : α → Prop} [decidable_pred p] [decidable_pred q] (h : disjoint p q) : disjoint (s.filter p) (t.filter q) := begin simp_rw [disjoint_left, mem_filter], rintros a ⟨hs, hp⟩ ⟨ht, hq⟩, exact h.le_bot _ ⟨hp, hq⟩, end lemma disjoint_filter_filter_neg (s t : finset α) (p : α → Prop) [decidable_pred p] [decidable_pred (λ a, ¬ p a)] : disjoint (s.filter p) (t.filter $ λ a, ¬ p a) := disjoint_filter_filter' s t disjoint_compl_right theorem filter_disj_union (s : finset α) (t : finset α) (h : disjoint s t) : filter p (disj_union s t h) = (filter p s).disj_union (filter p t) (disjoint_filter_filter h) := eq_of_veq $ multiset.filter_add _ _ _ theorem filter_cons {a : α} (s : finset α) (ha : a ∉ s) : filter p (cons a s ha) = (if p a then {a} else ∅ : finset α).disj_union (filter p s) (by { split_ifs, { rw disjoint_singleton_left, exact (mem_filter.not.mpr $ mt and.left ha) }, { exact disjoint_empty_left _ } }) := begin split_ifs with h, { rw [filter_cons_of_pos _ _ _ ha h, singleton_disj_union] }, { rw [filter_cons_of_neg _ _ _ ha h, empty_disj_union] }, end variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] : s.filter (λ i, i ∈ t) = s ∩ t := ext $ λ i, by rw [mem_filter, mem_inter] lemma filter_inter_distrib (s t : finset α) : (s ∩ t).filter p = s.filter p ∩ t.filter p := by { ext, simp only [mem_filter, mem_inter], exact and_and_distrib_right _ _ _ } theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_erase (a : α) (s : finset α) : filter p (erase s a) = erase (filter p s) a := by { ext x, simp only [and_assoc, mem_filter, iff_self, mem_erase] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter] lemma sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃ s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, em] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{x ∈ s | p x}` for `finset.filter p s`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{x ∈ s | p x}` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{x ∈ s | p x}` to `finset.filter p s`. If `p` happens to be decidable, the simp-lemma `finset.filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩ }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintro m ⟨e⟩, exact h m } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b := by { ext, simp only [mem_filter, mem_erase, ne.def], tauto } lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b := trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b) theorem filter_inter_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s t : finset α) : s.filter p ∩ t.filter (λa, ¬ p a) = ∅ := (disjoint_filter_filter_neg s t p).eq_bot theorem filter_union_filter_of_codisjoint (s : finset α) (h : codisjoint p q) : s.filter p ∪ s.filter q = s := (filter_or _ _ _).symm.trans $ filter_true_of_mem $ λ x hx, h.top_le x trivial theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := filter_union_filter_of_codisjoint _ _ _ codisjoint_hnot_right end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp, norm_cast] lemma coe_range (n : ℕ) : (range n : set ℕ) = set.Iio n := set.ext $ λ _, mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm lemma range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b := finset.mem_range.trans nat.lt_succ_iff lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := (mem_range.1 hx).le lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 := ne_of_gt $ tsub_pos_of_lt $ mem_range.1 hx @[simp] lemma nonempty_range_iff : (range n).nonempty ↔ n ≠ 0 := ⟨λ ⟨k, hk⟩, ((zero_le k).trans_lt $ mem_range.1 hk).ne', λ h, ⟨0, mem_range.2 $ pos_iff_ne_zero.2 h⟩⟩ @[simp] lemma range_eq_empty_iff : range n = ∅ ↔ n = 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_range_iff, not_not] lemma nonempty_range_succ : (range $ n + 1).nonempty := nonempty_range_iff.2 n.succ_ne_zero @[simp] lemma range_filter_eq {n m : ℕ} : (range n).filter (= m) = if m < n then {m} else ∅ := begin convert filter_eq (range n) m, { ext, exact comm }, { simp } end end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] lemma exists_mem_insert [decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ ∃ x, x ∈ s ∧ p x := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim lemma forall_mem_insert [decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ ∀ x, x ∈ s → p x := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ := { to_fun := λ i, i.1 - k, inv_fun := λ j, ⟨j + k, by simp⟩, left_inv := λ j, begin rw subtype.ext_iff_val, apply tsub_add_cancel_of_le, simpa using j.2 end, right_inv := λ j, add_tsub_cancel_right _ _ } @[simp] lemma coe_not_mem_range_equiv (k : ℕ) : (not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl @[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) : ((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl /-! ### dedup on list and multiset -/ namespace multiset variables [decidable_eq α] {s t : multiset α} /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_dedup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.dedup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 n.dedup.symm lemma nodup.to_finset_inj {l l' : multiset α} (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l = l' := by simpa [←to_finset_eq hl, ←to_finset_eq hl'] using h @[simp] lemma mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_dedup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a ::ₘ s) = insert a (to_finset s) := finset.eq_of_veq dedup_cons @[simp] lemma to_finset_singleton (a : α) : to_finset ({a} : multiset α) = {a} := by rw [←cons_zero, to_finset_cons, to_finset_zero, is_lawful_singleton.insert_emptyc_eq] @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_nsmul (s : multiset α) : ∀ (n : ℕ) (hn : n ≠ 0), (n • s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, one_nsmul] }, { rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp @[simp] theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.dedup_eq_zero @[simp] lemma to_finset_subset : s.to_finset ⊆ t.to_finset ↔ s ⊆ t := by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset] @[simp] lemma to_finset_ssubset : s.to_finset ⊂ t.to_finset ↔ s ⊂ t := by { simp_rw [finset.ssubset_def, to_finset_subset], refl } @[simp] lemma to_finset_dedup (m : multiset α) : m.dedup.to_finset = m.to_finset := by simp_rw [to_finset, dedup_idempotent] @[simp] lemma to_finset_bind_dedup [decidable_eq β] (m : multiset α) (f : α → multiset β) : (m.dedup.bind f).to_finset = (m.bind f).to_finset := by simp_rw [to_finset, dedup_bind_dedup] instance is_well_founded_ssubset : is_well_founded (multiset β) (⊂) := subrelation.is_well_founded (inv_image _ _) $ λ _ _, by classical; exact to_finset_ssubset.2 end multiset namespace finset @[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s := by { ext, rw [multiset.mem_to_finset, ←mem_def] } lemma val_le_iff_val_subset {a : finset α} {b : multiset α} : a.val ≤ b ↔ a.val ⊆ b := multiset.le_iff_subset a.nodup end finset namespace list variables [decidable_eq α] {l l' : list α} {a : α} /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.dedup : multiset α) := rfl @[simp] theorem to_finset_coe (l : list α) : (l : multiset α).to_finset = l.to_finset := rfl lemma to_finset_eq (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] lemma mem_to_finset : a ∈ l.to_finset ↔ a ∈ l := mem_dedup @[simp, norm_cast] lemma coe_to_finset (l : list α) : (l.to_finset : set α) = {a | a ∈ l} := set.ext $ λ _, list.mem_to_finset @[simp] lemma to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] lemma to_finset_cons : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.dedup_cons, h] lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ := by { rintro ⟨⟨l⟩, hl⟩ _, exact ⟨l, hl, (to_finset_eq hl).symm⟩ } theorem to_finset_surjective : surjective (to_finset : list α → finset α) := λ s, let ⟨l, _, hls⟩ := to_finset_surj_on (set.mem_univ s) in ⟨l, hls⟩ lemma to_finset_eq_iff_perm_dedup : l.to_finset = l'.to_finset ↔ l.dedup ~ l'.dedup := by simp [finset.ext_iff, perm_ext (nodup_dedup _) (nodup_dedup _)] lemma to_finset.ext_iff {a b : list α} : a.to_finset = b.to_finset ↔ ∀ x, x ∈ a ↔ x ∈ b := by simp only [finset.ext_iff, mem_to_finset] lemma to_finset.ext : (∀ x, x ∈ l ↔ x ∈ l') → l.to_finset = l'.to_finset := to_finset.ext_iff.mpr lemma to_finset_eq_of_perm (l l' : list α) (h : l ~ l') : l.to_finset = l'.to_finset := to_finset_eq_iff_perm_dedup.mpr h.dedup lemma perm_of_nodup_nodup_to_finset_eq (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l ~ l' := by { rw ←multiset.coe_eq_coe, exact multiset.nodup.to_finset_inj hl hl' h } @[simp] lemma to_finset_append : to_finset (l ++ l') = l.to_finset ∪ l'.to_finset := begin induction l with hd tl hl, { simp }, { simp [hl] } end @[simp] lemma to_finset_reverse {l : list α} : to_finset l.reverse = l.to_finset := to_finset_eq_of_perm _ _ (reverse_perm l) lemma to_finset_repeat_of_ne_zero {n : ℕ} (hn : n ≠ 0) : (list.repeat a n).to_finset = {a} := by { ext x, simp [hn, list.mem_repeat] } @[simp] lemma to_finset_union (l l' : list α) : (l ∪ l').to_finset = l.to_finset ∪ l'.to_finset := by { ext, simp } @[simp] lemma to_finset_inter (l l' : list α) : (l ∩ l').to_finset = l.to_finset ∩ l'.to_finset := by { ext, simp } @[simp] lemma to_finset_eq_empty_iff (l : list α) : l.to_finset = ∅ ↔ l = nil := by cases l; simp end list namespace finset section to_list /-- Produce a list of the elements in the finite set using choice. -/ noncomputable def to_list (s : finset α) : list α := s.1.to_list lemma nodup_to_list (s : finset α) : s.to_list.nodup := by { rw [to_list, ←multiset.coe_nodup, multiset.coe_to_list], exact s.nodup } @[simp] lemma mem_to_list {a : α} {s : finset α} : a ∈ s.to_list ↔ a ∈ s := mem_to_list @[simp] lemma to_list_eq_nil {s : finset α} : s.to_list = [] ↔ s = ∅ := to_list_eq_nil.trans val_eq_zero @[simp] lemma empty_to_list {s : finset α} : s.to_list.empty ↔ s = ∅ := list.empty_iff_eq_nil.trans to_list_eq_nil @[simp] lemma to_list_empty : (∅ : finset α).to_list = [] := to_list_eq_nil.mpr rfl lemma nonempty.to_list_ne_nil {s : finset α} (hs : s.nonempty) : s.to_list ≠ [] := mt to_list_eq_nil.mp hs.ne_empty lemma nonempty.not_empty_to_list {s : finset α} (hs : s.nonempty) : ¬s.to_list.empty := mt empty_to_list.mp hs.ne_empty @[simp, norm_cast] lemma coe_to_list (s : finset α) : (s.to_list : multiset α) = s.val := s.val.coe_to_list @[simp] lemma to_list_to_finset [decidable_eq α] (s : finset α) : s.to_list.to_finset = s := by { ext, simp } lemma exists_list_nodup_eq [decidable_eq α] (s : finset α) : ∃ (l : list α), l.nodup ∧ l.to_finset = s := ⟨s.to_list, s.nodup_to_list, s.to_list_to_finset⟩ lemma to_list_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).to_list ~ a :: s.to_list := (list.perm_ext (nodup_to_list _) (by simp [h, nodup_to_list s])).2 $ λ x, by simp only [list.mem_cons_iff, finset.mem_to_list, finset.mem_cons] lemma to_list_insert [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : (insert a s).to_list ~ a :: s.to_list := cons_eq_insert _ _ h ▸ to_list_cons _ end to_list /-! ### disj_Union This section is about the bounded union of a disjoint indexed family `t : α → finset β` of finite sets over a finite set `s : finset α`. In most cases `finset.bUnion` should be preferred. -/ section disj_Union variables {s s₁ s₂ : finset α} {t t₁ t₂ : α → finset β} /-- `disj_Union s f h` is the set such that `a ∈ disj_Union s f` iff `a ∈ f i` for some `i ∈ s`. It is the same as `s.bUnion f`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_Union (s : finset α) (t : α → finset β) (hf : (s : set α).pairwise_disjoint t) : finset β := ⟨(s.val.bind (finset.val ∘ t)), multiset.nodup_bind.mpr ⟨λ a ha, (t a).nodup, s.nodup.pairwise $ λ a ha b hb hab, disjoint_val.2 $ hf ha hb hab⟩⟩ @[simp] theorem disj_Union_val (s : finset α) (t : α → finset β) (h) : (s.disj_Union t h).1 = (s.1.bind (λ a, (t a).1)) := rfl @[simp] theorem disj_Union_empty (t : α → finset β) : disj_Union ∅ t (by simp) = ∅ := rfl @[simp] lemma mem_disj_Union {b : β} {h} : b ∈ s.disj_Union t h ↔ ∃ a ∈ s, b ∈ t a := by simp only [mem_def, disj_Union_val, mem_bind, exists_prop] @[simp, norm_cast] lemma coe_disj_Union {h} : (s.disj_Union t h : set β) = ⋃ x ∈ (s : set α), t x := by simp only [set.ext_iff, mem_disj_Union, set.mem_Union, iff_self, mem_coe, implies_true_iff] @[simp] theorem disj_Union_cons (a : α) (s : finset α) (ha : a ∉ s) (f : α → finset β) (H) : disj_Union (cons a s ha) f H = (f a).disj_union (s.disj_Union f $ λ b hb c hc, H (mem_cons_of_mem hb) (mem_cons_of_mem hc)) (disjoint_left.mpr $ λ b hb h, let ⟨c, hc, h⟩ := mem_disj_Union.mp h in disjoint_left.mp (H (mem_cons_self a s) (mem_cons_of_mem hc) (ne_of_mem_of_not_mem hc ha).symm) hb h) := eq_of_veq $ multiset.cons_bind _ _ _ @[simp] lemma singleton_disj_Union (a : α) {h} : finset.disj_Union {a} t h = t a := eq_of_veq $ multiset.singleton_bind _ _ lemma disj_Union_disj_Union (s : finset α) (f : α → finset β) (g : β → finset γ) (h1 h2) : (s.disj_Union f h1).disj_Union g h2 = s.attach.disj_Union (λ a, (f a).disj_Union g $ λ b hb c hc, h2 (mem_disj_Union.mpr ⟨_, a.prop, hb⟩) (mem_disj_Union.mpr ⟨_, a.prop, hc⟩)) (λ a ha b hb hab, disjoint_left.mpr $ λ x hxa hxb, begin obtain ⟨xa, hfa, hga⟩ := mem_disj_Union.mp hxa, obtain ⟨xb, hfb, hgb⟩ := mem_disj_Union.mp hxb, refine disjoint_left.mp (h2 (mem_disj_Union.mpr ⟨_, a.prop, hfa⟩) (mem_disj_Union.mpr ⟨_, b.prop, hfb⟩) _) hga hgb, rintro rfl, exact disjoint_left.mp (h1 a.prop b.prop $ subtype.coe_injective.ne hab) hfa hfb, end) := eq_of_veq $ multiset.bind_assoc.trans (multiset.attach_bind_coe _ _).symm lemma disj_Union_filter_eq_of_maps_to [decidable_eq β] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.disj_Union (λ a, s.filter $ (λ c, f c = a)) (λ x' hx y' hy hne, disjoint_filter_filter' _ _ begin simp_rw [pi.disjoint_iff, Prop.disjoint_iff], rintros i ⟨rfl, rfl⟩, exact hne rfl, end) = s := ext $ λ b, by simpa using h b end disj_Union section bUnion /-! ### bUnion This section is about the bounded union of an indexed family `t : α → finset β` of finite sets over a finite set `s : finset α`. -/ variables [decidable_eq β] {s s₁ s₂ : finset α} {t t₁ t₂ : α → finset β} /-- `bUnion s t` is the union of `t x` over `x ∈ s`. (This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/ protected def bUnion (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bUnion_val (s : finset α) (t : α → finset β) : (s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).dedup := rfl @[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl @[simp] lemma mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃ a ∈ s, b ∈ t a := by simp only [mem_def, bUnion_val, mem_dedup, mem_bind, exists_prop] @[simp, norm_cast] lemma coe_bUnion : (s.bUnion t : set β) = ⋃ x ∈ (s : set α), t x := by simp only [set.ext_iff, mem_bUnion, set.mem_Union, iff_self, mem_coe, implies_true_iff] @[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t := ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib] lemma bUnion_congr (hs : s₁ = s₂) (ht : ∀ a ∈ s₁, t₁ a = t₂ a) : s₁.bUnion t₁ = s₂.bUnion t₂ := ext $ λ x, by simp [hs, ht] { contextual := tt } @[simp] lemma disj_Union_eq_bUnion (s : finset α) (f : α → finset β) (hf) : s.disj_Union f hf = s.bUnion f := begin dsimp [disj_Union, finset.bUnion, function.comp], generalize_proofs h, exact eq_of_veq h.dedup.symm, end theorem bUnion_subset {s' : finset β} : s.bUnion t ⊆ s' ↔ ∀ x ∈ s, t x ⊆ s' := by simp only [subset_iff, mem_bUnion]; exact ⟨λ H a ha b hb, H ⟨a, ha, hb⟩, λ H b ⟨a, ha, hb⟩, H a ha hb⟩ @[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a := by { classical, rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty] } theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) := begin ext x, simp only [mem_bUnion, mem_inter], tauto end theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) := by rw [inter_comm, bUnion_inter]; simp [inter_comm] lemma bUnion_bUnion [decidable_eq γ] (s : finset α) (f : α → finset β) (g : β → finset γ) : (s.bUnion f).bUnion g = s.bUnion (λ a, (f a).bUnion g) := begin ext, simp only [finset.mem_bUnion, exists_prop], simp_rw [←exists_and_distrib_right, ←exists_and_distrib_left, and_assoc], rw exists_comm, end theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) := ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop] lemma bUnion_mono (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion t₂ := have ∀ b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bUnion, exists_imp_distrib, and_imp, exists_prop] lemma bUnion_subset_bUnion_of_subset_left (t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bUnion t ⊆ s₂.bUnion t := begin intro x, simp only [and_imp, mem_bUnion, exists_prop], exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩) end lemma subset_bUnion_of_mem (u : α → finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.bUnion u := singleton_bUnion.superset.trans $ bUnion_subset_bUnion_of_subset_left u $ singleton_subset_iff.2 xs @[simp] lemma bUnion_subset_iff_forall_subset {α β : Type*} [decidable_eq β] {s : finset α} {t : finset β} {f : α → finset β} : s.bUnion f ⊆ t ↔ ∀ x ∈ s, f x ⊆ t := ⟨λ h x hx, (subset_bUnion_of_mem f hx).trans h, λ h x hx, let ⟨a, ha₁, ha₂⟩ := mem_bUnion.mp hx in h _ ha₁ ha₂⟩ @[simp] lemma bUnion_singleton_eq_self [decidable_eq α] : s.bUnion (singleton : α → finset α) = s := ext $ λ x, by simp only [mem_bUnion, mem_singleton, exists_prop, exists_eq_right'] lemma filter_bUnion (s : finset α) (f : α → finset β) (p : β → Prop) [decidable_pred p] : (s.bUnion f).filter p = s.bUnion (λ a, (f a).filter p) := begin ext b, simp only [mem_bUnion, exists_prop, mem_filter], split, { rintro ⟨⟨a, ha, hba⟩, hb⟩, exact ⟨a, ha, hba, hb⟩ }, { rintro ⟨a, ha, hba, hb⟩, exact ⟨⟨a, ha, hba⟩, hb⟩ } end lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.bUnion (λ a, s.filter $ (λ c, f c = a)) = s := by simpa only [disj_Union_eq_bUnion] using disj_Union_filter_eq_of_maps_to h lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) : (s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) := by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] } @[simp] lemma bUnion_nonempty : (s.bUnion t).nonempty ↔ ∃ x ∈ s, (t x).nonempty := by simp [finset.nonempty, ← exists_and_distrib_left, @exists_swap α] lemma nonempty.bUnion (hs : s.nonempty) (ht : ∀ x ∈ s, (t x).nonempty) : (s.bUnion t).nonempty := bUnion_nonempty.2 $ hs.imp $ λ x hx, ⟨hx, ht x hx⟩ lemma disjoint_bUnion_left (s : finset α) (f : α → finset β) (t : finset β) : disjoint (s.bUnion f) t ↔ (∀ i ∈ s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] } end lemma disjoint_bUnion_right (s : finset β) (t : finset α) (f : α → finset β) : disjoint s (t.bUnion f) ↔ ∀ i ∈ t, disjoint s (f i) := by simpa only [disjoint.comm] using disjoint_bUnion_left t f s end bUnion /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose section pairwise variables {s : finset α} lemma pairwise_subtype_iff_pairwise_finset' (r : β → β → Prop) (f : α → β) : pairwise (r on λ x : s, f x) ↔ (s : set α).pairwise (r on f) := pairwise_subtype_iff_pairwise_set (s : set α) (r on f) lemma pairwise_subtype_iff_pairwise_finset (r : α → α → Prop) : pairwise (r on λ x : s, x) ↔ (s : set α).pairwise r := pairwise_subtype_iff_pairwise_finset' r id lemma pairwise_cons' {a : α} (ha : a ∉ s) (r : β → β → Prop) (f : α → β) : pairwise (r on λ a : s.cons a ha, f a) ↔ pairwise (r on λ a : s, f a) ∧ ∀ b ∈ s, r (f a) (f b) ∧ r (f b) (f a) := begin simp only [pairwise_subtype_iff_pairwise_finset', finset.coe_cons, set.pairwise_insert, finset.mem_coe, and.congr_right_iff], exact λ hsr, ⟨λ h b hb, h b hb $ by { rintro rfl, contradiction }, λ h b hb _, h b hb⟩, end lemma pairwise_cons {a : α} (ha : a ∉ s) (r : α → α → Prop) : pairwise (r on λ a : s.cons a ha, a) ↔ pairwise (r on λ a : s, a) ∧ ∀ b ∈ s, r a b ∧ r b a := pairwise_cons' ha r id end pairwise end finset namespace equiv /-- Inhabited types are equivalent to `option β` for some `β` by identifying `default α` with `none`. -/ def sigma_equiv_option_of_inhabited (α : Type u) [inhabited α] [decidable_eq α] : Σ (β : Type u), α ≃ option β := ⟨{x : α // x ≠ default}, { to_fun := λ (x : α), if h : x = default then none else some ⟨x, h⟩, inv_fun := option.elim default coe, left_inv := λ x, by { dsimp only, split_ifs; simp [*] }, right_inv := begin rintro (_|⟨x,h⟩), { simp }, { dsimp only, split_ifs with hi, { simpa [h] using hi }, { simp } } end }⟩ end equiv namespace multiset variable [decidable_eq α] lemma disjoint_to_finset {m1 m2 : multiset α} : _root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 := begin rw finset.disjoint_iff_ne, refine ⟨λ h a ha1 ha2, _, _⟩, { rw ← multiset.mem_to_finset at ha1 ha2, exact h _ ha1 _ ha2 rfl }, { rintros h a ha b hb rfl, rw multiset.mem_to_finset at ha hb, exact h ha hb } end end multiset namespace list variables [decidable_eq α] {l l' : list α} lemma disjoint_to_finset_iff_disjoint : _root_.disjoint l.to_finset l'.to_finset ↔ l.disjoint l' := multiset.disjoint_to_finset end list -- Assert that we define `finset` without the material on `list.sublists`. -- Note that we cannot use `list.sublists` itself as that is defined very early. assert_not_exists list.sublists_len assert_not_exists multiset.powerset
96c6a17f9b86d8d45ee54faf203bac025191cb56
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/pfun.lean
f698b62007161c0df100a8ff7d0c0a4175d5819d
[ "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
22,631
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Jeremy Avigad, Simon Hudon -/ import data.part import data.rel /-! # Partial functions This file defines partial functions. Partial functions are like functions, except they can also be "undefined" on some inputs. We define them as functions `α → part β`. ## Definitions * `pfun α β`: Type of partial functions from `α` to `β`. Defined as `α → part β` and denoted `α →. β`. * `pfun.dom`: Domain of a partial function. Set of values on which it is defined. Not to be confused with the domain of a function `α → β`, which is a type (`α` presently). * `pfun.fn`: Evaluation of a partial function. Takes in an element and a proof it belongs to the partial function's `dom`. * `pfun.as_subtype`: Returns a partial function as a function from its `dom`. * `pfun.to_subtype`: Restricts the codomain of a function to a subtype. * `pfun.eval_opt`: Returns a partial function with a decidable `dom` as a function `a → option β`. * `pfun.lift`: Turns a function into a partial function. * `pfun.id`: The identity as a partial function. * `pfun.comp`: Composition of partial functions. * `pfun.restrict`: Restriction of a partial function to a smaller `dom`. * `pfun.res`: Turns a function into a partial function with a prescribed domain. * `pfun.fix` : First return map of a partial function `f : α →. β ⊕ α`. * `pfun.fix_induction`: A recursion principle for `pfun.fix`. ### Partial functions as relations Partial functions can be considered as relations, so we specialize some `rel` definitions to `pfun`: * `pfun.image`: Image of a set under a partial function. * `pfun.ran`: Range of a partial function. * `pfun.preimage`: Preimage of a set under a partial function. * `pfun.core`: Core of a set under a partial function. * `pfun.graph`: Graph of a partial function `a →. β`as a `set (α × β)`. * `pfun.graph'`: Graph of a partial function `a →. β`as a `rel α β`. ### `pfun α` as a monad Monad operations: * `pfun.pure`: The monad `pure` function, the constant `x` function. * `pfun.bind`: The monad `bind` function, pointwise `part.bind` * `pfun.map`: The monad `map` function, pointwise `part.map`. -/ open function /-- `pfun α β`, or `α →. β`, is the type of partial functions from `α` to `β`. It is defined as `α → part β`. -/ def pfun (α β : Type*) := α → part β infixr ` →. `:25 := pfun namespace pfun variables {α β γ δ ε ι : Type*} instance : inhabited (α →. β) := ⟨λ a, part.none⟩ /-- The domain of a partial function -/ def dom (f : α →. β) : set α := {a | (f a).dom} @[simp] lemma mem_dom (f : α →. β) (x : α) : x ∈ dom f ↔ ∃ y, y ∈ f x := by simp [dom, part.dom_iff_mem] @[simp] lemma dom_mk (p : α → Prop) (f : Π a, p a → β) : pfun.dom (λ x, ⟨p x, f x⟩) = {x | p x} := rfl theorem dom_eq (f : α →. β) : dom f = {x | ∃ y, y ∈ f x} := set.ext (mem_dom f) /-- Evaluate a partial function -/ def fn (f : α →. β) (a : α) : dom f a → β := (f a).get @[simp] lemma fn_apply (f : α →. β) (a : α) : f.fn a = (f a).get := rfl /-- Evaluate a partial function to return an `option` -/ def eval_opt (f : α →. β) [D : decidable_pred (∈ dom f)] (x : α) : option β := @part.to_option _ _ (D x) /-- Partial function extensionality -/ theorem ext' {f g : α →. β} (H1 : ∀ a, a ∈ dom f ↔ a ∈ dom g) (H2 : ∀ a p q, f.fn a p = g.fn a q) : f = g := funext $ λ a, part.ext' (H1 a) (H2 a) theorem ext {f g : α →. β} (H : ∀ a b, b ∈ f a ↔ b ∈ g a) : f = g := funext $ λ a, part.ext (H a) /-- Turns a partial function into a function out of its domain. -/ def as_subtype (f : α →. β) (s : f.dom) : β := f.fn s s.2 /-- The type of partial functions `α →. β` is equivalent to the type of pairs `(p : α → Prop, f : subtype p → β)`. -/ def equiv_subtype : (α →. β) ≃ (Σ p : α → Prop, subtype p → β) := ⟨λ f, ⟨λ a, (f a).dom, as_subtype f⟩, λ f x, ⟨f.1 x, λ h, f.2 ⟨x, h⟩⟩, λ f, funext $ λ a, part.eta _, λ ⟨p, f⟩, by dsimp; congr; funext a; cases a; refl⟩ theorem as_subtype_eq_of_mem {f : α →. β} {x : α} {y : β} (fxy : y ∈ f x) (domx : x ∈ f.dom) : f.as_subtype ⟨x, domx⟩ = y := part.mem_unique (part.get_mem _) fxy /-- Turn a total function into a partial function. -/ protected def lift (f : α → β) : α →. β := λ a, part.some (f a) instance : has_coe (α → β) (α →. β) := ⟨pfun.lift⟩ @[simp] theorem lift_eq_coe (f : α → β) : pfun.lift f = f := rfl @[simp] theorem coe_val (f : α → β) (a : α) : (f : α →. β) a = part.some (f a) := rfl @[simp] lemma dom_coe (f : α → β) : (f : α →. β).dom = set.univ := rfl lemma coe_injective : injective (coe : (α → β) → α →. β) := λ f g h, funext $ λ a, part.some_injective $ congr_fun h a /-- Graph of a partial function `f` as the set of pairs `(x, f x)` where `x` is in the domain of `f`. -/ def graph (f : α →. β) : set (α × β) := {p | p.2 ∈ f p.1} /-- Graph of a partial function as a relation. `x` and `y` are related iff `f x` is defined and "equals" `y`. -/ def graph' (f : α →. β) : rel α β := λ x y, y ∈ f x /-- The range of a partial function is the set of values `f x` where `x` is in the domain of `f`. -/ def ran (f : α →. β) : set β := {b | ∃ a, b ∈ f a} /-- Restrict a partial function to a smaller domain. -/ def restrict (f : α →. β) {p : set α} (H : p ⊆ f.dom) : α →. β := λ x, (f x).restrict (x ∈ p) (@H x) @[simp] theorem mem_restrict {f : α →. β} {s : set α} (h : s ⊆ f.dom) (a : α) (b : β) : b ∈ f.restrict h a ↔ a ∈ s ∧ b ∈ f a := by simp [restrict] /-- Turns a function into a partial function with a prescribed domain. -/ def res (f : α → β) (s : set α) : α →. β := (pfun.lift f).restrict s.subset_univ theorem mem_res (f : α → β) (s : set α) (a : α) (b : β) : b ∈ res f s a ↔ (a ∈ s ∧ f a = b) := by simp [res, @eq_comm _ b] theorem res_univ (f : α → β) : pfun.res f set.univ = f := rfl theorem dom_iff_graph (f : α →. β) (x : α) : x ∈ f.dom ↔ ∃ y, (x, y) ∈ f.graph := part.dom_iff_mem theorem lift_graph {f : α → β} {a b} : (a, b) ∈ (f : α →. β).graph ↔ f a = b := show (∃ (h : true), f a = b) ↔ f a = b, by simp /-- The monad `pure` function, the total constant `x` function -/ protected def pure (x : β) : α →. β := λ _, part.some x /-- The monad `bind` function, pointwise `part.bind` -/ def bind (f : α →. β) (g : β → α →. γ) : α →. γ := λ a, (f a).bind (λ b, g b a) @[simp] lemma bind_apply (f : α →. β) (g : β → α →. γ) (a : α) : f.bind g a = (f a).bind (λ b, g b a) := rfl /-- The monad `map` function, pointwise `part.map` -/ def map (f : β → γ) (g : α →. β) : α →. γ := λ a, (g a).map f instance : monad (pfun α) := { pure := @pfun.pure _, bind := @pfun.bind _, map := @pfun.map _ } instance : is_lawful_monad (pfun α) := { bind_pure_comp_eq_map := λ β γ f x, funext $ λ a, part.bind_some_eq_map _ _, id_map := λ β f, by funext a; dsimp [functor.map, pfun.map]; cases f a; refl, pure_bind := λ β γ x f, funext $ λ a, part.bind_some.{u_1 u_2} _ (f x), bind_assoc := λ β γ δ f g k, funext $ λ a, (f a).bind_assoc (λ b, g b a) (λ b, k b a) } theorem pure_defined (p : set α) (x : β) : p ⊆ (@pfun.pure α _ x).dom := p.subset_univ theorem bind_defined {α β γ} (p : set α) {f : α →. β} {g : β → α →. γ} (H1 : p ⊆ f.dom) (H2 : ∀ x, p ⊆ (g x).dom) : p ⊆ (f >>= g).dom := λ a ha, (⟨H1 ha, H2 _ ha⟩ : (f >>= g).dom a) /-- First return map. Transforms a partial function `f : α →. β ⊕ α` into the partial function `α →. β` which sends `a : α` to the first value in `β` it hits by iterating `f`, if such a value exists. By abusing notation to illustrate, either `f a` is in the `β` part of `β ⊕ α` (in which case `f.fix a` returns `f a`), or it is undefined (in which case `f.fix a` is undefined as well), or it is in the `α` part of `β ⊕ α` (in which case we repeat the procedure, so `f.fix a` will return `f.fix (f a)`). -/ def fix (f : α →. β ⊕ α) : α →. β := λ a, part.assert (acc (λ x y, sum.inr x ∈ f y) a) $ λ h, @well_founded.fix_F _ (λ x y, sum.inr x ∈ f y) _ (λ a IH, part.assert (f a).dom $ λ hf, by cases e : (f a).get hf with b a'; [exact part.some b, exact IH _ ⟨hf, e⟩]) a h theorem dom_of_mem_fix {f : α →. β ⊕ α} {a : α} {b : β} (h : b ∈ f.fix a) : (f a).dom := let ⟨h₁, h₂⟩ := part.mem_assert_iff.1 h in by rw well_founded.fix_F_eq at h₂; exact h₂.fst.fst theorem mem_fix_iff {f : α →. β ⊕ α} {a : α} {b : β} : b ∈ f.fix a ↔ sum.inl b ∈ f a ∨ ∃ a', sum.inr a' ∈ f a ∧ b ∈ f.fix a' := ⟨λ h, let ⟨h₁, h₂⟩ := part.mem_assert_iff.1 h in begin rw well_founded.fix_F_eq at h₂, simp at h₂, cases h₂ with h₂ h₃, cases e : (f a).get h₂ with b' a'; simp [e] at h₃, { subst b', refine or.inl ⟨h₂, e⟩ }, { exact or.inr ⟨a', ⟨_, e⟩, part.mem_assert _ h₃⟩ } end, λ h, begin simp [fix], rcases h with ⟨h₁, h₂⟩ | ⟨a', h, h₃⟩, { refine ⟨⟨_, λ y h', _⟩, _⟩, { injection part.mem_unique ⟨h₁, h₂⟩ h' }, { rw well_founded.fix_F_eq, simp [h₁, h₂] } }, { simp [fix] at h₃, cases h₃ with h₃ h₄, refine ⟨⟨_, λ y h', _⟩, _⟩, { injection part.mem_unique h h' with e, exact e ▸ h₃ }, { cases h with h₁ h₂, rw well_founded.fix_F_eq, simp [h₁, h₂, h₄] } } end⟩ /-- If advancing one step from `a` leads to `b : β`, then `f.fix a = b` -/ theorem fix_stop {f : α →. β ⊕ α} {b : β} {a : α} (hb : sum.inl b ∈ f a) : b ∈ f.fix a := by { rw [pfun.mem_fix_iff], exact or.inl hb, } /-- If advancing one step from `a` on `f` leads to `a' : α`, then `f.fix a = f.fix a'` -/ theorem fix_fwd_eq {f : α →. β ⊕ α} {a a' : α} (ha' : sum.inr a' ∈ f a) : f.fix a = f.fix a' := begin ext b, split, { intro h, obtain h' | ⟨a, h', e'⟩ := mem_fix_iff.1 h; cases part.mem_unique ha' h', exact e', }, { intro h, rw pfun.mem_fix_iff, right, use a', exact ⟨ha', h⟩, } end theorem fix_fwd {f : α →. β ⊕ α} {b : β} {a a' : α} (hb : b ∈ f.fix a) (ha' : sum.inr a' ∈ f a) : b ∈ f.fix a' := by rwa [← fix_fwd_eq ha'] /-- A recursion principle for `pfun.fix`. -/ @[elab_as_eliminator] def fix_induction {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a) (H : ∀ a', b ∈ f.fix a' → (∀ a'', sum.inr a'' ∈ f a' → C a'') → C a') : C a := begin have h₂ := (part.mem_assert_iff.1 h).snd, generalize_proofs h₁ at h₂, clear h, induction h₁ with a ha IH, have h : b ∈ f.fix a := part.mem_assert_iff.2 ⟨⟨a, ha⟩, h₂⟩, exact H a h (λ a' fa', IH a' fa' ((part.mem_assert_iff.1 (fix_fwd h fa')).snd)), end lemma fix_induction_spec {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a) (H : ∀ a', b ∈ f.fix a' → (∀ a'', sum.inr a'' ∈ f a' → C a'') → C a') : @fix_induction _ _ C _ _ _ h H = H a h (λ a' h', fix_induction (fix_fwd h h') H) := by { unfold fix_induction, generalize_proofs ha, induction ha, refl, } /-- Another induction lemma for `b ∈ f.fix a` which allows one to prove a predicate `P` holds for `a` given that `f a` inherits `P` from `a` and `P` holds for preimages of `b`. -/ @[elab_as_eliminator] def fix_induction' {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a) (hbase : ∀ a_final : α, sum.inl b ∈ f a_final → C a_final) (hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) : C a := begin refine fix_induction h (λ a' h ih, _), cases e : (f a').get (dom_of_mem_fix h) with b' a''; replace e : _ ∈ f a' := ⟨_, e⟩, { apply hbase, convert e, exact part.mem_unique h (fix_stop e), }, { exact hind _ _ (fix_fwd h e) e (ih _ e), }, end lemma fix_induction'_stop {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a : α} (h : b ∈ f.fix a) (fa : sum.inl b ∈ f a) (hbase : ∀ a_final : α, sum.inl b ∈ f a_final → C a_final) (hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) : @fix_induction' _ _ C _ _ _ h hbase hind = hbase a fa := by { unfold fix_induction', rw [fix_induction_spec], simp [part.get_eq_of_mem fa], } lemma fix_induction'_fwd {C : α → Sort*} {f : α →. β ⊕ α} {b : β} {a a' : α} (h : b ∈ f.fix a) (h' : b ∈ f.fix a') (fa : sum.inr a' ∈ f a) (hbase : ∀ a_final : α, sum.inl b ∈ f a_final → C a_final) (hind : ∀ a₀ a₁ : α, b ∈ f.fix a₁ → sum.inr a₁ ∈ f a₀ → C a₁ → C a₀) : @fix_induction' _ _ C _ _ _ h hbase hind = hind a a' h' fa (fix_induction' h' hbase hind) := by { unfold fix_induction', rw [fix_induction_spec], simpa [part.get_eq_of_mem fa], } variables (f : α →. β) /-- Image of a set under a partial function. -/ def image (s : set α) : set β := f.graph'.image s lemma image_def (s : set α) : f.image s = {y | ∃ x ∈ s, y ∈ f x} := rfl lemma mem_image (y : β) (s : set α) : y ∈ f.image s ↔ ∃ x ∈ s, y ∈ f x := iff.rfl lemma image_mono {s t : set α} (h : s ⊆ t) : f.image s ⊆ f.image t := rel.image_mono _ h lemma image_inter (s t : set α) : f.image (s ∩ t) ⊆ f.image s ∩ f.image t := rel.image_inter _ s t lemma image_union (s t : set α) : f.image (s ∪ t) = f.image s ∪ f.image t := rel.image_union _ s t /-- Preimage of a set under a partial function. -/ def preimage (s : set β) : set α := rel.image (λ x y, x ∈ f y) s lemma preimage_def (s : set β) : f.preimage s = {x | ∃ y ∈ s, y ∈ f x} := rfl @[simp] lemma mem_preimage (s : set β) (x : α) : x ∈ f.preimage s ↔ ∃ y ∈ s, y ∈ f x := iff.rfl lemma preimage_subset_dom (s : set β) : f.preimage s ⊆ f.dom := λ x ⟨y, ys, fxy⟩, part.dom_iff_mem.mpr ⟨y, fxy⟩ lemma preimage_mono {s t : set β} (h : s ⊆ t) : f.preimage s ⊆ f.preimage t := rel.preimage_mono _ h lemma preimage_inter (s t : set β) : f.preimage (s ∩ t) ⊆ f.preimage s ∩ f.preimage t := rel.preimage_inter _ s t lemma preimage_union (s t : set β) : f.preimage (s ∪ t) = f.preimage s ∪ f.preimage t := rel.preimage_union _ s t lemma preimage_univ : f.preimage set.univ = f.dom := by ext; simp [mem_preimage, mem_dom] lemma coe_preimage (f : α → β) (s : set β) : (f : α →. β).preimage s = f ⁻¹' s := by ext; simp /-- Core of a set `s : set β` with respect to a partial function `f : α →. β`. Set of all `a : α` such that `f a ∈ s`, if `f a` is defined. -/ def core (s : set β) : set α := f.graph'.core s lemma core_def (s : set β) : f.core s = {x | ∀ y, y ∈ f x → y ∈ s} := rfl @[simp] lemma mem_core (x : α) (s : set β) : x ∈ f.core s ↔ ∀ y, y ∈ f x → y ∈ s := iff.rfl lemma compl_dom_subset_core (s : set β) : f.domᶜ ⊆ f.core s := λ x hx y fxy, absurd ((mem_dom f x).mpr ⟨y, fxy⟩) hx lemma core_mono {s t : set β} (h : s ⊆ t) : f.core s ⊆ f.core t := rel.core_mono _ h lemma core_inter (s t : set β) : f.core (s ∩ t) = f.core s ∩ f.core t := rel.core_inter _ s t lemma mem_core_res (f : α → β) (s : set α) (t : set β) (x : α) : x ∈ (res f s).core t ↔ x ∈ s → f x ∈ t := by simp [mem_core, mem_res] section open_locale classical lemma core_res (f : α → β) (s : set α) (t : set β) : (res f s).core t = sᶜ ∪ f ⁻¹' t := by { ext, rw mem_core_res, by_cases h : x ∈ s; simp [h] } end lemma core_restrict (f : α → β) (s : set β) : (f : α →. β).core s = s.preimage f := by ext x; simp [core_def] lemma preimage_subset_core (f : α →. β) (s : set β) : f.preimage s ⊆ f.core s := λ x ⟨y, ys, fxy⟩ y' fxy', have y = y', from part.mem_unique fxy fxy', this ▸ ys lemma preimage_eq (f : α →. β) (s : set β) : f.preimage s = f.core s ∩ f.dom := set.eq_of_subset_of_subset (set.subset_inter (f.preimage_subset_core s) (f.preimage_subset_dom s)) (λ x ⟨xcore, xdom⟩, let y := (f x).get xdom in have ys : y ∈ s, from xcore _ (part.get_mem _), show x ∈ f.preimage s, from ⟨(f x).get xdom, ys, part.get_mem _⟩) lemma core_eq (f : α →. β) (s : set β) : f.core s = f.preimage s ∪ f.domᶜ := by rw [preimage_eq, set.union_distrib_right, set.union_comm (dom f), set.compl_union_self, set.inter_univ, set.union_eq_self_of_subset_right (f.compl_dom_subset_core s)] lemma preimage_as_subtype (f : α →. β) (s : set β) : f.as_subtype ⁻¹' s = subtype.val ⁻¹' f.preimage s := begin ext x, simp only [set.mem_preimage, set.mem_set_of_eq, pfun.as_subtype, pfun.mem_preimage], show f.fn (x.val) _ ∈ s ↔ ∃ y ∈ s, y ∈ f (x.val), exact iff.intro (λ h, ⟨_, h, part.get_mem _⟩) (λ ⟨y, ys, fxy⟩, have f.fn x.val x.property ∈ f x.val := part.get_mem _, part.mem_unique fxy this ▸ ys) end /-- Turns a function into a partial function to a subtype. -/ def to_subtype (p : β → Prop) (f : α → β) : α →. subtype p := λ a, ⟨p (f a), subtype.mk _⟩ @[simp] lemma dom_to_subtype (p : β → Prop) (f : α → β) : (to_subtype p f).dom = {a | p (f a)} := rfl @[simp] lemma to_subtype_apply (p : β → Prop) (f : α → β) (a : α) : to_subtype p f a = ⟨p (f a), subtype.mk _⟩ := rfl lemma dom_to_subtype_apply_iff {p : β → Prop} {f : α → β} {a : α} : (to_subtype p f a).dom ↔ p (f a) := iff.rfl lemma mem_to_subtype_iff {p : β → Prop} {f : α → β} {a : α} {b : subtype p} : b ∈ to_subtype p f a ↔ ↑b = f a := by rw [to_subtype_apply, part.mem_mk_iff, exists_subtype_mk_eq_iff, eq_comm] /-- The identity as a partial function -/ protected def id (α : Type*) : α →. α := part.some @[simp] lemma coe_id (α : Type*) : ((id : α → α) : α →. α) = pfun.id α := rfl @[simp] lemma id_apply (a : α) : pfun.id α a = part.some a := rfl /-- Composition of partial functions as a partial function. -/ def comp (f : β →. γ) (g : α →. β) : α →. γ := λ a, (g a).bind f @[simp] lemma comp_apply (f : β →. γ) (g : α →. β) (a : α) : f.comp g a = (g a).bind f := rfl @[simp] lemma id_comp (f : α →. β) : (pfun.id β).comp f = f := ext $ λ _ _, by simp @[simp] lemma comp_id (f : α →. β) : f.comp (pfun.id α) = f := ext $ λ _ _, by simp @[simp] lemma dom_comp (f : β →. γ) (g : α →. β) : (f.comp g).dom = g.preimage f.dom := begin ext, simp_rw [mem_preimage, mem_dom, comp_apply, part.mem_bind_iff, exists_prop, ←exists_and_distrib_right], rw exists_comm, simp_rw and.comm, end @[simp] lemma preimage_comp (f : β →. γ) (g : α →. β) (s :set γ) : (f.comp g).preimage s = g.preimage (f.preimage s) := begin ext, simp_rw [mem_preimage, comp_apply, part.mem_bind_iff, exists_prop, ←exists_and_distrib_right, ←exists_and_distrib_left], rw exists_comm, simp_rw [and_assoc, and.comm], end @[simp] lemma _root_.part.bind_comp (f : β →. γ) (g : α →. β) (a : part α) : a.bind (f.comp g) = (a.bind g).bind f := begin ext c, simp_rw [part.mem_bind_iff, comp_apply, part.mem_bind_iff, exists_prop, ←exists_and_distrib_right, ←exists_and_distrib_left], rw exists_comm, simp_rw and_assoc, end @[simp] lemma comp_assoc (f : γ →. δ) (g : β →. γ) (h : α →. β) : (f.comp g).comp h = f.comp (g.comp h) := ext $ λ _ _, by simp only [comp_apply, part.bind_comp] -- This can't be `simp` lemma coe_comp (g : β → γ) (f : α → β) : ((g ∘ f : α → γ) : α →. γ) = (g : β →. γ).comp f := ext $ λ _ _, by simp only [coe_val, comp_apply, part.bind_some] /-- Product of partial functions. -/ def prod_lift (f : α →. β) (g : α →. γ) : α →. β × γ := λ x, ⟨(f x).dom ∧ (g x).dom, λ h, ((f x).get h.1, (g x).get h.2)⟩ @[simp] lemma dom_prod_lift (f : α →. β) (g : α →. γ) : (f.prod_lift g).dom = {x | (f x).dom ∧ (g x).dom} := rfl lemma get_prod_lift (f : α →. β) (g : α →. γ) (x : α) (h) : (f.prod_lift g x).get h = ((f x).get h.1, (g x).get h.2) := rfl @[simp] lemma prod_lift_apply (f : α →. β) (g : α →. γ) (x : α) : f.prod_lift g x = ⟨(f x).dom ∧ (g x).dom, λ h, ((f x).get h.1, (g x).get h.2)⟩ := rfl lemma mem_prod_lift {f : α →. β} {g : α →. γ} {x : α} {y : β × γ} : y ∈ f.prod_lift g x ↔ y.1 ∈ f x ∧ y.2 ∈ g x := begin transitivity ∃ hp hq, (f x).get hp = y.1 ∧ (g x).get hq = y.2, { simp only [prod_lift, part.mem_mk_iff, and.exists, prod.ext_iff] }, { simpa only [exists_and_distrib_left, exists_and_distrib_right] } end /-- Product of partial functions. -/ def prod_map (f : α →. γ) (g : β →. δ) : α × β →. γ × δ := λ x, ⟨(f x.1).dom ∧ (g x.2).dom, λ h, ((f x.1).get h.1, (g x.2).get h.2)⟩ @[simp] lemma dom_prod_map (f : α →. γ) (g : β →. δ) : (f.prod_map g).dom = {x | (f x.1).dom ∧ (g x.2).dom} := rfl lemma get_prod_map (f : α →. γ) (g : β →. δ) (x : α × β) (h) : (f.prod_map g x).get h = ((f x.1).get h.1, (g x.2).get h.2) := rfl @[simp] lemma prod_map_apply (f : α →. γ) (g : β →. δ) (x : α × β) : f.prod_map g x = ⟨(f x.1).dom ∧ (g x.2).dom, λ h, ((f x.1).get h.1, (g x.2).get h.2)⟩ := rfl lemma mem_prod_map {f : α →. γ} {g : β →. δ} {x : α × β} {y : γ × δ} : y ∈ f.prod_map g x ↔ y.1 ∈ f x.1 ∧ y.2 ∈ g x.2 := begin transitivity ∃ hp hq, (f x.1).get hp = y.1 ∧ (g x.2).get hq = y.2, { simp only [prod_map, part.mem_mk_iff, and.exists, prod.ext_iff] }, { simpa only [exists_and_distrib_left, exists_and_distrib_right] } end @[simp] lemma prod_lift_fst_comp_snd_comp (f : α →. γ) (g : β →. δ) : prod_lift (f.comp ((prod.fst : α × β → α) : α × β →. α)) (g.comp ((prod.snd : α × β → β) : α × β →. β)) = prod_map f g := ext $ λ a, by simp @[simp] lemma prod_map_id_id : (pfun.id α).prod_map (pfun.id β) = pfun.id _ := ext $ λ _ _, by simp [eq_comm] @[simp] lemma prod_map_comp_comp (f₁ : α →. β) (f₂ : β →. γ) (g₁ : δ →. ε) (g₂ : ε →. ι) : (f₂.comp f₁).prod_map (g₂.comp g₁) = (f₂.prod_map g₂).comp (f₁.prod_map g₁) := ext $ λ _ _, by tidy end pfun
66aaa6c8ef0a3bd32826050eace22d907c68cb91
98000ddc36f1ec26addea0df1853c69fa0e71d67
/nat_seq.lean
a0eb7115db77d577915edc57940769bb315964ae
[]
no_license
SCRK16/Intuitionism
50b7b5ed780a75c4ff1339c3d36f1133b8acdfe3
a3d9920ae056b39a66e37d1d0e03d246bca1e961
refs/heads/master
1,670,199,869,808
1,598,045,061,000
1,598,045,061,000
254,657,585
1
0
null
1,590,754,909,000
1,586,529,604,000
Lean
UTF-8
Lean
false
false
15,530
lean
/- This file defines natural sequences, here defined as functions ℕ → ℕ Also defined here are the comparisons =, ≠, <, ≤ and # -/ import data.nat.basic def nat_seq := ℕ → ℕ notation `𝒩` := nat_seq namespace nat_seq def zero : 𝒩 := λ n, 0 def eq (a b : 𝒩) : Prop := ∀ n : ℕ, a n = b n infix `='`:50 := eq lemma eq_iff {a b : 𝒩} : a = b ↔ a =' b := function.funext_iff def ne (a b : 𝒩) : Prop := ¬ a =' b infix `≠'`:50 := ne def lt (a b : 𝒩) : Prop := ∃ n : ℕ, (∀ i : ℕ, i < n → a i = b i) ∧ a n < b n infix `<` := lt def le (a b : 𝒩) : Prop := ∀ n : ℕ, (∀ i : ℕ, i < n → a i = b i) → a n ≤ b n infix `≤` := le theorem le_of_eq (a b : 𝒩) (h : a =' b) : a ≤ b := begin intro n, intro hn, rw h, end lemma imp_eq_iff_imp_eq (a b : 𝒩) (n: ℕ) : (∀ i : ℕ, i < n → a i = b i) ↔ (∀ i : ℕ, i < n → b i = a i) := begin split, repeat {intro h, intro i, intro hi, symmetry, exact h i hi}, end lemma imp_eq_trans (a b c : 𝒩) (n : ℕ) (h₁ : ∀ i : ℕ, i < n → a i = b i) (h₂ : ∀ i : ℕ, i < n → b i = c i) : ∀ i : ℕ, i < n → a i = c i := begin intro i, intro hi, have aibi := h₁ i hi, rw aibi, exact h₂ i hi, end @[trans] theorem eq_trans (a b c : 𝒩) : a =' b → b =' c → a =' c := begin intros ab bc n, rw ab n, exact bc n, end @[symm] theorem eq_symm {a b: 𝒩} : a =' b ↔ b =' a := begin split, repeat {intros h n, symmetry, exact h n}, end @[refl] theorem eq_refl {a : 𝒩} : a =' a := begin intro n, refl, end @[symm] theorem ne_symm (a b : 𝒩) : a ≠' b ↔ b ≠' a := begin repeat {rw ne}, rw eq_symm, end lemma lt_eq_lt_le (a b : 𝒩) (n m : ℕ) (h1 : ∀ i : ℕ, i < n → a i = b i) (h2 : a m < b m) : n ≤ m := begin cases le_or_gt n m with nlem ngtm, {-- case: n ≤ m exact nlem, }, {-- case: m < n exfalso, rw gt_iff_lt at ngtm, have aibi := h1 m ngtm, rw eq_iff_le_not_lt at aibi, exact (and.elim_right aibi) h2, } end lemma lt_eq_ne_le (a b : 𝒩) (n m : ℕ) (h1 : ∀ i : ℕ, i < n → a i = b i) (h2 : a m ≠ b m) : n ≤ m := begin rw ne_iff_lt_or_gt at h2, cases h2 with hlt hgt, {-- case: a m < b m exact lt_eq_lt_le a b n m h1 hlt, }, { rw gt_iff_lt at hgt, rw imp_eq_iff_imp_eq at h1, exact lt_eq_lt_le b a n m h1 hgt, } end --The following lemma immediately follows from lt_eq_ne_le and n = m ↔ (n ≤ m ∨ m ≤ n) --We will use this in reckless.lean to prove weak_LEM_implies_LLPO lemma first_zero_eq (a : 𝒩) (n m : ℕ) (hn1 : ∀ i : ℕ, i < n → a i = 0) (hn2 : a n ≠ 0) (hm1 : ∀ i : ℕ, i < m → a i = 0) (hm2 : a m ≠ 0) : n = m := begin rw eq_iff_le_not_lt, split, {-- need to prove: n ≤ m apply lt_eq_ne_le a zero n m hn1 hm2, }, {-- need to prove: ¬n < m apply not_lt_of_le, apply lt_eq_ne_le a zero m n hm1 hn2, } end theorem le_of_lt (a b : 𝒩) (less: a < b) : a ≤ b := begin rw le, rw lt at less, intro n, intro h, cases less with d hd, cases hd with p q, have hnd := lt_eq_lt_le a b n d h q, rw le_iff_eq_or_lt at hnd, cases hnd with ndeq ndlt, { --case n = d rw ← ndeq at q, exact nat.le_of_lt q, }, { --case n < d apply nat.le_of_eq, apply p, exact ndlt, } end @[trans] theorem lt_trans (a b c : 𝒩) : a < b → b < c → a < c := begin intros hab hbc, cases hab with n hn, cases hbc with m hm, cases hn with p₁ p₂, cases hm with q₁ q₂, use min n m, split, {--need to prove: ∀ (i : ℕ), i < min n m → a i = c i intros i hi, rw lt_min_iff at hi, rw p₁ i hi.elim_left, exact q₁ i hi.elim_right, }, {--need to prove: a (min n m) < c (min n m) cases nat.lt_trichotomy n m with nltm h, {-- n < m rw min_eq_left (nat.le_of_lt nltm), rw ← q₁ n nltm, exact p₂, }, { cases h with neqm mltn, {-- n = m rw neqm at *, rw min_self, exact nat.lt_trans p₂ q₂, }, {-- m < n rw min_eq_right (nat.le_of_lt mltn), rw p₁ m mltn, exact q₂, } } } end -- Doing a finite amount of comparisons is allowed lemma all_eq_or_exists_neq (a b : 𝒩) (n : ℕ): (∀ i : ℕ, i < n → a i = b i) ∨ (∃ i : ℕ, i < n ∧ (∀ j : ℕ, j < i → a j = b j) ∧ a i ≠ b i) := begin induction n with d hd, {-- case: n = 0 left, intro i, intro hi, exfalso, rw ← not_le at hi, exact hi (zero_le i), }, {-- case: succ(n) cases hd with all_eq exists_neq, {-- hypothesis: ∀ i < d, a i = b i have tri := lt_trichotomy (a d) (b d), rw or_comm at tri, rw or_assoc at tri, cases tri with aeqb anb, {-- case: a d = b d left, intro i, intro hi, rw nat.lt_succ_iff_lt_or_eq at hi, cases hi with iltd ieqd, exact all_eq i iltd, rw ieqd, exact aeqb, }, {-- case: a d ≠ b d right, use d, split, exact nat.lt_succ_self d, split, exact all_eq, rwa [ne_iff_lt_or_gt, or.comm, gt_iff_lt], } }, {-- hypothesis: ∃ i < d, (∀ j < i, a j = b j) ∧ a i ≠ b i right, cases exists_neq with i hi, use i, split, exact nat.lt_succ_of_lt (and.elim_left hi), exact and.elim_right hi, } } end lemma nat_lt_cotrans (a b : ℕ) (h : a < b) : ∀ c : ℕ, a < c ∨ c < b := begin intro c, induction c with d hd, {-- case: c = d = 0 right, -- need to prove: 0 < b have ha := nat.eq_zero_or_pos a, cases ha with hal har, rw hal at h, exact h, rw gt_iff_lt at har, exact nat.lt_trans har h, }, {-- case: c = succ(d) cases hd with ad db, {-- case: a < d left, exact nat.lt_trans ad (nat.lt_succ_self d), }, {-- case d < b cases db with i hi, {-- b = nat.succ d left, exact h, }, {-- b > nat.succ d right, rw nat.lt_succ_iff_lt_or_eq, rw or.comm, rw ← le_iff_eq_or_lt, exact hi, } } } end theorem lt_cotrans (a b : 𝒩) (h : a < b) : ∀ c : 𝒩, a < c ∨ c < b := begin intro c, rw lt at h, cases h with n hn, cases hn with hnl hnr, cases all_eq_or_exists_neq a c n with all_eq exists_neq, {-- hypothesis all_eq: ∀ i < n, a i = c i have hlt := nat_lt_cotrans (a n) (b n) hnr, have ltcn := hlt (c n), cases ltcn with ancn cnbn, {-- hypothesis ancn: a n < c n left, -- need to prove: a < c rw lt, use n, exact and.intro all_eq ancn, }, {-- hypothesis cnbn: c n < b n right, -- need to prove: c < b rw lt, use n, split, {-- need to prove: ∀ i < n, c i = b i rw imp_eq_iff_imp_eq a c n at all_eq, exact imp_eq_trans c a b n all_eq hnl, }, {-- need to prove: c n < b n exact cnbn, } } }, {-- hypothesis exists_neq: ∃ i < n, a i ≠ c i cases exists_neq with i hi, cases hi with hil hi2, cases hi2 with him hir, rw ne_iff_lt_or_gt at hir, cases hir with ailtci aigtci, {-- hypothesis ailtci: a i < c i left, -- need to prove: a < c rw lt, use i, split, exact him, exact ailtci, }, {-- hypothesis aigtci: i > c i rw gt_iff_lt at aigtci, right, -- need to prove: c < b rw lt, use i, split, {-- need to prove: ∀ j < i, c j = b j intro j, intro hj, rw ← him j hj, have jltn := nat.lt_trans hj hil, exact hnl j jltn, }, {-- need to prove: c i < b i rw hnl i hil at aigtci, exact aigtci, } } } end theorem le_iff_not_lt (a b : 𝒩) : a ≤ b ↔ ¬ b < a := begin split, {-- need to prove: a ≤ b → ¬ b < a intro h, intro ex, cases ex with n hn, have g := h n, cases hn with ind blta, rw imp_eq_iff_imp_eq b a n at ind, have aleb := g ind, rw nat.lt_iff_le_not_le at blta, exact and.elim_right blta aleb, }, {-- need to prove: ¬ b < a → a ≤ b intros h n hi, cases le_or_gt (a n) (b n) with hle hgt, exact hle, -- case: a ≤ b exfalso, -- case: b < a rw gt_iff_lt at hgt, apply h, use n, split, {-- need to prove: ∀ i < n, b i = a i rw imp_eq_iff_imp_eq b a n, exact hi, }, -- need to prove: b n < a n exact hgt, } end -- The following theorem now easily follows from le_iff_not_lt and lt_cotrans theorem le_trans (a b c : 𝒩) : a ≤ b → b ≤ c → a ≤ c := begin intro h₁, intro h₂, rw le_iff_not_lt at *, intro h₃, have ltorlt := lt_cotrans c a h₃ b, cases ltorlt with cb ba, exact h₂ cb, exact h₁ ba, end theorem le_stable (a b : 𝒩) : ¬¬a ≤ b → a ≤ b := begin rw le_iff_not_lt, exact not_of_not_not_not, end theorem eq_of_le_le {a b : 𝒩} (hab : a ≤ b) (hba : b ≤ a) : a =' b := begin intro n, apply nat.strong_induction_on n, intros d hd, rw le at *, have hle := hab d hd, have hge : b d ≤ a d, by { apply hba, intros i hi, symmetry, exact hd i hi, }, exact le_antisymm hle hge, end def apart (a b : 𝒩) : Prop := ∃ n, a n ≠ b n infix `#` := apart -- If two natural sequences are apart from eachother, they are not equal theorem ne_of_apart (a b : 𝒩) : a # b → a ≠' b := begin intros r h, cases r with n hn, apply hn, apply h, end theorem eq_iff_not_apart (a b : 𝒩) : a =' b ↔ ¬ a # b := begin split, {-- a = b → ¬ a # b intro h, intro g, cases g with n hn, exact hn (h n), }, {-- ¬ a # b → a = b intro h, intro n, rwa [apart, not_exists] at h, have g := h n, rwa [ne_iff_lt_or_gt, not_or_distrib] at g, cases lt_trichotomy (a n) (b n) with l r, {-- case: a n < b n, can't happen because ¬ a n < b n exfalso, exact (and.elim_left g) l, }, cases r with rl rr, {-- case: a n = b n, trivial exact rl, }, {-- case: b n < a n, can't happen because ¬ a n > b n exfalso, exact (and.elim_right g) rr, } } end theorem eq_stable (a b : 𝒩) : ¬¬ a =' b → a =' b := begin rw eq_iff_not_apart, exact not_of_not_not_not, end theorem apart_iff_lt_or_lt (a b : 𝒩) : a # b ↔ a < b ∨ b < a := begin split, {-- need to prove: a # b → a < b ∨ b < a intro ab, cases ab with n hn, have h := all_eq_or_exists_neq a b n, cases h with all_eq exists_neq, {-- case: ∀ i < n → a i = b i rw ne_iff_lt_or_gt at hn, cases hn with ab ba, {-- case: a n < b n left, use n, exact and.intro all_eq ab, }, {-- case: a n > b n right, use n, rw gt_iff_lt at ba, split, rw imp_eq_iff_imp_eq b a n, exact all_eq, exact ba, } }, {-- case: ∃ i < n, (∀ j < i, a j = b j) ∧ a i ≠ b i cases exists_neq with i hi, cases hi with iltn r, cases r with ajbj aineqbi, rw ne_iff_lt_or_gt at aineqbi, cases aineqbi with aibi biai, {-- case: a i < b i left, use i, exact and.intro ajbj aibi, }, {-- case: b i < a i right, use i, split, rw imp_eq_iff_imp_eq b a i, exact ajbj, rw gt_iff_lt at biai, exact biai, } } }, {-- need to prove: a < b ∨ b < a → a # b intro aborba, cases aborba with ab ba, {-- case: a < b cases ab with n hn, use n, rw ne_iff_lt_or_gt, left, exact and.elim_right hn, }, {-- case: b < a cases ba with n hn, use n, rw ne_iff_lt_or_gt, right, exact and.elim_right hn, } } end -- The following theorem now easily follows from combining lt_cotrans and apart_iff_lt_or_lt theorem apart_cotrans (a b : 𝒩) (h : a # b) : ∀ c : 𝒩, a # c ∨ c # b := begin intro c, repeat {rw apart_iff_lt_or_lt at *}, cases h with ab ba, {-- case: a < b cases lt_cotrans a b ab c with ac cb, {-- case: a < c left, left, exact ac, }, {-- case: c < b right, left, exact cb, } }, {-- case: b < a cases lt_cotrans b a ba c with bc ca, {-- case: b < c right, right, exact bc, }, {-- case: c < a left, right, exact ca, } } end @[symm] theorem apart_symm (a b : 𝒩) : a # b ↔ b # a := begin split, repeat { intro h, cases h with n hn, use n, symmetry, exact hn, }, end -- 0 is the smallest sequence lemma zero_le (a : 𝒩) : zero ≤ a := begin intros n h, rw zero, simp, end lemma apart_zero_lt (a : 𝒩) (h : a # zero) : zero < a := begin rw apart_iff_lt_or_lt at h, cases h with alt agt, {-- case: a < 0, impossible exfalso, have h₁ := zero_le a, rw le_iff_not_lt at h₁, exact h₁ alt, }, {-- case: 0 < a, trivial exact agt, } end /- There are uncountably (defined positively) many natural sequences. The proof of this theorem is Cantor's Diagonal argument -/ theorem uncountable (f : ℕ → 𝒩) : ∃ a : 𝒩, ∀ n : ℕ, a # (f n) := begin use λ n : ℕ, (f n n) + 1, intro n, use n, exact nat.succ_ne_self (f n n), end end nat_seq
6e69d64c0dc3357852d1ed8e45851cee7e595077
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/basic.lean
0f1de17f09fcb80d01841bff6f961bb76d59bff3
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
109,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, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import algebra.big_operators.pi import algebra.module.hom import algebra.module.pi import algebra.module.prod import algebra.module.submodule import algebra.module.submodule_lattice import algebra.group.prod import data.finsupp.basic import data.dfinsupp import algebra.pointwise import order.compactly_generated import order.omega_complete_partial_order /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module`. ## Main definitions * Many constructors for linear maps * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `quotient_inf_equiv_sup_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. * We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is `\.`, not the same as the scalar multiplication `•`/`\bub`. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [semiring R] [add_comm_monoid M] [module R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum @[simp] lemma sum_smul_index_linear_map' {α : Type u} {R : Type v} {M : Type w} {M₂ : Type x} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] {v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} : (c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) := begin rw [finsupp.sum_smul_index', finsupp.smul_sum], { simp only [linear_map.map_smul], }, { intro i, exact (h i).map_zero }, end variable (R) /-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between `α →₀ β` and `α → β`. -/ @[simps apply] noncomputable def linear_equiv_fun_on_fintype {α} [fintype α] [add_comm_monoid M] [semiring R] [module R M] : (α →₀ M) ≃ₗ[R] (α → M) := { to_fun := coe_fn, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl }, .. equiv_fun_on_fintype } end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f g : M →ₗ[R] M₂) include R theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := (f.dom_restrict p).cod_restrict p $ set_like.forall.2 hf lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl @[simp] lemma default_def : default (M →ₗ[R] M₂) = 0 := rfl instance unique_of_left [subsingleton M] : unique (M →ₗ[R] M₂) := { uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero], .. linear_map.inhabited } instance unique_of_right [subsingleton M₂] : unique (M →ₗ[R] M₂) := coe_injective.unique /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp [add_comm, add_left_comm], by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := { zero := 0, add := (+), add_assoc := by intros; ext; simp [add_comm, add_left_comm], zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, nsmul_zero' := λ f, by { ext x, simp }, nsmul_succ' := λ n f, by { ext x, simp [nat.succ_eq_one_add, add_nsmul] } } instance linear_map_apply_is_add_monoid_hom (a : M) : is_add_monoid_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a, map_zero := rfl } lemma add_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (h + g).comp f = h.comp f + g.comp f := rfl lemma comp_add (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (f + g) = h.comp f + h.comp g := by { ext, simp } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm section smul_right variables {S : Type*} [semiring S] [module R S] [module S M] [is_scalar_tower R S M] /-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/ def smul_right (f : M₂ →ₗ[R] S) (x : M) : M₂ →ₗ[R] M := { to_fun := λb, f b • x, map_add' := λ x y, by rw [f.map_add, add_smul], map_smul' := λ b y, by rw [f.map_smul, smul_assoc] } @[simp] theorem coe_smul_right (f : M₂ →ₗ[R] S) (x : M) : (smul_right f x : M₂ → M) = λ c, f c • x := rfl theorem smul_right_apply (f : M₂ →ₗ[R] S) (x : M) (c : M₂) : smul_right f x c = f c • x := rfl end smul_right instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ lemma one_eq_id : (1 : M →ₗ[R] M) = id := rfl lemma mul_eq_comp (f g : M →ₗ[R] M) : f * g = f.comp g := rfl @[simp] lemma one_apply (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_apply (f g : M →ₗ[R] M) (x : M) : (f * g) x = f (g x) := rfl lemma coe_one : ⇑(1 : M →ₗ[R] M) = _root_.id := rfl lemma coe_mul (f g : M →ₗ[R] M) : ⇑(f * g) = f ∘ g := rfl instance [nontrivial M] : nontrivial (module.End R M) := begin obtain ⟨m, ne⟩ := (nontrivial_iff_exists_ne (0 : M)).mp infer_instance, exact nontrivial_of_ne 1 0 (λ p, ne (linear_map.congr_fun p m)), end @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩ }; intros; try { refl }; apply linear_map.ext; simp {proj := ff} @[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) : (f^n) m = (f^[n] m) := begin induction n with n ih, { refl, }, { simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih], exact (function.commute.iterate_self _ _ m).symm, }, end lemma pow_map_zero_of_le {f : module.End R M} {m : M} {k l : ℕ} (hk : k ≤ l) (hm : (f^k) m = 0) : (f^l) m = 0 := by rw [← nat.sub_add_cancel hk, pow_add, mul_apply, hm, map_zero] lemma commute_pow_left_of_commute {f : M →ₗ[R] M₂} {g : module.End R M} {g₂ : module.End R M₂} (h : g₂.comp f = f.comp g) (k : ℕ) : (g₂^k).comp f = f.comp (g^k) := begin induction k with k ih, { simpa only [pow_zero], }, { rw [pow_succ, pow_succ, linear_map.mul_eq_comp, linear_map.comp_assoc, ih, ← linear_map.comp_assoc, h, linear_map.comp_assoc, linear_map.mul_eq_comp], }, end lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) := by { ext m, apply pow_apply, } @[simp] lemma id_pow (n : ℕ) : (id : M →ₗ[R] M)^n = id := one_pow n section variables {f' : M →ₗ[R] M} lemma iterate_succ (n : ℕ) : (f' ^ (n + 1)) = comp (f' ^ n) f' := by rw [pow_succ', mul_eq_comp] lemma iterate_surjective (h : surjective f') : ∀ n : ℕ, surjective ⇑(f' ^ n) | 0 := surjective_id | (n + 1) := by { rw [iterate_succ], exact surjective.comp (iterate_surjective n) h, } lemma iterate_injective (h : injective f') : ∀ n : ℕ, injective ⇑(f' ^ n) | 0 := injective_id | (n + 1) := by { rw [iterate_succ], exact injective.comp (iterate_injective n) h, } lemma iterate_bijective (h : bijective f') : ∀ n : ℕ, bijective ⇑(f' ^ n) | 0 := bijective_id | (n + 1) := by { rw [iterate_succ], exact bijective.comp (iterate_bijective n) h, } lemma injective_of_iterate_injective {n : ℕ} (hn : n ≠ 0) (h : injective ⇑(f' ^ n)) : injective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), iterate_succ, coe_comp] at h, exact injective.of_comp h, end end section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] (f g : M →ₗ[R] M₂) /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp [add_comm], by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl @[simp] lemma comp_neg (g : M₂ →ₗ[R] M₃) : g.comp (- f) = - g.comp f := by { ext, simp } /-- The negation of a linear map is linear. -/ instance : has_sub (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b - g b, by { simp only [map_add, sub_eq_add_neg, neg_add], cc }, by { intros, simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl lemma sub_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (g - f) = h.comp g - h.comp f := by { ext, simp } /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, add_left_neg := _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, gsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. linear_map.add_comm_monoid }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } end add_comm_group section has_scalar variables {S : Type*} [semiring R] [monoid S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [distrib_mul_action S M₂] [smul_comm_class R S M₂] (f : M →ₗ[R] M₂) instance : has_scalar S (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, λ x y, by rw [f.map_add, smul_add], λ c x, by simp only [f.map_smul, smul_comm c]⟩⟩ @[simp] lemma smul_apply (a : S) (x : M) : (a • f) x = a • f x := rfl instance {T : Type*} [monoid T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [smul_comm_class S T M₂] : smul_comm_class S T (M →ₗ[R] M₂) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ -- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and -- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible. instance {T : Type*} [monoid T] [has_scalar S T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [is_scalar_tower S T M₂] : is_scalar_tower S T (M →ₗ[R] M₂) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance : distrib_mul_action S (M →ₗ[R] M₂) := { one_smul := λ f, ext $ λ _, one_smul _ _, mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _, smul_add := λ c f g, ext $ λ x, smul_add _ _ _, smul_zero := λ c, ext $ λ x, smul_zero _ } theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) := rfl end has_scalar section module variables {S : Type*} [semiring R] [semiring S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] (f : M →ₗ[R] M₂) instance : module S (M →ₗ[R] M₂) := { add_smul := λ a b f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variable (S) /-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`. See `linear_map.applyₗ` for a version where `S = R`. -/ @[simps] def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ := { to_fun := λ v, { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v }, map_zero' := linear_map.ext $ λ f, f.map_zero, map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ } section variables (R M) /-- The equivalence between R-linear maps from `R` to `M`, and points of `M` itself. This says that the forgetful functor from `R`-modules to types is representable, by `R`. This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`. When `R` is commutative, we can take this to be the usual action with `S = R`. Otherwise, `S = ℕ` shows that the equivalence is additive. See note [bundled maps over different rings]. -/ @[simps] def ring_lmap_equiv_self [module S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M := { to_fun := λ f, f 1, inv_fun := smul_right (1 : R →ₗ[R] R), left_inv := λ f, by { ext, simp }, right_inv := λ x, by simp, .. applyₗ' S (1 : R) } end end module section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (f g : M →ₗ[R] M₂) include R theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨f.comp, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. See also `linear_map.applyₗ'` for a version that works with two different semirings. This is the `linear_map` version of `add_monoid_hom.eval`. -/ @[simps] def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ := { to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v }, map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _, ..applyₗ' R } /-- Alternative version of `dom_restrict` as a linear map. -/ def dom_restrict' (p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) := { to_fun := λ φ, φ.dom_restrict p, map_add' := by simp [linear_map.ext_iff], map_smul' := by simp [linear_map.ext_iff] } @[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : dom_restrict' p f x = f x := rfl end comm_semiring section semiring variables [semiring R] [add_comm_monoid M] [module R M] instance endomorphism_semiring : semiring (M →ₗ[R] M) := by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), zero := 0, add := (+), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, .. linear_map.add_comm_monoid, .. }; intros; try { refl }; apply linear_map.ext; simp {proj := ff} end semiring section ring variables [ring R] [add_comm_group M] [module R M] instance endomorphism_ring : ring (M →ₗ[R] M) := { ..linear_map.endomorphism_semiring, ..linear_map.add_comm_group } end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map /-- The `ℕ`-linear equivalence between additive morphisms `A →+ B` and `ℕ`-linear morphisms `A →ₗ[ℕ] B`. -/ @[simps] def add_monoid_hom_lequiv_nat {A B : Type*} [add_comm_monoid A] [add_comm_monoid B] : (A →+ B) ≃ₗ[ℕ] (A →ₗ[ℕ] B) := { to_fun := add_monoid_hom.to_nat_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-- The `ℤ`-linear equivalence between additive morphisms `A →+ B` and `ℤ`-linear morphisms `A →ₗ[ℤ] B`. -/ @[simps] def add_monoid_hom_lequiv_int {A B : Type*} [add_comm_group A] [add_comm_group B] : (A →+ B) ≃ₗ[ℤ] (A →ₗ[ℤ] B) := { to_fun := add_monoid_hom.to_int_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set variables {p p'} /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } instance add_comm_monoid_submodule : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl variables (R) lemma subsingleton_iff : subsingleton M ↔ subsingleton (submodule R M) := add_submonoid.subsingleton_iff.trans $ begin rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top], convert to_add_submonoid_eq; refl end lemma nontrivial_iff : nontrivial M ↔ nontrivial (submodule R M) := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans not_nontrivial_iff_subsingleton.symm) variables {R} instance [subsingleton M] : unique (submodule R M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mp ‹_›) a _⟩ instance unique' [subsingleton R] : unique (submodule R M) := by haveI := module.subsingleton R M; apply_instance instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mp ‹_› theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma apply_coe_mem_map (f : M →ₗ[R] M₂) {p : submodule R M} (r : p) : f r ∈ map f p := mem_map_of_mem r.prop @[simp] lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := set_like.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] lemma range_map_nonempty (N : submodule R M) : (set.range (λ ϕ, submodule.map ϕ N : (M →ₗ[R] M₂) → submodule R M₂)).nonempty := ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩ /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := set_like.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span lemma map_span (f : M →ₗ[R] M₂) (s : set M) : (span R s).map f = span R (f '' s) := eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩ alias submodule.map_span ← linear_map.map_span lemma map_span_le {R M M₂ : Type*} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) (s : set M) (N : submodule R M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N := begin rw [f.map_span, span_le, set.image_subset_iff], exact iff.rfl end alias submodule.map_span_le ← linear_map.map_span_le /- See also `span_preimage_eq` below. -/ lemma span_preimage_le (f : M →ₗ[R] M₂) (s : set M₂) : span R (f ⁻¹' s) ≤ (span R s).comap f := by { rw [span_le, comap_coe], exact preimage_mono (subset_span), } alias submodule.span_preimage_le ← linear_map.span_preimage_le /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h lemma span_nat_eq_add_submonoid_closure (s : set M) : (span ℕ s).to_add_submonoid = add_submonoid.closure s := begin refine eq.symm (add_submonoid.closure_eq_of_le subset_span _), apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _, rw span_le, exact add_submonoid.subset_closure, end @[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s := by rw [span_nat_eq_add_submonoid_closure, s.closure_eq] lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) : (span ℤ s).to_add_subgroup = add_subgroup.closure s := eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx (λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _) (λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _) @[simp] lemma span_int_eq {M : Type*} [add_comm_group M] (s : add_subgroup M) : (span ℤ (s : set M)).to_add_subgroup = s := by rw [span_int_eq_add_subgroup_closure, s.closure_eq] section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} := by simp only [←span_Union, set.bUnion_of_singleton s] @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M} (h : ∀ i ∈ s, f i ∈ p i) : ∑ i in s, f i ∈ ⨆ i ∈ s, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi) lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M} (h : ∀ i, f i ∈ p i) : ∑ i, f i ∈ ⨆ i, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i (h i) @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] end @[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →ₘ submodule R M) : (↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) := coe_supr_of_directed a a.monotone.directed_le /-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/ lemma coe_scott_continuous : omega_complete_partial_order.continuous' (coe : submodule R M → set M) := ⟨set_like.coe_mono, coe_supr_of_chain⟩ @[simp] lemma mem_supr_of_chain (a : ℕ →ₘ submodule R M) (m : M) : m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k := mem_supr_of_directed a a.monotone.directed_le section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] end /- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar multiplication character `•`, with escape sequence `\bub`. -/ notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x) lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} : s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v := by simp_rw [set_like.le_def, mem_span_singleton] lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v := begin rw [eq_top_iff, le_span_singleton_iff], finish, end @[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ := by { ext, simp [mem_span_singleton, eq_comm] } lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x := begin rw [span_le, set.singleton_subset_iff, set_like.mem_coe], exact smul_mem _ _ (mem_span_singleton_self _) end lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x := begin refine le_antisymm (span_singleton_smul_le r x) _, convert span_singleton_smul_le r⁻¹ (r • x), exact (inv_smul_smul' hr _).symm end lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {p : submodule K E} {x : E} (x0 : x ≠ 0) : disjoint p (K ∙ x) ↔ x ∉ p := disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩ lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma apply_mem_span_image_of_mem_span (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) : f x ∈ submodule.span R (f '' s) := begin rw submodule.span_image, exact submodule.mem_map_of_mem h end /-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/ lemma not_mem_span_of_apply_not_mem_span_image (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : f x ∉ submodule.span R (f '' s)) : x ∉ submodule.span R s := not.imp h (apply_mem_span_image_of_mem_span f) lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, set_like.mem_coe] lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end instance : is_compactly_generated (submodule R M) := ⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩, apply singleton_span_is_compact_element, end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩ lemma lt_add_iff_not_mem {I : submodule R M} {a : M} : I < I + (R ∙ a) ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I + (R ∙ a) ≤ I, { simp only [add_eq_sup, sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply set_like.lt_iff_le_and_exists.mpr, split, simp only [add_eq_sup, le_sup_left], use a, split, swap, { assumption, }, { have : (R ∙ a) ≤ I + (R ∙ a) := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end section open_locale classical /-- For every element in the span of a set, there exists a finite subset of the set such that the element is contained in the span of the subset. -/ lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) : ∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) := begin refine span_induction hx (λ x hx, _) _ _ _, { refine ⟨{x}, _, _⟩, { rwa [finset.coe_singleton, set.singleton_subset_iff] }, { rw finset.coe_singleton, exact submodule.mem_span_singleton_self x } }, { use ∅, simp }, { rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩, refine ⟨X ∪ Y, _, _⟩, { rw finset.coe_union, exact set.union_subset hX hY }, rw [finset.coe_union, span_union, mem_sup], exact ⟨x, hxX, y, hyY, rfl⟩, }, { rintros a x ⟨T, hT, h2⟩, exact ⟨T, hT, smul_mem _ _ h2⟩ } end end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := set_like.coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [set_like.le_def], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set @[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff @[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p := ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩, λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩ @[simp] lemma span_neg (s : set M) : span R (-s) = span R s := calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp ... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm ... = span R s : by simp lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : has_sub (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a - b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ (neg_mem p h₂)⟩ @[simp] theorem mk_sub : (mk (x - y) : quotient p) = mk x - mk y := rfl instance : add_comm_group (quotient p) := { zero := (0 : quotient p), add := (+), neg := has_neg.neg, sub := has_sub.sub, add_assoc := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, simp only [←mk_add p, quot_mk_eq_mk, add_assoc] }, zero_add := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, quot_mk_eq_mk, zero_add] }, add_zero := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, add_zero, quot_mk_eq_mk] }, add_comm := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, quot_mk_eq_mk, add_comm] }, add_left_neg := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, ←mk_neg p, quot_mk_eq_mk, add_left_neg] }, sub_eq_add_neg := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, ←mk_neg p, ←mk_sub p, sub_eq_add_neg, quot_mk_eq_mk] }, nsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, nsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, nsmul_succ' := by { rintros n ⟨⟩, simp only [nat.succ_eq_one_add, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul], refl }, gsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, gsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, gsmul_succ' := by { rintros n ⟨⟩, simp [nat.succ_eq_add_one, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul, add_smul, add_comm], refl }, gsmul_neg' := by { rintros n ⟨x⟩, simp_rw [gsmul_neg_succ_of_nat, gsmul_coe_nat], refl }, } instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl @[simp] theorem mk_nsmul (n : ℕ) : (mk (n • x) : quotient p) = n • mk x := rfl instance : module R (quotient p) := module.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) := by { rintros ⟨x⟩, exact ⟨x, rfl⟩ } lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) := begin obtain ⟨x, _, not_mem_s⟩ := set_like.exists_of_lt h, refine ⟨⟨mk x, 0, _⟩⟩, simpa using not_mem_s end end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/ lemma eq_on_span {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`. See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/ lemma eq_on_span' {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) : set.eq_on f g (span R s : set M) := eq_on_span H /-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are equal. -/ lemma ext_on {s : set M} {f g : M →ₗ[R] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) : f = g := linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _)) /-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at each `v i`, then they are equal. -/ lemma ext_on_range {v : ι → M} {f g : M →ₗ[R] M₂} (hv : span R (set.range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := ext_on hv (set.forall_range_iff.2 h) section finsupp variables {γ : Type*} [has_zero γ] @[simp] lemma map_finsupp_sum (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end finsupp section dfinsupp variables {γ : ι → Type*} [decidable_eq ι] [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] @[simp] lemma map_dfinsupp_sum (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end dfinsupp theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. See Note [range copy pattern]. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := (map f ⊤).copy (set.range f) set.image_univ.symm theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := rfl @[simp] theorem mem_range {f : M →ₗ[R] M₂} {x} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl lemma range_eq_map (f : M →ₗ[R] M₂) : f.range = map f ⊤ := by { ext, simp } theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := set_like.coe_injective set.range_id theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := set_like.coe_injective (set.range_comp g f) theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := set_like.coe_mono (set.range_comp_subset_range f g) theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [set_like.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := set_like.coe_mono (set.image_subset_range f p) /-- The decreasing sequence of submodules consisting of the ranges of the iterates of a linear map. -/ @[simps] def iterate_range {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (f ^ n).range, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_range at h, obtain ⟨m, rfl⟩ := h, rw linear_map.mem_range, use (f ^ c) m, rw [pow_add, linear_map.mul_apply], end⟩ /-- Restrict the codomain of a linear map `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₗ[R] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot_of_inverse {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M} (h : g.comp f = id) : ker f = ⊥ := ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero] lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := by simpa only [range_eq_map] using map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf map_le_range (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := by simpa only [range_eq_map] using submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem range_eq_bot {f : M →ₗ[R] M₂} : range f = ⊥ ↔ f = 0 := by rw [← range_le_bot_iff, le_bot_iff] lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ ⟨_, rfl⟩, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y hy, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end /-- The increasing sequence of submodules consisting of the kernels of the iterates of a linear map. -/ @[simps] def iterate_ker {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ submodule R M := ⟨λ n, (f ^ n).ker, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_ker at h, rw [linear_map.mem_ker, add_comm, pow_add, linear_map.mul_apply, h, linear_map.map_zero], end⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range_eq_map, map_le_map_iff] end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables {f : M →ₗ[R] M₂} include R open submodule theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ lemma ker_le_iff {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p := begin split, { intros h, use 0, rw [← set_like.mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, }, { rintros ⟨y, h₁, h₂⟩, rw set_like.le_def, intros z hz, simp only [mem_ker, set_like.mem_coe] at hz, rw [← set_like.mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁, have hx' : x ∈ p, { exact h₂ hx, }, have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], }, suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], }, exact p.sub_mem hxz hx', }, end end ring section field variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := by simpa only [range_eq_map] using submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := by simpa only [range_eq_map] using submodule.map_smul' f _ a lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) : (K ∙ x) ⊔ f.ker = ⊤ := eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x, submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩, ⟨y - (f y * (f x)⁻¹) • x, by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc, inv_mul_cancel hx, mul_one, sub_self], by simp only [add_sub_cancel'_right]⟩⟩) end field end linear_map namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [module R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := f.range_eq_map.symm @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_le_range : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, map_le_map_iff' (ker_subtype p) } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := by simpa only [range_eq_map] using map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.rel_iso : submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p], map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.order_embedding : submodule R p.quotient ↪o submodule R M := (rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.order_embedding p p' = comap p.mkq p' := rfl lemma span_preimage_eq {f : M →ₗ[R] M₂} {s : set M₂} (h₀ : s.nonempty) (h₁ : s ⊆ range f) : span R (f ⁻¹' s) = (span R s).comap f := begin suffices : (span R s).comap f ≤ span R (f ⁻¹' s), { exact le_antisymm (span_preimage_le f s) this, }, have hk : ker f ≤ span R (f ⁻¹' s), { let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, }, rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy, exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), }, rw ← left_eq_sup at hk, rw f.range_coe at h₁, rw [hk, ← map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁], exact inf_le_right, end end ring end submodule namespace linear_map section semiring variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end lemma range_comp_of_range_eq_top {f : M →ₗ[R] M₂} (g : M₂ →ₗ[R] M₃) (hf : range f = ⊤) : range (g.comp f) = range g := by rw [range_comp, hf, submodule.map_top] lemma ker_comp_of_ker_eq_bot (f : M →ₗ[R] M₂) {g : M₂ →ₗ[R] M₃} (hg : ker g = ⊥) : ker (g.comp f) = ker f := by rw [ker_comp, hg, submodule.comap_bot] end semiring section ring variables [ring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] lemma range_mkq_comp (f : M →ₗ[R] M₂) : f.range.mkq.comp f = 0 := linear_map.ext $ λ x, by simp lemma ker_le_range_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 := by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype] /-- An epimorphism is surjective. -/ lemma range_eq_top_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : M₂ →ₗ[R] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R] f.range.quotient).comp f = 0 := zero_comp _, rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)], exact ker_zero end end ring end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables {module_M : module R M} {module_M₂ : module R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := set_like.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule `p` of the domain onto the image of that submodule. This is `linear_equiv.of_submodule'` but with `map` on the right instead of `comap` on the left. -/ def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) := { inv_fun := λ y, ⟨e.symm y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) } @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl end /-- A family of linear equivalences `Π j, (Ms j ≃ₗ[R] Ns j)` generates a linear equivalence between `Π j, Ms j` and `Π j, Ns j`. -/ @[simps apply] def Pi_congr_right {η : Type*} {Ms Ns : η → Type*} [Π j, add_comm_monoid (Ms j)] [Π j, module R (Ms j)] [Π j, add_comm_monoid (Ns j)] [Π j, module R (Ns j)] (es : ∀ j, Ms j ≃ₗ[R] Ns j) : (Π j, Ms j) ≃ₗ[R] (Π j, Ns j) := { to_fun := λ x j, es j (x j), inv_fun := λ x j, (es j).symm (x j), map_smul' := λ m x, by { ext j, simp }, .. add_equiv.Pi_congr_right (λ j, (es j).to_add_equiv) } @[simp] lemma Pi_congr_right_refl {η : Type*} {Ms : η → Type*} [Π j, add_comm_monoid (Ms j)] [Π j, module R (Ms j)] : Pi_congr_right (λ j, refl R (Ms j)) = refl _ _ := rfl @[simp] lemma Pi_congr_right_symm {η : Type*} {Ms Ns : η → Type*} [Π j, add_comm_monoid (Ms j)] [Π j, module R (Ms j)] [Π j, add_comm_monoid (Ns j)] [Π j, module R (Ns j)] (es : ∀ j, Ms j ≃ₗ[R] 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, add_comm_monoid (Ms j)] [Π j, module R (Ms j)] [Π j, add_comm_monoid (Ns j)] [Π j, module R (Ns j)] [Π j, add_comm_monoid (Ps j)] [Π j, module R (Ps j)] (es : ∀ j, Ms j ≃ₗ[R] Ns j) (fs : ∀ j, Ns j ≃ₗ[R] Ps j) : (Pi_congr_right es).trans (Pi_congr_right fs) = (Pi_congr_right $ λ i, (es i).trans (fs i)) := rfl section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def curry : (V × V₂ → R) ≃ₗ[R] (V → V₂ → R) := { map_add' := λ _ _, by { ext, refl }, map_smul' := λ _ _, by { ext, refl }, .. equiv.curry _ _ _ } @[simp] lemma coe_curry : ⇑(linear_equiv.curry R V V₂) = curry := rfl @[simp] lemma coe_curry_symm : ⇑(linear_equiv.curry R V V₂).symm = uncurry := rfl end uncurry section variables {module_M : module R M} {module_M₂ : module R M₂} {module_M₃ : module R M₃} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) (l : M₃ →ₗ[R] M) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl /-- A linear equivalence of two modules restricts to a linear equivalence from the preimage of any submodule to that submodule. This is `linear_equiv.of_submodule` but with `comap` on the left instead of `map` on the right. -/ def of_submodule' [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) : U.comap (f : M →ₗ[R] M₂) ≃ₗ[R] U := (f.symm.of_submodules _ _ f.symm.map_eq_comap).symm lemma of_submodule'_to_linear_map [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) : (f.of_submodule' U).to_linear_map = (f.to_linear_map.dom_restrict _).cod_restrict _ subtype.prop := by { ext, refl } @[simp] lemma of_submodule'_apply [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U.comap (f : M →ₗ[R] M₂)) : (f.of_submodule' U x : M₂) = f (x : M) := rfl @[simp] lemma of_submodule'_symm_apply [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U) : ((f.of_submodule' U).symm x : M) = f.symm (x : M₂) := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [module R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (set_like.le_def.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective @[simp] theorem range_comp : (h.comp (e : M →ₗ[R] M₂)).range = h.range := linear_map.range_comp_of_range_eq_top _ e.range @[simp] theorem ker_comp : ((e : M →ₗ[R] M₂).comp l).ker = l.ker := linear_map.ker_comp_of_ker_eq_bot _ e.ker variables {f g} /-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear equivalence between `M` and `f.range`. This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of `linear_map.range_restrict`. -/ def of_left_inverse {g : M₂ → M} (h : function.left_inverse g f) : M ≃ₗ[R] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.range_restrict } @[simp] lemma of_left_inverse_apply (h : function.left_inverse g f) (x : M) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl end end add_comm_monoid section add_comm_group variables [semiring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b end add_comm_group section neg variables (R) [semiring R] [add_comm_group M] [module R M] /-- `x ↦ -x` as a `linear_equiv` -/ def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) } variable {R} @[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl lemma neg_apply (x : M) : neg R x = -x := by simp @[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl end neg section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] variables {module_M : module R M} {module_M₂ : module R M₂} variables (f : M →ₗ[R] M₂) (e : M ≃ₗ[R] M₂) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/ noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range := of_left_inverse $ classical.some_spec (linear_map.ker_eq_bot.1 h).has_left_inverse @[simp] theorem of_injective_apply {h : f.ker = ⊥} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp }, right_inv := λ f, by { ext x, simp }, map_add' := λ f g, by { ext x, simp }, map_smul' := λ c f, by { ext x, simp } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl @[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) : (arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_group N] [add_comm_group N₂] [add_comm_group N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁] [add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ := begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) := linear_equiv.trans (linear_equiv.of_injective (to_span_singleton K M x) (ker_to_span_singleton K M h)) (of_eq (to_span_singleton K M x).range (K ∙ x) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) := begin apply set_like.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section module variables [semiring R] [add_comm_monoid M] [module R M] /-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q` is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/ def equiv_subtype_map (p : submodule R M) (q : submodule R p) : q ≃ₗ[R] q.map p.subtype := { inv_fun := begin rintro ⟨x, hx⟩, refine ⟨⟨x, _⟩, _⟩; rcases hx with ⟨⟨_, h⟩, _, rfl⟩; assumption end, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl, .. (p.subtype.dom_restrict q).cod_restrict _ begin rintro ⟨x, hx⟩, refine ⟨x, hx, rfl⟩, end } @[simp] lemma equiv_subtype_map_apply {p : submodule R M} {q : submodule R p} (x : q) : (p.equiv_subtype_map q x : M) = p.subtype.dom_restrict q x := rfl @[simp] lemma equiv_subtype_map_symm_apply {p : submodule R M} {q : submodule R p} (x : q.map p.subtype) : ((p.equiv_subtype_map q).symm x : M) = x := by { cases x, refl } /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, set_like.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, set_like.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end module variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl variables (q : submodule R M) /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = q) : p.quotient ≃ₗ[R] q.quotient := { map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl }, ..@quotient.congr _ _ (quotient_rel p) (quotient_rel q) (equiv.refl _) $ λ a b, by { subst h, refl } } end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) @[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw set_like.le_def, intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw set_like.le_def, intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, map_smul' := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace add_equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl end add_equiv namespace linear_map open submodule section isomorphism_laws variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) /-- The first isomorphism theorem for surjective linear maps. -/ noncomputable def quot_ker_equiv_of_surjective (f : M →ₗ[R] M₂) (hf : function.surjective f) : f.ker.quotient ≃ₗ[R] M₂ := f.quot_ker_equiv_range.trans (linear_equiv.of_top f.range (linear_map.range_eq_top.2 hf)) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws section fun_left variables (R M) [semiring R] [add_comm_monoid M] [module R M] variables {m n p : Type*} /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := mk (∘f) (λ _ _, rfl) (λ _ _, rfl) @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl theorem fun_left_surjective_of_injective (f : m → n) (hf : injective f) : surjective (fun_left R M f) := begin classical, intro g, refine ⟨λ x, if h : ∃ y, f y = x then g h.some else 0, _⟩, { ext, dsimp only [fun_left_apply], split_ifs with w, { congr, exact hf w.some_spec, }, { simpa only [not_true, exists_apply_eq_apply] using w } }, end theorem fun_left_injective_of_surjective (f : m → n) (hf : surjective f) : injective (fun_left R M f) := begin obtain ⟨g, hg⟩ := hf.has_right_inverse, suffices : left_inverse (fun_left R M g) (fun_left R M f), { exact this.injective }, intro x, simp only [← linear_map.comp_apply, ← fun_left_comp, hg.id, fun_left_id] end /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end fun_left universe i variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map namespace submodule variables [ring R] [add_comm_group M] [module R M] instance : is_modular_lattice (submodule R M) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw [← add_sub_cancel c b, add_comm], apply z.sub_mem haz (xz hb), end⟩ end submodule
6cb6c34be07f5ad7a4663b730b414ace654a7d91
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/metric_space/closeds.lean
59138f970f214e11ac5419bf22b879150c56dafb
[ "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
21,095
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.metric_space.hausdorff_distance import topology.compacts import analysis.specific_limits /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical topological_space ennreal universe u open classical set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right inf_edist_le_inf_edist_add_edist _ ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, add_left_comm, Hausdorff_edist_comm, -subtype.val_eq_coe] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff.2 (λε εpos, _), rcases mem_closure_iff.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa hs.closure_eq at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ℝ≥0∞ := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ℝ≥0∞) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.inv_pow, div_eq_mul_inv], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto y_lim begin simp only [exists_prop, set.mem_Union, filter.eventually_at_top, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine tendsto_at_top.2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.const_mul (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b, from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top, exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_Union₂.1 this with ⟨y, ys, dy⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { exact subtype.val_injective.inj_on F }, { refine fs.finite_subsets.subset (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : is_closed t0 := (fs.subset t0s).is_compact.is_closed, let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_Union₂.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [s.property.2.is_closed.closure_eq, t.property.2.is_closed.closure_eq] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (range $ @nonempty_compacts.to_closeds α _ _) := begin have : range nonempty_compacts.to_closeds = {s : closeds α | s.val.nonempty ∧ is_compact s.val}, from range_inclusion _, rw this, refine is_closed_of_closure_subset (λs hs, ⟨_, _⟩), { -- take a set set t which is nonempty and at a finite distance of s rcases mem_closure_iff.1 hs ⊤ ennreal.coe_lt_top with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- since `t` is nonempty, so is `s` exact nonempty_of_Hausdorff_edist_ne_top ht.1 (ne_of_lt Dst) }, { refine compact_iff_totally_bounded_complete.2 ⟨_, s.property.is_complete⟩, refine totally_bounded_iff.2 (λε (εpos : 0 < ε), _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff.1 hs (ε/2) (ennreal.half_pos εpos.ne') with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos.ne') with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_Union₂.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := (complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding.to_uniform_inducing).2 $ nonempty_compacts.is_closed_in_closeds.is_complete /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw nonempty_compacts.to_closeds.uniform_embedding.embedding.is_compact_iff_is_compact_image, rw [image_univ], exact nonempty_compacts.is_closed_in_closeds.is_compact end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ rcases exists_countable_dense α with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable v0, from countable_set_of_finite_subset cs, exact this.preimage subtype.coe_injective }, { refine λt, mem_closure_iff.2 (λε εpos, _), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases exists_between εpos with ⟨δ, δpos, δlt⟩, have δpos' : 0 < δ / 2, from ennreal.half_pos δpos.ne', -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, rcases mem_closure_iff.1 (s_dense x) (δ/2) δpos' with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := t.property.2.totally_bounded, rcases totally_bounded_iff.1 this (δ/2) δpos' with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := af.image _, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_Union₂.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := ‹finite b›.subset (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have hc : c.nonempty, from nonempty_of_Hausdorff_edist_ne_top t.property.1 (ne_top_of_lt Dtc), -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.is_compact⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply uniform_space.second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1 x.2.2.bounded y.2.2.bounded /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.uniform_continuous end --section end metric --namespace
36f5ddf375841a3b956ea96488b6be3d82eb1a7c
4727251e0cd73359b15b664c3170e5d754078599
/archive/imo/imo2021_q1.lean
2555d8cc6fddc4850254e169496c33e8456b8efb
[ "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
8,311
lean
/- Copyright (c) 2021 Mantas Bakšys. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mantas Bakšys -/ import data.real.sqrt import tactic.interval_cases import tactic.linarith import tactic.norm_cast import tactic.norm_num import tactic.ring_exp /-! # IMO 2021 Q1 Let `n≥100` be an integer. Ivan writes the numbers `n, n+1,..., 2n` each on different cards. He then shuffles these `n+1` cards, and divides them into two piles. Prove that at least one of the piles contains two cards such that the sum of their numbers is a perfect square. # Solution We show there exists a triplet `a, b, c ∈ [n , 2n]` with `a < b < c` and each of the sums `(a + b)`, `(b + c)`, `(a + c)` being a perfect square. Specifically, we consider the linear system of equations a + b = (2 * l - 1) ^ 2 a + c = (2 * l) ^ 2 b + c = (2 * l + 1) ^ 2 which can be solved to give a = 2 * l * l - 4 * l b = 2 * l * l + 1 c = 2 * l * l + 4 * l Therefore, it is enough to show that there exists a natural number l such that `n ≤ 2 * l * l - 4 * l` and `2 * l * l + 4 * l ≤ 2 * n` for `n ≥ 100`. Then, by the Pigeonhole principle, at least two numbers in the triplet must lie in the same pile, which finishes the proof. -/ open real lemma lower_bound (n l : ℕ) (hl : 2 + sqrt (4 + 2 * n) ≤ 2 * l) : n + 4 * l ≤ 2 * l * l := begin suffices : 2 * ((n : ℝ) + 4 * l) - 8 * l + 4 ≤ 2 * (2 * l * l) - 8 * l + 4, { simp only [mul_le_mul_left, sub_le_sub_iff_right, add_le_add_iff_right, zero_lt_two] at this, exact_mod_cast this, }, rw [← le_sub_iff_add_le', sqrt_le_iff, pow_two] at hl, convert hl.2 using 1; ring, end lemma upper_bound (n l : ℕ) (hl : (l : ℝ) ≤ sqrt (1 + n) - 1) : 2 * l * l + 4 * l ≤ 2 * n := begin have h1 : ∀ n : ℕ, 0 ≤ 1 + (n : ℝ), by { intro n, exact_mod_cast nat.zero_le (1 + n) }, rw [le_sub_iff_add_le', le_sqrt (h1 l) (h1 n), pow_two] at hl, rw [← add_le_add_iff_right 2, ← @nat.cast_le ℝ], simp only [nat.cast_bit0, nat.cast_add, nat.cast_one, nat.cast_mul], convert (mul_le_mul_left zero_lt_two).mpr hl using 1; ring, end lemma radical_inequality {n : ℕ} (h : 107 ≤ n) : sqrt (4 + 2 * n) ≤ 2 * (sqrt (1 + n) - 3) := begin have h1n : 0 ≤ 1 + (n : ℝ), by { norm_cast, exact nat.zero_le _ }, rw sqrt_le_iff, split, { simp only [sub_nonneg, zero_le_mul_left, zero_lt_two, le_sqrt zero_lt_three.le h1n], norm_cast, linarith only [h] }, ring_exp, rw [pow_two, ← sqrt_mul h1n, sqrt_mul_self h1n], suffices : 24 * sqrt (1 + n) ≤ 2 * n + 36, by linarith, rw mul_self_le_mul_self_iff, swap, { norm_num, apply sqrt_nonneg }, swap, { norm_cast, linarith }, ring_exp, rw [pow_two, ← sqrt_mul h1n, sqrt_mul_self h1n], -- Not splitting into cases lead to a deterministic timeout on my machine obtain ⟨rfl, h'⟩ : 107 = n ∨ 107 < n := eq_or_lt_of_le h, { norm_num }, { norm_cast, nlinarith }, end -- We will later make use of the fact that there exists (l : ℕ) such that -- n ≤ 2 * l * l - 4 * l and 2 * l * l + 4 * l ≤ 2 * n for n ≥ 107. lemma exists_numbers_in_interval (n : ℕ) (hn : 107 ≤ n) : ∃ (l : ℕ), (n + 4 * l ≤ 2 * l * l ∧ 2 * l * l + 4 * l ≤ 2 * n) := begin suffices : ∃ (l : ℕ), 2 + sqrt (4 + 2 * n) ≤ 2 * (l : ℝ) ∧ (l : ℝ) ≤ sqrt (1 + n) - 1, { cases this with l t, exact ⟨l, lower_bound n l t.1, upper_bound n l t.2⟩ }, let x := sqrt (1 + n) - 1, refine ⟨⌊x⌋₊, _, _⟩, { transitivity 2 * (x - 1), { dsimp only [x], linarith only [radical_inequality hn] }, { simp only [mul_le_mul_left, zero_lt_two], linarith only [(nat.lt_floor_add_one x).le], } }, { apply nat.floor_le, rw [sub_nonneg, le_sqrt], all_goals { norm_cast, simp only [one_pow, le_add_iff_nonneg_right, zero_le'], } }, end lemma exists_triplet_summing_to_squares (n : ℕ) (hn : 100 ≤ n) : (∃ (a b c : ℕ), n ≤ a ∧ a < b ∧ b < c ∧ c ≤ 2 * n ∧ (∃ (k : ℕ), a + b = k * k) ∧ (∃ (l : ℕ), c + a = l * l) ∧ (∃ (m : ℕ), b + c = m * m)) := begin -- If n ≥ 107, we do not explicitly construct the triplet but use an existence -- argument from lemma above. obtain p|p : 107 ≤ n ∨ n < 107 := le_or_lt 107 n, { obtain ⟨l, hl1, hl2⟩ := exists_numbers_in_interval n p, have p : 1 < l, { contrapose! hl1, interval_cases l; linarith }, have h₁ : 4 * l ≤ 2 * l * l, { linarith }, have h₂ : 1 ≤ 2 * l, { linarith }, refine ⟨2 * l * l - 4 * l, 2 * l * l + 1, 2 * l * l + 4 * l, _, _, _, ⟨_, ⟨2 * l - 1, _⟩, ⟨2 * l, _⟩, 2 * l + 1, _⟩⟩, all_goals { zify [h₁, h₂], linarith } }, -- Otherwise, if 100 ≤ n < 107, then it suffices to consider explicit -- construction of a triplet {a, b, c}, which is constructed by setting l=9 -- in the argument at the start of the file. { refine ⟨126, 163, 198, p.le.trans _, _, _, _, ⟨17, _⟩, ⟨18, _⟩, 19, _⟩, swap 4, { linarith }, all_goals { norm_num } }, end -- Since it will be more convenient to work with sets later on, we will translate the above claim -- to state that there always exists a set B ⊆ [n, 2n] of cardinality at least 3, such that each -- pair of pairwise unequal elements of B sums to a perfect square. lemma exists_finset_3_le_card_with_pairs_summing_to_squares (n : ℕ) (hn : 100 ≤ n) : ∃ B : finset ℕ, (2 * 1 + 1 ≤ B.card) ∧ (∀ (a b ∈ B), a ≠ b → ∃ k, a + b = k * k) ∧ (∀ (c ∈ B), n ≤ c ∧ c ≤ 2 * n) := begin obtain ⟨a, b, c, hna, hab, hbc, hcn, h₁, h₂, h₃⟩ := exists_triplet_summing_to_squares n hn, refine ⟨{a, b, c}, _, _, _⟩, { suffices : ({a, b, c} : finset ℕ).card = 3, { rw this, exact le_rfl }, suffices : a ∉ {b, c} ∧ b ∉ {c}, { rw [finset.card_insert_of_not_mem this.1, finset.card_insert_of_not_mem this.2, finset.card_singleton], }, { rw [finset.mem_insert, finset.mem_singleton, finset.mem_singleton], push_neg, exact ⟨⟨hab.ne, (hab.trans hbc).ne⟩, hbc.ne⟩ } }, { intros x hx y hy hxy, simp only [finset.mem_insert, finset.mem_singleton] at hx hy, rcases hx with rfl|rfl|rfl; rcases hy with rfl|rfl|rfl, all_goals { contradiction <|> assumption <|> simpa only [add_comm x y], } }, { simp only [finset.mem_insert, finset.mem_singleton], rintros d (rfl|rfl|rfl); split; linarith only [hna, hab, hbc, hcn], }, end theorem IMO_2021_Q1 : ∀ (n : ℕ), 100 ≤ n → ∀ (A ⊆ finset.Icc n (2 * n)), (∃ (a b ∈ A), a ≠ b ∧ ∃ (k : ℕ), a + b = k * k) ∨ (∃ (a b ∈ finset.Icc n (2 * n) \ A), a ≠ b ∧ ∃ (k : ℕ), a + b = k * k) := begin intros n hn A hA, -- For each n ∈ ℕ such that 100 ≤ n, there exists a pairwise unequal triplet {a, b, c} ⊆ [n, 2n] -- such that all pairwise sums are perfect squares. In practice, it will be easier to use -- a finite set B ⊆ [n, 2n] such that all pairwise unequal pairs of B sum to a perfect square -- noting that B has cardinality greater or equal to 3, by the explicit construction of the -- triplet {a, b, c} before. obtain ⟨B, hB, h₁, h₂⟩ := exists_finset_3_le_card_with_pairs_summing_to_squares n hn, have hBsub : B ⊆ finset.Icc n (2 * n), { intros c hcB, simpa only [finset.mem_Icc] using h₂ c hcB }, have hB' : 2 * 1 < ((B ∩ (finset.Icc n (2 * n) \ A)) ∪ (B ∩ A)).card, { rw [← finset.inter_distrib_left, finset.sdiff_union_self_eq_union, finset.union_eq_left_iff_subset.mpr hA, (finset.inter_eq_left_iff_subset _ _).mpr hBsub], exact nat.succ_le_iff.mp hB }, -- Since B has cardinality greater or equal to 3, there must exist a subset C ⊆ B such that -- for any A ⊆ [n, 2n], either C ⊆ A or C ⊆ [n, 2n] \ A and C has cardinality greater -- or equal to 2. obtain ⟨C, hC, hCA⟩ := finset.exists_subset_or_subset_of_two_mul_lt_card hB', rw finset.one_lt_card at hC, rcases hC with ⟨a, ha, b, hb, hab⟩, simp only [finset.subset_iff, finset.mem_inter] at hCA, -- Now we split into the two cases C ⊆ [n, 2n] \ A and C ⊆ A, which can be dealt with identically. cases hCA; [right, left]; exact ⟨a, (hCA ha).2, b, (hCA hb).2, hab, h₁ a (hCA ha).1 b (hCA hb).1 hab⟩, end
d53fab0e3552c1686b94c442ebc40c30c465673f
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/archive/oxford_invariants/2021summer/week3_p1.lean
687431d86510b2fd894944a7e7a0a3f8fbd9d3c4
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,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 algebra.big_operators.order import algebra.big_operators.ring /-! # The Oxford Invariants Puzzle Challenges - Summer 2021, Week 3, Problem 1 ## Original statement Let `n ≥ 3`, `a₁, ..., aₙ` be strictly positive integers such that `aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` for `i = 2, ..., n - 1`. Show that $\sum_{i=1}^{n-1}\dfrac{a_0a_n}{a_ia_{i+1}} ∈ \mathbb N$. ## Comments Mathlib is based on type theory, so saying that a rational is a natural doesn't make sense. Instead, we ask that there exists `b : ℕ` whose cast to `α` is the sum we want. In mathlib, `ℕ` starts at `0`. To make the indexing cleaner, we use `a₀, ..., aₙ₋₁` instead of `a₁, ..., aₙ`. Similarly, it's nicer to not use substraction of naturals, so we replace `aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` by `aᵢ₊₁ ∣ aᵢ + aᵢ₊₂`. We don't actually have to work in `ℚ` or `ℝ`. We can be even more general by stating the result for any linearly ordered field. Instead of having `n` naturals, we use a function `a : ℕ → ℕ`. In the proof itself, we replace `n : ℕ, 1 ≤ n` by `n + 1`. The statement is actually true for `n = 0, 1` (`n = 1, 2` before the reindexing) as the sum is simply `0` and `1` respectively. So the version we prove is slightly more general. Overall, the indexing is a bit of a mess to understand. But, trust Lean, it works. ## Formalised statement Let `n : ℕ`, `a : ℕ → ℕ`, `∀ i ≤ n, 0 < a i`, `∀ i, i + 2 ≤ n → aᵢ₊₁ ∣ aᵢ + aᵢ₊₂` (read `→` as "implies"). Then there exists `b : ℕ` such that `b` as an element of any linearly ordered field equals $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$. ## Proof outline The case `n = 0` is trivial. For `n + 1`, we prove the result by induction but by adding `aₙ₊₁ ∣ aₙ * b - a₀` to the induction hypothesis, where `b` is the previous sum, $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$, as a natural. * Base case: * $\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1})$ is a natural: $\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1}) = (a_0 a_1) / (a_0 a_1) = 1$. * Divisibility condition: `a₀ * 1 - a₀ = 0` is clearly divisible by `a₁`. * Induction step: * $\sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1})$ is a natural: $$\sum_{i=0}^{n+1} (a_0 a_{n+2}) / (a_i a_{i+1}) = \sum_{i=0}^n\ (a_0 a_{n+2}) / (a_i a_{i+1}) + (a_0 a_{n+2}) / (a_{n+1} a_{n+2}) = a_{n+2} / a_{n+1} × \sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1}) + a_0 / a_{n+1} = a_{n+2} / a_{n+1} × b + a_0 / a_{n+1} = (a_n + a_{n+2}) / a_{n+1} × b - (a_n b - a_0)(a_{n+1})$$ which is a natural because `(aₙ + aₙ₊₂)/aₙ₊₁`, `b` and `(aₙ * b - a₀)/aₙ₊₁` are (plus an annoying inequality, or the fact that the original sum is positive because its terms are). * Divisibility condition: `aₙ₊₁ * ((aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁) - a₀ = aₙ₊₁aₙ₊₂b` is divisible by `aₙ₊₂`. -/ open_locale big_operators variables {α : Type*} [linear_ordered_field α] theorem week3_p1 (n : ℕ) (a : ℕ → ℕ) (a_pos : ∀ i ≤ n, 0 < a i) (ha : ∀ i, i + 2 ≤ n → a (i + 1) ∣ a i + a (i + 2)) : ∃ b : ℕ, (b : α) = ∑ i in finset.range n, (a 0 * a n)/(a i * a (i + 1)) := begin -- Treat separately `n = 0` and `n ≥ 1` cases n, /- Case `n = 0` The sum is trivially equal to `0` -/ { exact ⟨0, by rw [nat.cast_zero, finset.sum_range_zero]⟩ }, -- `⟨Claim it, Prove it⟩` /- Case `n ≥ 1`. We replace `n` by `n + 1` everywhere to make this inequality explicit Set up the stronger induction hypothesis -/ suffices h : ∃ b : ℕ, (b : α) = ∑ i in finset.range (n + 1), (a 0 * a (n + 1))/(a i * a (i + 1)) ∧ a (n + 1) ∣ a n * b - a 0, { obtain ⟨b, hb, -⟩ := h, exact ⟨b, hb⟩ }, simp_rw ←@nat.cast_pos α at a_pos, /- Declare the induction `ih` will be the induction hypothesis -/ induction n with n ih, /- Base case Claim that the sum equals `1`-/ { refine ⟨1, _, _⟩, -- Check that this indeed equals the sum { rw [nat.cast_one, finset.sum_range_one, div_self], exact (mul_pos (a_pos 0 (nat.zero_le _)) (a_pos 1 (nat.zero_lt_succ _))).ne' }, -- Check the divisibility condition { rw [mul_one, nat.sub_self], exact dvd_zero _ } }, /- Induction step `b` is the value of the previous sum as a natural, `hb` is the proof that it is indeed the value, and `han` is the divisibility condition -/ obtain ⟨b, hb, han⟩ := ih (λ i hi, ha i $ nat.le_succ_of_le hi) (λ i hi, a_pos i $ nat.le_succ_of_le hi), specialize ha n le_rfl, have ha₀ : a 0 ≤ a n * b, -- Needing this is an artifact of `ℕ`-substraction. { rw [←@nat.cast_le α, nat.cast_mul, hb, ←div_le_iff' (a_pos _ $ n.le_succ.trans $ nat.le_succ _), ←mul_div_mul_right _ _ (a_pos _ $ nat.le_succ _).ne'], suffices h : ∀ i, i ∈ finset.range (n + 1) → 0 ≤ (a 0 : α) * a (n + 1) / (a i * a (i + 1)), { exact finset.single_le_sum h (finset.self_mem_range_succ n) }, refine (λ i _, div_nonneg _ _); refine mul_nonneg _ _; exact nat.cast_nonneg _ }, -- Claim that the sum equals `(aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁` refine ⟨(a n + a (n + 2))/ a (n + 1) * b - (a n * b - a 0) / a (n + 1), _, _⟩, -- Check that this indeed equals the sum { calc (((a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : ℕ) : α) = (a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : begin norm_cast, rw nat.cast_sub (nat.div_le_of_le_mul _), rw [←mul_assoc, nat.mul_div_cancel' ha, add_mul], exact (nat.sub_le_self _ _).trans (nat.le_add_right _ _), end ... = a (n + 2) / a (n + 1) * b + (a 0 * a (n + 2)) / (a (n + 1) * a (n + 2)) : by rw [add_div, add_mul, sub_div, mul_div_right_comm, add_sub_sub_cancel, mul_div_mul_right _ _ (a_pos _ le_rfl).ne'] ... = ∑ (i : ℕ) in finset.range (n + 2), a 0 * a (n + 2) / (a i * a (i + 1)) : begin rw [finset.sum_range_succ, hb, finset.mul_sum], congr, ext i, rw [←mul_div_assoc, ←mul_div_right_comm, mul_div_assoc, mul_div_cancel _ (a_pos _ $ nat.le_succ _).ne', mul_comm], end }, -- Check the divisibility condition { rw [nat.mul_sub_left_distrib, ← mul_assoc, nat.mul_div_cancel' ha, add_mul, nat.mul_div_cancel' han, nat.add_sub_sub_cancel ha₀, nat.add_sub_cancel], exact dvd_mul_right _ _ } end
ac419354ef8b1e0ca54c3befed6a6bb94697bfd4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/init/funext.hlean
eba7eaf9cbe31e767311b5f24f0b11f91faae956
[ "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
10,545
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .trunc .equiv .ua open eq is_trunc sigma function is_equiv equiv prod unit prod.ops lift /- We now prove that funext follows from a couple of weaker-looking forms of function extensionality. This proof is originally due to Voevodsky; it has since been simplified by Peter Lumsdaine and Michael Shulman. -/ definition funext.{l k} := Π ⦃A : Type.{l}⦄ {P : A → Type.{k}} (f g : Π x, P x), is_equiv (@apd10 A P f g) -- Naive funext is the simple assertion that pointwise equal functions are equal. definition naive_funext := Π ⦃A : Type⦄ {P : A → Type} (f g : Πx, P x), (f ~ g) → f = g -- Weak funext says that a product of contractible types is contractible. definition weak_funext := Π ⦃A : Type⦄ (P : A → Type) [H: Πx, is_contr (P x)], is_contr (Πx, P x) definition weak_funext_of_naive_funext : naive_funext → weak_funext := (λ nf A P (Pc : Πx, is_contr (P x)), let c := λx, center (P x) in is_contr.mk c (λ f, have eq' : (λx, center (P x)) ~ f, from (λx, center_eq (f x)), have eq : (λx, center (P x)) = f, from nf A P (λx, center (P x)) f eq', eq ) ) /- The less obvious direction is that weak_funext implies funext (and hence all three are logically equivalent). The point is that under weak funext, the space of "pointwise homotopies" has the same universal property as the space of paths. -/ section universe variables l k parameters [wf : weak_funext.{l k}] {A : Type.{l}} {B : A → Type.{k}} (f : Π x, B x) definition is_contr_sigma_homotopy : is_contr (Σ (g : Π x, B x), f ~ g) := is_contr.mk (sigma.mk f (homotopy.refl f)) (λ dp, sigma.rec_on dp (λ (g : Π x, B x) (h : f ~ g), let r := λ (k : Π x, Σ y, f x = y), @sigma.mk _ (λg, f ~ g) (λx, pr1 (k x)) (λx, pr2 (k x)) in let s := λ g h x, @sigma.mk _ (λy, f x = y) (g x) (h x) in have t1 : Πx, is_contr (Σ y, f x = y), from (λx, !is_contr_sigma_eq), have t2 : is_contr (Πx, Σ y, f x = y), from !wf, have t3 : (λ x, @sigma.mk _ (λ y, f x = y) (f x) idp) = s g h, from @eq_of_is_contr (Π x, Σ y, f x = y) t2 _ _, have t4 : r (λ x, sigma.mk (f x) idp) = r (s g h), from ap r t3, have endt : sigma.mk f (homotopy.refl f) = sigma.mk g h, from t4, endt ) ) local attribute is_contr_sigma_homotopy [instance] parameters (Q : Π g (h : f ~ g), Type) (d : Q f (homotopy.refl f)) definition homotopy_ind (g : Πx, B x) (h : f ~ g) : Q g h := @transport _ (λ gh, Q (pr1 gh) (pr2 gh)) (sigma.mk f (homotopy.refl f)) (sigma.mk g h) (@eq_of_is_contr _ is_contr_sigma_homotopy _ _) d local attribute weak_funext [reducible] local attribute homotopy_ind [reducible] definition homotopy_ind_comp : homotopy_ind f (homotopy.refl f) = d := (@prop_eq_of_is_contr _ _ _ _ !eq_of_is_contr idp)⁻¹ ▸ idp end /- Now the proof is fairly easy; we can just use the same induction principle on both sides. -/ section universe variables l k local attribute weak_funext [reducible] theorem funext_of_weak_funext (wf : weak_funext.{l k}) : funext.{l k} := λ A B f g, let eq_to_f := (λ g' x, f = g') in let sim2path := homotopy_ind f eq_to_f idp in have t1 : sim2path f (homotopy.refl f) = idp, proof homotopy_ind_comp f eq_to_f idp qed, have t2 : apd10 (sim2path f (homotopy.refl f)) = (homotopy.refl f), proof ap apd10 t1 qed, have left_inv : apd10 ∘ (sim2path g) ~ id, proof (homotopy_ind f (λ g' x, apd10 (sim2path g' x) = x) t2) g qed, have right_inv : (sim2path g) ∘ apd10 ~ id, from (λ h, eq.rec_on h (homotopy_ind_comp f _ idp)), is_equiv.adjointify apd10 (sim2path g) left_inv right_inv definition funext_from_naive_funext : naive_funext → funext := compose funext_of_weak_funext weak_funext_of_naive_funext end section universe variables l private theorem ua_isequiv_postcompose {A B : Type.{l}} {C : Type} {w : A → B} [H0 : is_equiv w] : is_equiv (@compose C A B w) := let w' := equiv.mk w H0 in let eqinv : A = B := ((@is_equiv.inv _ _ _ (univalence A B)) w') in let eq' := equiv_of_eq eqinv in is_equiv.adjointify (@compose C A B w) (@compose C B A (is_equiv.inv w)) (λ (x : C → B), have eqretr : eq' = w', from (@right_inv _ _ (@equiv_of_eq A B) (univalence A B) w'), have invs_eq : (to_fun eq')⁻¹ = (to_fun w')⁻¹, from inv_eq eq' w' eqretr, have eqfin : (to_fun eq') ∘ ((to_fun eq')⁻¹ ∘ x) = x, from (λ p, (@eq.rec_on Type.{l} A (λ B' p', Π (x' : C → B'), (to_fun (equiv_of_eq p')) ∘ ((to_fun (equiv_of_eq p'))⁻¹ ∘ x') = x') B p (λ x', idp)) ) eqinv x, have eqfin' : (to_fun w') ∘ ((to_fun eq')⁻¹ ∘ x) = x, from eqretr ▸ eqfin, have eqfin'' : (to_fun w') ∘ ((to_fun w')⁻¹ ∘ x) = x, from invs_eq ▸ eqfin', eqfin'' ) (λ (x : C → A), have eqretr : eq' = w', from (@right_inv _ _ (@equiv_of_eq A B) (univalence A B) w'), have invs_eq : (to_fun eq')⁻¹ = (to_fun w')⁻¹, from inv_eq eq' w' eqretr, have eqfin : (to_fun eq')⁻¹ ∘ ((to_fun eq') ∘ x) = x, from (λ p, eq.rec_on p idp) eqinv, have eqfin' : (to_fun eq')⁻¹ ∘ ((to_fun w') ∘ x) = x, from eqretr ▸ eqfin, have eqfin'' : (to_fun w')⁻¹ ∘ ((to_fun w') ∘ x) = x, from invs_eq ▸ eqfin', eqfin'' ) -- We are ready to prove functional extensionality, -- starting with the naive non-dependent version. private definition diagonal [reducible] (B : Type) : Type := Σ xy : B × B, pr₁ xy = pr₂ xy private definition isequiv_src_compose {A B : Type} : @is_equiv (A → diagonal B) (A → B) (compose (pr₁ ∘ pr1)) := @ua_isequiv_postcompose _ _ _ (pr₁ ∘ pr1) (is_equiv.adjointify (pr₁ ∘ pr1) (λ x, sigma.mk (x , x) idp) (λx, idp) (λ x, sigma.rec_on x (λ xy, prod.rec_on xy (λ b c p, eq.rec_on p idp)))) private definition isequiv_tgt_compose {A B : Type} : is_equiv (compose (pr₂ ∘ pr1) : (A → diagonal B) → (A → B)) := begin refine @ua_isequiv_postcompose _ _ _ (pr2 ∘ pr1) _, fapply adjointify, { intro b, exact ⟨(b, b), idp⟩}, { intro b, reflexivity}, { intro a, induction a with q p, induction q, esimp at *, induction p, reflexivity} end theorem nondep_funext_from_ua {A : Type} {B : Type} : Π {f g : A → B}, f ~ g → f = g := (λ (f g : A → B) (p : f ~ g), let d := λ (x : A), @sigma.mk (B × B) (λ (xy : B × B), xy.1 = xy.2) (f x , f x) (eq.refl (f x, f x).1) in let e := λ (x : A), @sigma.mk (B × B) (λ (xy : B × B), xy.1 = xy.2) (f x , g x) (p x) in let precomp1 := compose (pr₁ ∘ sigma.pr1) in have equiv1 : is_equiv precomp1, from @isequiv_src_compose A B, have equiv2 : Π (x y : A → diagonal B), is_equiv (ap precomp1), from is_equiv.is_equiv_ap precomp1, have H' : Π (x y : A → diagonal B), pr₁ ∘ pr1 ∘ x = pr₁ ∘ pr1 ∘ y → x = y, from (λ x y, is_equiv.inv (ap precomp1)), have eq2 : pr₁ ∘ pr1 ∘ d = pr₁ ∘ pr1 ∘ e, from idp, have eq0 : d = e, from H' d e eq2, have eq1 : (pr₂ ∘ pr1) ∘ d = (pr₂ ∘ pr1) ∘ e, from ap _ eq0, eq1 ) end -- Now we use this to prove weak funext, which as we know -- implies (with dependent eta) also the strong dependent funext. theorem weak_funext_of_ua : weak_funext := (λ (A : Type) (P : A → Type) allcontr, let U := (λ (x : A), lift unit) in have pequiv : Π (x : A), P x ≃ unit, from (λ x, @equiv_unit_of_is_contr (P x) (allcontr x)), have psim : Π (x : A), P x = U x, from (λ x, eq_of_equiv_lift (pequiv x)), have p : P = U, from @nondep_funext_from_ua A Type P U psim, have tU' : is_contr (A → lift unit), from is_contr.mk (λ x, up ⋆) (λ f, nondep_funext_from_ua (λa, by induction (f a) with u;induction u;reflexivity)), have tU : is_contr (Π x, U x), from tU', have tlast : is_contr (Πx, P x), from p⁻¹ ▸ tU, tlast) -- In the following we will proof function extensionality using the univalence axiom definition funext_of_ua : funext := funext_of_weak_funext (@weak_funext_of_ua) variables {A : Type} {P : A → Type} {f g : Π x, P x} namespace funext theorem is_equiv_apd [instance] (f g : Π x, P x) : is_equiv (@apd10 A P f g) := funext_of_ua f g end funext open funext definition eq_equiv_homotopy : (f = g) ≃ (f ~ g) := equiv.mk apd10 _ definition eq_of_homotopy [reducible] : f ~ g → f = g := (@apd10 A P f g)⁻¹ definition apd10_eq_of_homotopy (p : f ~ g) : apd10 (eq_of_homotopy p) = p := right_inv apd10 p definition eq_of_homotopy_apd10 (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p definition eq_of_homotopy_idp (f : Π x, P x) : eq_of_homotopy (λx : A, idpath (f x)) = idpath f := is_equiv.left_inv apd10 idp definition naive_funext_of_ua : naive_funext := λ A P f g h, eq_of_homotopy h protected definition homotopy.rec_on [recursor] {Q : (f ~ g) → Type} (p : f ~ g) (H : Π(q : f = g), Q (apd10 q)) : Q p := right_inv apd10 p ▸ H (eq_of_homotopy p) protected definition homotopy.rec_on_idp [recursor] {Q : Π{g}, (f ~ g) → Type} {g : Π x, P x} (p : f ~ g) (H : Q (homotopy.refl f)) : Q p := homotopy.rec_on p (λq, eq.rec_on q H) definition eq_of_homotopy_inv {f g : Π x, P x} (H : f ~ g) : eq_of_homotopy (λx, (H x)⁻¹) = (eq_of_homotopy H)⁻¹ := begin apply homotopy.rec_on_idp H, rewrite [+eq_of_homotopy_idp] end definition eq_of_homotopy_con {f g h : Π x, P x} (H1 : f ~ g) (H2 : g ~ h) : eq_of_homotopy (λx, H1 x ⬝ H2 x) = eq_of_homotopy H1 ⬝ eq_of_homotopy H2 := begin apply homotopy.rec_on_idp H1, apply homotopy.rec_on_idp H2, rewrite [+eq_of_homotopy_idp] end
5ad80f970c55a5a03bdd4efd899855147691911f
4767244035cdd124e1ce3d0c81128f8929df6163
/data/fintype.lean
2fd98fd79ef4984e9358be97426ef70c1912dbe5
[ "Apache-2.0" ]
permissive
5HT/mathlib
b941fecacd31a9c5dd0abad58770084b8a1e56b1
40fa9ade2f5649569639608db5e621e5fad0cc02
refs/heads/master
1,586,978,681,358
1,546,681,764,000
1,546,681,764,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,956
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas data.vector2 data.equiv.encodable universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ e, match F, G, e with ⟨⟨s, nd⟩, h⟩, ⟨⟨s', nd'⟩, h'⟩, e' := begin change multiset.card s = multiset.card s' at e', revert nd nd' h h' e', refine quotient.induction_on₂ s s' (λ l₁ l₂ (nd₁ : l₁.nodup) (nd₂ : l₂.nodup) (h₁ : ∀ x, x ∈ l₁) (h₂ : ∀ x, x ∈ l₂) (e' : l₁.length = l₂.length), _), haveI := classical.dec_eq α, refine ⟨equiv.of_bijective ⟨_, _⟩⟩, { refine λ a, l₂.nth_le (l₁.index_of a) _, rw ← e', exact list.index_of_lt_length.2 (h₁ a) }, { intros a b h, simpa [h₁] using congr_arg l₁.nth (list.nodup_iff_nth_le_inj.1 nd₂ _ _ _ _ h) }, { have := classical.dec_eq β, refine λ b, ⟨l₁.nth_le (l₂.index_of b) _, _⟩, { rw e', exact list.index_of_lt_length.2 (h₂ b) }, { simp [nd₁] } } end end, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem fintype.univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem fintype.card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype instance (n : ℕ) : fintype (fin n) := ⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1), list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩, λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := by rw [fin.fintype]; simp [fintype.card, card, univ] instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.bijective.1 (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_card_gt_one [fintype α] (h : fintype.card α > 1) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.bijective.2 (this.1 (injective_comp e.symm.bijective.1 hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.bijective.1 (this.2 (surjective_comp e.symm.bijective.2 hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive finset.sum_attach_univ] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.bijective.1 h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.bijective.1 h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.bijective.1 h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.bijective.1 $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse end fintype
3f78d78e927e6f89832cd0c121eefbe7e88ccc19
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/explictOpenDeclIssue.lean
b021e1b04524da351047c69f954decf25c4ae6b9
[ "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
253
lean
namespace Foo inductive Bar | a : Bar | b : Bar #check Bar.a end Foo open Foo (Bar) #check Foo.Bar.a #check Bar.a def isA : Bar → Bool | Foo.Bar.a => true | Foo.Bar.b => false def isB : Bar → Bool | Bar.a => true | Bar.b => false
78cf4e3a05457c56bc9ccc385aae3815198344a6
48ee71c79a2d430812d2a0c56d69480c8e22fd71
/InsideOut/Syntax.lean
a3beb526f844b1fdca40bf57cf64028e1061f666
[ "MIT" ]
permissive
intsuc/inside-out
a49d08c04f992bdc28607345facd63597db28cab
5f14d511b8cab8703611d071027311f9967ec3a8
refs/heads/main
1,691,829,769,552
1,633,103,533,000
1,633,103,533,000
411,958,950
0
0
null
null
null
null
UTF-8
Lean
false
false
3,167
lean
inductive Typ where | func : Typ → Typ → Typ | bool : Typ | hole : Typ deriving Inhabited, BEq inductive Exp where | «let» : String → Typ → Exp → Exp → Exp | var : String → Exp | abs : String → Exp → Exp | app : Exp → Exp → Exp | ff : Exp | tt : Exp | iff : Exp → Exp → Exp → Exp | anno : Exp → Typ → Exp declare_syntax_cat typ declare_syntax_cat exp syntax typ " ⇒ " typ : typ syntax "bool" : typ syntax "?" : typ syntax "( " typ " )" : typ syntax term : typ syntax "let " ident " ∷ " typ " ≔ " exp " ; " exp : exp syntax:100 "# " ident : exp syntax "abs " ident " ⇒ " exp : exp syntax:65 exp:65 " ◁ " exp:66 : exp syntax "ff" : exp syntax "tt" : exp syntax "iff " exp " then " exp " else " exp : exp syntax exp " ∷ " typ : exp syntax "( " exp " )" : exp syntax term : exp macro_rules | `(typ| $t₁ ⇒ $t₂) => `(Typ.func $t₁ $t₂) | `(typ| bool) => `(Typ.bool) | `(typ| ?) => `(Typ.hole) | `(typ| ($t:typ)) => `(typ| $t) | `(typ| $t:term) => t open Lean Parser in macro_rules | `(exp| let $x₁ ∷ $t₂ ≔ $e₃; $e₄) => `(Exp.let $(quote x₁.getId.toString) $t₂ $e₃ $e₄) | `(exp| #$x₁) => `(Exp.var $(quote x₁.getId.toString)) | `(exp| abs $x₁ ⇒ $e₂) => `(Exp.abs $(quote x₁.getId.toString) $e₂) | `(exp| $e₁ ◁ $e₂) => `(Exp.app $e₁ $e₂) | `(exp| ff) => `(Exp.ff) | `(exp| tt) => `(Exp.tt) | `(exp| iff $e₁ then $e₂ else $e₃) => `(Exp.iff $e₁ $e₂ $e₃) | `(exp| $e₁ ∷ $t₂) => `(Exp.anno $e₁ $t₂) | `(exp| ($e:exp)) => `(exp| $e) | `(exp| $e:term) => e macro "typ " t:typ : term => t macro "exp " e:exp : term => e private def paren (p₁ p₂ : Nat) (s : String) : String := if p₂ < p₁ then s!"({s})" else s instance : ToString Typ where toString := let rec go (p : Nat) : Typ → String | typ t₁ ⇒ t₂ => paren p 0 s!"{go 1 t₁} ⇒ {go 0 t₂}" | typ bool => "bool" | typ ? => "?" go 0 instance : ToString Exp where toString := let rec go (p : Nat) : Exp → String | exp Exp.let x₁ t₂ e₃ e₄ => paren p 0 s!"let {x₁} ∷ {t₂} ≔ {go 0 e₃}; {go 0 e₄}" | exp Exp.var x₁ => s!"#{x₁}" | exp Exp.abs x₁ e₂ => paren p 0 s!"abs {x₁} ⇒ {go 0 e₂}" | exp e₁ ◁ e₂ => paren p 2 s!"{go 2 e₁} ◁ {go 3 e₂}" | exp ff => "ff" | exp tt => "tt" | exp iff e₁ then e₂ else e₃ => paren p 0 s!"iff {go 0 e₁} then {go 0 e₂} else {go 0 e₃}" | exp e₁ ∷ t₂ => paren p 1 s!"{go 1 e₁} ∷ {t₂}" go 0
93ec93119d98cfcf45cee16bf56be363194b355e
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast10.lean
97fab264855599cf39a5c518ec2f2dfecd3f32cd
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
176
lean
import data.list set_option blast.trace true definition lemma1 : true := by blast open perm definition lemma2 (l : list nat) : l ~ l := by blast print lemma1 print lemma2
f4593d1df9dcff4c818948c3acb9a0eb72610389
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/test/spread.lean
bd28395c73c9314d1ab029349a2d550039a26214
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
327
lean
import Mathlib.Tactic.Spread class Foo (α : Type) where bar : True class Something where bar : True instance : Something where bar := by trivial instance : Foo α where __ := instSomething -- include fields from `instSomething` example : Foo α := { __ := instSomething -- include fields from `instSomething` }
180367b947d6ad84ae49aaa9e08857f66cc24199
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_1260.lean
84fb63fc9023909b446d2feba2f374a6780727fe
[]
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
184
lean
variables {α : Type*} [inhabited α] #check default α variables (P : α → Prop) (h : ∃ x, P x) #check classical.some h example : P (classical.some h) := classical.some_spec h
c05d156a4e9c4ec16b98af69c072f1e7ff1839d8
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/cubical/squareover.lean
074720586a98b247381d59e7a0fdf29513cdaec1
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
16,761
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Squareovers -/ import .square universe u hott_theory namespace hott open eq hott.equiv hott.is_equiv hott.sigma namespace eq -- we give the argument B explicitly, because Lean would find (λa, B a) by itself, which -- makes the type uglier (of course the two terms are definitionally equal) inductive squareover {A : Type _} (B : A → Type _) {a₀₀ : A} {b₀₀ : B a₀₀} : Π{a₂₀ a₀₂ a₂₂ : A} {p₁₀ : a₀₀ = a₂₀} {p₁₂ : a₀₂ = a₂₂} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} (q₁₀ : b₀₀ =[p₁₀; B] b₂₀) (q₁₂ : b₀₂ =[p₁₂; B] b₂₂) (q₀₁ : b₀₀ =[p₀₁; B] b₀₂) (q₂₁ : b₂₀ =[p₂₁; B] b₂₂), Type _ | idsquareo : squareover ids idpo idpo idpo idpo variables {A : Type _} {A' : Type _} {B : A → Type _} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ : A} /-a₀₀-/ {p₁₀ : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₄₀ : B a₄₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {b₄₂ : B a₄₂} {b₀₄ : B a₀₄} {b₂₄ : B a₂₄} {b₄₄ : B a₄₄} /-b₀₀-/ {q₁₀ : b₀₀ =[p₁₀] b₂₀} /-b₂₀-/ {q₃₀ : b₂₀ =[p₃₀] b₄₀} /-b₄₀-/ {q₀₁ : b₀₀ =[p₀₁] b₀₂} /-t₁₁-/ {q₂₁ : b₂₀ =[p₂₁] b₂₂} /-t₃₁-/ {q₄₁ : b₄₀ =[p₄₁] b₄₂} /-b₀₂-/ {q₁₂ : b₀₂ =[p₁₂] b₂₂} /-b₂₂-/ {q₃₂ : b₂₂ =[p₃₂] b₄₂} /-b₄₂-/ {q₀₃ : b₀₂ =[p₀₃] b₀₄} /-t₁₃-/ {q₂₃ : b₂₂ =[p₂₃] b₂₄} /-t₃₃-/ {q₄₃ : b₄₂ =[p₄₃] b₄₄} /-b₀₄-/ {q₁₄ : b₀₄ =[p₁₄] b₂₄} /-b₂₄-/ {q₃₄ : b₂₄ =[p₃₄] b₄₄} /-b₄₄-/ @[hott] def squareo := @squareover A B a₀₀ @[hott, reducible] def idsquareo (b₀₀ : B a₀₀) := @squareover.idsquareo A B a₀₀ b₀₀ @[hott, reducible] def idso := @squareover.idsquareo A B a₀₀ b₀₀ @[hott] def apds (f : Πa, B a) (s : square p₁₀ p₁₂ p₀₁ p₂₁) : squareover B s (apd f p₁₀) (apd f p₁₂) (apd f p₀₁) (apd f p₂₁) := by induction s; constructor @[hott] def vrflo : squareover B vrfl q₁₀ q₁₀ idpo idpo := by induction q₁₀; exact idso @[hott] def hrflo : squareover B hrfl idpo idpo q₁₀ q₁₀ := by induction q₁₀; exact idso @[hott] def vdeg_squareover {p₁₀'} {s : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀} (r : change_path s q₁₀ = q₁₀') : squareover B (vdeg_square s) q₁₀ q₁₀' idpo idpo := by induction s; induction r; exact vrflo @[hott] def hdeg_squareover {p₀₁'} {s : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂} (r : change_path s q₀₁ = q₀₁') : squareover B (hdeg_square s) idpo idpo q₀₁ q₀₁' := by induction s; induction r; exact hrflo @[hott] def hconcato (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₃₁ : squareover B s₃₁ q₃₀ q₃₂ q₂₁ q₄₁) : squareover B (hconcat s₁₁ s₃₁) (q₁₀ ⬝o q₃₀) (q₁₂ ⬝o q₃₂) q₀₁ q₄₁ := by induction t₃₁; exact t₁₁ @[hott] def vconcato (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₁₃ : squareover B s₁₃ q₁₂ q₁₄ q₀₃ q₂₃) : squareover B (vconcat s₁₁ s₁₃) q₁₀ q₁₄ (q₀₁ ⬝o q₀₃) (q₂₁ ⬝o q₂₃) := by induction t₁₃; exact t₁₁ @[hott] def hinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (hinverse s₁₁) q₁₀⁻¹ᵒ q₁₂⁻¹ᵒ q₂₁ q₀₁ := by induction t₁₁; constructor @[hott] def vinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (vinverse s₁₁) q₁₂ q₁₀ q₀₁⁻¹ᵒ q₂₁⁻¹ᵒ := by induction t₁₁; constructor @[hott] def eq_vconcato {q : b₀₀ =[p₁₀] b₂₀} (r : q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q q₁₂ q₀₁ q₂₁ := by induction r; exact t₁₁ @[hott] def vconcato_eq {q : b₀₂ =[p₁₂] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₁₂ = q) : squareover B s₁₁ q₁₀ q q₀₁ q₂₁ := by induction r; exact t₁₁ @[hott] def eq_hconcato {q : b₀₀ =[p₀₁] b₀₂} (r : q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q q₂₁ := by induction r; exact t₁₁ @[hott] def hconcato_eq {q : b₂₀ =[p₂₁] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₂₁ = q) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q := by induction r; exact t₁₁ @[hott] def pathover_vconcato {p : a₀₀ = a₂₀} {sp : p = p₁₀} {q : b₀₀ =[p] b₂₀} (r : change_path sp q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (sp ⬝pv s₁₁) q q₁₂ q₀₁ q₂₁ := by induction sp; induction r; exact t₁₁ @[hott] def vconcato_pathover {p : a₀₂ = a₂₂} {sp : p₁₂ = p} {q : b₀₂ =[p] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₁₂ = q) : squareover B (s₁₁ ⬝vp sp) q₁₀ q q₀₁ q₂₁ := by induction sp; induction r; exact t₁₁ @[hott] def pathover_hconcato {p : a₀₀ = a₀₂} {sp : p = p₀₁} {q : b₀₀ =[p] b₀₂} (r : change_path sp q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (sp ⬝ph s₁₁) q₁₀ q₁₂ q q₂₁ := by induction sp; induction r; exact t₁₁ @[hott] def hconcato_pathover {p : a₂₀ = a₂₂} {sp : p₂₁ = p} {q : b₂₀ =[p] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₂₁ = q) : squareover B (s₁₁ ⬝hp sp) q₁₀ q₁₂ q₀₁ q := by induction sp; induction r; exact t₁₁ infix ` ⬝ho `:69 := hconcato --type using \tr infix ` ⬝vo `:70 := vconcato --type using \tr infix ` ⬝hop `:72 := hconcato_eq --type using \tr infix ` ⬝vop `:74 := vconcato_eq --type using \tr infix ` ⬝pho `:71 := eq_hconcato --type using \tr infix ` ⬝pvo `:73 := eq_vconcato --type using \tr @[hott] def square_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : square (con_tr p₁₀ p₂₁ b₀₀ ⬝ ap (λa : B a₂₀, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (transport2 _ (eq_of_square s₁₁) b₀₀ ⬝ con_tr _ _ _ ⬝ ap (λa : B a₀₂, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁) := by induction t₁₁; constructor variable (B) @[hott] def square_of_squareover_ids {b₀₀ b₀₂ b₂₀ b₂₂ : B a} {t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (so : squareover B ids (pathover_idp_of_eq B t) (pathover_idp_of_eq B b) (pathover_idp_of_eq B l) (pathover_idp_of_eq B r)) : square t b l r := begin let H := square_of_squareover so, hsimp at H, exact whisker_square (to_right_inv (pathover_equiv_tr_eq (refl a) _ _) _) (to_right_inv (pathover_equiv_tr_eq (refl a) _ _) _) (to_right_inv (pathover_equiv_tr_eq (refl a) _ _) _) (to_right_inv (pathover_equiv_tr_eq (refl a) _ _) _) H end @[hott] def squareover_ids_of_square {b₀₀ b₀₂ b₂₀ b₂₂ : B a} {t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (q : square t b l r) : squareover B ids (pathover_idp_of_eq B t) (pathover_idp_of_eq B b) (pathover_idp_of_eq B l) (pathover_idp_of_eq B r) := by induction q; constructor -- relating pathovers to squareovers variable {B} @[hott] def pathover_of_squareover' (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : pathover (λp, b₀₀ =[p] b₂₂) (q₁₀ ⬝o q₂₁) (eq_of_square s₁₁) (q₀₁ ⬝o q₁₂) := by induction t₁₁; constructor @[hott] def pathover_of_squareover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (t₁₁ : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ ⬝o q₂₁ =[s; λp, b₀₀ =[p] b₂₂] q₀₁ ⬝o q₁₂ := begin revert s t₁₁, refine equiv_rect' (square_equiv_eq p₁₀ p₁₂ p₀₁ p₂₁)⁻¹ᵉ (λa b, squareover B b q₁₀ q₁₂ q₀₁ q₂₁ → pathover (λp, b₀₀ =[p] b₂₂) (q₁₀ ⬝o q₂₁) a (q₀₁ ⬝o q₁₂)) _, intro s, exact pathover_of_squareover' end @[hott] def squareover_of_pathover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (r : q₁₀ ⬝o q₂₁ =[s; λp, b₀₀ =[p] b₂₂] q₀₁ ⬝o q₁₂) : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₁₂; hsimp at r; induction r; induction q₁₀; induction q₂₁; constructor @[hott] def pathover_top_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ =[eq_top_of_square s₁₁; λp, b₀₀ =[p] b₂₀] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction t₁₁; constructor @[hott] def squareover_of_pathover_top {s : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹} (r : q₁₀ =[s; λp, b₀₀ =[p] b₂₀] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B (square_of_eq_top s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₂₁; induction q₁₂; dsimp at r; induction r; induction q₁₀; constructor @[hott] def pathover_of_hdeg_squareover {p₀₁' : a₀₀ = a₀₂} {r : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (hdeg_square r) idpo idpo q₀₁ q₀₁') : q₀₁ =[r; λp, b₀₀ =[p] b₀₂] q₀₁' := by induction r; induction q₀₁'; exact (pathover_of_squareover' t)⁻¹ᵒ @[hott] def pathover_of_vdeg_squareover {p₁₀' : a₀₀ = a₂₀} {r : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀} (t : squareover B (vdeg_square r) q₁₀ q₁₀' idpo idpo) : q₁₀ =[r; λp, b₀₀ =[p] b₂₀] q₁₀' := by induction r; induction q₁₀'; exact pathover_of_squareover' t @[hott] def squareover_of_eq_top (r : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ := begin induction s₁₁, revert q₁₂ q₁₀ r, refine idp_rec_on q₂₁ _, clear q₂₁, intro q₁₂, refine idp_rec_on q₁₂ _, clear q₁₂, dsimp, intros, induction r, eapply idp_rec_on q₁₀, constructor end @[hott] def eq_top_of_squareover (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction r; reflexivity @[hott] def change_square {s₁₁'} (p : s₁₁ = s₁₁') (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁' q₁₀ q₁₂ q₀₁ q₂₁ := by induction p; exact r -- in Lean 2 defined using transport @[hott] lemma eq_of_vdeg_squareover {q₁₀' : b₀₀ =[p₁₀] b₂₀} (p : squareover B vrfl q₁₀ q₁₀' idpo idpo) : q₁₀ = q₁₀' := begin let H := square_of_squareover p, induction p₁₀, hsimp at H, let H' := eq_of_vdeg_square H, exact eq_of_fn_eq_fn (pathover_equiv_tr_eq _ _ _) H' end /- A version of eq_pathover where the type of the equality also varies -/ @[hott] lemma eq_pathover_dep {f g : Πa, B a} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : squareover B hrfl (pathover_idp_of_eq B q) (pathover_idp_of_eq B r) (apd f p) (apd g p)) : q =[p; λx, f x = g x] r := begin induction p, apply pathover_idp_of_eq, apply eq_of_vdeg_square, exact square_of_squareover_ids _ s end /- charcaterization of pathovers in pathovers -/ -- in this version the fibration (B) of the pathover does not depend on the variable (a) @[hott] lemma pathover_pathover {a' a₂' : A'} {p : a' = a₂'} {f g : A' → A} {b : Πa, B (f a)} {b₂ : Πa, B (g a)} {q : Π(a' : A'), f a' = g a'} (r : pathover B (b a') (q a') (b₂ a')) (r₂ : pathover B (b a₂') (q a₂') (b₂ a₂')) (s : squareover B (natural_square q p) r r₂ (pathover_ap B f (apd b p)) (pathover_ap B g (apd b₂ p))) : pathover (λa, pathover B (b a) (q a) (b₂ a)) r p r₂ := begin induction p, apply pathover_idp_of_eq, apply eq_of_vdeg_squareover, exact s end @[hott] def squareover_change_path_left {p₀₁' : a₀₀ = a₀₂} (r : p₀₁' = p₀₁) {q₀₁ : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (r ⬝ph s₁₁) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ (change_path r q₀₁) q₂₁ := by induction r; exact t @[hott] def squareover_change_path_right {p₂₁' : a₂₀ = a₂₂} (r : p₂₁' = p₂₁) {q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r⁻¹) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r q₂₁) := by induction r; exact t @[hott] def squareover_change_path_right' {p₂₁' : a₂₀ = a₂₂} (r : p₂₁ = p₂₁') {q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r⁻¹ q₂₁) := by induction r; exact t /- You can construct a square in a sigma-type by giving a squareover -/ @[hott] def square_dpair_eq_dpair {a₀₀ a₂₀ a₀₂ a₂₂ : A} {p₁₀ : a₀₀ = a₂₀} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} {p₁₂ : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {q₁₀ : b₀₀ =[p₁₀] b₂₀} {q₀₁ : b₀₀ =[p₀₁] b₀₂} {q₂₁ : b₂₀ =[p₂₁] b₂₂} {q₁₂ : b₀₂ =[p₁₂] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : square (sigma.dpair_eq_dpair p₁₀ q₁₀) (dpair_eq_dpair p₁₂ q₁₂) (dpair_eq_dpair p₀₁ q₀₁) (dpair_eq_dpair p₂₁ q₂₁) := by induction t₁₁; constructor @[hott] lemma sigma_square {v₀₀ v₂₀ v₀₂ v₂₂ : Σa, B a} {p₁₀ : v₀₀ = v₂₀} {p₀₁ : v₀₀ = v₀₂} {p₂₁ : v₂₀ = v₂₂} {p₁₂ : v₀₂ = v₂₂} (s₁₁ : square p₁₀..1 p₁₂..1 p₀₁..1 p₂₁..1) (t₁₁ : squareover B s₁₁ p₁₀..2 p₁₂..2 p₀₁..2 p₂₁..2) : square p₁₀ p₁₂ p₀₁ p₂₁ := begin induction v₀₀, induction v₂₀, induction v₀₂, induction v₂₂, rwr [(sigma_eq_eta p₁₀)⁻¹, (sigma_eq_eta p₀₁)⁻¹, (sigma_eq_eta p₁₂)⁻¹, (sigma_eq_eta p₂₁)⁻¹], exact square_dpair_eq_dpair s₁₁ t₁₁ end end eq end hott
d98eafb276818226aca4e9265f4236c2671b28f5
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/analysis/measure_theory/measurable_space.lean
43f047aa2848e3e38aab3deea0803d4dd090c689
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
25,853
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 Measurable spaces -- σ-algberas -/ import data.set.disjointed data.finset order.galois_connection data.set.countable open set lattice encodable local attribute [instance] classical.prop_decidable universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {s t u : set α} structure measurable_space (α : Type u) := (is_measurable : set α → Prop) (is_measurable_empty : is_measurable ∅) (is_measurable_compl : ∀s, is_measurable s → is_measurable (- s)) (is_measurable_Union : ∀f:ℕ → set α, (∀i, is_measurable (f i)) → is_measurable (⋃i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable (-s) := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.compl_iff : is_measurable (-s) ↔ is_measurable s := ⟨λ h, by simpa using h.compl, is_measurable.compl⟩ lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma encodable.Union_decode2 {α} [encodable β] (f : β → set α) : (⋃ b, f b) = ⋃ (i : ℕ) (b ∈ decode2 β i), f b := ext $ by simp [mem_decode2, exists_swap] @[elab_as_eliminator] lemma encodable.Union_decode2_cases {α} [encodable β] {f : β → set α} {C : set α → Prop} (H0 : C ∅) (H1 : ∀ b, C (f b)) {n} : C (⋃ b ∈ decode2 β n, f b) := match decode2 β n with | none := by simp; apply H0 | (some b) := by convert H1 b; simp [ext_iff] end lemma is_measurable.Union [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by rw encodable.Union_decode2; exact ‹measurable_space α›.is_measurable_Union (λ n, ⋃ b ∈ decode2 β n, f b) (λ n, encodable.Union_decode2_cases is_measurable.empty h) lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋃b∈s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋃₀ s) := by rw sUnion_eq_bUnion; exact is_measurable.bUnion hs h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by by_cases p; simp [h, hf, is_measurable.empty] lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := is_measurable.compl_iff.1 $ by rw compl_Inter; exact is_measurable.Union (λ b, (h b).compl) lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋂b∈s, f b) := is_measurable.compl_iff.1 $ by rw compl_bInter; exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋂₀ s) := by rw sInter_eq_bInter; exact is_measurable.bInter hs h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := by by_cases p; simp [h, hf, is_measurable.univ] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by rw union_eq_Union; exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by rw inter_eq_compl_compl_union_compl; exact (h₁.compl.union h₂.compl).compl lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl lemma is_measurable.sub {s₁ s₂ : set α} : is_measurable s₁ → is_measurable s₂ → is_measurable (s₁ - s₂) := is_measurable.diff lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ end @[extensionality] lemma measurable_space.ext : ∀{m₁ m₂ : measurable_space α}, (∀s:set α, m₁.is_measurable s ↔ m₂.is_measurable s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λm₁ m₂, m₁.is_measurable ≤ m₂.is_measurable, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀u∈s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀s, generate_measurable s → generate_measurable (-s) | union : ∀f:ℕ → set α, (∀n, generate_measurable (f n)) → generate_measurable (⋃i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable := generate_measurable s, is_measurable_empty := generate_measurable.empty s, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀t∈s, m.is_measurable t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} {m : measurable_space α} : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable t} = g) : measurable_space α := { is_measurable := λs, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by rw [← hs] {occs := occurrences.pos [1] }; refl def gi_generate_from : galois_insertion (@generate_from α) (λm, {t | @is_measurable α m t}) := { gc := assume s m, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λg hg, measurable_space.mk_of_closure g $ le_antisymm hg $ generate_from_le_iff.1 $ le_refl _, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable := λs, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (assume s, s.symm ▸ @is_measurable_empty _ ⊥) (assume s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.refl _ @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂m∈ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λm, {s | @is_measurable _ m s }) (infi m) ↔ _, by rw (@gi_generate_from α).gc.u_infi; simp; refl end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable := λs, m.is_measurable $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by rw [preimage_Union]; exact m.is_measurable_Union _ hf } @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable := λs, ∃s', m.is_measurable s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨-s', m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃i, s' i, m.is_measurable_Union _ (λi, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥:measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} :(⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤:measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (assume u ⟨v, (hv : generate_measurable s v), eq⟩, begin rw [←eq], clear eq, induction hv, case generate_measurable.basic : u hu { exact (generate_measurable.basic _ $ ⟨u, hu, rfl⟩) }, case generate_measurable.empty { simp [measurable_space.is_measurable_empty] }, case generate_measurable.compl : u hu ih { rw [preimage_compl], exact measurable_space.is_measurable_compl _ _ ih }, case generate_measurable.union : u hu ih { rw [preimage_Union], exact measurable_space.is_measurable_Union _ _ ih } end) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [m₁ : measurable_space α] [m₂ : measurable_space β] (f : α → β) : Prop := m₂ ≤ m₁.map f lemma measurable_id [measurable_space α] : measurable (@id α) := le_refl _ lemma measurable.preimage [measurable_space α] [measurable_space β] {f : α → β} (hf : measurable f) {s : set β} : is_measurable s → is_measurable (f ⁻¹' s) := hf _ lemma measurable.comp [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β} {g : β → γ} (hf : measurable f) (hg : measurable g) : measurable (g ∘ f) := le_trans hg $ map_mono hf lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀t∈s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := generate_from_le h lemma measurable.if [measurable_space α] [measurable_space β] {p : α → Prop} {h : decidable_pred p} {f g : α → β} (hp : is_measurable {a | p a}) (hf : measurable f) (hg : measurable g) : measurable (λa, if p a then f a else g a) := λ s hs, show is_measurable {a | (if p a then f a else g a) ∈ s}, begin convert (hp.inter $ hf s hs).union (hp.compl.inter $ hg s hs), exact ext (λ a, by by_cases p a; simp [h, mem_def]) end lemma measurable_const {α β} [measurable_space α] [measurable_space β] {a : α} : measurable (λb:β, a) := assume s hs, show is_measurable {b : β | a ∈ s}, from classical.by_cases (assume h : a ∈ s, by simp [h]; from is_measurable.univ) (assume h : a ∉ s, by simp [h]; from is_measurable.empty) end measurable_functions section constructions instance : measurable_space empty := ⊤ instance : measurable_space unit := ⊤ instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ section subtype instance {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap subtype.val lemma measurable_subtype_val [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λa:α, (f a).val) := hf.comp $ measurable_space.comap_le_iff_le_map.mp $ le_refl _ lemma measurable_subtype_mk [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable (λa, (f a).val)) : measurable f := measurable_space.comap_le_iff_le_map.mpr $ by rw [measurable_space.map_comp]; exact hf end subtype section prod instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd lemma measurable_fst [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).1) := hf.comp $ measurable_space.comap_le_iff_le_map.mp $ le_sup_left lemma measurable_snd [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).2) := hf.comp $ measurable_space.comap_le_iff_le_map.mp $ le_sup_right lemma measurable.prod [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf₁ : measurable (λa, (f a).1)) (hf₂ : measurable (λa, (f a).2)) : measurable f := sup_le (by rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp]; exact hf₁) (by rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp]; exact hf₂) lemma measurable_prod_mk [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λa:α, (f a, g a)) := measurable.prod hf hg lemma is_measurable_set_prod [measurable_space α] [measurable_space β] {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (set.prod s t) := is_measurable.inter (measurable_fst measurable_id _ hs) (measurable_snd measurable_id _ ht) end prod instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr instance {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions namespace measurable_space /-- Dynkin systems The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀{a}, has a → has (-a)) (has_Union_nat : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, has (f i)) → has (⋃i, f i)) theorem Union_decode2_disjoint_on {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) : pairwise (disjoint on λ i, ⋃ b ∈ decode2 β i, f b) := begin rintro i j ij x ⟨h₁, h₂⟩, revert h₁ h₂, simp, intros b₁ e₁ h₁ b₂ e₂ h₂, refine hd _ _ _ ⟨h₁, h₂⟩, cases encodable.mem_decode2.1 e₁, cases encodable.mem_decode2.1 e₂, exact mt (congr_arg _) ij end namespace dynkin_system @[extensionality] lemma ext : ∀{d₁ d₂ : dynkin_system α}, (∀s:set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has (-a) ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀i, d.has (f i)) : d.has (⋃i, f i) := by rw encodable.Union_decode2; exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by rw union_eq_Union; exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := d.has_compl_iff.1 begin simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λm₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable, has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀t∈s, generate_has t | empty : generate_has ∅ | compl : ∀{a}, generate_has a → generate_has (-a) | Union : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, generate_has (f i)) → generate_has (⋃i, f i) def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty s, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } def to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λt, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have -t ∩ s = (- (t ∩ s)) \ -s, from set.ext $ assume x, by by_cases x ∈ s; simp [h], by rw [this]; from d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _), has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union_left], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀t∈s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_inter {s : set (set α)} (hs : ∀t₁ t₂, t₁ ∈ s → t₂ ∈ s → t₁ ∩ t₂ ≠ ∅ → t₁ ∩ t₂ ∈ s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from if h : s₂ ∩ s₁ = ∅ then by rw [h]; exact generate_has.empty _ else generate_has.basic _ (hs _ _ hs₂ hs₁ h), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ lemma generate_from_eq {s : set (set α)} (hs : ∀t₁ t₂, t₁ ∈ s → t₂ ∈ s → t₁ ∩ t₂ ≠ ∅ → t₁ ∩ t₂ ∈ s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by rw [of_measurable_space_to_measurable_space]; from (generate_le _ $ assume t ht, is_measurable_generate_from ht)) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} {m : measurable_space α} (h_eq : m = generate_from s) (h_inter : ∀t₁ t₂, t₁ ∈ s → t₂ ∈ s → t₁ ∩ t₂ ≠ ∅ → t₁ ∩ t₂ ∈ s) (h_empty : C ∅) (h_basic : ∀t∈s, C t) (h_compl : ∀t, m.is_measurable t → C t → C (- t)) (h_union : ∀f:ℕ → set α, (∀i j, i ≠ j → f i ∩ f j ⊆ ∅) → (∀i, m.is_measurable (f i)) → (∀i, C (f i)) → C (⋃i, f i)) : ∀{t}, m.is_measurable t → C t := have eq : m.is_measurable = dynkin_system.generate_has s, by rw [h_eq, dynkin_system.generate_from_eq h_inter]; refl, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by rw [eq]; exact ht) (assume f hf ht, h_union f hf $ assume i, by rw [eq]; exact ht _) end measurable_space
1e4f911400c706c5298c647f60921e8867ad7f67
367134ba5a65885e863bdc4507601606690974c1
/src/data/seq/computation.lean
b787eff87ea673f3fbc545d8ef15695ab0ce73ad
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
37,948
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Coinductive formalization of unbounded computations. -/ import data.stream import tactic.basic 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 ~ := 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 ~ := 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 (function.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 (function.swap R) (function.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 (function.swap C) (λ cb ca h, cast (lift_rel_aux.swap _ _ _ _).symm $ H h) cb ca Hc b hb) end computation
a935abeaff3371ce8345336dfc9456107e72ae9e
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/topology/metric_space/gromov_hausdorff.lean
e90f51ecbf151bda027619d423819adfd8b5a30c
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,313
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.metric_space.closeds import set_theory.cardinal import topology.metric_space.gromov_hausdorff_realized import topology.metric_space.completion import topology.metric_space.kuratowski /-! # Gromov-Hausdorff distance This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduce the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance between all possible isometric embeddings of `X` and `Y` in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. ## Main results We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ noncomputable theory open_locale classical topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function nat Kuratowski_embedding open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section GH_space /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to `GH_space`. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop := λ x y, nonempty (x.val ≃ᵢ y.val) /-- This is indeed an equivalence relation -/ private lemma is_equivalence_isometry_rel : equivalence isometry_rel := ⟨λ x, ⟨isometric.refl _⟩, λ x y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩ /-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/ instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ definition GH_space : Type := quotient (isometry_rel.setoid) /-- Map any nonempty compact type to `GH_space` -/ definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space := ⟦nonempty_compacts.Kuratowski_embedding X⟧ instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp⟩⟩ /-- A metric space representative of any abstract point in `GH_space` -/ @[nolint has_inhabited_instance] definition GH_space.rep (p : GH_space) : Type := (quot.out p).val lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X] {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space X ↔ ∃ Ψ : X → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val := begin simp only [to_GH_space, quotient.eq], split, { assume h, rcases setoid.symm h with ⟨e⟩, have f := (Kuratowski_embedding.isometry X).isometric_on_range.trans e, use λ x, f x, split, { apply isometry_subtype_coe.comp f.isometry }, { rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe] } }, { rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩, have f := ((Kuratowski_embedding.isometry X).isometric_on_range.symm.trans isomΨ.isometric_on_range).symm, have E : (range Ψ ≃ᵢ (nonempty_compacts.Kuratowski_embedding X).val) = (p.val ≃ᵢ range (Kuratowski_embedding X)), by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl }, have g := cast E f, exact ⟨g⟩ } end lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val := begin refine eq_to_GH_space_iff.2 ⟨((λ x, x) : p.val → ℓ_infty_ℝ), _, subtype.range_coe⟩, apply isometry_subtype_coe end section local attribute [reducible] GH_space.rep instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) := by apply_instance instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) := by apply_instance instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) := by apply_instance end lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p := begin change to_GH_space (quot.out p).val = p, rw ← eq_to_GH_space, exact quot.out_eq p end /-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric. -/ lemma to_GH_space_eq_to_GH_space_iff_isometric {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] : to_GH_space X = to_GH_space Y ↔ nonempty (X ≃ᵢ Y) := ⟨begin simp only [to_GH_space, quotient.eq], assume h, rcases h with ⟨e⟩, have I : ((nonempty_compacts.Kuratowski_embedding X).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding Y).val) = ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have e' := cast I e, have f := (Kuratowski_embedding.isometry X).isometric_on_range, have g := (Kuratowski_embedding.isometry Y).isometric_on_range.symm, have h := (f.trans e').trans g, exact ⟨h⟩ end, begin rintros ⟨e⟩, simp only [to_GH_space, quotient.eq], have f := (Kuratowski_embedding.isometry X).isometric_on_range.symm, have g := (Kuratowski_embedding.isometry Y).isometric_on_range, have h := (f.trans e).trans g, have I : ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))) = ((nonempty_compacts.Kuratowski_embedding X).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding Y).val), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have h' := cast I h, exact ⟨h'⟩ end⟩ /-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/ instance : has_dist (GH_space) := { dist := λ x y, Inf $ (λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) } /-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/ def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X] [metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y) lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) := by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep] /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] {γ : Type w} [metric_space γ] {Φ : X → γ} {Ψ : Y → γ} (ha : isometry Φ) (hb : isometry Ψ) : GH_dist X Y ≤ Hausdorff_dist (range Φ) (range Ψ) := begin /- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not separable in general. We restrict to the union of the images of `X` and `Y` in `γ`, which is separable and therefore embeddable in `ℓ^∞(ℝ)`. -/ rcases exists_mem_of_nonempty X with ⟨xX, _⟩, let s : set γ := (range Φ) ∪ (range Ψ), let Φ' : X → subtype s := λ y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩, let Ψ' : Y → subtype s := λ y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩, have IΦ' : isometry Φ' := λ x y, ha x y, have IΨ' : isometry Ψ' := λ x y, hb x y, have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous), letI : metric_space (subtype s) := by apply_instance, haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 ‹is_compact s›⟩, haveI : nonempty (subtype s) := ⟨Φ' xX⟩, have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl }, have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl }, have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'), { rw [ΦΦ', ΨΨ', range_comp, range_comp], exact Hausdorff_dist_image (isometry_subtype_coe) }, rw this, -- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding let F := Kuratowski_embedding (subtype s), have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _), rw ← this, -- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `ℓ^∞(ℝ)`, and -- their Hausdorff distance is the same as in the original space. let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨(range_nonempty _).image _, (is_compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _, (is_compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, have AX : ⟦A⟧ = to_GH_space X, { rw eq_to_GH_space_iff, exact ⟨λ x, F (Φ' x), ⟨(Kuratowski_embedding.isometry _).comp IΦ', by rw range_comp⟩⟩ }, have BY : ⟦B⟧ = to_GH_space Y, { rw eq_to_GH_space_iff, exact ⟨λ x, F (Ψ' x), ⟨(Kuratowski_embedding.isometry _).comp IΨ', by rw range_comp⟩⟩ }, refine cInf_le ⟨0, begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _, apply (mem_image _ _ _).2, existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), simp [AX, BY] end /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y := begin inhabit X, inhabit Y, /- we only need to check the inequality `≤`, as the other one follows from the previous lemma. As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance in the optimal coupling is smaller than the Hausdorff distance of any coupling. First, we check this for couplings which already have small Hausdorff distance: in this case, the induced "distance" on `X ⊕ Y` belongs to the candidates family introduced in the definition of the optimal coupling, and the conclusion follows from the optimality of the optimal coupling within this family. -/ have A : ∀ p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y → Hausdorff_dist (p.val) (q.val) < diam (univ : set X) + 1 + diam (univ : set Y) → Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq bound, rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩, rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩, have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y), { rcases exists_mem_of_nonempty X with ⟨xX, _⟩, have : ∃ y ∈ range Ψ, dist (Φ xX) y < diam (univ : set X) + 1 + diam (univ : set Y), { rw Ψrange, have : Φ xX ∈ p.val := Φrange ▸ mem_range_self _, exact exists_dist_lt_of_Hausdorff_dist_lt this bound (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) }, rcases this with ⟨y, hy, dy⟩, rcases mem_range.1 hy with ⟨z, hzy⟩, rw ← hzy at dy, have DΦ : diam (range Φ) = diam (univ : set X) := Φisom.diam_range, have DΨ : diam (range Ψ) = diam (univ : set Y) := Ψisom.diam_range, calc diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xX) (Ψ z) + diam (range Ψ) : diam_union (mem_range_self _) (mem_range_self _) ... ≤ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) + diam (univ : set Y) : by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) } ... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring }, let f : X ⊕ Y → ℓ_infty_ℝ := λ x, match x with | inl y := Φ y | inr z := Ψ z end, let F : (X ⊕ Y) × (X ⊕ Y) → ℝ := λ p, dist (f p.1) (f p.2), -- check that the induced "distance" is a candidate have Fgood : F ∈ candidates X Y, { simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero, and_self, set.mem_set_of_eq], repeat {split}, { exact λ x y, calc F (inl x, inl y) = dist (Φ x) (Φ y) : rfl ... = dist x y : Φisom.dist_eq x y }, { exact λ x y, calc F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl ... = dist x y : Ψisom.dist_eq x y }, { exact λ x y, dist_comm _ _ }, { exact λ x y z, dist_triangle _ _ _ }, { exact λ x y, calc F (x, y) ≤ diam (range Φ ∪ range Ψ) : begin have A : ∀ z : X ⊕ Y, f z ∈ range Φ ∪ range Ψ, { assume z, cases z, { apply mem_union_left, apply mem_range_self }, { apply mem_union_right, apply mem_range_self } }, refine dist_le_diam_of_mem _ (A _) (A _), rw [Φrange, Ψrange], exact (p.2.2.union q.2.2).bounded, end ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } }, let Fb := candidates_b_of_candidates F Fgood, have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD Fb := Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood), refine le_trans this (le_of_forall_le_of_dense (λ r hr, _)), have I1 : ∀ x : X, (⨅ y, Fb (inl x, inr y)) ≤ r, { assume x, have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Ψ, by rwa [← Ψrange] at zq, rcases mem_range.1 this with ⟨y, hy⟩, calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux1 0) y ... = dist (Φ x) (Ψ y) : rfl ... = dist (f (inl x)) z : by rw hy ... ≤ r : le_of_lt hz }, have I2 : ∀ y : Y, (⨅ x, Fb (inl x, inr y)) ≤ r, { assume y, have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Φ, by rwa [← Φrange] at zq, rcases mem_range.1 this with ⟨x, hx⟩, calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux2 0) x ... = dist (Φ x) (Ψ y) : rfl ... = dist z (f (inr y)) : by rw hx ... ≤ r : le_of_lt hz }, simp [HD, csupr_le I1, csupr_le I2] }, /- Get the same inequality for any coupling. If the coupling is quite good, the desired inequality has been proved above. If it is bad, then the inequality is obvious. -/ have B : ∀ p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y → Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq, by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set X) + 1 + diam (univ : set Y), { exact A p q hp hq h }, { calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD (candidates_b_dist X Y) : Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b) ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le ... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } }, refine le_antisymm _ _, { apply le_cInf, { refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ }, { rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩, exact B p q hp hq } }, { exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) } end /-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X] (Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] : ∃ Φ : X → ℓ_infty_ℝ, ∃ Ψ : Y → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧ GH_dist X Y = Hausdorff_dist (range Φ) (range Ψ) := begin let F := Kuratowski_embedding (optimal_GH_coupling X Y), let Φ := F ∘ optimal_GH_injl X Y, let Ψ := F ∘ optimal_GH_injr X Y, refine ⟨Φ, Ψ, _, _, _⟩, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) }, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) }, { rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y), image_univ, ← Hausdorff_dist_optimal], exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm }, end /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ instance : metric_space GH_space := { dist_self := λ x, begin rcases exists_rep x with ⟨y, hy⟩, refine le_antisymm _ _, { apply cInf_le, { exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩}, { simp, existsi [y, y], simpa } }, { apply le_cInf, { exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ }, { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } }, end, dist_comm := λ x y, begin have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) = ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) := by { congr, funext, simp, rw Hausdorff_dist_comm }, simp only [dist, A, image_comp, image_swap_prod], end, eq_of_dist_eq_zero := λ x y hxy, begin /- To show that two spaces at zero distance are isometric, we argue that the distance is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance, i.e., they coincide. Therefore, the original spaces are isometric. -/ rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩, rw [← dist_GH_dist, hxy] at DΦΨ, have : range Φ = range Ψ, { have hΦ : is_compact (range Φ) := is_compact_range Φisom.continuous, have hΨ : is_compact (range Ψ) := is_compact_range Ψisom.continuous, apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm), { exact hΦ.is_closed }, { exact hΨ.is_closed }, { exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) hΦ.bounded hΨ.bounded } }, have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this, have eΨ := cast T Ψisom.isometric_on_range.symm, have e := Φisom.isometric_on_range.trans eΨ, rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], exact ⟨e⟩ end, dist_triangle := λ x y z, begin /- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space `γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff distance in `γ` to conclude. -/ let X := x.rep, let Y := y.rep, let Z := z.rep, let γ1 := optimal_GH_coupling X Y, let γ2 := optimal_GH_coupling Y Z, let Φ : Y → γ1 := optimal_GH_injr X Y, have hΦ : isometry Φ := isometry_optimal_GH_injr X Y, let Ψ : Y → γ2 := optimal_GH_injl Y Z, have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z, let γ := glue_space hΦ hΨ, letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ, have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ, calc dist x z = dist (to_GH_space X) (to_GH_space Z) : by rw [x.to_GH_space_rep, z.to_GH_space_rep] ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : GH_dist_le_Hausdorff_dist ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)) ((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z)) ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) + Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : begin refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) _ _), { exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)))).bounded }, { exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injr X Y)))).bounded } end ... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y))) ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y))) + Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z))) ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) : by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj] ... = Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) + Hausdorff_dist (range (optimal_GH_injl Y Z)) (range (optimal_GH_injr Y Z)) : by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ), Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)] ... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) : by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist] ... = dist x y + dist y z: by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep] end } end GH_space --section end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/ definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X] (p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val open topological_space namespace Gromov_Hausdorff section nonempty_compacts variables {X : Type u} [metric_space X] theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) : dist p.to_GH_space q.to_GH_space ≤ dist p q := begin have ha : isometry (coe : p.val → X) := isometry_subtype_coe, have hb : isometry (coe : q.val → X) := isometry_subtype_coe, have A : dist p q = Hausdorff_dist p.val q.val := rfl, have I : p.val = range (coe : p.val → X), by simp, have J : q.val = range (coe : q.val → X), by simp, rw [I, J] at A, rw A, exact GH_dist_le_Hausdorff_dist ha hb end lemma to_GH_space_lipschitz : lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) := lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist lemma to_GH_space_continuous : continuous (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) := to_GH_space_lipschitz.continuous end nonempty_compacts section /- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/ variables {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] -- we want to ignore these instances in the following theorem local attribute [instance, priority 10] sum.topological_space sum.uniform_space /-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. -/ theorem GH_dist_le_of_approx_subsets {s : set X} (Φ : s → Y) {ε₁ ε₂ ε₃ : ℝ} (hs : ∀ x : X, ∃ y ∈ s, dist x y ≤ ε₁) (hs' : ∀ x : Y, ∃ y : s, dist x (Φ y) ≤ ε₃) (H : ∀ x y : s, |dist x y - dist (Φ x) (Φ y)| ≤ ε₂) : GH_dist X Y ≤ ε₁ + ε₂ / 2 + ε₃ := begin refine le_of_forall_pos_le_add (λ δ δ0, _), rcases exists_mem_of_nonempty X with ⟨xX, _⟩, rcases hs xX with ⟨xs, hxs, Dxs⟩, have sne : s.nonempty := ⟨xs, hxs⟩, letI : nonempty s := sne.to_subtype, have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩), have : ∀ p q : s, |dist p q - dist (Φ p) (Φ q)| ≤ 2 * (ε₂/2 + δ) := λ p q, calc |dist p q - dist (Φ p) (Φ q)| ≤ ε₂ : H p q ... ≤ 2 * (ε₂/2 + δ) : by linarith, -- glue `X` and `Y` along the almost matching subsets letI : metric_space (X ⊕ Y) := glue_metric_approx (λ x:s, (x:X)) (λ x, Φ x) (ε₂/2 + δ) (by linarith) this, let Fl := @sum.inl X Y, let Fr := @sum.inr X Y, have Il : isometry Fl := isometry_emetric_iff_metric.2 (λ x y, rfl), have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λ x y, rfl), /- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and `Φ s`, and of `Φ s` and `Y` (in the coupling or, equivalently, in the original space). The first term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive constant where positivity is used to ensure that the coupling is really a metric space and not a premetric space on `X ⊕ Y`). -/ have : GH_dist X Y ≤ Hausdorff_dist (range Fl) (range Fr) := GH_dist_le_Hausdorff_dist Il Ir, have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s) + Hausdorff_dist (Fl '' s) (range Fr), { have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded, exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) }, have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) + Hausdorff_dist (Fr '' (range Φ)) (range Fr), { have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded, exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded ((range_nonempty _).image _) (range_nonempty _) (bounded.subset (image_subset_range _ _) B) B) }, have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁, { rw [← image_univ, Hausdorff_dist_image Il], have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs, refine Hausdorff_dist_le_of_mem_dist this (λ x hx, hs x) (λ x hx, ⟨x, mem_univ _, by simpa⟩) }, have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ, { refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩, rw ← xx', use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)], exact le_of_eq (glue_dist_glued_points (λ x:s, (x:X)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) }, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩, rcases mem_range.1 y_in_s' with ⟨x, xy⟩, use [Fl x, mem_image_of_mem _ x.2], rw [← yx', ← xy, dist_comm], exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Φ (ε₂/2 + δ) x) } }, have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃, { rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir], rcases exists_mem_of_nonempty Y with ⟨xY, _⟩, rcases hs' xY with ⟨xs', Dxs'⟩, have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs', refine Hausdorff_dist_le_of_mem_dist this (λ x hx, ⟨x, mem_univ _, by simpa⟩) (λ x _, _), rcases hs' x with ⟨y, Dy⟩, exact ⟨Φ y, mem_range_self _, Dy⟩ }, linarith end end --section /-- The Gromov-Hausdorff space is second countable. -/ instance : second_countable_topology GH_space := begin refine second_countable_of_countable_discretization (λ δ δpos, _), let ε := (2/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, have : ∀ p:GH_space, ∃ s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) := λ p, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos, -- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space -- `p.rep` representing `p`) choose s hs using this, have : ∀ p:GH_space, ∀ t:set (p.rep), finite t → ∃ n:ℕ, ∃ e:equiv t (fin n), true, { assume p t ht, letI : fintype t := finite.fintype ht, exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ }, choose N e hne using this, -- cardinality of the nice finite subset `s p` of `p.rep`, called `N p` let N := λ p:GH_space, N p (s p) (hs p).1, -- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p` let E := λ p:GH_space, e p (s p) (hs p).1, -- A function `F` associating to `p : GH_space` the data of all distances between points -- in the `ε`-dense set `s p`. let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) := λ p, ⟨N p, λ a b, floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))⟩, refine ⟨_, by apply_instance, F, λ p q hpq, _⟩, /- As the target space of F is countable, it suffices to show that two points `p` and `q` with `F p = F q` are at distance `≤ δ`. For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`) to `q.rep` (representing `q`) which is almost an isometry on `s p`, and with image `s q`. For this, we compose the identification of `s p` with `fin (N p)` and the inverse of the identification of `s q` with `fin (N q)`. Together with the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then composing with the canonical inclusion we get `Φ`. -/ have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λ x, Ψ x, -- Use the almost isometry `Φ` to show that `p.rep` and `q.rep` -- are within controlled Gromov-Hausdorff distance. have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε, { refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_of_lt hy⟩ }, show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).is_lt, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_of_lt hy }, show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y), by simp only [F, (E p).symm_apply_apply], have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y), by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl }, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by simp only [F, (E q).symm_apply_apply], have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, rw [Ap, Aq] at this, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc |ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| = |ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm ... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc |dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ : by { simp [ε], ring } end /-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the interesting direction that these conditions imply compactness. -/ lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ} (ulim : tendsto u at_top (𝓝 0)) (hdiam : ∀ p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C) (hcov : ∀ p ∈ t, ∀ n:ℕ, ∃ s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) : totally_bounded t := begin /- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`, up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/ refine metric.totally_bounded_of_finite_discretization (λ δ δpos, _), let ε := (1/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, -- choose `n` for which `u n < ε` rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩, have u_le_ε : u n ≤ ε, { have := hn n (le_refl _), simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this, exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) }, -- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n` have : ∀ p:GH_space, ∃ s : set (p.rep), ∃ N ≤ K n, ∃ E : equiv s (fin N), p ∈ t → univ ⊆ ⋃x∈s, ball x (u n), { assume p, by_cases hp : p ∉ t, { have : nonempty (equiv (∅ : set (p.rep)) (fin 0)), { rw ← fintype.card_eq, simp }, use [∅, 0, bot_le, choice (this)] }, { rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩, rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩, rw [hN, cardinal.nat_cast_le] at scard, have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin], cases quotient.exact this with E, use [s, N, scard, E], simp [hp, scover] } }, choose s N hN E hs using this, -- Define a function `F` taking values in a finite type and associating to `p` enough data -- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`. let M := (floor (ε⁻¹ * max C 0)).to_nat, let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) := λ p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩, λ a b, ⟨min M (floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))).to_nat, lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩, refine ⟨_, by apply_instance, (λ p, F p), _⟩, -- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq, have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λ x, Ψ x, have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε, { -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense -- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows -- from `GH_dist_le_of_approx_subsets` refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ }, show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_trans (le_of_lt hy) u_le_ε }, show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)), by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 : by { congr; apply (fin.ext_iff _ _).2; refl } ... = min M (floor (ε⁻¹ * dist x y)).to_nat : by simp only [F, (E p).symm_apply_apply] ... = (floor (ε⁻¹ * dist x y)).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (x : p.rep) y ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam p pt end, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 : by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] } ... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : by simp only [F, (E q).symm_apply_apply] ... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (Ψ x : q.rep) (Ψ y) ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam q qt end, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), { rw [Ap, Aq] at this, have D : 0 ≤ floor (ε⁻¹ * dist x y) := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] }, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc |ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| = |ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm ... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc |dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ/2 : by { simp [ε], ring } ... < δ : half_lt_self δpos end section complete /- We will show that a sequence `u n` of compact metric spaces satisfying `dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space. We need to exhibit the limiting compact metric space. For this, start from a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)` for all `n`, in a common metric space. Formally, this is done as follows. Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space `Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive limit of the `Y n`, and finally let `Z` be the completion of `Z0`. The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty compact metric space we are looking for. -/ variables (X : ℕ → Type) [∀ n, metric_space (X n)] [∀ n, compact_space (X n)] [∀ n, nonempty (X n)] /-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding of a type `A` in another metric space. -/ structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 := (space : Type) (metric : metric_space space) (embed : A → space) (isom : isometry embed) instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) := ⟨{ space := A, metric := by apply_instance, embed := id, isom := λ x y, rfl }⟩ /-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each `X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/ def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n { space := X 0, metric := by apply_instance, embed := id, isom := λ x y, rfl } (λ n Y, by letI : metric_space Y.space := Y.metric; exact { space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))), metric := by apply_instance, embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1)))) ∘ (optimal_GH_injr (X n) (X (n+1))), isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) }) /-- The Gromov-Hausdorff space is complete. -/ instance : complete_space GH_space := begin have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num }, -- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) this (λ u hu, _), -- `X n` is a representative of `u n` let X := λ n, (u n).rep, -- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n` let Y := aux_gluing X, letI : ∀ n, metric_space (Y n).space := λ n, (Y n).metric, have E : ∀ n : ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space := λ n, by { simp [Y, aux_gluing], refl }, let c := λ n, cast (E n), have ic : ∀ n, isometry (c n) := λ n x y, rfl, -- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction let f : Πn, (Y n).space → (Y n.succ).space := λ n, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))), have I : ∀ n, isometry (f n), { assume n, apply isometry.comp, { assume x y, refl }, { apply to_glue_l_isometry } }, -- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z` let Z0 := metric.inductive_limit I, let Z := uniform_space.completion Z0, let Φ := to_inductive_limit I, let coeZ := (coe : Z0 → Z), -- let `X2 n` be the image of `X n` in the space `Z` let X2 := λ n, range (coeZ ∘ (Φ n) ∘ (Y n).embed), have isom : ∀ n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed), { assume n, apply isometry.comp completion.coe_isometry _, apply isometry.comp _ (Y n).isom, apply to_inductive_limit_isometry }, -- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between -- `u n` and `u (n+1)`, therefore bounded by `1/2^n` have D2 : ∀ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n, { assume n, have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injl (X n) (X n.succ))), { change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injl (X n) (X n.succ))), simp only [X2, Φ], rw [← to_inductive_limit_commute I], simp only [f], rw ← to_glue_commute }, rw range_comp at X2n, have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injr (X n) (X n.succ))), by refl, rw range_comp at X2nsucc, rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist], { exact hu n n n.succ (le_refl n) (le_succ n) }, { apply isometry.comp completion.coe_isometry _, apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)), apply to_inductive_limit_isometry } }, -- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which -- is a metric space let X3 : ℕ → nonempty_compacts Z := λ n, ⟨X2 n, ⟨range_nonempty _, is_compact_range (isom n).continuous ⟩⟩, -- `X3 n` is a Cauchy sequence by construction, as the successive distances are -- bounded by `(1/2)^n` have : cauchy_seq X3, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λ n, _), rw one_mul, exact le_of_lt (D2 n) }, -- therefore, it converges to a limit `L` rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩, -- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L` have M : tendsto (λ n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) := tendsto.comp (to_GH_space_continuous.tendsto _) hL, -- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`. have : ∀ n, (X3 n).to_GH_space = u n, { assume n, rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], constructor, convert (isom n).isometric_on_range.symm, }, -- Finally, we have proved the convergence of `u n` exact ⟨L.to_GH_space, by simpa [this] using M⟩ end end complete--section end Gromov_Hausdorff --namespace
488d63e5ea599c72ba44ba9d338109da3e29d1f0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/coe4.lean
1b82da9d80e119f9f9b7717ff91db96d254608e7
[ "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
420
lean
universe variables u structure Functor (A : Type u) := (fn : A → A → A) (inj : ∀ x y, fn x = fn y → x = y) attribute [instance] definition coe_functor_to_fn (A : Type u) : has_coe_to_fun (Functor A) (λ f, A → A → A) := ⟨Functor.fn⟩ constant f : Functor nat #check f 0 1 set_option pp.coercions false #check f 0 1 set_option pp.coercions true #check f 0 1 set_option pp.all true #check f 0 1
f00c82488cd8d8ebbdeb71ba84eb1e55a8620296
367134ba5a65885e863bdc4507601606690974c1
/src/geometry/manifold/algebra/monoid.lean
b25681f234b434701fa8015db29f1442d214bb22
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,664
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.times_cont_mdiff /-! # Smooth monoid A smooth monoid is a monoid that is also a smooth manifold, in which multiplication is a smooth map of the product manifold `G` × `G` into `G`. In this file we define the basic structures to talk about smooth monoids: `has_smooth_mul` and its additive counterpart `has_smooth_add`. These structures are general enough to also talk about smooth semigroups. -/ section set_option old_structure_cmd true /-- 1. All smooth algebraic structures on `G` are `Prop`-valued classes that extend `smooth_manifold_with_corners I G`. This way we save users from adding both `[smooth_manifold_with_corners I G]` and `[has_smooth_mul I G]` to the assumptions. While many API lemmas hold true without the `smooth_manifold_with_corners I G` assumption, we're not aware of a mathematically interesting monoid on a topological manifold such that (a) the space is not a `smooth_manifold_with_corners`; (b) the multiplication is smooth at `(a, b)` in the charts `ext_chart_at I a`, `ext_chart_at I b`, `ext_chart_at I (a * b)`. 2. Because of `model_prod` we can't assume, e.g., that a `lie_group` is modelled on `𝓘(𝕜, E)`. So, we formulate the definitions and lemmas for any model. 3. While smoothness of an operation implies its continuity, lemmas like `has_continuous_mul_of_smooth` can't be instances becausen otherwise Lean would have to search for `has_smooth_mul I G` with unknown `𝕜`, `E`, `H`, and `I : model_with_corners 𝕜 E H`. If users needs `[has_continuous_mul G]` in a proof about a smooth monoid, then they need to either add `[has_continuous_mul G]` as an assumption (worse) or use `haveI` in the proof (better). -/ library_note "Design choices about smooth algebraic structures" /-- Basic hypothesis to talk about a smooth (Lie) additive monoid or a smooth additive semigroup. A smooth additive monoid over `α`, for example, is obtained by requiring both the instances `add_monoid α` and `has_smooth_add α`. -/ -- See note [Design choices about smooth algebraic structures] @[ancestor smooth_manifold_with_corners] class has_smooth_add {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [has_add G] [topological_space G] [charted_space H G] extends smooth_manifold_with_corners I G : Prop := (smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2)) /-- Basic hypothesis to talk about a smooth (Lie) monoid or a smooth semigroup. A smooth monoid over `G`, for example, is obtained by requiring both the instances `monoid G` and `has_smooth_mul I G`. -/ -- See note [Design choices about smooth algebraic structures] @[ancestor smooth_manifold_with_corners, to_additive] class has_smooth_mul {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [has_mul G] [topological_space G] [charted_space H G] extends smooth_manifold_with_corners I G : Prop := (smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2)) end section has_smooth_mul variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [has_mul G] [topological_space G] [charted_space H G] [has_smooth_mul I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type*} [topological_space M] [charted_space H' M] section variables (I) @[to_additive] lemma smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2) := has_smooth_mul.smooth_mul /-- If the multiplication is smooth, then it is continuous. This is not an instance for technical reasons, see note [Design choices about smooth algebraic structures]. -/ @[to_additive "If the addition is smooth, then it is continuous. This is not an instance for technical reasons, see note [Design choices about smooth algebraic structures]."] lemma has_continuous_mul_of_smooth : has_continuous_mul G := ⟨(smooth_mul I).continuous⟩ end @[to_additive] lemma smooth.mul {f : M → G} {g : M → G} (hf : smooth I' I f) (hg : smooth I' I g) : smooth I' I (f * g) := (smooth_mul I).comp (hf.prod_mk hg) @[to_additive] lemma smooth_mul_left {a : G} : smooth I I (λ b : G, a * b) := smooth_const.mul smooth_id @[to_additive] lemma smooth_mul_right {a : G} : smooth I I (λ b : G, b * a) := smooth_id.mul smooth_const @[to_additive] lemma smooth_on.mul {f : M → G} {g : M → G} {s : set M} (hf : smooth_on I' I f s) (hg : smooth_on I' I g s) : smooth_on I' I (f * g) s := ((smooth_mul I).comp_smooth_on (hf.prod_mk hg) : _) /- Instance of product -/ @[to_additive] instance has_smooth_mul.prod {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_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] [has_mul G] [has_smooth_mul I G] {E' : Type*} [normed_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'] [has_mul G'] [has_smooth_mul I' G'] : has_smooth_mul (I.prod I') (G×G') := { smooth_mul := ((smooth_fst.comp smooth_fst).smooth.mul (smooth_fst.comp smooth_snd)).prod_mk ((smooth_snd.comp smooth_fst).smooth.mul (smooth_snd.comp smooth_snd)), .. smooth_manifold_with_corners.prod G G' } variable (I) end has_smooth_mul section monoid variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [monoid G] [topological_space G] [charted_space H G] [has_smooth_mul I G] {H' : Type*} [topological_space H'] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {I' : model_with_corners 𝕜 E' H'} {G' : Type*} [monoid G'] [topological_space G'] [charted_space H' G'] [has_smooth_mul I' G'] lemma smooth_pow : ∀ n : ℕ, smooth I I (λ a : G, a ^ n) | 0 := by { simp only [pow_zero], exact smooth_const } | (k+1) := show smooth I I (λ (a : G), a * a ^ k), from smooth_id.mul (smooth_pow _) /-- Morphism of additive smooth monoids. -/ structure smooth_add_monoid_morphism (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (G : Type*) [topological_space G] [charted_space H G] [add_monoid G] [has_smooth_add I G] (G' : Type*) [topological_space G'] [charted_space H' G'] [add_monoid G'] [has_smooth_add I' G'] extends G →+ G' := (smooth_to_fun : smooth I I' to_fun) /-- Morphism of smooth monoids. -/ @[to_additive] structure smooth_monoid_morphism (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (G : Type*) [topological_space G] [charted_space H G] [monoid G] [has_smooth_mul I G] (G' : Type*) [topological_space G'] [charted_space H' G'] [monoid G'] [has_smooth_mul I' G'] extends G →* G' := (smooth_to_fun : smooth I I' to_fun) @[to_additive] instance : has_one (smooth_monoid_morphism I I' G G') := ⟨{ smooth_to_fun := smooth_const, to_monoid_hom := 1 }⟩ @[to_additive] instance : inhabited (smooth_monoid_morphism I I' G G') := ⟨1⟩ @[to_additive] instance : has_coe_to_fun (smooth_monoid_morphism I I' G G') := ⟨_, λ a, a.to_fun⟩ end monoid
35901d3d57eca870b4fc1abbd2c5be3fc8a11238
1437b3495ef9020d5413178aa33c0a625f15f15f
/analysis/topology/bounded_continuous_function.lean
79e8cc72bcbb786422fc5f882e01292b97f39e90
[ "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
23,162
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Mario Carneiro Type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ import analysis.normed_space data.real.cau_seq_filter noncomputable theory local attribute [instance] classical.decidable_inhabited classical.prop_decidable open set lattice filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- A locally uniform limit of continuous functions is continuous -/ lemma continuous_of_locally_uniform_limit_of_continuous [topological_space α] [metric_space β] {F : ℕ → α → β} {f : α → β} (L : ∀x:α, ∃s ∈ (nhds x).sets, ∀ε>(0:ℝ), ∃n, ∀y∈s, dist (F n y) (f y) ≤ ε) (C : ∀ n, continuous (F n)) : continuous f := continuous_topo_metric.2 $ λ x ε ε0, begin rcases L x with ⟨r, rx, hr⟩, rcases hr (ε/2/2) (half_pos $ half_pos ε0) with ⟨n, hn⟩, rcases continuous_topo_metric.1 (C n) x (ε/2) (half_pos ε0) with ⟨s, sx, hs⟩, refine ⟨_, (nhds x).inter_sets rx sx, _⟩, rintro y ⟨yr, ys⟩, calc dist (f y) (f x) ≤ dist (F n y) (F n x) + (dist (F n y) (f y) + dist (F n x) (f x)) : dist_triangle4_left _ _ _ _ ... < ε/2 + (ε/2/2 + ε/2/2) : add_lt_add_of_lt_of_le (hs _ ys) (add_le_add (hn _ yr) (hn _ (mem_of_nhds rx))) ... = ε : by rw [add_halves, add_halves] end /-- A uniform limit of continuous functions is continuous -/ lemma continuous_of_uniform_limit_of_continuous [topological_space α] {β : Type v} [metric_space β] {F : ℕ → α → β} {f : α → β} (L : ∀ε>(0:ℝ), ∃N, ∀y, dist (F N y) (f y) ≤ ε) : (∀ n, continuous (F n)) → continuous f := continuous_of_locally_uniform_limit_of_continuous $ λx, ⟨univ, by simpa [filter.univ_mem_sets] using L⟩ /-- A Lipschitz function is continuous -/ lemma continuous_of_lipschitz [metric_space α] [metric_space β] {C : ℝ} {f : α → β} (H : ∀x y, dist (f x) (f y) ≤ C * dist x y) : continuous f := continuous_of_metric.2 $ λ x ε ε0, have 0 < max C 1 := lt_of_lt_of_le zero_lt_one (le_max_right C 1), ⟨ε/max C 1, div_pos ε0 this, λ y hy, calc dist (f y) (f x) ≤ C * dist y x : H y x ... ≤ max C 1 * dist y x : mul_le_mul_of_nonneg_right (le_max_left C 1) dist_nonneg ... < ε : (lt_div_iff' this).1 hy⟩ /-- The type of bounded continuous functions from a topological space to a metric space -/ def bounded_continuous_function (α : Type u) (β : Type v) [topological_space α] [metric_space β] : Type (max u v) := {f : α → β // continuous f ∧ ∃C, ∀x y:α, dist (f x) (f y) ≤ C} local infixr ` →ᵇ `:25 := bounded_continuous_function namespace bounded_continuous_function section basics variables [topological_space α] [metric_space β] [metric_space γ] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_coe_to_fun (α →ᵇ β) := ⟨_, subtype.val⟩ lemma bounded_range : bounded (range f) := bounded_range_iff.2 f.2.2 /-- If a function is continuous on a compact space, it is automatically bounded, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_compact [compact_space α] (f : α → β) (hf : continuous f) : α →ᵇ β := ⟨f, hf, bounded_range_iff.1 $ by rw ← image_univ; exact bounded_of_compact (compact_image compact_univ hf)⟩ /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions -/ def mk_of_discrete [discrete_topology α] (f : α → β) (hf : ∃C, ∀x y, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨f, continuous_of_discrete_topology, hf⟩ /-- The uniform distance between two bounded continuous functions -/ instance : has_dist (α →ᵇ β) := ⟨λf g, Inf {C | C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩ lemma dist_eq : dist f g = Inf {C | C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl lemma dist_set_exists : ∃ C, C ≥ 0 ∧ ∀ x : α, dist (f x) (g x) ≤ C := begin refine if h : nonempty α then _ else ⟨0, le_refl _, λ x, h.elim ⟨x⟩⟩, cases h with x, rcases f.2 with ⟨_, Cf, hCf⟩, /- hCf : ∀ (x y : α), dist (f.val x) (f.val y) ≤ Cf -/ rcases g.2 with ⟨_, Cg, hCg⟩, /- hCg : ∀ (x y : α), dist (g.val x) (g.val y) ≤ Cg -/ let C := max 0 (dist (f x) (g x) + (Cf + Cg)), exact ⟨C, le_max_left _ _, λ y, calc dist (f y) (g y) ≤ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) : dist_triangle4_left _ _ _ _ ... ≤ dist (f x) (g x) + (Cf + Cg) : add_le_add_left (add_le_add (hCf _ _) (hCg _ _)) _ ... ≤ C : le_max_right _ _⟩ end /-- The pointwise distance is controlled by the distance between functions, by definition -/ lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g := le_cInf (ne_empty_iff_exists_mem.2 dist_set_exists) $ λb hb, hb.2 x @[extensionality] lemma ext (H : ∀x, f x = g x) : f = g := subtype.eq $ by ext; apply H /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superceded by the general result that the distance is nonnegative is metric spaces. -/ private lemma dist_nonneg' : 0 ≤ dist f g := le_cInf (ne_empty_iff_exists_mem.2 dist_set_exists) (λ C, and.left) /-- The distance between two functions is controlled by the supremum of the pointwise distances -/ lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C := ⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩ /-- On an empty space, bounded continuous functions are at distance 0 -/ lemma dist_zero_of_empty (e : ¬ nonempty α) : dist f g = 0 := le_antisymm ((dist_le (le_refl _)).2 $ λ x, e.elim ⟨x⟩) dist_nonneg' /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance : metric_space (α →ᵇ β) := { dist_self := λ f, le_antisymm ((dist_le (le_refl _)).2 $ λ x, by simp) dist_nonneg', eq_of_dist_eq_zero := λ f g hfg, by ext x; exact eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg), dist_comm := λ f g, by simp [dist_eq, dist_comm], dist_triangle := λ f g h, (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x, le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) } def const (b : β) : α →ᵇ β := ⟨λx, b, continuous_const, 0, by simp [le_refl]⟩ /-- If the target space is inhabited, so is the space of bounded continuous functions -/ instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const (default β)⟩ /-- The evaluation map is continuous, as a joint function of `u` and `x` -/ theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) := continuous_topo_metric.2 $ λ ⟨f, x⟩ ε ε0, /- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/ let ⟨s, sx, Hs⟩ := continuous_topo_metric.1 f.2.1 x (ε/2) (half_pos ε0) in /- s : set α, sx : s ∈ (nhds x).sets, Hs : ∀ (b : α), b ∈ s → dist (f.val b) (f.val x) < ε / 2 -/ ⟨set.prod (ball f (ε/2)) s, prod_mem_nhds_sets (ball_mem_nhds _ (half_pos ε0)) sx, λ ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x) ≤ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _ ... < ε/2 + ε/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) (Hs _ hy) ... = ε : add_halves _⟩ /-- In particular, when `x` is fixed, `f → f x` is continuous -/ theorem continuous_evalx {x : α} : continuous (λ f : α →ᵇ β, f x) := (continuous_id.prod_mk continuous_const).comp continuous_eval /-- When `f` is fixed, `x → f x` is also continuous, by definition -/ theorem continuous_evalf {f : α →ᵇ β} : continuous f := f.2.1 /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space (α →ᵇ β) := complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f), begin /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm), have fx_cau : ∀x, cauchy_seq (λn, f n x) := λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩, choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x), /- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (nhds (F x)) `F` is the desired limit function. Check that it is uniformly approximated by `f N` -/ have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N := λ x N, le_of_tendsto (by simp) (tendsto_dist tendsto_const_nhds (hF x)) (filter.mem_at_top_sets.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩), refine ⟨⟨F, _, _⟩, _⟩, { /- Check that `F` is continuous -/ refine continuous_of_uniform_limit_of_continuous (λ ε ε0, _) (λN, (f N).2.1), rcases tendsto_at_top_metric.1 b_lim ε ε0 with ⟨N, hN⟩, exact ⟨N, λy, calc dist (f N y) (F y) ≤ b N : fF_bdd y N ... ≤ dist (b N) 0 : begin simp, show b N ≤ abs(b N), from le_abs_self _ end ... ≤ ε : le_of_lt (hN N (le_refl N))⟩ }, { /- Check that `F` is bounded -/ rcases (f 0).2.2 with ⟨C, hC⟩, exact ⟨C + (b 0 + b 0), λ x y, calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) : dist_triangle4_left _ _ _ _ ... ≤ C + (b 0 + b 0) : add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0))⟩ }, { /- Check that `F` is close to `f N` in distance terms -/ refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim), exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) } end /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function -/ def comp (G : β → γ) (H : ∀x y, dist (G x) (G y) ≤ C * dist x y) (f : α →ᵇ β) : α →ᵇ γ := ⟨λx, G (f x), f.2.1.comp (continuous_of_lipschitz H), let ⟨D, hD⟩ := f.2.2 in ⟨max C 0 * D, λ x y, calc dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H _ _ ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg ... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩ /-- The composition operator (in the target) with a Lipschitz map is continuous -/ lemma continuous_comp {G : β → γ} (H : ∀x y, dist (G x) (G y) ≤ C * dist x y) : continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := continuous_of_lipschitz $ λ f g, (dist_le (mul_nonneg (le_max_right C 0) dist_nonneg)).2 $ λ x, calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H _ _ ... ≤ max C 0 * dist (f x) (g x) : mul_le_mul_of_nonneg_right (le_max_left C 0) (dist_nonneg) ... ≤ max C 0 * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) (le_max_right C 0) /-- Restriction (in the target) of a bounded continuous function taking values in a subset -/ def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s := ⟨λx, ⟨f x, H x⟩, continuous_subtype_mk _ f.2.1, f.2.2⟩ end basics section arzela_ascoli variables [topological_space α] [compact_space α] [metric_space β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} /- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing a common modulus of continuity and taking values in a compact set forms a compact subset for the topology of uniform convergence. In this section, we prove this theorem and several useful variations around it. -/ /-- First version, with pointwise equicontinuity and range in a compact space -/ theorem arzela_ascoli₁ [compact_space β] (A : set (α →ᵇ β)) (closed : is_closed A) (H : ∀ (x:α) (ε > 0), ∃U ∈ (nhds x).sets, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact A := begin refine compact_of_totally_bounded_is_closed _ closed, refine totally_bounded_of_finite_discretization (λ ε ε0, _), rcases dense ε0 with ⟨ε₁, ε₁0, εε₁⟩, let ε₂ := ε₁/2/2, /- We have to find a finite discretization of `u`, i.e., finite information that is sufficient to reconstruct `u` up to ε. This information will be provided by the values of `u` on a sufficiently dense set tα, slightly translated to fit in a finite ε₂-dense set tβ in the image. Such sets exist by compactness of the source and range. Then, to check that these data determine the function up to ε, one uses the control on the modulus of continuity to extend the closeness on tα to closeness everywhere. -/ have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0), have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β}, f ∈ A → dist (f y) (f z) < ε₂ := λ x, let ⟨U, nhdsU, hU⟩ := H x _ ε₂0, ⟨V, VU, openV, xV⟩ := mem_nhds_sets_iff.1 nhdsU in ⟨V, xV, openV, λy z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩, choose U hU using this, /- For all x, the set hU x is an open set containing x on which the elements of A fluctuate by at most ε₂. We extract finitely many of these sets that cover the whole space, by compactness -/ rcases compact_elim_finite_subcover_image compact_univ (λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1) with ⟨tα, _, ⟨_⟩, htα⟩, /- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/ rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0 with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI, /- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/ /- Associate to every point `y` in the space a nearby point `F y` in tβ -/ choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y), /- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/ /- Associate to every function a discrete approximation, mapping each point in `tα` to a point in `tβ` close to its true image by the function. -/ refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).fst⟩, _⟩, rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g, /- If two functions have the same approximation, then they are within distance ε -/ refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁, have : ∃x', x' ∈ tα ∧ x ∈ U x' := mem_bUnion_iff.1 (htα (mem_univ x)), rcases this with ⟨x', x'tα, hx'⟩, refine calc dist (f x) (g x) ≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _ ... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _) ... = ε₁ : by rw [add_halves, add_halves], { exact (hU x').2.2 _ _ hx' ((hU x').1) hf }, { exact (hU x').2.2 _ _ hx' ((hU x').1) hg }, { have F_f_g : F (f x') = F (g x') := (congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _), calc dist (f x') (g x') ≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _ ... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g ... < ε₂ + ε₂ : add_lt_add (hF (f x')).snd (hF (g x')).snd ... = ε₁/2 : add_halves _ } end /-- Second version, with pointwise equicontinuity and range in a compact subset -/ theorem arzela_ascoli₂ (s : set β) (hs : compact s) (A : set (α →ᵇ β)) (closed : is_closed A) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ (nhds x).sets, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact A := /- This version is deduced from the previous one by restricting to the compact type in the target, using compactness there and then lifting everything to the original space. -/ begin have M : ∀x y : s, dist (x : β) y ≤ 1 * dist x y := λ x y, ge_of_eq (one_mul _), let F : (α →ᵇ s) → α →ᵇ β := comp coe M, refine compact_of_is_closed_subset (compact_image (_ : compact (F ⁻¹' A)) (continuous_comp M)) closed (λ f hf, _), { haveI : compact_space s := compact_iff_compact_space.1 hs, refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed) (λ x ε ε0, bex.imp_right (λ U U_nhds hU y z hy hz f hf, _) (H x ε ε0)), calc dist (f y) (f z) = dist (F f y) (F f z) : rfl ... < ε : hU y z hy hz (F f) hf }, { let g := cod_restrict s f (λx, in_s f x hf), rw [show f = F g, by ext; refl] at hf ⊢, exact ⟨g, hf, rfl⟩ } end /-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but without closedness. The closure is then compact -/ theorem arzela_ascoli (s : set β) (hs : compact s) (A : set (α →ᵇ β)) (in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s) (H : ∀(x:α) (ε > 0), ∃U ∈ (nhds x).sets, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε) : compact (closure A) := /- This version is deduced from the previous one by checking that the closure of A, in addition to being closed, still satisfies the properties of compact range and equicontinuity -/ arzela_ascoli₂ s hs (closure A) is_closed_closure (λ f x hf, (mem_of_closed' (closed_of_compact _ hs)).2 $ λ ε ε0, let ⟨g, gA, dist_fg⟩ := mem_closure_iff'.1 hf ε ε0 in ⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩) (λ x ε ε0, show ∃ U ∈ (nhds x).sets, ∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε, begin refine bex.imp_right (λ U U_set hU y z hy hz f hf, _) (H x (ε/2) (half_pos ε0)), rcases mem_closure_iff'.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩, replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg, calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) : dist_triangle4_right _ _ _ _ ... < ε/2/2 + ε/2/2 + ε/2 : add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA) ... = ε : by rw [add_halves, add_halves] end) /- To apply the previous theorems, one needs to check the equicontinuity. An important instance is when the source space is a metric space, and there is a fixed modulus of continuity for all the functions in the set A -/ lemma equicontinuous_of_continuity_modulus {α : Type u} [metric_space α] (b : ℝ → ℝ) (b_lim : tendsto b (nhds 0) (nhds 0)) (A : set (α →ᵇ β)) (H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y)) (x:α) (ε : ℝ) (ε0 : ε > 0) : ∃U ∈ (nhds x).sets, ∀ (y z ∈ U) (f : α →ᵇ β), f ∈ A → dist (f y) (f z) < ε := begin rcases tendsto_nhds_of_metric.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩, refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y z hy hz f hf, _⟩, have : dist y z < δ := calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... < δ/2 + δ/2 : add_lt_add hy hz ... = δ : add_halves _, calc dist (f y) (f z) ≤ b (dist y z) : H y z f hf ... ≤ abs (b (dist y z)) : le_abs_self _ ... = dist (b (dist y z)) 0 : by simp [real.dist_eq] ... < ε : hδ (by simpa [real.dist_eq] using this), end end arzela_ascoli section normed_group /- In this section, if β is a normed group, then we show that the space of bounded continuous functions from α to β inherits a normed group structure, by using pointwise operations and checking that they are compatible with the uniform distance. -/ variables [topological_space α] [normed_group β] variables {f g : α →ᵇ β} {x : α} {C : ℝ} instance : has_zero (α →ᵇ β) := ⟨const 0⟩ @[simp] lemma coe_zero : (0 : α →ᵇ β) x = 0 := rfl instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩ lemma norm_def : ∥f∥ = dist f 0 := rfl lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc ∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right] ... ≤ ∥f∥ : dist_coe_le_dist _ /-- The norm of a function is controlled by the supremum of the pointwise norms -/ lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C := by simpa only [coe_zero, dist_zero_right] using @dist_le _ _ _ _ f 0 _ C0 /-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/ instance : has_add (α →ᵇ β) := ⟨λf g, ⟨λx, f x + g x, continuous_add f.2.1 g.2.1, (∥f∥ + ∥g∥) + (∥f∥ + ∥g∥), λ x y, have ∀x, dist (f x + g x) 0 ≤ ∥f∥ + ∥g∥ := λx, calc dist (f x + g x) 0 = ∥f x + g x∥ : dist_zero_right _ ... ≤ ∥f x∥ + ∥g x∥ : norm_triangle _ _ ... ≤ ∥f∥ + ∥g∥ : add_le_add (norm_coe_le_norm _) (norm_coe_le_norm _), calc dist (f x + g x) (f y + g y) ≤ dist (f x + g x) 0 + dist (f y + g y) 0 : dist_triangle_right _ _ _ ... ≤ (∥f∥ + ∥g∥) + (∥f∥ + ∥g∥) : add_le_add (this x) (this y) ⟩⟩ /-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/ instance : has_neg (α →ᵇ β) := ⟨λf, ⟨λx, -f x, continuous_neg f.2.1, begin have dn : ∀a b : β, dist (-a) (-b) = dist a b := λ a b, by rw [dist_eq_norm, neg_sub_neg, ← dist_eq_norm, dist_comm], simpa only [dn] using f.2.2 end⟩⟩ @[simp] lemma coe_add : (f + g) x = f x + g x := rfl @[simp] lemma coe_neg : (-f) x = - (f x) := rfl lemma forall_coe_zero_iff_zero : (∀x, f x = 0) ↔ f = 0 := ⟨@ext _ _ _ _ f 0, by rintro rfl _; refl⟩ instance : add_comm_group (α →ᵇ β) := { add_assoc := assume f g h, by ext; simp, zero_add := assume f, by ext; simp, add_zero := assume f, by ext; simp, add_left_neg := assume f, by ext; simp, add_comm := assume f g, by ext; simp, ..bounded_continuous_function.has_add, ..bounded_continuous_function.has_neg, ..bounded_continuous_function.has_zero } @[simp] lemma coe_diff : (f - g) x = f x - g x := rfl instance : normed_group (α →ᵇ β) := normed_group.of_add_dist (λ _, rfl) $ λ f g h, (dist_le dist_nonneg).2 $ λ x, le_trans (by rw [dist_eq_norm, dist_eq_norm, coe_add, coe_add, add_sub_add_right_eq_sub]) (dist_coe_le_dist x) lemma abs_diff_coe_le_dist : norm (f x - g x) ≤ dist f g := by rw normed_group.dist_eq; exact @norm_coe_le_norm _ _ _ _ (f-g) x lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g := sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2 end normed_group end bounded_continuous_function
70c5695ecc1d38fdd1d03fc87d408c7db3d2b9c4
618003631150032a5676f229d13a079ac875ff77
/src/topology/uniform_space/basic.lean
136a1f3fca876f9ba056f595b523a81d3e66c49e
[ "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
49,266
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter.lift import topology.separation open set filter classical open_locale classical topological_space set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) /-- An alternative constructor for `uniform_space.core`. This version unfolds various `filter`-related definitions. -/ def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, {p | prod.swap p ∈ r} ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] section prio set_option default_priority 100 -- see Note [default priority] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) end prio @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ /-- Construct a `uniform_space` from a `uniform_space.core`. -/ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } /-- Construct a `uniform_space` from a `u : uniform_space.core` and a `topological_space` structure that is equal to `u.to_topological_space`. -/ def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), comp_rel s s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, comp_rel t t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), comp_rel t t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is transitive. -/ lemma filter.tendsto.uniformity_trans {l : filter β} {f₁ f₂ f₃ : β → α} (h₁₂ : tendsto (λ x, (f₁ x, f₂ x)) l (𝓤 α)) (h₂₃ : tendsto (λ x, (f₂ x, f₃ x)) l (𝓤 α)) : tendsto (λ x, (f₁ x, f₃ x)) l (𝓤 α) := begin refine le_trans (le_lift' $ λ s hs, mem_map.2 _) comp_le_uniformity, filter_upwards [h₁₂ hs, h₂₃ hs], exact λ x hx₁₂ hx₂₃, ⟨_, hx₁₂, hx₂₃⟩ end /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is symmetric -/ lemma filter.tendsto.uniformity_symm {l : filter β} {f : β → α × α} (h : tendsto f l (𝓤 α)) : tendsto (λ x, ((f x).2, (f x).1)) l (𝓤 α) := tendsto_swap_uniformity.comp h /-- Relation `λ f g, tendsto (λ x, (f x, g x)) l (𝓤 α)` is reflexive. -/ lemma tendsto_diag_uniformity (f : β → α) (l : filter β) : tendsto (λ x, (f x, f x)) l (𝓤 α) := assume s hs, mem_map.2 $ univ_mem_sets' $ λ x, refl_mem_uniformity hs lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := tendsto_diag_uniformity (λ _, a) f lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (comp_rel s s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (comp_rel s s)) = ((𝓤 α).lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma filter.has_basis.mem_uniformity_iff {p : β → Prop} {s : β → set (α×α)} (h : (𝓤 α).has_basis p s) {t : set (α × α)} : t ∈ 𝓤 α ↔ ∃ i (hi : p i), ∀ a b, (a, b) ∈ s i → (a, b) ∈ t := h.mem_iff.trans $ by simp only [prod.forall, subset_def] lemma mem_nhds_uniformity_iff_right {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma mem_nhds_uniformity_iff_left {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.2 = x → p.1 ∈ s} ∈ 𝓤 α := by { rw [uniformity_eq_symm, mem_nhds_uniformity_iff_right], refl } lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff_right, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, (𝓤 α).sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_basis_uniformity' {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (x, y) ∈ s i}) := by { rw [nhds_eq_comap_uniformity], exact h.comap (prod.mk x) } lemma nhds_basis_uniformity {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {x : α} : (𝓝 x).has_basis p (λ i, {y | (y, x) ∈ s i}) := begin replace h := h.comap prod.swap, rw [← map_swap_eq_comap_swap, ← uniformity_eq_symm] at h, exact nhds_basis_uniformity' h end lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) := (nhds_basis_uniformity' (𝓤 α).basis_sets).eq_binfi lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := (nhds_basis_uniformity' (𝓤 α).basis_sets).mem_of_mem h lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (𝓝 a) (𝓝 b) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, (set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t).nonempty) : begin rw [lift'_inf_principal_eq, lift'_ne_bot_iff], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h, have ∃ t ∈ 𝓤 α, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /-! ### Uniform continuity -/ /-- A function `f : α → β` is *uniformly continuous* if `(f x, f y)` tends to the diagonal as `(x, y)` tends to the diagonal. In other words, if `x` is sufficiently close to `y`, then `f x` is close to `f y` no matter where `x` and `y` are located in `α`. -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, {x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := uniform_continuous_of_const $ λ _ _, rfl lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma filter.has_basis.uniform_continuous_iff [uniform_space β] {p : γ → Prop} {s : γ → set (α×α)} (ha : (𝓤 α).has_basis p s) {q : δ → Prop} {t : δ → set (β×β)} (hb : (𝓤 β).has_basis q t) {f : α → β} : uniform_continuous f ↔ ∀ i (hi : q i), ∃ j (hj : p j), ∀ x y, (x, y) ∈ s j → (f x, f y) ∈ t i := (ha.tendsto_iff hb).trans $ by simp only [prod.forall] end uniform_space end open_locale uniformity section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₁, exact (mem_singleton_iff.1 h).symm ▸ h₂ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ instance inhabited_uniform_space_core : inhabited (uniform_space.core α) := ⟨@uniform_space.to_core _ (default _)⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff_right, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff_right.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume ⟨x, hx⟩, have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, begin rw [infi_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, (@nhds_eq_uniformity α (u i) a).symm), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (le_infi $ assume i, to_topological_space_mono $ infi_le _ _) (have infi u = ⊤, from top_unique $ le_infi $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (infi u) = ⊤, from this.symm ▸ to_topological_space_top, this.symm ▸ le_top)) lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi, to_topological_space_infi], apply congr rfl, funext x, exact to_topological_space_infi end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space unit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod (𝓤 α) (𝓤 β)) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invariant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma uniform_continuous.prod_map [uniform_space δ] {f : α → γ} {g : β → δ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (prod.map f g) := (hf.comp uniform_continuous_fst).prod_mk (hg.comp uniform_continuous_snd) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables {δ' : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] [uniform_space δ'] local notation f `∘₂` g := function.bicompr f g def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry f) := iff.rfl lemma uniform_continuous₂.uniform_continuous {f : α → β → γ} (h : uniform_continuous₂ f) : uniform_continuous (uncurry f) := h lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [uniform_continuous₂, uncurry_curry] lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf lemma uniform_continuous₂.bicompl {f : α → β → γ} {ga : δ → α} {gb : δ' → β} (hf : uniform_continuous₂ f) (hga : uniform_continuous ga) (hgb : uniform_continuous gb) : uniform_continuous₂ (bicompl f ga gb) := hf.uniform_continuous.comp (hga.prod_map hgb) end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ comp_rel tα tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ comp_rel tβ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff_right.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff_right.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases hs.elim_finite_subcover_image hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂ /-! ### Expressing continuity properties in uniform spaces We reformulate the various continuity properties of functions taking values in a uniform space in terms of the uniformity in the target. Since the same lemmas (essentially with the same names) also exist for metric spaces and emetric spaces (reformulating things in terms of the distance or the edistance in the target), we put them in a namespace `uniform` here. In the metric and emetric space setting, there are also similar lemmas where one assumes that both the source and the target are metric spaces, reformulating things in terms of the distance on both sides. These lemmas are generally written without primes, and the versions where only the target is a metric space is primed. We follow the same convention here, thus giving lemmas with primes. -/ namespace uniform variables {α : Type*} {β : Type*} [uniform_space α] theorem tendsto_nhds_right {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (a, u x)) f (𝓤 α) := ⟨λ H, tendsto_left_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_right.1 hs)⟩ theorem tendsto_nhds_left {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ tendsto (λ x, (u x, a)) f (𝓤 α) := ⟨λ H, tendsto_right_nhds_uniformity.comp H, λ H s hs, by simpa [mem_of_nhds hs] using H (mem_nhds_uniformity_iff_left.1 hs)⟩ theorem continuous_at_iff'_right [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_right] theorem continuous_at_iff'_left [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := by rw [continuous_at, tendsto_nhds_left] theorem continuous_within_at_iff'_right [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f b, f x)) (nhds_within b s) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_right] theorem continuous_within_at_iff'_left [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ tendsto (λ x, (f x, f b)) (nhds_within b s) (𝓤 α) := by rw [continuous_within_at, tendsto_nhds_left] theorem continuous_on_iff'_right [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f b, f x)) (nhds_within b s) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_right] theorem continuous_on_iff'_left [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ b ∈ s, tendsto (λ x, (f x, f b)) (nhds_within b s) (𝓤 α) := by simp [continuous_on, continuous_within_at_iff'_left] theorem continuous_iff'_right [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f b, f x)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_right theorem continuous_iff'_left [topological_space β] {f : β → α} : continuous f ↔ ∀ b, tendsto (λ x, (f x, f b)) (𝓝 b) (𝓤 α) := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_left end uniform lemma filter.tendsto.congr_uniformity {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hf : tendsto f l (𝓝 b)) (hg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto g l (𝓝 b) := uniform.tendsto_nhds_right.2 $ (uniform.tendsto_nhds_right.1 hf).uniformity_trans hg lemma uniform.tendsto_congr {α β} [uniform_space β] {f g : α → β} {l : filter α} {b : β} (hfg : tendsto (λ x, (f x, g x)) l (𝓤 β)) : tendsto f l (𝓝 b) ↔ tendsto g l (𝓝 b) := ⟨λ h, h.congr_uniformity hfg, λ h, h.congr_uniformity hfg.uniformity_symm⟩
d05962c45b0063e8cf98f8b7878733f3d409244b
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/condensed/proetale_site.lean
52fe0a5b4abb3e275a59294e6324ad13b3cacf01
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,866
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import topology.category.Profinite import category_theory.sites.pretopology import category_theory.sites.sheaf_of_types import category_theory.sites.sheaf import category_theory.limits.opposites import algebra.category.Group import algebra.category.CommRing /-! # Proetale site of a point on Profinite Defines the proetale site of a point on the category of Profinite sets. -/ open category_theory category_theory.limits universes v u variables {C : Type u} [category.{v} C] -- This section is in the process of being generalised for mathlib, PR #7436. section to_generalise /-- A terminal Profinite type, which has the important property that morphisms to `X` are the same thing as elements of `X`. -/ def point : Profinite.{u} := Profinite.of punit /-- There is a (natural) bijection between morphisms `* ⟶ X` and elements of `X`. -/ def from_point {X : Profinite.{u}} : (point ⟶ X) ≃ X := { to_fun := λ f, f punit.star, inv_fun := λ x, ⟨λ _, x⟩, left_inv := λ x, by { ext ⟨⟩, refl }, right_inv := λ x, rfl} lemma from_point_apply {X Y : Profinite} (f : point ⟶ X) (g : X ⟶ Y) : g (from_point f) = from_point (f ≫ g) := rfl noncomputable def mk_pullback {X Y Z : Profinite.{u}} {f : X ⟶ Z} {g : Y ⟶ Z} {x : X} {y : Y} (h : f x = g y) : (pullback f g : Profinite) := from_point (pullback.lift (from_point.symm x) (from_point.symm y) (by { ext ⟨⟩, exact h })) lemma mk_pullback_fst {X Y Z : Profinite} {f : X ⟶ Z} {g : Y ⟶ Z} {x : X} {y : Y} {h : f x = g y} : (pullback.fst : pullback f g ⟶ _) (mk_pullback h) = x := begin rw [mk_pullback, from_point_apply], simp end lemma mk_pullback_snd {X Y Z : Profinite.{u}} {f : X ⟶ Z} {g : Y ⟶ Z} {x : X} {y : Y} {h : f x = g y} : (pullback.snd : pullback f g ⟶ _) (mk_pullback h) = y := begin rw [mk_pullback, from_point_apply], simp end end to_generalise /-- The proetale pretopology on Profinites. -/ def proetale_pretopology : pretopology.{u} Profinite.{u} := { coverings := λ X S, ∃ (ι : Type u) [fintype ι] (Y : ι → Profinite) (f : Π (i : ι), Y i ⟶ X), (∀ (x : X), ∃ i (y : Y i), f i y = x) ∧ S = presieve.of_arrows Y f, has_isos := λ X Y f i, begin refine ⟨punit, infer_instance, λ _, Y, λ _, f, _, _⟩, { introI x, refine ⟨punit.star, inv f x, _⟩, change (inv f ≫ f) x = x, rw is_iso.inv_hom_id, simp }, { rw presieve.of_arrows_punit }, end, pullbacks := λ X Y f S, begin rintro ⟨ι, hι, Z, g, hg, rfl⟩, refine ⟨ι, hι, λ i, pullback (g i) f, λ i, pullback.snd, _, _⟩, { intro y, rcases hg (f y) with ⟨i, z, hz⟩, exact ⟨i, mk_pullback hz, mk_pullback_snd⟩ }, { rw presieve.of_arrows_pullback } end, transitive := λ X S Ti, begin rintro ⟨ι, hι, Z, g, hY, rfl⟩ hTi, choose j hj W k hk₁ hk₂ using hTi, resetI, refine ⟨Σ (i : ι), j (g i) (presieve.of_arrows.mk _), infer_instance, λ i, W _ _ i.2, _, _, _⟩, { intro ij, exact k _ _ ij.2 ≫ g ij.1 }, { intro x, obtain ⟨i, y, rfl⟩ := hY x, obtain ⟨i', z, rfl⟩ := hk₁ (g i) (presieve.of_arrows.mk _) y, refine ⟨⟨i, i'⟩, z, rfl⟩ }, { have : Ti = λ Y f H, presieve.of_arrows (W f H) (k f H), { ext Y f H : 3, apply hk₂ }, rw this, apply presieve.of_arrows_bind }, end } def proetale_topology : grothendieck_topology.{u} Profinite.{u} := proetale_pretopology.to_grothendieck _ -- TODO (BM): We either want to generalise this topology to coherent? categories, or (less -- generally) appropriate concrete categories; or (even less generally) repeat the construction for -- ED and CH.
2de24c7dc7a25bde21f9f6988763144675677169
b561a44b48979a98df50ade0789a21c79ee31288
/src/Lean/Widget/InteractiveDiagnostic.lean
eb3d60f5bebd48665c48cb85858fb96218c6ed59
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,997
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Data.Lsp import Lean.Message import Lean.Elab.InfoTree import Lean.PrettyPrinter import Lean.Server.Utils import Lean.Server.Rpc.Basic import Lean.Widget.TaggedText import Lean.Widget.InteractiveCode import Lean.Widget.InteractiveGoal namespace Lean.Widget open Lsp Server deriving instance RpcEncoding with { withRef := true } for MessageData inductive MsgEmbed where | expr : CodeWithInfos → MsgEmbed | goal : InteractiveGoal → MsgEmbed | lazyTrace : Nat → Name → WithRpcRef MessageData → MsgEmbed deriving Inhabited namespace MsgEmbed -- TODO(WN): `deriving RpcEncoding` for `inductive` to replace the following hack @[reducible] def rpcPacketFor {β : outParam Type} (α : Type) [RpcEncoding α β] := β private inductive RpcEncodingPacket where | expr : TaggedText (rpcPacketFor CodeToken) → RpcEncodingPacket | goal : rpcPacketFor InteractiveGoal → RpcEncodingPacket | lazyTrace : Nat → Name → Lsp.RpcRef → RpcEncodingPacket deriving Inhabited, FromJson, ToJson instance : RpcEncoding MsgEmbed RpcEncodingPacket where rpcEncode a := match a with | expr t => return RpcEncodingPacket.expr (← rpcEncode t) | goal g => return RpcEncodingPacket.goal (← rpcEncode g) | lazyTrace col n t => return RpcEncodingPacket.lazyTrace col n (← rpcEncode t) rpcDecode a := match a with | RpcEncodingPacket.expr t => return expr (← rpcDecode t) | RpcEncodingPacket.goal g => return goal (← rpcDecode g) | RpcEncodingPacket.lazyTrace col n t => return lazyTrace col n (← rpcDecode t) end MsgEmbed /-- We embed objects in LSP diagnostics by storing them in the tag of an empty subtree (`text ""`). In other words, we terminate the `MsgEmbed`-tagged tree at embedded objects and instead store the pretty-printed embed (which can itself be a `TaggedText`) in the tag. -/ abbrev InteractiveDiagnostic := Lsp.DiagnosticWith (TaggedText MsgEmbed) namespace InteractiveDiagnostic open Lsp private abbrev RpcEncodingPacket := Lsp.DiagnosticWith (TaggedText MsgEmbed.RpcEncodingPacket) instance : RpcEncoding InteractiveDiagnostic RpcEncodingPacket where rpcEncode a := return { a with message := ← rpcEncode a.message } rpcDecode a := return { a with message := ← rpcDecode a.message } end InteractiveDiagnostic namespace InteractiveDiagnostic open MsgEmbed def toDiagnostic (diag : InteractiveDiagnostic) : Lsp.Diagnostic := { diag with message := prettyTt diag.message } where prettyTt (tt : TaggedText MsgEmbed) : String := let tt : TaggedText MsgEmbed := tt.rewrite fun | expr tt, _ => TaggedText.text tt.stripTags | goal g, _ => TaggedText.text (toString g.pretty) | lazyTrace _ _ _, subTt => subTt tt.stripTags end InteractiveDiagnostic private def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := { env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts, currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls } private inductive EmbedFmt /- Tags denote `Info` objects. -/ | expr (ctx : Elab.ContextInfo) (infos : Std.RBMap Nat Elab.Info compare) | goal (ctx : Elab.ContextInfo) (lctx : LocalContext) (g : MVarId) /- Some messages (in particular, traces) are too costly to print eagerly. Instead, we allow the user to expand sub-traces interactively. -/ | lazyTrace (nCtx : NamingContext) (ctx? : Option MessageDataContext) (cls : Name) (m : MessageData) /- Ignore any tags in this subtree. -/ | ignoreTags deriving Inhabited private abbrev MsgFmtM := StateT (Array EmbedFmt) IO open MessageData in /-- We first build a `Nat`-tagged `Format` with the most shallow tag, if any, in every branch indexing into the array of embedded objects. -/ private partial def msgToInteractiveAux (msgData : MessageData) : IO (Format × Array EmbedFmt) := go { currNamespace := Name.anonymous, openDecls := [] } none msgData #[] where pushEmbed (e : EmbedFmt) : MsgFmtM Nat := modifyGet fun es => (es.size, es.push e) withIgnoreTags (x : MsgFmtM Format) : MsgFmtM Format := do let fmt ← x let t ← pushEmbed EmbedFmt.ignoreTags return Format.tag t fmt go : NamingContext → Option MessageDataContext → MessageData → MsgFmtM Format | _, _, ofFormat fmt => withIgnoreTags fmt | _, _, ofLevel u => format u | _, _, ofName n => format n | nCtx, some ctx, ofSyntax s => withIgnoreTags (ppTerm (mkPPContext nCtx ctx) s) -- HACK: might not be a term | _, none, ofSyntax s => withIgnoreTags s.formatStx | _, none, ofExpr e => format (toString e) | nCtx, some ctx, ofExpr e => do let ci : Elab.ContextInfo := { env := ctx.env mctx := ctx.mctx fileMap := arbitrary options := ctx.opts currNamespace := nCtx.currNamespace openDecls := nCtx.openDecls } let (fmt, infos) ← ci.runMetaM ctx.lctx (formatInfos e) let t ← pushEmbed <| EmbedFmt.expr ci infos return Format.tag t fmt | _, none, ofGoal mvarId => pure $ "goal " ++ format (mkMVar mvarId) | nCtx, some ctx, ofGoal mvarId => withIgnoreTags <| ppGoal (mkPPContext nCtx ctx) mvarId | nCtx, _, withContext ctx d => go nCtx ctx d | _, ctx, withNamingContext nCtx d => go nCtx ctx d | nCtx, ctx, tagged t d => do -- We postfix trace contexts with `_traceCtx` in order to detect them in messages. if let Name.str cls "_traceCtx" _ := t then let f ← pushEmbed <| EmbedFmt.lazyTrace nCtx ctx cls d Format.tag f s!"[{cls}] (trace hidden)" else go nCtx ctx d | nCtx, ctx, nest n d => Format.nest n <$> go nCtx ctx d | nCtx, ctx, compose d₁ d₂ => do let d₁ ← go nCtx ctx d₁; let d₂ ← go nCtx ctx d₂; pure $ d₁ ++ d₂ | nCtx, ctx, group d => Format.group <$> go nCtx ctx d | nCtx, ctx, node ds => Format.nest 2 <$> ds.foldlM (fun r d => do let d ← go nCtx ctx d; pure $ r ++ Format.line ++ d) Format.nil partial def msgToInteractive (msgData : MessageData) (indent : Nat := 0) : IO (TaggedText MsgEmbed) := do let (fmt, embeds) ← msgToInteractiveAux msgData let tt := TaggedText.prettyTagged fmt indent /- Here we rewrite a `TaggedText Nat` corresponding to a whole `MessageData` into one where the tags are `TaggedText MsgEmbed`s corresponding to embedded objects with their subtree empty (`text ""`). In other words, we terminate the `MsgEmbed`-tagged -tree at embedded objects and store the pretty-printed embed (which can itself be a `TaggedText`) in the tag. -/ tt.rewriteM fun (n, col) subTt => match embeds.get! n with | EmbedFmt.expr ctx infos => let subTt' := tagExprInfos ctx infos subTt TaggedText.tag (MsgEmbed.expr subTt') (TaggedText.text subTt.stripTags) | EmbedFmt.goal ctx lctx g => -- TODO(WN): use InteractiveGoal types here unreachable! | EmbedFmt.lazyTrace nCtx ctx? cls m => let msg := match ctx? with | some ctx => MessageData.withNamingContext nCtx <| MessageData.withContext ctx m | none => MessageData.withNamingContext nCtx m TaggedText.tag (MsgEmbed.lazyTrace col cls ⟨msg⟩) (TaggedText.text subTt.stripTags) | EmbedFmt.ignoreTags => TaggedText.text subTt.stripTags /-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/ def msgToInteractiveDiagnostic (text : FileMap) (m : Message) : IO InteractiveDiagnostic := do let low : Lsp.Position := text.leanPosToLspPos m.pos let fullHigh := text.leanPosToLspPos <| m.endPos.getD m.pos let high : Lsp.Position := match m.endPos with | some endPos => /- Truncate messages that are more than one line long. This is a workaround to avoid big blocks of "red squiggly lines" on VS Code. TODO: should it be a parameter? -/ let endPos := if endPos.line > m.pos.line then { line := m.pos.line + 1, column := 0 } else endPos text.leanPosToLspPos endPos | none => low let range : Range := ⟨low, high⟩ let fullRange : Range := ⟨low, fullHigh⟩ let severity := match m.severity with | MessageSeverity.information => DiagnosticSeverity.information | MessageSeverity.warning => DiagnosticSeverity.warning | MessageSeverity.error => DiagnosticSeverity.error let source := "Lean 4" pure { range := range fullRange := fullRange severity? := severity source? := source message := ← msgToInteractive m.data } end Lean.Widget
adeffb9bee1abdc4ec558c4d7386baa9772b7a32
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/group_theory/subsemigroup/operations.lean
f7d869856605f1731ed082727c73abcb4506ee0c
[ "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
28,654
lean
/- Copyright (c) 2022 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov, Yakov Pechersky, Jireh Loreaux -/ import group_theory.subsemigroup.basic /-! # Operations on `subsemigroup`s In this file we define various operations on `subsemigroup`s and `mul_hom`s. ## Main definitions ### Conversion between multiplicative and additive definitions * `subsemigroup.to_add_subsemigroup`, `subsemigroup.to_add_subsemigroup'`, `add_subsemigroup.to_subsemigroup`, `add_subsemigroup.to_subsemigroup'`: convert between multiplicative and additive subsemigroups of `M`, `multiplicative M`, and `additive M`. These are stated as `order_iso`s. ### (Commutative) semigroup structure on a subsemigroup * `subsemigroup.to_semigroup`, `subsemigroup.to_comm_semigroup`: a subsemigroup inherits a (commutative) semigroup structure. ### Operations on subsemigroups * `subsemigroup.comap`: preimage of a subsemigroup under a semigroup homomorphism as a subsemigroup of the domain; * `subsemigroup.map`: image of a subsemigroup under a semigroup homomorphism as a subsemigroup of the codomain; * `subsemigroup.prod`: product of two subsemigroups `s : subsemigroup M` and `t : subsemigroup N` as a subsemigroup of `M × N`; ### Semigroup homomorphisms between subsemigroups * `subsemigroup.subtype`: embedding of a subsemigroup into the ambient semigroup. * `subsemigroup.inclusion`: given two subsemigroups `S`, `T` such that `S ≤ T`, `S.inclusion T` is the inclusion of `S` into `T` as a semigroup homomorphism; * `mul_equiv.subsemigroup_congr`: converts a proof of `S = T` into a semigroup isomorphism between `S` and `T`. * `subsemigroup.prod_equiv`: semigroup isomorphism between `s.prod t` and `s × t`; ### Operations on `mul_hom`s * `mul_hom.srange`: range of a semigroup homomorphism as a subsemigroup of the codomain; * `mul_hom.restrict`: restrict a semigroup homomorphism to a subsemigroup; * `mul_hom.cod_restrict`: restrict the codomain of a semigroup homomorphism to a subsemigroup; * `mul_hom.srange_restrict`: restrict a semigroup homomorphism to its range; ### Implementation notes This file follows closely `group_theory/submonoid/operations.lean`, omitting only that which is necessary. ## Tags subsemigroup, range, product, map, comap -/ variables {M N P σ : Type*} /-! ### Conversion to/from `additive`/`multiplicative` -/ section variables [has_mul M] /-- Subsemigroups of semigroup `M` are isomorphic to additive subsemigroups of `additive M`. -/ @[simps] def subsemigroup.to_add_subsemigroup : subsemigroup M ≃o add_subsemigroup (additive M) := { to_fun := λ S, { carrier := additive.to_mul ⁻¹' S, add_mem' := S.mul_mem' }, inv_fun := λ S, { carrier := additive.of_mul ⁻¹' S, mul_mem' := S.add_mem' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Additive subsemigroups of an additive semigroup `additive M` are isomorphic to subsemigroups of `M`. -/ abbreviation add_subsemigroup.to_subsemigroup' : add_subsemigroup (additive M) ≃o subsemigroup M := subsemigroup.to_add_subsemigroup.symm lemma subsemigroup.to_add_subsemigroup_closure (S : set M) : (subsemigroup.closure S).to_add_subsemigroup = add_subsemigroup.closure (additive.to_mul ⁻¹' S) := le_antisymm (subsemigroup.to_add_subsemigroup.le_symm_apply.1 $ subsemigroup.closure_le.2 add_subsemigroup.subset_closure) (add_subsemigroup.closure_le.2 subsemigroup.subset_closure) lemma add_subsemigroup.to_subsemigroup'_closure (S : set (additive M)) : (add_subsemigroup.closure S).to_subsemigroup' = subsemigroup.closure (multiplicative.of_add ⁻¹' S) := le_antisymm (add_subsemigroup.to_subsemigroup'.le_symm_apply.1 $ add_subsemigroup.closure_le.2 subsemigroup.subset_closure) (subsemigroup.closure_le.2 add_subsemigroup.subset_closure) end section variables {A : Type*} [has_add A] /-- Additive subsemigroups of an additive semigroup `A` are isomorphic to multiplicative subsemigroups of `multiplicative A`. -/ @[simps] def add_subsemigroup.to_subsemigroup : add_subsemigroup A ≃o subsemigroup (multiplicative A) := { to_fun := λ S, { carrier := multiplicative.to_add ⁻¹' S, mul_mem' := S.add_mem' }, inv_fun := λ S, { carrier := multiplicative.of_add ⁻¹' S, add_mem' := S.mul_mem' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Subsemigroups of a semigroup `multiplicative A` are isomorphic to additive subsemigroups of `A`. -/ abbreviation subsemigroup.to_add_subsemigroup' : subsemigroup (multiplicative A) ≃o add_subsemigroup A := add_subsemigroup.to_subsemigroup.symm lemma add_subsemigroup.to_subsemigroup_closure (S : set A) : (add_subsemigroup.closure S).to_subsemigroup = subsemigroup.closure (multiplicative.to_add ⁻¹' S) := le_antisymm (add_subsemigroup.to_subsemigroup.to_galois_connection.l_le $ add_subsemigroup.closure_le.2 subsemigroup.subset_closure) (subsemigroup.closure_le.2 add_subsemigroup.subset_closure) lemma subsemigroup.to_add_subsemigroup'_closure (S : set (multiplicative A)) : (subsemigroup.closure S).to_add_subsemigroup' = add_subsemigroup.closure (additive.of_mul ⁻¹' S) := le_antisymm (subsemigroup.to_add_subsemigroup'.to_galois_connection.l_le $ subsemigroup.closure_le.2 add_subsemigroup.subset_closure) (add_subsemigroup.closure_le.2 subsemigroup.subset_closure) end namespace subsemigroup open set /-! ### `comap` and `map` -/ variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The preimage of a subsemigroup along a semigroup homomorphism is a subsemigroup. -/ @[to_additive "The preimage of an `add_subsemigroup` along an `add_semigroup` homomorphism is an `add_subsemigroup`."] def comap (f : M →ₙ* N) (S : subsemigroup N) : subsemigroup M := { carrier := (f ⁻¹' S), mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw map_mul; exact mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : subsemigroup N) (f : M →ₙ* N) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : subsemigroup N} {f : M →ₙ* N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[to_additive] lemma comap_comap (S : subsemigroup P) (g : N →ₙ* P) (f : M →ₙ* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl @[simp, to_additive] lemma comap_id (S : subsemigroup P) : S.comap (mul_hom.id _) = S := ext (by simp) /-- The image of a subsemigroup along a semigroup homomorphism is a subsemigroup. -/ @[to_additive "The image of an `add_subsemigroup` along an `add_semigroup` homomorphism is an `add_subsemigroup`."] def map (f : M →ₙ* N) (S : subsemigroup M) : subsemigroup N := { carrier := (f '' S), mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, @mul_mem (subsemigroup M) M _ _ _ _ _ _ hx hy, by rw map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : M →ₙ* N) (S : subsemigroup M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : M →ₙ* N} {S : subsemigroup M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma mem_map_of_mem (f : M →ₙ* N) {S : subsemigroup M} {x : M} (hx : x ∈ S) : f x ∈ S.map f := mem_image_of_mem f hx @[to_additive] lemma apply_coe_mem_map (f : M →ₙ* N) (S : subsemigroup M) (x : S) : f x ∈ S.map f := mem_map_of_mem f x.prop @[to_additive] lemma map_map (g : N →ₙ* P) (f : M →ₙ* N) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ @[to_additive] lemma mem_map_iff_mem {f : M →ₙ* N} (hf : function.injective f) {S : subsemigroup M} {x : M} : f x ∈ S.map f ↔ x ∈ S := hf.mem_set_image @[to_additive] lemma map_le_iff_le_comap {f : M →ₙ* N} {S : subsemigroup M} {T : subsemigroup N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : M →ₙ* N) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap @[to_additive] lemma map_le_of_le_comap {T : subsemigroup N} {f : M →ₙ* N} : S ≤ T.comap f → S.map f ≤ T := (gc_map_comap f).l_le @[to_additive] lemma le_comap_of_map_le {T : subsemigroup N} {f : M →ₙ* N} : S.map f ≤ T → S ≤ T.comap f := (gc_map_comap f).le_u @[to_additive] lemma le_comap_map {f : M →ₙ* N} : S ≤ (S.map f).comap f := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_le {S : subsemigroup N} {f : M →ₙ* N} : (S.comap f).map f ≤ S := (gc_map_comap f).l_u_le _ @[to_additive] lemma monotone_map {f : M →ₙ* N} : monotone (map f) := (gc_map_comap f).monotone_l @[to_additive] lemma monotone_comap {f : M →ₙ* N} : monotone (comap f) := (gc_map_comap f).monotone_u @[simp, to_additive] lemma map_comap_map {f : M →ₙ* N} : ((S.map f).comap f).map f = S.map f := (gc_map_comap f).l_u_l_eq_l _ @[simp, to_additive] lemma comap_map_comap {S : subsemigroup N} {f : M →ₙ* N} : ((S.comap f).map f).comap f = S.comap f := (gc_map_comap f).u_l_u_eq_u _ @[to_additive] lemma map_sup (S T : subsemigroup M) (f : M →ₙ* N) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : M →ₙ* N) (s : ι → subsemigroup M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (S T : subsemigroup N) (f : M →ₙ* N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : M →ₙ* N) (s : ι → subsemigroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : M →ₙ* N) : (⊥ : subsemigroup M).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : M →ₙ* N) : (⊤ : subsemigroup N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma map_id (S : subsemigroup M) : S.map (mul_hom.id M) = S := ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩) section galois_coinsertion variables {ι : Type*} {f : M →ₙ* N} (hf : function.injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. "-/] def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) @[to_additive] lemma comap_map_eq_of_injective (S : subsemigroup M) : (S.map f).comap f = S := (gci_map_comap hf).u_l_eq _ @[to_additive] lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective @[to_additive] lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective @[to_additive] lemma comap_inf_map_of_injective (S T : subsemigroup M) : (S.map f ⊓ T.map f).comap f = S ⊓ T := (gci_map_comap hf).u_inf_l _ _ @[to_additive] lemma comap_infi_map_of_injective (S : ι → subsemigroup M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ @[to_additive] lemma comap_sup_map_of_injective (S T : subsemigroup M) : (S.map f ⊔ T.map f).comap f = S ⊔ T := (gci_map_comap hf).u_sup_l _ _ @[to_additive] lemma comap_supr_map_of_injective (S : ι → subsemigroup M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ @[to_additive] lemma map_le_map_iff_of_injective {S T : subsemigroup M} : S.map f ≤ T.map f ↔ S ≤ T := (gci_map_comap hf).l_le_l_iff @[to_additive] lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion section galois_insertion variables {ι : Type*} {f : M →ₙ* N} (hf : function.surjective f) include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_insertion` when `f` is surjective. "-/] def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩) @[to_additive] lemma map_comap_eq_of_surjective (S : subsemigroup N) : (S.comap f).map f = S := (gi_map_comap hf).l_u_eq _ @[to_additive] lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective @[to_additive] lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective @[to_additive] lemma map_inf_comap_of_surjective (S T : subsemigroup N) : (S.comap f ⊓ T.comap f).map f = S ⊓ T := (gi_map_comap hf).l_inf_u _ _ @[to_additive] lemma map_infi_comap_of_surjective (S : ι → subsemigroup N) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ @[to_additive] lemma map_sup_comap_of_surjective (S T : subsemigroup N) : (S.comap f ⊔ T.comap f).map f = S ⊔ T := (gi_map_comap hf).l_sup_u _ _ @[to_additive] lemma map_supr_comap_of_surjective (S : ι → subsemigroup N) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ @[to_additive] lemma comap_le_comap_iff_of_surjective {S T : subsemigroup N} : S.comap f ≤ T.comap f ↔ S ≤ T := (gi_map_comap hf).u_le_u_iff @[to_additive] lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion end subsemigroup namespace mul_mem_class variables {A : Type*} [has_mul M] [set_like A M] [hA : mul_mem_class A M] (S' : A) include hA /-- A submagma of a magma inherits a multiplication. -/ @[to_additive "An additive submagma of an additive magma inherits an addition.", priority 900] -- lower priority so other instances are found first instance has_mul : has_mul S' := ⟨λ a b, ⟨a.1 * b.1, mul_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive, priority 900] -- lower priority so later simp lemmas are used first; to appease simp_nf lemma coe_mul (x y : S') : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive, priority 900] -- lower priority so later simp lemmas are used first; to appease simp_nf lemma mk_mul_mk (x y : M) (hx : x ∈ S') (hy : y ∈ S') : (⟨x, hx⟩ : S') * ⟨y, hy⟩ = ⟨x * y, mul_mem hx hy⟩ := rfl @[to_additive] lemma mul_def (x y : S') : x * y = ⟨x * y, mul_mem x.2 y.2⟩ := rfl omit hA /-- A subsemigroup of a semigroup inherits a semigroup structure. -/ @[to_additive "An `add_subsemigroup` of an `add_semigroup` inherits an `add_semigroup` structure."] instance to_semigroup {M : Type*} [semigroup M] {A : Type*} [set_like A M] [mul_mem_class A M] (S : A) : semigroup S := subtype.coe_injective.semigroup coe (λ _ _, rfl) /-- A subsemigroup of a `comm_semigroup` is a `comm_semigroup`. -/ @[to_additive "An `add_subsemigroup` of an `add_comm_semigroup` is an `add_comm_semigroup`."] instance to_comm_semigroup {M} [comm_semigroup M] {A : Type*} [set_like A M] [mul_mem_class A M] (S : A) : comm_semigroup S := subtype.coe_injective.comm_semigroup coe (λ _ _, rfl) include hA /-- The natural semigroup hom from a subsemigroup of semigroup `M` to `M`. -/ @[to_additive "The natural semigroup hom from an `add_subsemigroup` of `add_semigroup` `M` to `M`."] def subtype : S' →ₙ* M := ⟨coe, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : (mul_mem_class.subtype S' : S' → M) = coe := rfl end mul_mem_class namespace subsemigroup variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The top subsemigroup is isomorphic to the semigroup. -/ @[to_additive "The top additive subsemigroup is isomorphic to the additive semigroup.", simps] def top_equiv : (⊤ : subsemigroup M) ≃* M := { to_fun := λ x, x, inv_fun := λ x, ⟨x, mem_top x⟩, left_inv := λ x, x.eta _, right_inv := λ _, rfl, map_mul' := λ _ _, rfl } @[simp, to_additive] lemma top_equiv_to_mul_hom : (top_equiv : _ ≃* M).to_mul_hom = mul_mem_class.subtype (⊤ : subsemigroup M) := rfl /-- A subsemigroup is isomorphic to its image under an injective function -/ @[to_additive "An additive subsemigroup is isomorphic to its image under an injective function"] noncomputable def equiv_map_of_injective (f : M →ₙ* N) (hf : function.injective f) : S ≃* S.map f := { map_mul' := λ _ _, subtype.ext (map_mul f _ _), ..equiv.set.image f S hf } @[simp, to_additive] lemma coe_equiv_map_of_injective_apply (f : M →ₙ* N) (hf : function.injective f) (x : S) : (equiv_map_of_injective S f hf x : N) = f x := rfl @[simp, to_additive] lemma closure_closure_coe_preimage {s : set M} : closure ((coe : closure s → M) ⁻¹' s) = ⊤ := eq_top_iff.2 $ λ x, subtype.rec_on x $ λ x hx _, begin refine closure_induction' _ (λ g hg, _) (λ g₁ g₂ hg₁ hg₂, _) hx, { exact subset_closure hg }, { exact subsemigroup.mul_mem _ }, end /-- Given `subsemigroup`s `s`, `t` of semigroups `M`, `N` respectively, `s × t` as a subsemigroup of `M × N`. -/ @[to_additive prod "Given `add_subsemigroup`s `s`, `t` of `add_semigroup`s `A`, `B` respectively, `s × t` as an `add_subsemigroup` of `A × B`."] def prod (s : subsemigroup M) (t : subsemigroup N) : subsemigroup (M × N) := { carrier := s ×ˢ t, mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : subsemigroup M) (t : subsemigroup N) : (s.prod t : set (M × N)) = s ×ˢ t := rfl @[to_additive mem_prod] lemma mem_prod {s : subsemigroup M} {t : subsemigroup N} {p : M × N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono {s₁ s₂ : subsemigroup M} {t₁ t₂ : subsemigroup N} (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht @[to_additive prod_top] lemma prod_top (s : subsemigroup M) : s.prod (⊤ : subsemigroup N) = s.comap (mul_hom.fst M N) := ext $ λ x, by simp [mem_prod, mul_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : subsemigroup N) : (⊤ : subsemigroup M).prod s = s.comap (mul_hom.snd M N) := ext $ λ x, by simp [mem_prod, mul_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subsemigroup M).prod (⊤ : subsemigroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subsemigroup M).prod (⊥ : subsemigroup N) = ⊥ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] /-- The product of subsemigroups is isomorphic to their product as semigroups. -/ @[to_additive prod_equiv "The product of additive subsemigroups is isomorphic to their product as additive semigroups"] def prod_equiv (s : subsemigroup M) (t : subsemigroup N) : s.prod t ≃* s × t := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } open mul_hom @[to_additive] lemma mem_map_equiv {f : M ≃* N} {K : subsemigroup M} {x : N} : x ∈ K.map f.to_mul_hom ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x @[to_additive] lemma map_equiv_eq_comap_symm (f : M ≃* N) (K : subsemigroup M) : K.map f.to_mul_hom = K.comap f.symm.to_mul_hom := set_like.coe_injective (f.to_equiv.image_eq_preimage K) @[to_additive] lemma comap_equiv_eq_map_symm (f : N ≃* M) (K : subsemigroup M) : K.comap f.to_mul_hom = K.map f.symm.to_mul_hom := (map_equiv_eq_comap_symm f.symm K).symm @[simp, to_additive] lemma map_equiv_top (f : M ≃* N) : (⊤ : subsemigroup M).map f.to_mul_hom = ⊤ := set_like.coe_injective $ set.image_univ.trans f.surjective.range_eq @[to_additive le_prod_iff] lemma le_prod_iff {s : subsemigroup M} {t : subsemigroup N} {u : subsemigroup (M × N)} : u ≤ s.prod t ↔ u.map (fst M N) ≤ s ∧ u.map (snd M N) ≤ t := begin split, { intros h, split, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 }, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, } end end subsemigroup namespace mul_hom open subsemigroup variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The range of a semigroup homomorphism is a subsemigroup. See Note [range copy pattern]. -/ @[to_additive "The range of an `add_hom` is an `add_subsemigroup`."] def srange (f : M →ₙ* N) : subsemigroup N := ((⊤ : subsemigroup M).map f).copy (set.range f) set.image_univ.symm @[simp, to_additive] lemma coe_srange (f : M →ₙ* N) : (f.srange : set N) = set.range f := rfl @[simp, to_additive] lemma mem_srange {f : M →ₙ* N} {y : N} : y ∈ f.srange ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma srange_eq_map (f : M →ₙ* N) : f.srange = (⊤ : subsemigroup M).map f := copy_eq _ @[to_additive] lemma map_srange (g : N →ₙ* P) (f : M →ₙ* N) : f.srange.map g = (g.comp f).srange := by simpa only [srange_eq_map] using (⊤ : subsemigroup M).map_map g f @[to_additive] lemma srange_top_iff_surjective {N} [has_mul N] {f : M →ₙ* N} : f.srange = (⊤ : subsemigroup N) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective /-- The range of a surjective semigroup hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_semigroup` hom is the whole of the codomain."] lemma srange_top_of_surjective {N} [has_mul N] (f : M →ₙ* N) (hf : function.surjective f) : f.srange = (⊤ : subsemigroup N) := srange_top_iff_surjective.2 hf @[to_additive] lemma mclosure_preimage_le (f : M →ₙ* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a semigroup hom of the subsemigroup generated by a set equals the subsemigroup generated by the image of the set. -/ @[to_additive "The image under an `add_semigroup` hom of the `add_subsemigroup` generated by a set equals the `add_subsemigroup` generated by the image of the set."] lemma map_mclosure (f : M →ₙ* N) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (mclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) /-- Restriction of a semigroup hom to a subsemigroup of the domain. -/ @[to_additive "Restriction of an add_semigroup hom to an `add_subsemigroup` of the domain."] def restrict {N : Type*} [has_mul N] [set_like σ M] [mul_mem_class σ M] (f : M →ₙ* N) (S : σ) : S →ₙ* N := f.comp (mul_mem_class.subtype S) @[simp, to_additive] lemma restrict_apply {N : Type*} [has_mul N] [set_like σ M] [mul_mem_class σ M] (f : M →ₙ* N) {S : σ} (x : S) : f.restrict S x = f x := rfl /-- Restriction of a semigroup hom to a subsemigroup of the codomain. -/ @[to_additive "Restriction of an `add_semigroup` hom to an `add_subsemigroup` of the codomain.", simps] def cod_restrict [set_like σ N] [mul_mem_class σ N] (f : M →ₙ* N) (S : σ) (h : ∀ x, f x ∈ S) : M →ₙ* S := { to_fun := λ n, ⟨f n, h n⟩, map_mul' := λ x y, subtype.eq (map_mul f x y) } /-- Restriction of a semigroup hom to its range interpreted as a subsemigroup. -/ @[to_additive "Restriction of an `add_semigroup` hom to its range interpreted as a subsemigroup."] def srange_restrict {N} [has_mul N] (f : M →ₙ* N) : M →ₙ* f.srange := f.cod_restrict f.srange $ λ x, ⟨x, rfl⟩ @[simp, to_additive] lemma coe_srange_restrict {N} [has_mul N] (f : M →ₙ* N) (x : M) : (f.srange_restrict x : N) = f x := rfl @[to_additive] lemma srange_restrict_surjective (f : M →ₙ* N) : function.surjective f.srange_restrict := λ ⟨_, ⟨x, rfl⟩⟩, ⟨x, rfl⟩ @[to_additive] lemma prod_map_comap_prod' {M' : Type*} {N' : Type*} [has_mul M'] [has_mul N'] (f : M →ₙ* N) (g : M' →ₙ* N') (S : subsemigroup N) (S' : subsemigroup N') : (S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ /-- The `mul_hom` from the preimage of a subsemigroup to itself. -/ @[to_additive "the `add_hom` from the preimage of an additive subsemigroup to itself.", simps] def subsemigroup_comap (f : M →ₙ* N) (N' : subsemigroup N) : N'.comap f →ₙ* N' := { to_fun := λ x, ⟨f x, x.prop⟩, map_mul' := λ x y, subtype.eq (@map_mul M N _ _ _ _ f x y) } /-- The `mul_hom` from a subsemigroup to its image. See `mul_equiv.subsemigroup_map` for a variant for `mul_equiv`s. -/ @[to_additive "the `add_hom` from an additive subsemigroup to its image. See `add_equiv.add_subsemigroup_map` for a variant for `add_equiv`s.", simps] def subsemigroup_map (f : M →ₙ* N) (M' : subsemigroup M) : M' →ₙ* M'.map f := { to_fun := λ x, ⟨f x, ⟨x, x.prop, rfl⟩⟩, map_mul' := λ x y, subtype.eq $ @map_mul M N _ _ _ _ f x y } @[to_additive] lemma subsemigroup_map_surjective (f : M →ₙ* N) (M' : subsemigroup M) : function.surjective (f.subsemigroup_map M') := by { rintro ⟨_, x, hx, rfl⟩, exact ⟨⟨x, hx⟩, rfl⟩ } end mul_hom namespace subsemigroup open mul_hom variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) @[simp, to_additive] lemma srange_fst [nonempty N] : (fst M N).srange = ⊤ := (fst M N).srange_top_of_surjective $ prod.fst_surjective @[simp, to_additive] lemma srange_snd [nonempty M] : (snd M N).srange = ⊤ := (snd M N).srange_top_of_surjective $ prod.snd_surjective @[to_additive] lemma prod_eq_top_iff [nonempty M] [nonempty N] {s : subsemigroup M} {t : subsemigroup N} : s.prod t = ⊤ ↔ s = ⊤ ∧ t = ⊤ := by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, ← srange_eq_map, srange_fst, srange_snd] /-- The semigroup hom associated to an inclusion of subsemigroups. -/ @[to_additive "The `add_semigroup` hom associated to an inclusion of subsemigroups."] def inclusion {S T : subsemigroup M} (h : S ≤ T) : S →ₙ* T := (mul_mem_class.subtype S).cod_restrict _ (λ x, h x.2) @[simp, to_additive] lemma range_subtype (s : subsemigroup M) : (mul_mem_class.subtype s).srange = s := set_like.coe_injective $ (coe_srange _).trans $ subtype.range_coe @[to_additive] lemma eq_top_iff' : S = ⊤ ↔ ∀ x : M, x ∈ S := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ end subsemigroup namespace mul_equiv variables [has_mul M] [has_mul N] {S T : subsemigroup M} /-- Makes the identity isomorphism from a proof that two subsemigroups of a multiplicative semigroup are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subsemigroups of an additive semigroup are equal."] def subsemigroup_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } -- this name is primed so that the version to `f.range` instead of `f.srange` can be unprimed. /-- A semigroup homomorphism `f : M →ₙ* N` with a left-inverse `g : N → M` defines a multiplicative equivalence between `M` and `f.srange`. This is a bidirectional version of `mul_hom.srange_restrict`. -/ @[to_additive /-" An additive semigroup homomorphism `f : M →+ N` with a left-inverse `g : N → M` defines an additive equivalence between `M` and `f.srange`. This is a bidirectional version of `add_hom.srange_restrict`. "-/, simps {simp_rhs := tt}] def of_left_inverse (f : M →ₙ* N) {g : N → M} (h : function.left_inverse g f) : M ≃* f.srange := { to_fun := f.srange_restrict, inv_fun := g ∘ (mul_mem_class.subtype f.srange), left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := mul_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.srange_restrict } /-- A `mul_equiv` `φ` between two semigroups `M` and `N` induces a `mul_equiv` between a subsemigroup `S ≤ M` and the subsemigroup `φ(S) ≤ N`. See `mul_hom.subsemigroup_map` for a variant for `mul_hom`s. -/ @[to_additive "An `add_equiv` `φ` between two additive semigroups `M` and `N` induces an `add_equiv` between a subsemigroup `S ≤ M` and the subsemigroup `φ(S) ≤ N`. See `add_hom.add_subsemigroup_map` for a variant for `add_hom`s.", simps] def subsemigroup_map (e : M ≃* N) (S : subsemigroup M) : S ≃* S.map e.to_mul_hom := { to_fun := λ x, ⟨e x, _⟩, inv_fun := λ x, ⟨e.symm x, _⟩, -- we restate this for `simps` to avoid `⇑e.symm.to_equiv x` ..e.to_mul_hom.subsemigroup_map S, ..e.to_equiv.image S } end mul_equiv
8f1483e2cd5016b0c4abb43f5af3a5e2d94cb80d
dd24e6c3b8dc14dc504f8a906fc04c51e4312e6b
/src/instructor/lectures/lecture_10.lean
f30eef286f3ca74d12a3e4d2eb98ecb18a937b01
[]
no_license
njeyasingh/CS-2120
dd781a90dd0645b74e61cee1813483fb7cb4a111
b3356f665a246f295b3f1e6d61901bfca331810d
refs/heads/main
1,693,294,711,274
1,635,188,659,000
1,635,188,659,000
399,945,420
0
0
null
null
null
null
UTF-8
Lean
false
false
11,175
lean
/- In today's class, we'll continue with our exploration of the proposition, "false", its elimination rule, and their vital uses in logical reasoning: especially in - proof of ¬P by negation - proof of P by false elimination Here are the inference rules in display notation: NEGATION INTRODUCTION The first, proof by negation, says that from a proof of P → false you can derive a proof of ¬P. Indeed! It's definitional. Recall: def not (P : Prop) := P → false. (P : Prop) (np : P → false) --------------------------- [by defn'n] (pf : ¬P) This rule is the foundation for "proof by negation." To prove ¬P you first assume P, is true, then you show that in this context you can derive a contradiction. What you have then shown, of course, is P → false. So, to prove ¬P, assume P and show that in this context there is a contradiction. This is proof by negation. It is not to be confused with proof by contradition, which is a different thing entirely. (Proof by contradiction. You can use this approach to a proposition, P, by assuming ¬P and showing that this assumption leads to a contradiction. That proves ¬¬P. Then you use the *indepedent* axiom of negation elimination to infer P from ¬¬P.) FALSE ELIMINATION The second rule says that if you have a proof of false and any other proposition, P, the logic is useless and so you might as well just admit that P is true. Why is the logic useless? Well, if false is true then there's no longer a difference! In this situation, tHere's sense in reasoning any further, and you can just dismiss it. A contradiction makes a logic inconsistent. (P : Prop) (f : false) ---------------------- (false_elim f) (pf : P) -/ /- We covered the relatively simpler notion of negation introduction last time, so today we will start by focusing on false elimination. Understanding why it's not magic and in fact makes perfect sense takes a bit of thought. -/ /- To make sense of false elimination, think in terms of case analysis. Proof by case analysis says that if the truth of some proposition, Y, follows from *any possible form of proof* of X, then you've proved X → Y. If X is a disjunction, P ∨ Q (so now you want to prove P ∨ Q → Y) you must consider two cases: one where P is assumed true and one where Q is assumed true. If X is a proposition with just one form of proof (e.g., the proposition, true), there's just one case to consider. -/ -- two cases example : true ∨ false → true := begin assume h, cases h, assumption, -- context has exact proof contradiction, -- context has contradiction end -- one case example : true → true := begin assume t, cases t, -- just one case exact true.intro, end /- How many cases must you consider if you putatively have a putative proof of false? ZERO! To consider *all* cases you need consider exactly zero cases. Proving all cases when the number of cases is zero is trivial, so the conclusion *follows*. -/ example : false → false := begin assume f, cases f, -- case analysis: there are no cases! end /- In fact, it doesn't matter what your conclusion is: it will always be true in a context in which you have a proof of false. And this makes sense, because if you have a proof of false, then false is true, so whether a given proposition is true or false, it's true, because even if it's false, well, false is true, so it's also true! -/ theorem false_elim : ∀ (P : Prop), false → P := begin assume P, assume f, cases f, end /- This, then, is the general principle for false elimination: ANYTHING FOLLOWS FROM FALSE. This principle gives you a powerful way to prove any proposition is true (conditional on your having a proof that can't exist). The theorem states that if you're given any proposition, P, and a proof, f, of false, then in that context, you can return a proof of P by using false elimination. The only problem with this super-power is that in reality, there is no proof of false, so there's no real danger of any old proposition being automatically true! The rule of false elimination tells you that if you're in a situation that can't happen, then no worries, be happy, you're done (just use false elimination). -/ /- The elimination principle for false is called false.elim in Lean. If you are given or can derive a proof, f, of false, then all you have to do to finish your proof is to say, "this is situation can't happen, so we need not consider it any further." Or, formally, (false.elim f). -/ -- Suppose P is *any* (an arbitrary) proposition axiom P : Prop example : false → P := begin assume f, exact false.elim f, -- Using Lean's version -- P is implicit argument end /- SOME THEOREMS INVOLVING FALSE AND NEGATION -/ -- NO CONTRADICTION theorem no_contradiction : ∀ (P : Prop), ¬(P ∧ ¬P) := begin assume P, assume h, have p := h.left, have np := h.right, have f := np p, exact f, end -- EXCLUDED MIDDLE /- The so-called "law" (it's really an axiom) of the excluded middle says that any proposition is either true or false. There's no middle ground. But in the constructive logic of Lean, this isn't true. To prove P ∨ ¬P, as you recall, we need to have either a proof of P (in this case use or.intro_left) or a proof of ¬P, in which case we use or.intro_right to prove P ∨ ¬P. But what if we don't have a proof either way? There are many important questions in computer science and mathematics where we don't know either way. If you call one of those propositions, P, and try to prove P ∨ ¬P in Lean, you just get stuck. -/ theorem excluded_middle' : ∀ (P : Prop), (P ∨ ¬P) := begin assume P, -- we don't have a proof of either P or of ¬P! -- no neither or.inl nor or.inr applies end /- Here's a concrete example: Goldbach's Conjecture Let P be the conjecture, "every even whole number greater than 2 is the sum of two prime numbers." This conjecture, dating (in a slightly different form) to a letter from Goldback to Euler in 1742 is still neither proved nor disproved! Below you will find a placeholder for a proof. Just fill it in (correctly) and you will win $1M and probably a Fields Medal (the "Nobel Prize" in mathematics). -/ -- just assume that we have evenness and primeness predicates axioms (ev : ℕ → Prop) (prime : ℕ → Prop) -- here's the statment of Goldbach's conjecture def goldbach_conjecture := ∀ (n : ℕ), n > 2 → (∃ h k : ℕ, n = h + k ∧ prime h ∧ prime k) -- can you prove it true? theorem goldbach_conjecture_true : goldbach_conjecture := _ -- can you prove it false? theorem goldbach_conjecture_false : ¬goldbach_conjecture := _ -- or haven't you yet proved it either way? /- So is it true that Goldbach's conjecture is either true or it's false, with no other possibility? Well, yes, but only if you admit the axiom of the excluded middle into our logic. -/ example : goldbach_conjecture ∨ ¬goldbach_conjecture := _ /- Without this axiom, our only options are or.intro_left or or.intro_right applied to proofs/arguments that we do not have. The axioms of the constructive logic of Lean are not strong enough to prove the "law of the excluded middle." Rather, if we want to use it, we have to accept it as an additional axiom. We thus have two different logics: one without and one with the law of the excluded middle! -/ axiom excluded_middle : ∀ (P : Prop), (P ∨ ¬P) example : goldbach_conjecture ∨ ¬goldbach_conjecture := excluded_middle goldbach_conjecture /- That is all it took to add this axiom to our logic. In the official Lean libraries, it's called classical.em. -/ #check classical.em -- Understand what this is saying! example : goldbach_conjecture ∨ ¬goldbach_conjecture := classical.em goldbach_conjecture /- HOW TO USE EXCLUDED MIDDLE. The real power is in how we *use* this new axiom. You give it a proposition, P, it gives you a proof of a disjunction (P ∨ ¬P). Well, what do you do with a proof of a disjunction? Answer: a case analysis. Given a proposition, P, the "strategy," then, is to a case analysis on "em P." Remember "em P" gives you a proof of P ∨ ¬P, and its on this proof, of this disjunction, that you do a case analysis. In one case P is assumed true; in the other case, ¬P is assumed true; *and there are no other cases.* -/ /- At this point you should see that a proof in the constructive logic of Lean is *informative*. It tells you *why* a given proposition is true. But with excluded middle, a proof of P ∨ ¬P is not informative, in that it no longer contains a proof of either side. -/ /- Here is an example where we apply excluded middle to the proposition, ItsRaining, to obtain a proof of ItsRaining ∨ ¬ItsRaining. -/ axiom ItsRaining : Prop -- assume ItsRaining is any proposition #check excluded_middle ItsRaining -- apply em to ItsRaining theorem example_em : ItsRaining ∨ ¬ItsRaining := excluded_middle ItsRaining -- apply excluded_middle directly to ItsRaining -- to return a proof of ItsRaining ∨ ¬ItsRaining -- by universal instantiation of excluded middle /- In Lean's official libraries, excluded middle is called classical.em (the name is em in the classical namespace). -/ theorem example_em' : ItsRaining ∨ ¬ItsRaining := classical.em ItsRaining /- PROOF BY NEGATION, AGAIN -/ /- Next we return to the negation connective, which in logic is pronounced "not." Given any proposition, P, ¬P is also a proposition; and what it means is, exactly, P → false. If P is true, then false is true, and false cannot possibly be true, so P must not be. Thus, to prove ¬P you prove P → false. Another way to read P → false is that, if we assume that P is true, we can derive a contradiction, proof of false that cannot exist, so P must not be true. MEMORIZE THIS REASONING. Again, to prove ¬P, *assume P* and show that in that context you can derive a contradiction in the form of a proof of false. This is the strategy call proof by negation. (THERE WAS A TYPO HERE) -/ /- How about we prove ¬(0 = 1) in English. Proof. By negation. Assume 0 = 1 and show that this leads to a contradiction. That is, show 0 = 1 → false. The rest of the proof is by case analysis on the assumed proof of 0 = 1. The only way to have a proof of equality is by the reflexive property of =. But the reflexive property doesn't imply that there's a proof of 0 = 1. So there can be no proof of 0 = 1, and the assumption that 0 = 1 is thus a contradiction. We finish the proof by case analysis on the possible proofs of 0 = 1, of which there are zero. So in all (zero!) cases, the conclusion (false) follows. Therefore 0 = 1 → false, which is to say, ¬(0 = 1) is proved and thus true. QED. -/ example : ¬0 = 1 := begin show 0 = 1 → false, -- rewrite goal to a definitionally equal goal assume h, cases h, -- there are *zero* ways to build a proof of 0 = 1 -- case analysis discharges our "proof obligation" end
e93a9a51d9c33b66dcd64f524de15c6f2e9e0f87
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/order/well_founded_set.lean
21ae9fe38500823fbd82393710735179ac658e90
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,649
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.set.finite import data.fintype.basic import order.well_founded import order.order_iso_nat import algebra.pointwise /-! # Well-founded sets A well-founded subset of an ordered type is one on which the relation `<` is well-founded. ## Main Definitions * `set.well_founded_on s r` indicates that the relation `r` is well-founded when restricted to the set `s`. * `set.is_wf s` indicates that `<` is well-founded when restricted to `s`. * `set.is_partially_well_ordered s` indicates that any infinite sequence of elements in `s` contains an infinite monotone subsequence. ### Definitions for Hahn Series * `set.add_antidiagonal s t a` and `set.mul_antidiagonal s t a` are the sets of pairs of elements from `s` and `t` that add/multiply to `a`. * `finset.add_antidiagonal` and `finset.mul_antidiagonal` are finite versions of `set.add_antidiagonal` and `set.mul_antidiagonal` defined when `s` and `t` are well-founded. ## Main Results * `set.well_founded_on_iff` relates `well_founded_on` to the well-foundedness of a relation on the original type, to avoid dealing with subtypes. * `set.is_wf.mono` shows that a subset of a well-founded subset is well-founded. * `set.is_wf.union` shows that the union of two well-founded subsets is well-founded. * `finset.is_wf` shows that all `finset`s are well-founded. -/ variables {α : Type*} namespace set /-- `s.well_founded_on r` indicates that the relation `r` is well-founded when restricted to `s`. -/ def well_founded_on (s : set α) (r : α → α → Prop) : Prop := well_founded (λ (a : s) (b : s), r a b) lemma well_founded_on_iff {s : set α} {r : α → α → Prop} : s.well_founded_on r ↔ well_founded (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := begin have f : rel_embedding (λ (a : s) (b : s), r a b) (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := ⟨⟨coe, subtype.coe_injective⟩, λ a b, by simp⟩, refine ⟨λ h, _, f.well_founded⟩, rw well_founded.well_founded_iff_has_min, intros t ht, by_cases hst : (s ∩ t).nonempty, { rw ← subtype.preimage_coe_nonempty at hst, rcases well_founded.well_founded_iff_has_min.1 h (coe ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hm ⟨x, xs⟩ xt xm⟩ }, { rcases ht with ⟨m, mt⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hst ⟨m, ⟨ms, mt⟩⟩⟩ } end section has_lt variables [has_lt α] /-- `s.is_wf` indicates that `<` is well-founded when restricted to `s`. -/ def is_wf (s : set α) : Prop := well_founded_on s (<) lemma is_wf_univ_iff : is_wf (univ : set α) ↔ well_founded ((<) : α → α → Prop) := by simp [is_wf, well_founded_on_iff] variables {s t : set α} theorem is_wf.mono (h : is_wf t) (st : s ⊆ t) : is_wf s := begin rw [is_wf, well_founded_on_iff] at *, refine subrelation.wf (λ x y xy, _) h, exact ⟨xy.1, st xy.2.1, st xy.2.2⟩, end end has_lt section partial_order variables [partial_order α] {s t : set α} {a : α} theorem is_wf_iff_no_descending_seq : is_wf s ↔ ∀ (f : (order_dual ℕ) ↪o α), ¬ (range f) ⊆ s := begin haveI : is_strict_order α (λ (a b : α), a < b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ x con, lt_irrefl x con.1⟩, to_is_trans := ⟨λ a b c ab bc, ⟨lt_trans ab.1 bc.1, ab.2.1, bc.2.2⟩⟩, }, rw [is_wf, well_founded_on_iff, rel_embedding.well_founded_iff_no_descending_seq], refine ⟨λ h f con, h begin use f, { exact f.injective }, { intros a b, simp only [con (mem_range_self a), con (mem_range_self b), and_true, gt_iff_lt, function.embedding.coe_fn_mk, order_embedding.lt_iff_lt], refl } end, λ h con, _⟩, rcases con with ⟨f, hf⟩, have hfs' : ∀ n : ℕ, f n ∈ s := λ n, (hf.2 n.lt_succ_self).2.2, refine h ⟨f, λ a b, _⟩ (λ n hn, _), { split; intro hle, { cases lt_or_eq_of_le hle with hlt heq, { exact le_of_lt (hf.1 ⟨hlt, hfs' _, hfs' _⟩) }, { rw [f.injective heq] } }, { cases lt_or_eq_of_le hle with hlt heq, { exact le_of_lt (hf.2 hlt).1, }, { rw [heq] } } }, { rcases set.mem_range.1 hn with ⟨m, hm⟩, rw ← hm, apply hfs' } end theorem is_wf.union (hs : is_wf s) (ht : is_wf t) : is_wf (s ∪ t) := begin classical, rw [is_wf_iff_no_descending_seq] at *, rintros f fst, have h : infinite (f ⁻¹' s) ∨ infinite (f ⁻¹' t), { have h : infinite (univ : set ℕ) := infinite_univ, have hpre : f ⁻¹' (s ∪ t) = set.univ, { rw [← image_univ, image_subset_iff, univ_subset_iff] at fst, exact fst }, rw preimage_union at hpre, rw ← hpre at h, rw [infinite, infinite], rw infinite at h, contrapose! h, exact finite.union h.1 h.2, }, rw [← infinite_coe_iff, ← infinite_coe_iff] at h, cases h with inf inf; haveI := inf, { apply hs ((nat.order_embedding_of_set (f ⁻¹' s)).dual.trans f), change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' s))) ⊆ s, rw [range_comp, image_subset_iff], simp }, { apply ht ((nat.order_embedding_of_set (f ⁻¹' t)).dual.trans f), change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' t))) ⊆ t, rw [range_comp, image_subset_iff], simp } end end partial_order end set @[simp] theorem finset.is_wf [partial_order α] {f : finset α} : set.is_wf (↑f : set α) := fintype.preorder.well_founded namespace set variables [partial_order α] {s : set α} {a : α} theorem finite.is_wf (h : s.finite) : s.is_wf := begin rw ← h.coe_to_finset, exact finset.is_wf, end @[simp] theorem fintype.is_wf [fintype α] : s.is_wf := (finite.of_fintype s).is_wf @[simp] theorem is_wf_empty : is_wf (∅ : set α) := finite_empty.is_wf @[simp] theorem is_wf_singleton (a) : is_wf ({a} : set α) := (finite_singleton a).is_wf theorem is_wf.insert (a) (hs : is_wf s) : is_wf (insert a s) := by { rw ← union_singleton, exact hs.union (is_wf_singleton a) } /-- `is_wf.min` returns a minimal element of a nonempty well-founded set. -/ noncomputable def is_wf.min (hs : is_wf s) (hn : s.nonempty) : α := hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) lemma is_wf.min_mem (hs : is_wf s) (hn : s.nonempty) : hs.min hn ∈ s := (well_founded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2 lemma is_wf.not_lt_min (hs : is_wf s) (hn : s.nonempty) (ha : a ∈ s) : ¬ a < hs.min hn := hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s)) @[simp] lemma is_wf_min_singleton (a) {hs : is_wf ({a} : set α)} {hn : ({a} : set α).nonempty} : hs.min hn = a := eq_of_mem_singleton (is_wf.min_mem hs hn) end set namespace set variables [linear_order α] {s t : set α} {a : α} lemma is_wf.min_le (hs : s.is_wf) (hn : s.nonempty) (ha : a ∈ s) : hs.min hn ≤ a := le_of_not_lt (hs.not_lt_min hn ha) lemma is_wf.le_min_iff (hs : s.is_wf) (hn : s.nonempty) : a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b := ⟨λ ha b hb, le_trans ha (hs.min_le hn hb), λ h, h _ (hs.min_mem _)⟩ lemma is_wf.min_le_min_of_subset {hs : s.is_wf} {hsn : s.nonempty} {ht : t.is_wf} {htn : t.nonempty} (hst : s ⊆ t) : ht.min htn ≤ hs.min hsn := (is_wf.le_min_iff _ _).2 (λ b hb, ht.min_le htn (hst hb)) lemma is_wf.min_union (hs : s.is_wf) (hsn : s.nonempty) (ht : t.is_wf) (htn : t.nonempty) : (hs.union ht).min (union_nonempty.2 (or.intro_left _ hsn)) = min (hs.min hsn) (ht.min htn) := begin refine le_antisymm (le_min (is_wf.min_le_min_of_subset (subset_union_left _ _)) (is_wf.min_le_min_of_subset (subset_union_right _ _))) _, rw min_le_iff, exact ((mem_union _ _ _).1 ((hs.union ht).min_mem (union_nonempty.2 (or.intro_left _ hsn)))).imp (hs.min_le _) (ht.min_le _), end end set namespace set /-- A subset of a preorder is partially well-ordered when any infinite sequence contains a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/ def is_partially_well_ordered [preorder α] (s) : Prop := ∀ (f : ℕ → α), range f ⊆ s → ∃ (m n : ℕ), m < n ∧ f m ≤ f n section partial_order variables [partial_order α] {s : set α} {t : set α} lemma is_partially_well_ordered.is_wf (h : s.is_partially_well_ordered) : s.is_wf := begin rw is_wf_iff_no_descending_seq, intros f con, obtain ⟨m, n, hlt, hle⟩ := h f con, exact not_lt_of_le hle (f.lt_iff_lt.2 hlt), end theorem is_partially_well_ordered.exists_monotone_subseq (h : s.is_partially_well_ordered) (f : ℕ → α) (hf : range f ⊆ s) : ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := begin obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq (≤) f, { refine ⟨g, λ m n hle, _⟩, obtain hlt | heq := lt_or_eq_of_le hle, { exact h1 m n hlt, }, { rw [heq] } }, { exfalso, obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) (subset.trans (range_comp_subset_range _ _) hf), exact h2 m n hlt hle } end theorem is_partially_well_ordered_iff_exists_monotone_subseq : s.is_partially_well_ordered ↔ ∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := begin classical, split; intros h f hf, { exact h.exists_monotone_subseq f hf }, { obtain ⟨g, gmon⟩ := h f hf, refine ⟨g 0, g 1, g.lt_iff_lt.2 zero_lt_one, gmon zero_le_one⟩, } end lemma is_partially_well_ordered.prod (hs : s.is_partially_well_ordered) (ht : t.is_partially_well_ordered) : (s.prod t).is_partially_well_ordered := begin classical, rw is_partially_well_ordered_iff_exists_monotone_subseq at *, intros f hf, obtain ⟨g1, h1⟩ := hs (prod.fst ∘ f) _, swap, { rw [range_comp, image_subset_iff], refine subset.trans hf _, rintros ⟨x1, x2⟩ hx, simp only [mem_preimage, hx.1] }, obtain ⟨g2, h2⟩ := ht (prod.snd ∘ f ∘ g1) _, refine ⟨g2.trans g1, λ m n mn, _⟩, swap, { rw [range_comp, image_subset_iff], refine subset.trans (range_comp_subset_range _ _) (subset.trans hf _), rintros ⟨x1, x2⟩ hx, simp only [mem_preimage, hx.2] }, simp only [rel_embedding.coe_trans, function.comp_app], exact ⟨h1 (g2.le_iff_le.2 mn), h2 mn⟩, end theorem is_partially_well_ordered.image_of_monotone {β : Type*} [partial_order β] (hs : s.is_partially_well_ordered) {f : α → β} (hf : monotone f) : is_partially_well_ordered (f '' s) := λ g hg, begin have h := λ (n : ℕ), ((mem_image _ _ _).1 (hg (mem_range_self n))), obtain ⟨m, n, hlt, hmn⟩ := hs (λ n, classical.some (h n)) _, { refine ⟨m, n, hlt, _⟩, rw [← (classical.some_spec (h m)).2, ← (classical.some_spec (h n)).2], apply hf hmn }, { rintros _ ⟨n, rfl⟩, exact (classical.some_spec (h n)).1 } end end partial_order theorem is_wf.is_partially_well_ordered [linear_order α] {s : set α} (hs : s.is_wf) : s.is_partially_well_ordered := λ f hf, begin rw [is_wf, well_founded_on_iff] at hs, have hrange : (range f).nonempty := ⟨f 0, mem_range_self 0⟩, let a := hs.min (range f) hrange, obtain ⟨m, hm⟩ := hs.min_mem (range f) hrange, refine ⟨m, m.succ, m.lt_succ_self, le_of_not_lt (λ con, _)⟩, rw hm at con, apply hs.not_lt_min (range f) hrange (mem_range_self m.succ) ⟨con, hf (mem_range_self m.succ), hf _⟩, rw ← hm, apply mem_range_self, end section variables [linear_ordered_cancel_comm_monoid α] {s : set α} {t : set α} @[to_additive] theorem is_partially_well_ordered.mul (hs : s.is_partially_well_ordered) (ht : t.is_partially_well_ordered) : is_partially_well_ordered (s * t) := begin rw ← image_mul_prod, exact (is_partially_well_ordered.prod hs ht).image_of_monotone (λ _ _ h, mul_le_mul' h.1 h.2), end @[to_additive] theorem is_wf.mul (hs : s.is_wf) (ht : t.is_wf) : is_wf (s * t) := (hs.is_partially_well_ordered.mul ht.is_partially_well_ordered).is_wf @[to_additive] theorem is_wf.min_mul (hs : s.is_wf) (ht : t.is_wf) (hsn : s.nonempty) (htn : t.nonempty) : (hs.mul ht).min (hsn.mul htn) = hs.min hsn * ht.min htn := begin refine le_antisymm (is_wf.min_le _ _ (mem_mul.2 ⟨_, _, hs.min_mem _, ht.min_mem _, rfl⟩)) _, rw is_wf.le_min_iff, rintros _ ⟨x, y, hx, hy, rfl⟩, exact mul_le_mul' (hs.min_le _ hx) (ht.min_le _ hy), end end end set theorem not_well_founded_swap_of_infinite_of_well_order [infinite α] {r : α → α → Prop} [is_well_order α r] : ¬ well_founded (function.swap r) := begin haveI : is_strict_order α (function.swap r) := is_strict_order.swap _, rw [rel_embedding.well_founded_iff_no_descending_seq, not_not], obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq' r (infinite.nat_embedding α), { exact ⟨rel_embedding.nat_gt ((infinite.nat_embedding α) ∘ g) h1⟩ }, { exfalso, have h : well_founded r := is_well_order.wf, rw [rel_embedding.well_founded_iff_no_descending_seq] at h, refine h ⟨rel_embedding.nat_gt ((infinite.nat_embedding α) ∘ g) (λ n, _)⟩, obtain c1 | c2 | c3 := (is_trichotomous.trichotomous _ _ : r _ _ ∨ _), { exact c1 }, { exfalso, exact ne_of_gt n.lt_succ_self (g.injective ((infinite.nat_embedding α).injective c2)) }, { exact (h2 n (n + 1) n.lt_succ_self c3).elim } } end namespace set /-- `set.mul_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`. -/ @[to_additive "`set.add_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`."] def mul_antidiagonal [monoid α] (s t : set α) (a : α) : set (α × α) := { x | x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t } namespace mul_antidiagonal @[simp, to_additive] lemma mem_mul_antidiagonal [monoid α] {s t : set α} {a : α} {x : α × α} : x ∈ mul_antidiagonal s t a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := iff.refl _ variables [cancel_comm_monoid α] {s t : set α} {a : α} @[to_additive] lemma fst_eq_fst_iff_snd_eq_snd {x y : (mul_antidiagonal s t a)} : (x : α × α).fst = (y : α × α).fst ↔ (x : α × α).snd = (y : α × α).snd := ⟨λ h, begin have hx := x.2.1, rw [subtype.val_eq_coe, h] at hx, apply mul_left_cancel (hx.trans y.2.1.symm), end, λ h, begin have hx := x.2.1, rw [subtype.val_eq_coe, h] at hx, apply mul_right_cancel (hx.trans y.2.1.symm), end⟩ @[to_additive] lemma eq_of_fst_eq_fst {x y : (mul_antidiagonal s t a)} (h : (x : α × α).fst = (y : α × α).fst) : x = y := subtype.ext (prod.ext h (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.1 h)) @[to_additive] lemma eq_of_snd_eq_snd {x y : (mul_antidiagonal s t a)} (h : (x : α × α).snd = (y : α × α).snd) : x = y := subtype.ext (prod.ext (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.2 h) h) end mul_antidiagonal end set namespace set namespace mul_antidiagonal variables [linear_ordered_cancel_comm_monoid α] (s t : set α) (a : α) /-- The relation on `set.mul_antidagonal s t a` given by `<` on the first coordinate. -/ @[to_additive "The relation on `set.add_antidagonal s t a` given by `<` on the first coordinate."] def lt_left (x y : mul_antidiagonal s t a) : Prop := (x : α × α).1 < (y : α × α).1 /-- `set.mul_antidiagonal s t a` ordered by `lt_left` embeds into `s` -/ @[to_additive "`set.add_antidiagonal s t a` ordered by `lt_left` embeds into `s`"] def fst_rel_embedding : (lt_left s t a) ↪r ((<) : s → s → Prop) := ⟨⟨λ x, ⟨(↑x : α × α).1, x.2.2.1⟩, λ x y hxy, mul_antidiagonal.eq_of_fst_eq_fst (subtype.mk_eq_mk.1 hxy)⟩, λ x y, iff.refl _⟩ /-- `set.mul_antidiagonal s t a` ordered by `lt_left` embeds into the dual of `t` -/ @[to_additive "`set.add_antidiagonal s t a` ordered by `lt_left` embeds into the dual of `t`"] def snd_rel_embedding : (lt_left s t a) ↪r ((>) : t → t → Prop) := ⟨⟨λ x, ⟨(↑x : α × α).2, x.2.2.2⟩, λ x y hxy, eq_of_snd_eq_snd (subtype.mk_eq_mk.1 hxy)⟩, begin rintro ⟨⟨x1, x2⟩, rfl, _⟩, rintro ⟨⟨y1, y2⟩, h, _⟩, change x2 > y2 ↔ x1 < y1, change y1 * y2 = x1 * x2 at h, rw [← mul_lt_mul_iff_right x2, ← h, mul_lt_mul_iff_left], end⟩ variables {s} {t} @[to_additive] theorem finite_of_is_wf (hs : s.is_wf) (ht : t.is_wf) (a) : (mul_antidiagonal s t a).finite := begin by_contra h, rw [← set.infinite, ← infinite_coe_iff] at h, haveI := h, haveI : is_well_order s (<) := { wf := hs, .. (infer_instance : is_strict_total_order _ _), }, haveI : is_well_order (mul_antidiagonal s t a) (lt_left s t a) := (fst_rel_embedding s t a).is_well_order, have hwf : well_founded (function.swap (lt_left s t a)) := (snd_rel_embedding s t a).swap.well_founded ht, exact not_well_founded_swap_of_infinite_of_well_order (hwf), end end mul_antidiagonal end set namespace finset variables [linear_ordered_cancel_comm_monoid α] variables {s t : set α} (hs : s.is_wf) (ht : t.is_wf) (a : α) /-- `finset.mul_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`, but its construction requires proofs `hs` and `ht` that `s` and `t` are well-ordered. -/ @[to_additive "`finset.add_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`, but its construction requires proofs `hs` and `ht` that `s` and `t` are well-ordered."] noncomputable def mul_antidiagonal : finset (α × α) := (set.mul_antidiagonal.finite_of_is_wf hs ht a).to_finset variables {hs} {ht} {u : set α} {hu : u.is_wf} {a} {x : α × α} @[simp, to_additive] lemma mem_mul_antidiagonal : x ∈ mul_antidiagonal hs ht a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := by simp [mul_antidiagonal] @[to_additive] lemma mul_antidiagonal_mono_left (hus : u ⊆ s) : (finset.mul_antidiagonal hu ht a) ⊆ (finset.mul_antidiagonal hs ht a) := λ x hx, begin rw mem_mul_antidiagonal at *, exact ⟨hx.1, hus hx.2.1, hx.2.2⟩, end @[to_additive] lemma mul_antidiagonal_mono_right (hut : u ⊆ t) : (finset.mul_antidiagonal hs hu a) ⊆ (finset.mul_antidiagonal hs ht a) := λ x hx, begin rw mem_mul_antidiagonal at *, exact ⟨hx.1, hx.2.1, hut hx.2.2⟩, end @[to_additive] lemma support_mul_antidiagonal_subset_mul : { a : α | (mul_antidiagonal hs ht a).nonempty } ⊆ s * t := (λ x ⟨⟨a1, a2⟩, ha⟩, begin obtain ⟨hmul, h1, h2⟩ := mem_mul_antidiagonal.1 ha, exact ⟨a1, a2, h1, h2, hmul⟩, end) @[to_additive] theorem is_wf_support_mul_antidiagonal : { a : α | (mul_antidiagonal hs ht a).nonempty }.is_wf := (hs.mul ht).mono support_mul_antidiagonal_subset_mul @[to_additive] theorem mul_antidiagonal_min_mul_min (hns : s.nonempty) (hnt : t.nonempty) : mul_antidiagonal hs ht ((hs.min hns) * (ht.min hnt)) = {(hs.min hns, ht.min hnt)} := begin ext ⟨a1, a2⟩, rw [mem_mul_antidiagonal, finset.mem_singleton, prod.ext_iff], split, { rintro ⟨hast, has, hat⟩, cases eq_or_lt_of_le (hs.min_le hns has) with heq hlt, { refine ⟨heq.symm, _⟩, rw heq at hast, exact mul_left_cancel hast }, { contrapose hast, exact ne_of_gt (mul_lt_mul_of_lt_of_le hlt (ht.min_le hnt hat)) } }, { rintro ⟨ha1, ha2⟩, rw [ha1, ha2], exact ⟨rfl, hs.min_mem _, ht.min_mem _⟩ } end end finset lemma well_founded.is_wf [has_lt α] (h : well_founded ((<) : α → α → Prop)) (s : set α) : s.is_wf := (set.is_wf_univ_iff.2 h).mono (set.subset_univ s)
d44e2f9cb9d2d0e1b65232efd1641197290e976a
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/geom_sum.lean
297802008460772697abaf5fb2559bc5ea104214
[ "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
22,615
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import algebra.big_operators.order import algebra.big_operators.ring import algebra.big_operators.intervals import tactic.abel import data.nat.parity /-! # Partial sums of geometric series This file determines the values of the geometric series $\sum_{i=0}^{n-1} x^i$ and $\sum_{i=0}^{n-1} x^i y^{n-1-i}$ and variants thereof. We also provide some bounds on the "geometric" sum of `a/b^i` where `a b : ℕ`. ## Main statements * `geom_sum_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-x^m}{x-1}$ in a division ring. * `geom_sum₂_Ico` proves that $\sum_{i=m}^{n-1} x^i=\frac{x^n-y^{n-m}x^m}{x-y}$ in a field. Several variants are recorded, generalising in particular to the case of a noncommutative ring in which `x` and `y` commute. Even versions not using division or subtraction, valid in each semiring, are recorded. -/ universe u variable {α : Type u} open finset mul_opposite open_locale big_operators section semiring variable [semiring α] lemma geom_sum_succ {x : α} {n : ℕ} : ∑ i in range (n + 1), x ^ i = x * ∑ i in range n, x ^ i + 1 := by simp only [mul_sum, ←pow_succ, sum_range_succ', pow_zero] lemma geom_sum_succ' {x : α} {n : ℕ} : ∑ i in range (n + 1), x ^ i = x ^ n + ∑ i in range n, x ^ i := (sum_range_succ _ _).trans (add_comm _ _) theorem geom_sum_zero (x : α) : ∑ i in range 0, x ^ i = 0 := rfl theorem geom_sum_one (x : α) : ∑ i in range 1, x ^ i = 1 := by simp [geom_sum_succ'] @[simp] lemma geom_sum_two {x : α} : ∑ i in range 2, x ^ i = x + 1 := by simp [geom_sum_succ'] @[simp] lemma zero_geom_sum : ∀ {n}, ∑ i in range n, (0 : α) ^ i = if n = 0 then 0 else 1 | 0 := by simp | 1 := by simp | (n+2) := by { rw geom_sum_succ', simp [zero_geom_sum] } lemma one_geom_sum (n : ℕ) : ∑ i in range n, (1 : α) ^ i = n := by simp @[simp] lemma op_geom_sum (x : α) (n : ℕ) : op (∑ i in range n, x ^ i) = ∑ i in range n, (op x) ^ i := by simp @[simp] lemma op_geom_sum₂ (x y : α) (n : ℕ) : op (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) = ∑ i in range n, (op y) ^ i * ((op x) ^ (n - 1 - i)) := begin simp only [op_sum, op_mul, op_pow], rw ← sum_range_reflect, refine sum_congr rfl (λ j j_in, _), rw [mem_range, nat.lt_iff_add_one_le] at j_in, congr, apply tsub_tsub_cancel_of_le, exact le_tsub_of_add_le_right j_in end theorem geom_sum₂_with_one (x : α) (n : ℕ) : ∑ i in range n, x ^ i * (1 ^ (n - 1 - i)) = ∑ i in range n, x ^ i := sum_congr rfl (λ i _, by { rw [one_pow, mul_one] }) /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ protected theorem commute.geom_sum₂_mul_add {x y : α} (h : commute x y) (n : ℕ) : (∑ i in range n, (x + y) ^ i * (y ^ (n - 1 - i))) * x + y ^ n = (x + y) ^ n := begin let f := λ (m i : ℕ), (x + y) ^ i * y ^ (m - 1 - i), change (∑ i in range n, (f n) i) * x + y ^ n = (x + y) ^ n, induction n with n ih, { rw [range_zero, sum_empty, zero_mul, zero_add, pow_zero, pow_zero] }, { have f_last : f (n + 1) n = (x + y) ^ n := by { dsimp [f], rw [← tsub_add_eq_tsub_tsub, nat.add_comm, tsub_self, pow_zero, mul_one] }, have f_succ : ∀ i, i ∈ range n → f (n + 1) i = y * f n i := λ i hi, by { dsimp [f], have : commute y ((x + y) ^ i) := (h.symm.add_right (commute.refl y)).pow_right i, rw [← mul_assoc, this.eq, mul_assoc, ← pow_succ y (n - 1 - i)], congr' 2, rw [add_tsub_cancel_right, ← tsub_add_eq_tsub_tsub, add_comm 1 i], have : i + 1 + (n - (i + 1)) = n := add_tsub_cancel_of_le (mem_range.mp hi), rw [add_comm (i + 1)] at this, rw [← this, add_tsub_cancel_right, add_comm i 1, ← add_assoc, add_tsub_cancel_right] }, rw [pow_succ (x + y), add_mul, sum_range_succ_comm, add_mul, f_last, add_assoc], rw (((commute.refl x).add_right h).pow_right n).eq, congr' 1, rw [sum_congr rfl f_succ, ← mul_sum, pow_succ y, mul_assoc, ← mul_add y, ih] } end end semiring @[simp] lemma neg_one_geom_sum [ring α] {n : ℕ} : ∑ i in range n, (-1 : α) ^ i = if even n then 0 else 1 := begin induction n with k hk, { simp }, { simp only [geom_sum_succ', nat.even_add_one, hk], split_ifs, { rw [h.neg_one_pow, add_zero] }, { rw [(nat.odd_iff_not_even.2 h).neg_one_pow, neg_add_self] } } end theorem geom_sum₂_self {α : Type*} [comm_ring α] (x : α) (n : ℕ) : ∑ i in range n, x ^ i * (x ^ (n - 1 - i)) = n * x ^ (n-1) := calc ∑ i in finset.range n, x ^ i * x ^ (n - 1 - i) = ∑ i in finset.range n, x ^ (i + (n - 1 - i)) : by simp_rw [← pow_add] ... = ∑ i in finset.range n, x ^ (n - 1) : finset.sum_congr rfl (λ i hi, congr_arg _ $ add_tsub_cancel_of_le $ nat.le_pred_of_lt $ finset.mem_range.1 hi) ... = (finset.range n).card • (x ^ (n - 1)) : finset.sum_const _ ... = n * x ^ (n - 1) : by rw [finset.card_range, nsmul_eq_mul] /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ theorem geom_sum₂_mul_add [comm_semiring α] (x y : α) (n : ℕ) : (∑ i in range n, (x + y) ^ i * (y ^ (n - 1 - i))) * x + y ^ n = (x + y) ^ n := (commute.all x y).geom_sum₂_mul_add n theorem geom_sum_mul_add [semiring α] (x : α) (n : ℕ) : (∑ i in range n, (x + 1) ^ i) * x + 1 = (x + 1) ^ n := begin have := (commute.one_right x).geom_sum₂_mul_add n, rw [one_pow, geom_sum₂_with_one] at this, exact this end protected theorem commute.geom_sum₂_mul [ring α] {x y : α} (h : commute x y) (n : ℕ) : (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) * (x - y) = x ^ n - y ^ n := begin have := (h.sub_left (commute.refl y)).geom_sum₂_mul_add n, rw [sub_add_cancel] at this, rw [← this, add_sub_cancel] end lemma commute.mul_neg_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) : (y - x) * (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) = y ^ n - x ^ n := begin apply op_injective, simp only [op_mul, op_sub, op_geom_sum₂, op_pow], exact (commute.op h.symm).geom_sum₂_mul n end lemma commute.mul_geom_sum₂ [ring α] {x y : α} (h : commute x y) (n : ℕ) : (x - y) * (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) = x ^ n - y ^ n := by rw [← neg_sub (y ^ n), ← h.mul_neg_geom_sum₂, ← neg_mul, neg_sub] theorem geom_sum₂_mul [comm_ring α] (x y : α) (n : ℕ) : (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) * (x - y) = x ^ n - y ^ n := (commute.all x y).geom_sum₂_mul n theorem sub_dvd_pow_sub_pow [comm_ring α] (x y : α) (n : ℕ) : x - y ∣ x ^ n - y ^ n := dvd.intro_left _ (geom_sum₂_mul x y n) theorem nat_sub_dvd_pow_sub_pow (x y n : ℕ) : x - y ∣ x ^ n - y ^ n := begin cases le_or_lt y x with h, { have : y ^ n ≤ x ^ n := nat.pow_le_pow_of_le_left h _, exact_mod_cast sub_dvd_pow_sub_pow (x : ℤ) ↑y n }, { have : x ^ n ≤ y ^ n := nat.pow_le_pow_of_le_left h.le _, exact (nat.sub_eq_zero_of_le this).symm ▸ dvd_zero (x - y) } end theorem odd.add_dvd_pow_add_pow [comm_ring α] (x y : α) {n : ℕ} (h : odd n) : x + y ∣ x ^ n + y ^ n := begin have h₁ := geom_sum₂_mul x (-y) n, rw [odd.neg_pow h y, sub_neg_eq_add, sub_neg_eq_add] at h₁, exact dvd.intro_left _ h₁, end theorem odd.nat_add_dvd_pow_add_pow (x y : ℕ) {n : ℕ} (h : odd n) : x + y ∣ x ^ n + y ^ n := by exact_mod_cast odd.add_dvd_pow_add_pow (x : ℤ) ↑y h theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : (∑ i in range n, x ^ i) * (x - 1) = x ^ n - 1 := begin have := (commute.one_right x).geom_sum₂_mul n, rw [one_pow, geom_sum₂_with_one] at this, exact this end lemma mul_geom_sum [ring α] (x : α) (n : ℕ) : (x - 1) * (∑ i in range n, x ^ i) = x ^ n - 1 := op_injective $ by simpa using geom_sum_mul (op x) n theorem geom_sum_mul_neg [ring α] (x : α) (n : ℕ) : (∑ i in range n, x ^ i) * (1 - x) = 1 - x ^ n := begin have := congr_arg has_neg.neg (geom_sum_mul x n), rw [neg_sub, ← mul_neg, neg_sub] at this, exact this end lemma mul_neg_geom_sum [ring α] (x : α) (n : ℕ) : (1 - x) * (∑ i in range n, x ^ i) = 1 - x ^ n := op_injective $ by simpa using geom_sum_mul_neg (op x) n protected lemma commute.geom_sum₂_comm {α : Type u} [semiring α] {x y : α} (n : ℕ) (h : commute x y) : ∑ i in range n, x ^ i * y ^ (n - 1 - i) = ∑ i in range n, y ^ i * x ^ (n - 1 - i) := begin cases n, { simp }, simp only [nat.succ_eq_add_one, nat.add_sub_cancel], rw ← finset.sum_flip, refine finset.sum_congr rfl (λ i hi, _), simpa [nat.sub_sub_self (nat.succ_le_succ_iff.mp (finset.mem_range.mp hi))] using h.pow_pow _ _ end lemma geom_sum₂_comm {α : Type u} [comm_semiring α] (x y : α) (n : ℕ) : ∑ i in range n, x ^ i * y ^ (n - 1 - i) = ∑ i in range n, y ^ i * x ^ (n - 1 - i) := (commute.all x y).geom_sum₂_comm n protected theorem commute.geom_sum₂ [division_ring α] {x y : α} (h' : commute x y) (h : x ≠ y) (n : ℕ) : (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) = (x ^ n - y ^ n) / (x - y) := have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← h'.geom_sum₂_mul, mul_div_cancel _ this] theorem geom₂_sum [field α] {x y : α} (h : x ≠ y) (n : ℕ) : (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) = (x ^ n - y ^ n) / (x - y) := (commute.all x y).geom_sum₂ h n theorem geom_sum_eq [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (∑ i in range n, x ^ i) = (x ^ n - 1) / (x - 1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] protected theorem commute.mul_geom_sum₂_Ico [ring α] {x y : α} (h : commute x y) {m n : ℕ} (hmn : m ≤ n) : (x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) := begin rw [sum_Ico_eq_sub _ hmn], have : ∑ k in range m, x ^ k * y ^ (n - 1 - k) = ∑ k in range m, x ^ k * (y ^ (n - m) * y ^ (m - 1 - k)), { refine sum_congr rfl (λ j j_in, _), rw ← pow_add, congr, rw [mem_range, nat.lt_iff_add_one_le, add_comm] at j_in, have h' : n - m + (m - (1 + j)) = n - (1 + j) := tsub_add_tsub_cancel hmn j_in, rw [← tsub_add_eq_tsub_tsub m, h', ← tsub_add_eq_tsub_tsub] }, rw this, simp_rw pow_mul_comm y (n-m) _, simp_rw ← mul_assoc, rw [← sum_mul, mul_sub, h.mul_geom_sum₂, ← mul_assoc, h.mul_geom_sum₂, sub_mul, ← pow_add, add_tsub_cancel_of_le hmn, sub_sub_sub_cancel_right (x ^ n) (x ^ m * y ^ (n - m)) (y ^ n)], end protected theorem commute.geom_sum₂_succ_eq {α : Type u} [ring α] {x y : α} (h : commute x y) {n : ℕ} : ∑ i in range (n + 1), x ^ i * (y ^ (n - i)) = x ^ n + y * (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) := begin simp_rw [mul_sum, sum_range_succ_comm, tsub_self, pow_zero, mul_one, add_right_inj, ←mul_assoc, (h.symm.pow_right _).eq, mul_assoc, ←pow_succ], refine sum_congr rfl (λ i hi, _), suffices : n - 1 - i + 1 = n - i, { rw this }, cases n, { exact absurd (list.mem_range.mp hi) i.not_lt_zero }, { rw [tsub_add_eq_add_tsub (nat.le_pred_of_lt (list.mem_range.mp hi)), tsub_add_cancel_of_le (nat.succ_le_iff.mpr n.succ_pos)] }, end theorem geom_sum₂_succ_eq {α : Type u} [comm_ring α] (x y : α) {n : ℕ} : ∑ i in range (n + 1), x ^ i * (y ^ (n - i)) = x ^ n + y * (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) := (commute.all x y).geom_sum₂_succ_eq theorem mul_geom_sum₂_Ico [comm_ring α] (x y : α) {m n : ℕ} (hmn : m ≤ n) : (x - y) * (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) = x ^ n - x ^ m * y ^ (n - m) := (commute.all x y).mul_geom_sum₂_Ico hmn protected theorem commute.geom_sum₂_Ico_mul [ring α] {x y : α} (h : commute x y) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i)) * (x - y) = x ^ n - y ^ (n - m) * x ^ m := begin apply op_injective, simp only [op_sub, op_mul, op_pow, op_sum], have : ∑ k in Ico m n, op y ^ (n - 1 - k) * op x ^ k = ∑ k in Ico m n, op x ^ k * op y ^ (n - 1 - k), { refine sum_congr rfl (λ k k_in, _), apply commute.pow_pow (commute.op h.symm) }, rw this, exact (commute.op h).mul_geom_sum₂_Ico hmn end theorem geom_sum_Ico_mul [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (x - 1) = x^n - x^m := by rw [sum_Ico_eq_sub _ hmn, sub_mul, geom_sum_mul, geom_sum_mul, sub_sub_sub_cancel_right] theorem geom_sum_Ico_mul_neg [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : (∑ i in finset.Ico m n, x ^ i) * (1 - x) = x^m - x^n := by rw [sum_Ico_eq_sub _ hmn, sub_mul, geom_sum_mul_neg, geom_sum_mul_neg, sub_sub_sub_cancel_left] protected theorem commute.geom_sum₂_Ico [division_ring α] {x y : α} (h : commute x y) (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) := have x - y ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← h.geom_sum₂_Ico_mul hmn, mul_div_cancel _ this] theorem geom_sum₂_Ico [field α] {x y : α} (hxy : x ≠ y) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i * y ^ (n - 1 - i) = (x ^ n - y ^ (n - m) * x ^ m ) / (x - y) := (commute.all x y).geom_sum₂_Ico hxy hmn theorem geom_sum_Ico [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ n - x ^ m) / (x - 1) := by simp only [sum_Ico_eq_sub _ hmn, geom_sum_eq hx, div_sub_div_same, sub_sub_sub_cancel_right] theorem geom_sum_Ico' [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : ∑ i in finset.Ico m n, x ^ i = (x ^ m - x ^ n) / (1 - x) := by { simp only [geom_sum_Ico hx hmn], convert neg_div_neg_eq (x^m - x^n) (1-x); abel } lemma geom_sum_Ico_le_of_lt_one [linear_ordered_field α] {x : α} (hx : 0 ≤ x) (h'x : x < 1) {m n : ℕ} : ∑ i in Ico m n, x ^ i ≤ x ^ m / (1 - x) := begin rcases le_or_lt m n with hmn | hmn, { rw geom_sum_Ico' h'x.ne hmn, apply div_le_div (pow_nonneg hx _) _ (sub_pos.2 h'x) le_rfl, simpa using pow_nonneg hx _ }, { rw [Ico_eq_empty, sum_empty], { apply div_nonneg (pow_nonneg hx _), simpa using h'x.le }, { simpa using hmn.le } }, end lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (∑ i in range n, x⁻¹ ^ i) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * (x ^ n)⁻¹ = (x ^ n)⁻¹ * x := nat.rec_on n (by simp) (λ n h, by rw [pow_succ, mul_inv_rev, ←mul_assoc, h, mul_assoc, mul_inv_cancel hx0, mul_assoc, inv_mul_cancel hx0]), begin rw [geom_sum_eq h₁, div_eq_iff_mul_eq h₂, ← mul_right_inj' h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃], simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄, sub_eq_add_neg, add_comm, add_left_comm], end variables {β : Type*} theorem ring_hom.map_geom_sum [semiring α] [semiring β] (x : α) (n : ℕ) (f : α →+* β) : f (∑ i in range n, x ^ i) = ∑ i in range n, (f x) ^ i := by simp [f.map_sum] theorem ring_hom.map_geom_sum₂ [semiring α] [semiring β] (x y : α) (n : ℕ) (f : α →+* β) : f (∑ i in range n, x ^ i * (y ^ (n - 1 - i))) = ∑ i in range n, (f x) ^ i * ((f y) ^ (n - 1 - i)) := by simp [f.map_sum] /-! ### Geometric sum with `ℕ`-division -/ lemma nat.pred_mul_geom_sum_le (a b n : ℕ) : (b - 1) * ∑ i in range n.succ, a/b^i ≤ a * b - a/b^n := calc (b - 1) * (∑ i in range n.succ, a/b^i) = ∑ i in range n, a/b^(i + 1) * b + a * b - (∑ i in range n, a/b^i + a/b^n) : by rw [tsub_mul, mul_comm, sum_mul, one_mul, sum_range_succ', sum_range_succ, pow_zero, nat.div_one] ... ≤ ∑ i in range n, a/b^i + a * b - (∑ i in range n, a/b^i + a/b^n) : begin refine tsub_le_tsub_right (add_le_add_right (sum_le_sum $ λ i _, _) _) _, rw [pow_succ', ←nat.div_div_eq_div_mul], exact nat.div_mul_le_self _ _, end ... = a * b - a/b^n : add_tsub_add_eq_tsub_left _ _ _ lemma nat.geom_sum_le {b : ℕ} (hb : 2 ≤ b) (a n : ℕ) : ∑ i in range n, a/b^i ≤ a * b/(b - 1) := begin refine (nat.le_div_iff_mul_le $ tsub_pos_of_lt hb).2 _, cases n, { rw [sum_range_zero, zero_mul], exact nat.zero_le _ }, rw mul_comm, exact (nat.pred_mul_geom_sum_le a b n).trans tsub_le_self, end lemma nat.geom_sum_Ico_le {b : ℕ} (hb : 2 ≤ b) (a n : ℕ) : ∑ i in Ico 1 n, a/b^i ≤ a/(b - 1) := begin cases n, { rw [Ico_eq_empty_of_le (zero_le_one' ℕ), sum_empty], exact nat.zero_le _ }, rw ←add_le_add_iff_left a, calc a + ∑ (i : ℕ) in Ico 1 n.succ, a/b^i = a/b^0 + ∑ (i : ℕ) in Ico 1 n.succ, a/b^i : by rw [pow_zero, nat.div_one] ... = ∑ i in range n.succ, a/b^i : begin rw [range_eq_Ico, ←nat.Ico_insert_succ_left (nat.succ_pos _), sum_insert], exact λ h, zero_lt_one.not_le (mem_Ico.1 h).1, end ... ≤ a * b/(b - 1) : nat.geom_sum_le hb a _ ... = (a * 1 + a * (b - 1))/(b - 1) : by rw [←mul_add, add_tsub_cancel_of_le (one_le_two.trans hb)] ... = a + a/(b - 1) : by rw [mul_one, nat.add_mul_div_right _ _ (tsub_pos_of_lt hb), add_comm] end section order variables {n : ℕ} {x : α} lemma geom_sum_pos [strict_ordered_semiring α] (hx : 0 ≤ x) (hn : n ≠ 0) : 0 < ∑ i in range n, x ^ i := sum_pos' (λ k hk, pow_nonneg hx _) ⟨0, mem_range.2 hn.bot_lt, by simp⟩ lemma geom_sum_pos_and_lt_one [strict_ordered_ring α] (hx : x < 0) (hx' : 0 < x + 1) (hn : 1 < n) : 0 < ∑ i in range n, x ^ i ∧ ∑ i in range n, x ^ i < 1 := begin refine nat.le_induction _ _ n (show 2 ≤ n, from hn), { rw geom_sum_two, exact ⟨hx', (add_lt_iff_neg_right _).2 hx⟩ }, clear hn n, intros n hn ihn, rw [geom_sum_succ, add_lt_iff_neg_right, ← neg_lt_iff_pos_add', neg_mul_eq_neg_mul], exact ⟨mul_lt_one_of_nonneg_of_lt_one_left (neg_nonneg.2 hx.le) (neg_lt_iff_pos_add'.2 hx') ihn.2.le, mul_neg_of_neg_of_pos hx ihn.1⟩ end lemma geom_sum_alternating_of_le_neg_one [strict_ordered_ring α] (hx : x + 1 ≤ 0) (n : ℕ) : if even n then ∑ i in range n, x ^ i ≤ 0 else 1 ≤ ∑ i in range n, x ^ i := begin have hx0 : x ≤ 0 := (le_add_of_nonneg_right zero_le_one).trans hx, induction n with n ih, { simp only [even_zero, geom_sum_zero, le_refl] }, simp only [nat.even_add_one, geom_sum_succ], split_ifs at ih, { rw [if_neg (not_not_intro h), le_add_iff_nonneg_left], exact mul_nonneg_of_nonpos_of_nonpos hx0 ih }, { rw if_pos h, refine (add_le_add_right _ _).trans hx, simpa only [mul_one] using mul_le_mul_of_nonpos_left ih hx0 } end lemma geom_sum_alternating_of_lt_neg_one [strict_ordered_ring α] (hx : x + 1 < 0) (hn : 1 < n) : if even n then ∑ i in range n, x ^ i < 0 else 1 < ∑ i in range n, x ^ i := begin have hx0 : x < 0, from ((le_add_iff_nonneg_right _).2 zero_le_one).trans_lt hx, refine nat.le_induction _ _ n (show 2 ≤ n, from hn), { simp only [geom_sum_two, hx, true_or, even_bit0, if_true_left_eq_or] }, clear hn n, intros n hn ihn, simp only [nat.even_add_one, geom_sum_succ], by_cases hn' : even n, { rw [if_pos hn'] at ihn, rw [if_neg, lt_add_iff_pos_left], exact mul_pos_of_neg_of_neg hx0 ihn, exact not_not_intro hn', }, { rw [if_neg hn'] at ihn, rw [if_pos], swap, { exact hn' }, have := add_lt_add_right (mul_lt_mul_of_neg_left ihn hx0) 1, rw mul_one at this, exact this.trans hx } end lemma geom_sum_pos' [linear_ordered_ring α] (hx : 0 < x + 1) (hn : n ≠ 0) : 0 < ∑ i in range n, x ^ i := begin obtain _ | _ | n := n, { cases hn rfl }, { simp }, obtain hx' | hx' := lt_or_le x 0, { exact (geom_sum_pos_and_lt_one hx' hx n.one_lt_succ_succ).1 }, { exact geom_sum_pos hx' (by simp only [nat.succ_ne_zero, ne.def, not_false_iff]) } end lemma odd.geom_sum_pos [linear_ordered_ring α] (h : odd n) : 0 < ∑ i in range n, x ^ i := begin rcases n with (_ | _ | k), { exact ((show ¬ odd 0, from dec_trivial) h).elim }, { simp only [geom_sum_one, zero_lt_one] }, rw nat.odd_iff_not_even at h, rcases lt_trichotomy (x + 1) 0 with hx | hx | hx, { have := geom_sum_alternating_of_lt_neg_one hx k.one_lt_succ_succ, simp only [h, if_false] at this, exact zero_lt_one.trans this }, { simp only [eq_neg_of_add_eq_zero_left hx, h, neg_one_geom_sum, if_false, zero_lt_one] }, { exact geom_sum_pos' hx k.succ.succ_ne_zero } end lemma geom_sum_pos_iff [linear_ordered_ring α] (hn : n ≠ 0) : 0 < ∑ i in range n, x ^ i ↔ odd n ∨ 0 < x + 1 := begin refine ⟨λ h, _, _⟩, { rw [or_iff_not_imp_left, ←not_le, ←nat.even_iff_not_odd], refine λ hn hx, h.not_le _, simpa [if_pos hn] using geom_sum_alternating_of_le_neg_one hx n }, { rintro (hn | hx'), { exact hn.geom_sum_pos }, { exact geom_sum_pos' hx' hn } } end lemma geom_sum_ne_zero [linear_ordered_ring α] (hx : x ≠ -1) (hn : n ≠ 0) : ∑ i in range n, x ^ i ≠ 0 := begin obtain _ | _ | n := n, { cases hn rfl }, { simp }, rw [ne.def, eq_neg_iff_add_eq_zero, ←ne.def] at hx, obtain h | h := hx.lt_or_lt, { have := geom_sum_alternating_of_lt_neg_one h n.one_lt_succ_succ, split_ifs at this, { exact this.ne }, { exact (zero_lt_one.trans this).ne' } }, { exact (geom_sum_pos' h n.succ.succ_ne_zero).ne' } end lemma geom_sum_eq_zero_iff_neg_one [linear_ordered_ring α] (hn : n ≠ 0) : ∑ i in range n, x ^ i = 0 ↔ x = -1 ∧ even n := begin refine ⟨λ h, _, λ ⟨h, hn⟩, by simp only [h, hn, neg_one_geom_sum, if_true]⟩, contrapose! h, obtain rfl | hx := eq_or_ne x (-1), { simp only [h rfl, neg_one_geom_sum, if_false, ne.def, not_false_iff, one_ne_zero] }, { exact geom_sum_ne_zero hx hn } end lemma geom_sum_neg_iff [linear_ordered_ring α] (hn : n ≠ 0) : ∑ i in range n, x ^ i < 0 ↔ even n ∧ x + 1 < 0 := by rw [← not_iff_not, not_lt, le_iff_lt_or_eq, eq_comm, or_congr (geom_sum_pos_iff hn) (geom_sum_eq_zero_iff_neg_one hn), nat.odd_iff_not_even, ← add_eq_zero_iff_eq_neg, not_and, not_lt, le_iff_lt_or_eq, eq_comm, ← imp_iff_not_or, or_comm, and_comm, decidable.and_or_imp, or_comm] end order
c86bd4a7fae22ae147216e9fc9aaab0f73f99d7a
ce89339993655da64b6ccb555c837ce6c10f9ef4
/zeptometer/topprover/14.lean
6d41091a5d621045105d9ccf5153130eb247b207
[]
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
4,868
lean
-- 14.lean open nat def mod2 : ℕ → ℕ | 0 := 0 | (succ n) := match mod2 n with | 0 := 1 | (succ n) := 0 end inductive even : ℕ → Prop | even_zero : even 0 | even_succ : ∀ n, even n → even (n + 2) inductive odd : ℕ → Prop | odd_succ : ∀ n, even n → odd (n + 1) lemma even_or_odd : ∀n, even n ∨ odd n := begin intro n, induction n, left, apply even.even_zero, cases n_ih, right, apply odd.odd_succ, assumption, left, induction n_n, cases n_ih, apply even.even_succ, cases n_ih, assumption end lemma not_even_and_odd : ∀n, even n → odd n → false := begin intros n e_n, induction e_n, intro o_zero, cases o_zero, intro o_e_2, cases o_e_2, cases o_e_2_a, simp [nat.add] at *, induction o_e_2_a, apply e_n_ih, apply odd.odd_succ, assumption, assumption end lemma even_plus_even_is_even : ∀n, even n → ∀m, even m → even (n + m) := begin intros n e_n, induction e_n, intros, simp, assumption, intros m em, have comm : e_n_n + 2 + m = (e_n_n + m) + 2 := by simp, rw comm, apply even.even_succ, apply e_n_ih, assumption end lemma even_is_two_times : ∀n, even (2 * n) := begin intro n, induction n, simp, apply even.even_zero, rw mul_succ, have two_is_even : even 2 := even.even_succ 0 even.even_zero, apply even_plus_even_is_even; assumption end lemma even_times_is_even : ∀n, even n → ∀m, even (n * m) := begin intros n e_n, induction e_n, intros, simp, apply even.even_zero, intro m, rw right_distrib, have e_2_m : even (2 * m) := even_is_two_times m, apply even_plus_even_is_even, apply e_n_ih, assumption end lemma even_plus_odd_is_odd(n m : ℕ) : even n → odd m → odd (n + m) := begin intro e_n, induction e_n, intro, simp [nat.add], assumption, intro o_m, have comm1 : e_n_n + 2 = 2 + e_n_n := nat.add_comm e_n_n 2, have comm : e_n_n + 2 + m = nat.succ(nat.succ(e_n_n + m)) := calc e_n_n + 2 + m = 2 + e_n_n + m : by rw comm1 ... = 2 + (e_n_n + m) : by rw nat.add_assoc ... = nat.succ (nat.succ (e_n_n + m)) : begin rw nat.succ_add, congr, apply one_add end, rw comm, apply odd.odd_succ, induction o_m, have comm2 : (e_n_n + (o_m_n + 1)) = succ (e_n_n + o_m_n) := calc (e_n_n + (o_m_n + 1)) = e_n_n + (succ o_m_n) : by rw nat.add_succ ... = succ (e_n_n + o_m_n) : by rw nat.add_succ, rw comm2, apply even.even_succ, apply even_plus_even_is_even, assumption, assumption end lemma odd_times_odd_is_odd (n m : ℕ) : odd(n) → odd(m) → odd(n * m) := begin intro n, induction n, intro o_m, rw right_distrib, simp, rw add_comm, apply even_plus_odd_is_odd, apply even_times_is_even, assumption, assumption end theorem evenness_is_idempotent : ∀n, even n ↔ even (n * n) := begin intro n, apply iff.intro, intro e_n, apply even_times_is_even, assumption, have n_e_o : even n ∨ odd n := even_or_odd n, cases n_e_o, intros, assumption, have n_e_o_sq : odd (n * n) := begin apply odd_times_odd_is_odd; assumption end, intro e_n_sq, apply false.elim, apply not_even_and_odd, assumption, assumption end lemma even_is_0_in_mod2 (n : ℕ) : even n → mod2 n = 0 := begin intro e_n, induction e_n, simp [mod2], rw add_comm, simp [mod2], rw e_n_ih, simp [mod2] end lemma odd_is_1_in_mod2 (n : ℕ) : odd n → mod2 n = 1 := begin intro o_n, induction o_n, simp [mod2], have p : mod2 o_n_n = 0 := begin apply even_is_0_in_mod2, assumption end, rw p, simp [mod2] end theorem multiplication_in_f2_is_idempotent(n : ℕ) : mod2 n = mod2 (n * n) := begin have n_is_even_or_odd : even n ∨ odd n := by apply even_or_odd, cases n_is_even_or_odd, have e_n_sq : even (n * n) := begin apply (iff.elim_left (evenness_is_idempotent n)), assumption end, have mod2_n_0 : mod2 n = 0 := even_is_0_in_mod2 n n_is_even_or_odd, have mod2_n_sq_0 : mod2 (n * n) = 0 := even_is_0_in_mod2 (n * n) e_n_sq, rw mod2_n_0, rw mod2_n_sq_0, have o_n_sq : odd(n * n) := odd_times_odd_is_odd n n n_is_even_or_odd n_is_even_or_odd, have mod2_n_1 : mod2 n = 1 := odd_is_1_in_mod2 n n_is_even_or_odd, have mod2_n_sq_1 : mod2 (n * n) = 1 := odd_is_1_in_mod2 (n * n) o_n_sq, rw mod2_n_1, rw mod2_n_sq_1 end
40c8c62e47fd6912a4f360fe1d83880995e1a9de
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/cls_err.lean
c33b8ab57eee40f9c84bcc4bc6b992c477dba9e6
[ "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
217
lean
-- universe variables u class inductive H (A : Type u) | mk : A → H definition foo {A : Type u} [h : H A] : A := H.rec (λa, a) h section variable A : Type u variable h : H A definition tst : A := foo end
334661a5bb8c570e3ea54604df4c53147a5e22ae
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Module/basic.lean
3c3231364323ad0f67f25bbabe089bdecacc2158
[ "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
10,901
lean
/- Copyright (c) 2019 Robert A. Spencer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert A. Spencer, Markus Himmel -/ import algebra.category.Group.basic import category_theory.limits.shapes.kernels import category_theory.linear import linear_algebra.basic import category_theory.conj /-! # The category of `R`-modules `Module.{v} R` is the category of bundled `R`-modules with carrier in the universe `v`. We show that it is preadditive and show that being an isomorphism, monomorphism and epimorphism is equivalent to being a linear equivalence, an injective linear map and a surjective linear map, respectively. ## Implementation details To construct an object in the category of `R`-modules from a type `M` with an instance of the `module` typeclass, write `of R M`. There is a coercion in the other direction. Similarly, there is a coercion from morphisms in `Module R` to linear maps. Unfortunately, Lean is not smart enough to see that, given an object `M : Module R`, the expression `of R M`, where we coerce `M` to the carrier type, is definitionally equal to `M` itself. This means that to go the other direction, i.e., from linear maps/equivalences to (iso)morphisms in the category of `R`-modules, we have to take care not to inadvertently end up with an `of R M` where `M` is already an object. Hence, given `f : M →ₗ[R] N`, * if `M N : Module R`, simply use `f`; * if `M : Module R` and `N` is an unbundled `R`-module, use `↿f` or `as_hom_left f`; * if `M` is an unbundled `R`-module and `N : Module R`, use `↾f` or `as_hom_right f`; * if `M` and `N` are unbundled `R`-modules, use `↟f` or `as_hom f`. Similarly, given `f : M ≃ₗ[R] N`, use `to_Module_iso`, `to_Module_iso'_left`, `to_Module_iso'_right` or `to_Module_iso'`, respectively. The arrow notations are localized, so you may have to `open_locale Module` to use them. Note that the notation for `as_hom_left` clashes with the notation used to promote functions between types to morphisms in the category `Type`, so to avoid confusion, it is probably a good idea to avoid having the locales `Module` and `category_theory.Type` open at the same time. If you get an error when trying to apply a theorem and the `convert` tactic produces goals of the form `M = of R M`, then you probably used an incorrect variant of `as_hom` or `to_Module_iso`. -/ open category_theory open category_theory.limits open category_theory.limits.walking_parallel_pair universes v u variables (R : Type u) [ring R] /-- The category of R-modules and their morphisms. Note that in the case of `R = ℤ`, we can not impose here that the `ℤ`-multiplication field from the module structure is defeq to the one coming from the `is_add_comm_group` structure (contrary to what we do for all module structures in mathlib), which creates some difficulties down the road. -/ structure Module := (carrier : Type v) [is_add_comm_group : add_comm_group carrier] [is_module : module R carrier] attribute [instance] Module.is_add_comm_group Module.is_module namespace Module instance : has_coe_to_sort (Module.{v} R) (Type v) := ⟨Module.carrier⟩ instance Module_category : category (Module.{v} R) := { hom := λ M N, M →ₗ[R] N, id := λ M, 1, comp := λ A B C f g, g.comp f, id_comp' := λ X Y f, linear_map.id_comp _, comp_id' := λ X Y f, linear_map.comp_id _, assoc' := λ W X Y Z f g h, linear_map.comp_assoc _ _ _ } instance Module_concrete_category : concrete_category.{v} (Module.{v} R) := { forget := { obj := λ R, R, map := λ R S f, (f : R → S) }, forget_faithful := { } } instance has_forget_to_AddCommGroup : has_forget₂ (Module R) AddCommGroup := { forget₂ := { obj := λ M, AddCommGroup.of M, map := λ M₁ M₂ f, linear_map.to_add_monoid_hom f } } -- TODO: instantiate `linear_map_class` once that gets defined instance (M N : Module R) : add_monoid_hom_class (M ⟶ N) M N := { coe := λ f, f, .. linear_map.add_monoid_hom_class } /-- The object in the category of R-modules associated to an R-module -/ def of (X : Type v) [add_comm_group X] [module R X] : Module R := ⟨X⟩ @[simp] lemma forget₂_obj (X : Module R) : (forget₂ (Module R) AddCommGroup).obj X = AddCommGroup.of X := rfl @[simp] lemma forget₂_obj_Module_of (X : Type v) [add_comm_group X] [module R X] : (forget₂ (Module R) AddCommGroup).obj (of R X) = AddCommGroup.of X := rfl @[simp] lemma forget₂_map (X Y : Module R) (f : X ⟶ Y) : (forget₂ (Module R) AddCommGroup).map f = linear_map.to_add_monoid_hom f := rfl /-- Typecheck a `linear_map` as a morphism in `Module R`. -/ def of_hom {R : Type u} [ring R] {X Y : Type v} [add_comm_group X] [module R X] [add_comm_group Y] [module R Y] (f : X →ₗ[R] Y) : of R X ⟶ of R Y := f @[simp] lemma of_hom_apply {R : Type u} [ring R] {X Y : Type v} [add_comm_group X] [module R X] [add_comm_group Y] [module R Y] (f : X →ₗ[R] Y) (x : X) : of_hom f x = f x := rfl instance : inhabited (Module R) := ⟨of R punit⟩ instance of_unique {X : Type v} [add_comm_group X] [module R X] [i : unique X] : unique (of R X) := i @[simp] lemma coe_of (X : Type v) [add_comm_group X] [module R X] : (of R X : Type v) = X := rfl variables {R} /-- Forgetting to the underlying type and then building the bundled object returns the original module. -/ @[simps] def of_self_iso (M : Module R) : Module.of R M ≅ M := { hom := 𝟙 M, inv := 𝟙 M } lemma is_zero_of_subsingleton (M : Module R) [subsingleton M] : is_zero M := begin refine ⟨λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩⟩, { ext, have : x = 0 := subsingleton.elim _ _, rw [this, map_zero, map_zero], }, { ext, apply subsingleton.elim } end instance : has_zero_object (Module.{v} R) := ⟨⟨of R punit, is_zero_of_subsingleton _⟩⟩ variables {R} {M N U : Module.{v} R} @[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl @[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) : ((f ≫ g) : M → U) = g ∘ f := rfl lemma comp_def (f : M ⟶ N) (g : N ⟶ U) : f ≫ g = g.comp f := rfl end Module variables {R} variables {X₁ X₂ : Type v} /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom [add_comm_group X₁] [module R X₁] [add_comm_group X₂] [module R X₂] : (X₁ →ₗ[R] X₂) → (Module.of R X₁ ⟶ Module.of R X₂) := id localized "notation `↟` f : 1024 := Module.as_hom f" in Module /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom_right [add_comm_group X₁] [module R X₁] {X₂ : Module.{v} R} : (X₁ →ₗ[R] X₂) → (Module.of R X₁ ⟶ X₂) := id localized "notation `↾` f : 1024 := Module.as_hom_right f" in Module /-- Reinterpreting a linear map in the category of `R`-modules. -/ def Module.as_hom_left {X₁ : Module.{v} R} [add_comm_group X₂] [module R X₂] : (X₁ →ₗ[R] X₂) → (X₁ ⟶ Module.of R X₂) := id localized "notation `↿` f : 1024 := Module.as_hom_left f" in Module /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. -/ @[simps] def linear_equiv.to_Module_iso {g₁ : add_comm_group X₁} {g₂ : add_comm_group X₂} {m₁ : module R X₁} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) : Module.of R X₁ ≅ Module.of R X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := begin ext, exact e.left_inv x, end, inv_hom_id' := begin ext, exact e.right_inv x, end, } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso' {M N : Module.{v} R} (i : M ≃ₗ[R] N) : M ≅ N := { hom := i, inv := i.symm, hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso'_left {X₁ : Module.{v} R} {g₂ : add_comm_group X₂} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) : X₁ ≅ Module.of R X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. This version is better than `linear_equiv_to_Module_iso` when applicable, because Lean can't see `Module.of R M` is defeq to `M` when `M : Module R`. -/ @[simps] def linear_equiv.to_Module_iso'_right {g₁ : add_comm_group X₁} {m₁ : module R X₁} {X₂ : Module.{v} R} (e : X₁ ≃ₗ[R] X₂) : Module.of R X₁ ≅ X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := linear_map.ext $ λ x, by simp, inv_hom_id' := linear_map.ext $ λ x, by simp } namespace category_theory.iso /-- Build a `linear_equiv` from an isomorphism in the category `Module R`. -/ @[simps] def to_linear_equiv {X Y : Module R} (i : X ≅ Y) : X ≃ₗ[R] Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_smul' := by tidy, }. end category_theory.iso /-- linear equivalences between `module`s are the same as (isomorphic to) isomorphisms in `Module` -/ @[simps] def linear_equiv_iso_Module_iso {X Y : Type u} [add_comm_group X] [add_comm_group Y] [module R X] [module R Y] : (X ≃ₗ[R] Y) ≅ (Module.of R X ≅ Module.of R Y) := { hom := λ e, e.to_Module_iso, inv := λ i, i.to_linear_equiv, } namespace Module instance : preadditive (Module.{v} R) := { add_comp' := λ P Q R f f' g, show (f + f') ≫ g = f ≫ g + f' ≫ g, by { ext, simp }, comp_add' := λ P Q R f g g', show f ≫ (g + g') = f ≫ g + f ≫ g', by { ext, simp } } section variables {S : Type u} [comm_ring S] instance : linear S (Module.{v} S) := { hom_module := λ X Y, linear_map.module, smul_comp' := by { intros, ext, simp }, comp_smul' := by { intros, ext, simp }, } variables {X Y X' Y' : Module.{v} S} lemma iso.hom_congr_eq_arrow_congr (i : X ≅ X') (j : Y ≅ Y') (f : X ⟶ Y) : iso.hom_congr i j f = linear_equiv.arrow_congr i.to_linear_equiv j.to_linear_equiv f := rfl lemma iso.conj_eq_conj (i : X ≅ X') (f : End X) : iso.conj i f = linear_equiv.conj i.to_linear_equiv f := rfl end end Module instance (M : Type u) [add_comm_group M] [module R M] : has_coe (submodule R M) (Module R) := ⟨ λ N, Module.of R N ⟩
180edd127e8afdfc5a96f2dbeb05d8a8aedf6dbb
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/algebra/char_p.lean
b52010a3073946d49d82be095c5a76f801ec43f5
[ "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
5,382
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau Characteristic of semirings. -/ import data.padics.padic_norm data.nat.choose universes u v /-- The generator of the kernel of the unique homomorphism ℤ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (classical.not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ /-- Noncomuptable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x := by letI := (classical.some_spec (char_p.exists_unique α)).1; unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α) theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α := (classical.some_spec (char_p.exists_unique α)).2 p C theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p) [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := begin rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, choose_self], rw [nat.cast_one, mul_one, mul_one, add_left_inj], transitivity, { refine finset.sum_eq_single 0 _ _, { intros b h1 h2, have := nat.prime.dvd_choose (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp, rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p], simp only [mul_zero] }, { intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } }, rw [pow_zero, nat.sub_zero, one_mul, choose_zero_right, nat.cast_one, mul_one] end /-- The frobenius map that sends x to x^p -/ def frobenius (α : Type u) [monoid α] (p : ℕ) (x : α) : α := x^p theorem frobenius_def (α : Type u) [monoid α] (p : ℕ) (x : α) : frobenius α p x = x ^ p := rfl theorem frobenius_mul (α : Type u) [comm_monoid α] (p : ℕ) (x y : α) : frobenius α p (x * y) = frobenius α p x * frobenius α p y := mul_pow x y p theorem frobenius_one (α : Type u) [monoid α] (p : ℕ) : frobenius α p 1 = 1 := one_pow _ theorem is_monoid_hom.map_frobenius {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] (p : ℕ) (x : α) : f (frobenius α p x) = frobenius β p (f x) := by unfold frobenius; induction p; simp only [pow_zero, pow_succ, is_monoid_hom.map_one f, is_monoid_hom.map_mul f, *] instance {α : Type u} [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : is_ring_hom (frobenius α p) := { map_one := frobenius_one α p, map_mul := frobenius_mul α p, map_add := add_pow_char α hp } section variables (α : Type u) [comm_ring α] (p : ℕ) [hp : nat.prime p] theorem frobenius_zero : frobenius α p 0 = 0 := zero_pow hp.pos variables [char_p α p] (x y : α) include hp theorem frobenius_add : frobenius α p (x + y) = frobenius α p x + frobenius α p y := is_ring_hom.map_add _ theorem frobenius_neg : frobenius α p (-x) = -frobenius α p x := is_ring_hom.map_neg _ theorem frobenius_sub : frobenius α p (x - y) = frobenius α p x - frobenius α p y := is_ring_hom.map_sub _ end theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] (x y : α) (H : frobenius α p x = frobenius α p y) : x = y := by rw ← sub_eq_zero at H ⊢; rw ← frobenius_sub at H; exact pow_eq_zero H theorem frobenius_nat_cast (α : Type u) [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℕ) : frobenius α p x = x := by induction x; simp only [nat.cast_zero, nat.cast_succ, frobenius_zero, frobenius_one, frobenius_add, *]
e8b4acbbe79a9ec9577cd73bb3a206bf53b6960d
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/analysis/calculus/fderiv.lean
f002a8dc3f4bef12582fcc342535b385070e94b8
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
102,534
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.tangent_cone /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set open_locale topological_space classical noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = nhds_within x s` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (nhds_within x s) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (nhds_within x s), { conv in (nhds_within x s) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (nhds_within x s) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := begin have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y, { rintros y ⟨c, d, dtop, clim, cdlim⟩, exact tendsto_nhds_unique (by simp) (h.lim at_top dtop clim cdlim) (h₁.lim at_top dtop clim cdlim) }, have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y, { assume y hy, apply submodule.span_induction hy, { exact λy hy, A y hy }, { simp only [continuous_linear_map.map_zero] }, { simp {contextual := tt} }, { simp {contextual := tt} } }, have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B, have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K := closure_mono this, have : y ∈ closure K := this hy, rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this }, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := unique_diff_within_at.eq (H x hx) h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin split, { assume H, have : tendsto (λ (z : E), z + x) (𝓝 0) (𝓝 (0 + x)), from tendsto_id.add tendsto_const_nhds, rw [zero_add] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel', add_comm z] }, { assume H, have : tendsto (λ (z : E), z - x) (𝓝 x) (𝓝 (x - x)), from tendsto_id.sub tendsto_const_nhds, rw [sub_self] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel'_right] } end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only [], rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ nhds_within x s) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp [mem_closure_iff_nhds_within_ne_bot] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ nhds_within x s) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem has_strict_fderiv_at_congr_of_mem_sets (h : ∀ᶠ y in 𝓝 x, f₀ y = f₁ y) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall _ $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_mem_sets (h : has_strict_fderiv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f y = f₁ y) : has_strict_fderiv_at f₁ f' x := (has_strict_fderiv_at_congr_of_mem_sets h₁ (λ _, rfl)).1 h theorem has_fderiv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall _ $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_mem_sets (h : has_fderiv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (has_fderiv_at_filter_congr_of_mem_sets hx hL $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_mem_sets (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_mem_nhds_within (h : has_fderiv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_mem_sets h h₁ hx lemma has_fderiv_at.congr_of_mem_nhds (h : has_fderiv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_mem_nhds_within (h : differentiable_within_at 𝕜 f s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_mem_nhds_within h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_mem_nhds (h : differentiable_at 𝕜 f x) (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma fderiv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_mem_sets hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_mem_nhds_within (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply fderiv_within_congr_of_mem_nhds_within hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma fderiv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := (mem_of_nhds hL : _), rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact fderiv_within_congr_of_mem_nhds_within unique_diff_within_at_univ hL A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp]protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (nhds_within x s) ≤ nhds_within (f x) (f '' s) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (f x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, tendsto_le_left inf_le_right (tendsto_principal_principal.2 hs)] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 f₂ x) := has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at) lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at prod.fst (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at prod.snd (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.add_const c).fderiv_within hxs lemma fderiv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.add_const c).fderiv theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_add c).fderiv_within hxs lemma fderiv_const_add (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := (hf.has_fderiv_at.const_add c).fderiv end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at 𝕜 f x) : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := h.has_fderiv_at.neg.fderiv end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.sub_const c).fderiv_within hxs lemma fderiv_sub_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.sub_const c).fderiv theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_sub c).fderiv_within hxs lemma fderiv_const_sub (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := (hf.has_fderiv_at.const_sub c).fderiv end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext q, rcases q with ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall _ $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall _ $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall _ $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall _ $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : closure (range f') = univ) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E), f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F), { assume v hv, apply submodule.span_induction hv, { exact λ w hw, submodule.subset_span (h.maps_to_tangent_cone hw) }, { simp }, { assume w₁ w₂ hw₁ hw₂, rw continuous_linear_map.map_add, exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ }, { assume a w hw, rw continuous_linear_map.map_smul, exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } }, rw [unique_diff_within_at, ← univ_subset_iff], split, show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2, show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc univ ⊆ closure (range f') : univ_subset_iff.2 h' ... = closure (f' '' univ) : by rw image_univ ... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1 ... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : closure_mono (image_closure_subset_closure_image f'.cont) ... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure ... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) : closure_mono (image_subset_iff.mpr B) end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin apply h.unique_diff_within_at hs, have : set.range (e' : E →L[𝕜] F) = univ := e'.to_linear_equiv.to_equiv.range_eq_univ, rw [this, closure_univ] end lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} local attribute [instance] normed_space.restrict_scalars lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
b0b30698181dc7e886ed96d52302849e8ced5ffe
fe84e287c662151bb313504482b218a503b972f3
/src/undergraduate/MAS114/Semester 1/exercises_1.lean
ab8b4ba146af5658e31f1f1782cbc2d58142eebc
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
57,629
lean
import data.real.basic data.real.sqrt data.fintype.basic algebra.big_operators data.nat.modeq data.int.modeq data.fin.basic data.zmod.basic import tactic.find tactic.squeeze import combinatorics.fiber namespace MAS114 namespace exercises_1 namespace Q2 /- part (i) We are asked about the following definition: f : ℕ → ℝ is given by f n = sqrt n. There are two wrinkles when formalising this in Lean. Firstly, like most things with reals, we need to mark the definition as noncomputable. In Lean, "computation" means "exact computation", and we do not have algorithms for exact computation with real numbers. Secondly, the Lean library defines a function real.sqrt : ℝ → ℝ, which is the ordinary square root for nonnegative arguments, but is zero for negative arguments, so it does not satisfy (real.sqrt x) ^ 2 = x in general. Because of this, we feel obliged to provide a proof that our function f has the expected property (f n) ^ 2 = n. Note here that the right hand side of this equation involves an implicit cast from ℕ to ℝ. We will have to do quite a lot of messing around with casts like this. -/ noncomputable def f : ℕ → ℝ := λ n, real.sqrt n lemma f_spec : ∀ n : ℕ, (f n) ^ 2 = n := begin intro n, have h0 : (0 : ℝ) ≤ (n : ℝ) := nat.cast_le.mpr (nat.zero_le n), exact real.sq_sqrt h0, end /- f is injective -/ lemma f_inj : function.injective f := begin intros n₀ n₁ e, let n_R₀ := (n₀ : ℝ), let n_R₁ := (n₁ : ℝ), have e₁ : n_R₀ = n_R₁ := calc n_R₀ = (f n₀) ^ 2 : (f_spec n₀).symm ... = (f n₁) ^ 2 : by rw[e] ... = n_R₁ : (f_spec n₁), exact nat.cast_inj.mp e₁, end /- f is not surjective -/ lemma f_not_surj : ¬ (function.surjective f) := begin intro f_surj, rcases (f_surj (1/2)) with ⟨n,e0⟩, let n_R := (n : ℝ), have e1 : 4 * n_R = (((4 * n) : ℕ) : ℝ) := by { dsimp[n_R],rw[nat.cast_mul,nat.cast_bit0,nat.cast_bit0,nat.cast_one] }, let e2 := calc 4 * n_R = 4 * ((f n) ^ 2) : by rw[f_spec n] ... = 4 * ((1 / 2) ^ 2) : by rw[e0] ... = 1 : by ring ... = ((1 : ℕ) : ℝ) : by rw[nat.cast_one], let e3 : 4 * n = 1 := nat.cast_inj.mp (e1.symm.trans e2), let e4 := calc 0 = (4 * n) % 4 : (nat.mul_mod_right 4 n).symm ... = 1 % 4 : by rw[e3] ... = 1 : rfl, injection e4, end /- part (ii) -/ /- We are asked to pass judgement on the following "definition" : g : ℤ → ℝ is given by g n = sqrt n. We do this by proving that there is no map g : ℤ → ℝ such that (g n) ^ 2 = n for all n. -/ lemma square_nonneg {α : Type*} [linear_ordered_ring α] (x : α) : 0 ≤ x * x := begin rcases (le_or_gt 0 x) with x_nonneg | x_neg, {exact mul_nonneg x_nonneg x_nonneg,}, {have x_nonpos : x ≤ 0 := le_of_lt x_neg, exact mul_nonneg_of_nonpos_of_nonpos x_nonpos x_nonpos } end /- I am surprised that this does not seem to be in the library. Perhaps I did not look in the right way. -/ lemma neg_one_not_square {α : Type*} [linear_ordered_ring α] (x : α) : x * x ≠ -1 := begin intro e0, have e1 : (0 : α) ≤ -1 := e0.subst (square_nonneg x), have e2 : (-1 : α) < 0 := neg_neg_of_pos zero_lt_one, exact not_le_of_gt e2 e1, end lemma g_does_not_exist : ¬ ∃ (g : ℤ → ℝ), (∀ n : ℤ, (g n) ^ 2 = n) := begin rintro ⟨g,g_spec⟩, let x := g ( -1 ), have e0 : -1 = (( -1 : ℤ ) : ℝ) := by simp, have e1 : x * x = -1 := by { rw[← pow_two], dsimp[x], rw[e0], exact g_spec ( -1 )}, exact neg_one_not_square x e1, end /- part (iii) -/ /- We are asked about the following definition: h : ℤ → ℕ is given by h(n) = |n|. There is no problem with formalising the definition. Note, however, that the Lean library defines both int.abs : ℤ → ℤ and int.nat_abs : ℤ → ℕ; we need the latter here. -/ def h : ℤ → ℕ := int.nat_abs /- h is not injective -/ lemma h_not_inj : ¬ (function.injective h) := begin intro h_inj, let e : (1 : ℤ) = (-1 : ℤ) := @h_inj (1 : ℤ) (-1 : ℤ) rfl, injection e, end /- h is surjective -/ lemma h_surj : function.surjective h := begin intro n,use n,refl, end /- part (iv) -/ /- We are asked to pass judgement on the following "definition" : i : ℕ → ℕ is given by i n = 100 - n. We do this by proving that there is no map i : ℕ → ℕ such that (i n) + n = 100 for all n. Note, however, that Lean would happily accept the definition def i (n : ℕ) : ℕ := 100 - n, but it would interpret the minus sign as truncated subtraction, so that i n = 0 for n ≥ 100. -/ lemma i_does_not_exist : ¬ ∃ (i : ℕ → ℕ), (∀ n : ℕ, (i n) + n = 100) := begin rintro ⟨i,i_spec⟩, have e0 : 101 ≤ 100 := (i_spec 101).subst (nat.le_add_left 101 (i 101)), let e1 : 100 < 101 := nat.lt_succ_self 100, exact not_le_of_gt e1 e0, end /- part (v) -/ /- We are asked about the following definition: j : ℤ → ℤ is given by j(n) = - n. There is no problem with formalising the definition. We then prove that j j = 1, so j is self-inverse. We use theorems from the library to deduce from this that j is injective, surjective and bijective, rather than working directly from the definitions. -/ def j : ℤ → ℤ := λ n, - n lemma jj (n : ℤ) : j (j n) = n := by simp[j] lemma j_inj : function.injective j := function.left_inverse.injective jj lemma j_surj : function.surjective j := function.right_inverse.surjective jj lemma j_bij : function.bijective j := ⟨j_inj,j_surj⟩ /- part (vi) -/ /- We are asked to pass judgement on the following "definition" : k : ℝ → ℤ sends x ∈ ℝ to the closest integer. We define precisely what it means for n to be the closest integer to x : we should have | x - m | > | x - n | for any integer m ≠ n. We then show that if m ∈ ℤ, there is no closest integer to m + 1/2. From this we deduce that there is no function k with the expected properties. This is much harder work than you might think. A lot of the problem is caused by the cast maps ℤ → ℚ → ℝ -/ def is_closest_integer (n : ℤ) (x : ℝ) := ∀ m : ℤ, m ≠ n → abs ( x - m ) > abs ( x - n ) /- Even basic identities like 1/2 - 1 = -1/2 cannot easily be proved directly in ℝ, because there are no general algorithms for exact calculation in ℝ. We need to work in ℚ and then apply the cast map. -/ def half_Q : ℚ := 1 / 2 def neg_half_Q : ℚ := - half_Q noncomputable def half_R : ℝ := half_Q noncomputable def neg_half_R : ℝ := neg_half_Q /- Here is a small identity that could in principle be proved by a long string of applications of the commutative ring axioms. The "ring" tactic automates the process of finding this string. For reasons that I do not fully understand, the ring tactic seems to work more reliably if we do it in a separate lemma so that the terms are just free variables. We can then substitute values for this variables as an extra step. In particular, we will substitute h = 1/2, and then give a separate argument that the final term 2 * h - 1 is zero. -/ lemma misc_identity (m n h : ℝ) : (m + h) - (2 * m + 1 - n) = - ((m + h) - n) + (2 * h - 1) := by ring /- We now prove that there is no closest integer to m + 1/2. The obvious approach would be to focus attention on the candidates n = m and n = m + 1, but it turns out that that creates more work than necessary. It is more efficient to prove that for all n, the integer k = 2 m + 1 - n is different from n and lies at the same distance from m + 1/2, so n does not have the required property. -/ lemma no_closest_integer (n m : ℤ) : ¬ (is_closest_integer n ((m : ℝ) + half_R)) := begin intro h0, let x_Q : ℚ := (m : ℚ) + half_Q, let x_R : ℝ := (m : ℝ) + half_R, let k := 2 * m + 1 - n, by_cases e0 : k = n, {-- In this block we consider the possibility that k = n, and -- show that it is impossible. exfalso, dsimp[k] at e0, let e1 := calc (1 : ℤ) = (2 * m + 1 - n) + n - 2 * m : by ring ... = n + n - 2 * m : by rw[e0] ... = 2 * (n - m) : by ring, have e2 := calc (1 : ℤ) = int.mod 1 2 : rfl ... = int.mod (2 * (n - m)) 2 : congr_arg (λ x, int.mod x 2) e1 ... = 0 : int.mul_mod_right 2 (n - m), exact (dec_trivial : (1 : ℤ) ≠ 0) e2, },{ let h1 := ne_of_gt (h0 k e0), let u_R := x_R - n, let v_R := x_R - k, have h2 : v_R = - u_R + (2 * half_R - 1) := begin dsimp[u_R,v_R,x_R,k], rw[int.cast_sub,int.cast_add,int.cast_mul,int.cast_bit0,int.cast_one], exact misc_identity (↑ m) (↑ n) half_R, end, have h3 : 2 * half_R - 1 = 0 := by { dsimp[half_R,half_Q], norm_num }, rw[h3,add_zero] at h2, have h4 : abs v_R = abs u_R := by rw[h2,abs_neg], exact h1 h4, } end lemma k_does_not_exist : ¬ ∃ (k : ℝ → ℤ), (∀ x : ℝ, is_closest_integer (k x) x) := begin rintro ⟨k,k_spec⟩, let x : ℝ := (0 : ℤ) + half_R, exact no_closest_integer (k x) 0 (k_spec x) end end Q2 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q3 /- Here we ask various questions about functions between the sets A = {1,2,..,10} and B = {1,2,...,100}. Everything would be a bit easier if we modified the question and used the sets {0,...,9} and {0,...,99} instead, because Lean starts things at zero by default. However, we have decided to bite the bullet and deal with the extra complexity. -/ def A0 : finset ℕ := (finset.range 11).erase 0 def B0 : finset ℕ := (finset.range 101).erase 0 def A := {n // n ∈ A0} def B := {n // n ∈ B0} instance A_fintype : fintype A := by {dsimp[A],apply_instance} instance B_fintype : fintype B := by {dsimp[B],apply_instance} lemma A_card : fintype.card A = 10 := fintype.subtype_card A0 (by {intro H,refl}) lemma B_card : fintype.card B = 100 := fintype.subtype_card B0 (by {intro H,refl}) lemma A_in_B {i : ℕ} (i_in_A : i ∈ A0) : i ∈ B0 := begin rcases (finset.mem_erase.mp i_in_A) with ⟨i_ne_0,i_in_range_11⟩, have i_lt_11 := finset.mem_range.mp i_in_range_11, have : 11 < 101 := dec_trivial, have i_lt_101 : i < 101 := lt_trans i_lt_11 this, have i_in_range_101 := finset.mem_range.mpr i_lt_101, exact finset.mem_erase.mpr ⟨i_ne_0,i_in_range_101⟩ end /- We want to define f : A → B to be the inclusion. In Lean, the proof that A is contained in B has to be wrapped in to the definition of f. -/ def f : A → B := λ ⟨i,i_in_A⟩, ⟨i,A_in_B i_in_A⟩ /- f is injective -/ lemma f_inj : function.injective f := begin rintros ⟨i,i_in_A⟩ ⟨j,j_in_A⟩ e, dsimp[f] at e, have e1 : i = j := congr_arg subtype.val e, exact subtype.eq e1 end /- We now want to define g : B → A by g n = n for n ≤ 10, and g n = 10 for n > 10. We first define this as a map g0 : B → ℕ, then give the proof that g0 B ⊆ A, then use this to construct g as a map B → A. -/ def g0 : B → ℕ := λ ⟨j,j_in_B⟩, if j < 11 then j else 10 lemma g0_in_A : ∀ b : B, (g0 b ∈ A0) | ⟨j,j_in_B⟩ := begin rcases (finset.mem_erase.mp j_in_B) with ⟨j_ne_0,j_in_range_101⟩, have j_lt_101 := finset.mem_range.mp j_in_range_101, by_cases h : j < 11, {have : g0 ⟨j,j_in_B⟩ = j := by {dsimp[g0],rw[if_pos h]}, rw[this], let j_in_range_11 := finset.mem_range.mpr h, exact finset.mem_erase.mpr ⟨j_ne_0,j_in_range_11⟩, },{ have : g0 ⟨j,j_in_B⟩ = 10 := by {dsimp[g0],rw[if_neg h]}, rw[this], exact finset.mem_erase.mpr ⟨dec_trivial,finset.mem_range.mpr dec_trivial⟩, } end def g (b : B) : A := ⟨g0 b,g0_in_A b⟩ /- We have g f a = a for all a ∈ A, so g is a left inverse for f -/ lemma gf : function.left_inverse g f | ⟨i,i_in_A⟩ := begin rcases (finset.mem_erase.mp i_in_A) with ⟨i_ne_0,i_in_range_11⟩, have i_lt_11 := finset.mem_range.mp i_in_range_11, apply subtype.eq, dsimp[f,g,g0], rw[if_pos i_lt_11], end /- g is surjective (because it has a right inverse) -/ lemma g_surj : function.surjective g := function.right_inverse.surjective gf /- There is no injective map j : B → A, because |B| > |A|. We use the library theorem fintype.card_le_of_injective for this. -/ lemma no_injection : ¬ ∃ j : B → A, function.injective j := begin rintro ⟨j,j_inj⟩, let h := fintype.card_le_of_injective j j_inj, rw[A_card,B_card] at h, exact not_lt_of_ge h dec_trivial, end /- There is no surjective map p : A → B, because |B| > |A|. We use the theorem card_le_of_projective for this. Surprisingly, this does not seem to be in the standard library. It is proved in the separate file fiber.lean distributed alongside this one. -/ lemma no_surjection : ¬ ∃ p : A → B, function.surjective p := begin rintro ⟨p,p_surj⟩, let h := combinatorics.card_le_of_surjective p_surj, rw[A_card,B_card] at h, exact not_lt_of_ge h dec_trivial, end end Q3 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q4 /- This question is about "gappy sets", ie subsets s in fin n = {0,...,n-1} such that s contains no adjacent pairs {i,i+1}. -/ /- We find it convenient to introduce a new notation for the zero element in fin m. Notice that this only exists when m > 0, or equivalently, when m has the form n.succ = n + 1 for some n. -/ def fin.z {n : ℕ} : fin (n.succ) := 0 lemma fin.z_val {n : ℕ} : (@fin.z n).val = 0 := rfl lemma fin.succ_ne_z {n : ℕ} (a : fin n) : a.succ ≠ fin.z := begin cases a with a_val a_is_lt, intro e, replace e := fin.veq_of_eq e, cases e end def is_gappy : ∀ {n : ℕ} (s : finset (fin n)), Prop | 0 _ := true | (nat.succ n) s := ∀ a : fin n, ¬ (a.cast_succ ∈ s ∧ a.succ ∈ s) instance is_gappy_decidable : forall {n : ℕ} (s : finset (fin n)), decidable (is_gappy s) | 0 _ := by {dsimp[is_gappy],apply_instance} | (nat.succ n) s := by {dsimp[is_gappy],apply_instance} def gappy' (n : ℕ) : finset (finset (fin n)) := finset.univ.filter is_gappy def gappy (n : ℕ) : Type := { s : finset (fin n) // is_gappy s } instance {n : ℕ} : fintype (gappy n) := by { dsimp[gappy], apply_instance } instance {n : ℕ} : decidable_eq (gappy n) := by { dsimp[gappy], apply_instance } instance {n : ℕ} : has_repr (gappy n) := ⟨λ (s : gappy n), repr s.val⟩ instance {n : ℕ} : has_mem (fin n) (gappy n) := ⟨λ i s, i ∈ s.val⟩ def shift {n : ℕ} (s : finset (fin n)) : finset (fin n.succ) := s.image fin.succ def unshift {n : ℕ} (s : finset (fin n.succ)) : finset (fin n) := finset.univ.filter (λ a, a.succ ∈ s) lemma mem_shift {n : ℕ} (s : finset (fin n)) (a : fin n.succ) : a ∈ shift s ↔ ∃ b : fin n, b ∈ s ∧ b.succ = a := begin rw[shift],split, {intro a_in_shift, rcases finset.mem_image.mp a_in_shift with ⟨b,⟨b_in_s,e⟩⟩, use b, exact ⟨b_in_s,e⟩, },{ rintro ⟨b,⟨b_in_s,e⟩⟩, exact finset.mem_image.mpr ⟨b,⟨b_in_s,e⟩⟩, } end lemma zero_not_in_shift {n : ℕ} (s : finset (fin n)) : fin.z ∉ shift s := begin intro h0, rcases ((mem_shift s) 0).mp h0 with ⟨⟨b,b_is_lt⟩,⟨b_in_s,e⟩⟩, cases congr_arg subtype.val e end lemma succ_mem_shift_iff {n : ℕ} (s : finset (fin n)) (a : fin n) : a.succ ∈ shift s ↔ a ∈ s := begin rw[mem_shift s a.succ], split,{ rintro ⟨b,⟨b_in_s,u⟩⟩, rw[(fin.succ_inj.mp u).symm], exact b_in_s, },{ intro a_in_s,use a,exact ⟨a_in_s,rfl⟩, } end lemma mem_unshift {n : ℕ} (s : finset (fin n.succ)) (a : fin n) : a ∈ unshift s ↔ a.succ ∈ s := begin rw[unshift,finset.mem_filter], split, {intro h,exact h.right}, {intro h,exact ⟨finset.mem_univ a,h⟩ } end lemma unshift_shift {n : ℕ} (s : finset (fin n)) : unshift (shift s) = s := begin ext,rw[mem_unshift (shift s) a],rw[succ_mem_shift_iff], end lemma unshift_insert {n : ℕ} (s : finset (fin n.succ)) : unshift (insert fin.z s) = unshift s := begin ext,rw[mem_unshift,mem_unshift,finset.mem_insert], split, {intro h,rcases h with h0 | h1, {exfalso,exact fin.succ_ne_z a h0}, {exact h1} }, {exact λ h,or.inr h} end lemma shift_unshift0 {n : ℕ} (s : finset (fin n.succ)) (h : fin.z ∉ s) : shift (unshift s) = s := begin ext, rcases a with ⟨_ | b_val,a_is_lt⟩, {have e : @fin.z n = ⟨0,a_is_lt⟩ := fin.eq_of_veq rfl, rw[← e],simp only[zero_not_in_shift,h], },{ let b : fin n := ⟨b_val,nat.lt_of_succ_lt_succ a_is_lt⟩, have e : b.succ = ⟨b_val.succ,a_is_lt⟩ := by { apply fin.eq_of_veq, refl }, rw[← e,succ_mem_shift_iff (unshift s) b,mem_unshift s b], } end lemma shift_unshift1 {n : ℕ} (s : finset (fin n.succ)) (h : fin.z ∈ s) : insert fin.z (shift (unshift s)) = s := begin ext, rw[finset.mem_insert], rcases a with ⟨_ | b_val,a_is_lt⟩, {have e : @fin.z n = ⟨0,a_is_lt⟩ := fin.eq_of_veq rfl, rw[← e],simp only[h,eq_self_iff_true,true_or], },{ let b : fin n := ⟨b_val,nat.lt_of_succ_lt_succ a_is_lt⟩, have e : b.succ = ⟨b_val.succ,a_is_lt⟩ := by { apply fin.eq_of_veq, refl, }, rw[← e,succ_mem_shift_iff (unshift s) b,mem_unshift s b], split, {rintro (u0 | u1), {exfalso,exact fin.succ_ne_z b u0,}, {exact u1} }, {intro h,right,exact h,} } end lemma shift_gappy : ∀ {n : ℕ} {s : finset (fin n)}, is_gappy s → is_gappy (shift s) | 0 _ _ := λ a, fin.elim0 a | (nat.succ n) s s_gappy := begin rintros ⟨a,a_is_lt⟩ ⟨a_in_shift,a_succ_in_shift⟩, let a₀ : fin n.succ := ⟨a,a_is_lt⟩, let a_in_s : a₀ ∈ s := (succ_mem_shift_iff s a₀).mp a_succ_in_shift, rcases (mem_shift s a₀.cast_succ).mp a_in_shift with ⟨⟨b,b_is_lt⟩,⟨b_in_s,eb⟩⟩, let b₀ : fin n.succ := ⟨b,b_is_lt⟩, replace eb := congr_arg subtype.val eb, change b.succ = a at eb, let c_is_lt : b < n := nat.lt_of_succ_lt_succ (eb.symm ▸ a_is_lt), let c₀ : fin n := ⟨b,c_is_lt⟩, have ebc : b₀ = fin.cast_succ c₀ := fin.eq_of_veq rfl, have eac : a₀ = fin.succ c₀ := fin.eq_of_veq (nat.succ.inj (by { change a.succ = b.succ.succ, rw[← eb],})), change b₀ ∈ s at b_in_s, rw[ebc] at b_in_s, rw[eac] at a_in_s, exact s_gappy c₀ ⟨b_in_s,a_in_s⟩, end lemma unshift_gappy : ∀ {n : ℕ} {s : finset (fin n.succ)}, is_gappy s → is_gappy (unshift s) | 0 _ _ := trivial | (nat.succ n) s s_gappy := begin rintros ⟨a,a_is_lt⟩ ⟨a_in_unshift,a_succ_in_unshift⟩, let a₀ : fin n := ⟨a,a_is_lt⟩, let a_succ_in_s := (mem_unshift s a₀.cast_succ).mp a_in_unshift, let a_succ_succ_in_s := (mem_unshift s a₀.succ).mp a_succ_in_unshift, have e : a₀.cast_succ.succ = a₀.succ.cast_succ := fin.eq_of_veq rfl, rw[e] at a_succ_in_s, exact s_gappy a₀.succ ⟨a_succ_in_s,a_succ_succ_in_s⟩, end lemma insert_gappy : ∀ {n : ℕ} {s : finset (fin n.succ.succ)}, is_gappy s → (∀ (a : fin n.succ.succ), a ∈ s → a.val ≥ 2) → is_gappy (insert fin.z s) := begin rintros n s s_gappy s_big ⟨a,a_is_lt⟩ ⟨a_in_t,a_succ_in_t⟩, rcases finset.mem_insert.mp a_succ_in_t with a_succ_zero | a_succ_in_s; let a₀ : fin n.succ := ⟨a,a_is_lt⟩, {exact fin.succ_ne_z a₀ a_succ_zero}, let a_pos : 0 < a := nat.lt_of_succ_lt_succ (s_big a₀.succ a_succ_in_s), rcases finset.mem_insert.mp a_in_t with a_zero | a_in_s, {replace a_zero : a = 0 := congr_arg subtype.val a_zero, rw[a_zero] at a_pos, exact lt_irrefl 0 a_pos, },{ exact s_gappy a₀ ⟨a_in_s,a_succ_in_s⟩, } end def i {n : ℕ} (s : gappy n) : gappy n.succ := ⟨shift s.val,shift_gappy s.property⟩ lemma i_val {n : ℕ} (s : gappy n) : (i s).val = shift s.val := rfl lemma zero_not_in_i {n : ℕ} (s : gappy n) : fin.z ∉ (i s) := zero_not_in_shift s.val lemma shift_big {n : ℕ} (s : finset (fin n)) : ∀ (a : fin n.succ.succ), a ∈ shift (shift s) → a.val ≥ 2 := begin rintro ⟨a,a_is_lt⟩ ma, rcases (mem_shift (shift s) ⟨a,a_is_lt⟩).mp ma with ⟨⟨b,b_is_lt⟩,⟨mb,eb⟩⟩, rcases (mem_shift s ⟨b,b_is_lt⟩).mp mb with ⟨⟨c,c_is_lt⟩,⟨mc,ec⟩⟩, rw[← eb,← ec], apply nat.succ_le_succ, apply nat.succ_le_succ, exact nat.zero_le c end def j {n : ℕ} (s : gappy n) : gappy n.succ.succ := ⟨insert fin.z (shift (shift s.val)), begin let h := insert_gappy (shift_gappy (shift_gappy s.property)) (shift_big s.val), exact h, end⟩ lemma j_val {n : ℕ} (s : gappy n) : (j s).val = insert fin.z (shift (shift s.val)) := rfl lemma zero_in_j {n : ℕ} (s : gappy n) : fin.z ∈ (j s) := finset.mem_insert_self _ _ def p {n : ℕ} : (gappy n) ⊕ (gappy n.succ) → gappy n.succ.succ | (sum.inl s) := j s | (sum.inr s) := i s def q {n : ℕ} (s : gappy n.succ.succ) : (gappy n) ⊕ (gappy n.succ) := if fin.z ∈ s then sum.inl ⟨unshift (unshift s.val),unshift_gappy (unshift_gappy s.property)⟩ else sum.inr ⟨unshift s.val,unshift_gappy s.property⟩ lemma qp {n : ℕ} (s : (gappy n) ⊕ (gappy n.succ)) : q (p s) = s := begin rcases s with s | s; dsimp[p,q], {rw[if_pos (zero_in_j s)], congr,apply subtype.eq, change unshift (unshift (j s).val) = s.val, rw[j_val,unshift_insert,unshift_shift,unshift_shift], }, {rw[if_neg (zero_not_in_i s)],congr,apply subtype.eq, change unshift (i s).val = s.val, rw[i_val,unshift_shift], } end lemma pq {n : ℕ} (s : gappy n.succ.succ) : p (q s) = s := begin dsimp[q],split_ifs; dsimp[p]; apply subtype.eq, {rw[j_val], change insert fin.z (shift (shift (unshift (unshift s.val )))) = s.val, have z_not_in_us : fin.z ∉ unshift s.val := begin intro z_in_us, let z_succ_in_s := (mem_unshift s.val fin.z).mp z_in_us, exact s.property fin.z ⟨h,z_succ_in_s⟩, end, rw[shift_unshift0 (unshift s.val) z_not_in_us], rw[shift_unshift1 s.val h], },{ rw[i_val], change shift (unshift s.val) = s.val, exact shift_unshift0 s.val h, } end def gappy_equiv {n : ℕ} : ((gappy n) ⊕ (gappy n.succ)) ≃ (gappy n.succ.succ) := { to_fun := p, inv_fun := q, left_inv := qp, right_inv := pq } lemma gappy_card_step (n : ℕ) : fintype.card (gappy n.succ.succ) = fintype.card (gappy n) + fintype.card (gappy n.succ) := by rw[← fintype.card_congr (@gappy_equiv n),fintype.card_sum] def fibonacci : ℕ → ℕ | 0 := 0 | 1 := 1 | (nat.succ (nat.succ n)) := (fibonacci n) + (fibonacci n.succ) lemma gappy_card : ∀ (n : ℕ), fintype.card (gappy n) = fibonacci n.succ.succ | 0 := rfl | 1 := rfl | (nat.succ (nat.succ n)) := begin rw[gappy_card_step n,gappy_card n,gappy_card n.succ], dsimp[fibonacci],refl, end end Q4 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q5 def A : finset ℕ := [0,1,2].to_finset def B : finset ℕ := [0,1,2,3].to_finset def C : finset ℤ := [-2,-1,0,1,2].to_finset def D : finset ℤ := [-3,-2,-1,0,1,2,3].to_finset lemma int.lt_succ_iff {n m : ℤ} : n < m + 1 ↔ n ≤ m := ⟨int.le_of_lt_add_one,int.lt_add_one_of_le⟩ lemma nat.square_le {n m : ℕ} : m ^ 2 ≤ n ↔ m ≤ n.sqrt := ⟨λ h0, le_of_not_gt (λ h1, not_le_of_gt ((pow_two m).symm.subst (nat.sqrt_lt.mp h1)) h0), λ h0, le_of_not_gt (λ h1,not_le_of_gt (nat.sqrt_lt.mpr ((pow_two m).subst h1)) h0)⟩ lemma nat.square_lt {n m : ℕ} : m ^ 2 < n.succ ↔ m ≤ n.sqrt := (@nat.lt_succ_iff (m ^ 2) n).trans (@nat.square_le n m) lemma int.abs_le {n m : ℤ} : abs m ≤ n ↔ (- n ≤ m ∧ m ≤ n) := begin by_cases hm : 0 ≤ m, { rw[abs_of_nonneg hm], exact ⟨ λ hmn, ⟨le_trans (neg_nonpos_of_nonneg (le_trans hm hmn)) hm,hmn⟩, λ hmn, hmn.right ⟩ },{ let hma := le_of_lt (lt_of_not_ge hm), let hmb := neg_nonneg_of_nonpos hma, rw[abs_of_nonpos hma], exact ⟨ λ hmn, ⟨(neg_neg m) ▸ (neg_le_neg hmn),le_trans (le_trans hma hmb) hmn⟩, λ hmn, (neg_neg n) ▸ (neg_le_neg hmn.left), ⟩ } end lemma int.abs_le' {n : ℕ} {m : ℤ} : m.nat_abs ≤ n ↔ (- (n : ℤ) ≤ m ∧ m ≤ n) := begin let h := @int.abs_le n m, rw[int.abs_eq_nat_abs,int.coe_nat_le] at h, exact h, end lemma int.abs_square (n : ℤ) : n ^ 2 = (abs n) ^ 2 := begin by_cases h0 : n ≥ 0, {rw[abs_of_nonneg h0]}, {rw[abs_of_neg (lt_of_not_ge h0),pow_two,pow_two,neg_mul_neg],} end lemma int.abs_square' (n : ℤ) : n ^ 2 = ((int.nat_abs n) ^ 2 : ℕ) := calc n ^ 2 = n * n : pow_two n ... = ↑ (n.nat_abs * n.nat_abs) : int.nat_abs_mul_self.symm ... = ↑ (n.nat_abs ^ 2 : ℕ) : by rw[(pow_two n.nat_abs).symm] lemma int.square_le {n : ℕ} {m : ℤ} : m ^ 2 ≤ n ↔ - (n.sqrt : ℤ) ≤ m ∧ m ≤ n.sqrt := begin rw[int.abs_square',int.coe_nat_le,nat.square_le,int.abs_le'], end lemma int.square_lt {n : ℕ} {m : ℤ} : m ^ 2 < n.succ ↔ - (n.sqrt : ℤ) ≤ m ∧ m ≤ n.sqrt := begin rw[int.abs_square',int.coe_nat_lt,nat.square_lt,int.abs_le'], end lemma A_spec (n : ℕ) : n ∈ A ↔ n ^ 2 < 9 := begin have sqrt_8 : 2 = nat.sqrt 8 := nat.eq_sqrt.mpr ⟨dec_trivial,dec_trivial⟩, exact calc n ∈ A ↔ n ∈ finset.range 3 : by rw[(dec_trivial : A = finset.range 3)] ... ↔ n < 3 : finset.mem_range ... ↔ n ≤ 2 : by rw[nat.lt_succ_iff] ... ↔ n ≤ nat.sqrt 8 : by rw[← sqrt_8] ... ↔ n ^ 2 < 9 : by rw[nat.square_lt] end lemma B_spec (n : ℕ) : n ∈ B ↔ n ^ 2 ≤ 9 := begin have sqrt_9 : 3 = nat.sqrt 9 := nat.eq_sqrt.mpr ⟨dec_trivial,dec_trivial⟩, exact calc n ∈ B ↔ n ∈ finset.range 4 : by rw[(dec_trivial : B = finset.range 4)] ... ↔ n < 4 : finset.mem_range ... ↔ n ≤ 3 : by rw[nat.lt_succ_iff] ... ↔ n ≤ nat.sqrt 9 : by rw[← sqrt_9] ... ↔ n ^ 2 ≤ 9 : by rw[nat.square_le] end lemma C_spec (n : ℤ) : n ∈ C ↔ n ^ 2 < 9 := begin have sqrt_8 : 2 = nat.sqrt 8 := nat.eq_sqrt.mpr ⟨dec_trivial,dec_trivial⟩, have e0 : (3 : ℤ) = ((2 : ℕ) : ℤ) + (1 : ℤ) := rfl, have e1 : (-2 : ℤ) = - ((2 : ℕ) : ℤ) := rfl, have e2 : ((nat.succ 8) : ℤ) = 9 := rfl, let e3 := @int.square_lt 8 n, let J := finset.Ico (-2 : ℤ) (3 : ℤ), exact calc n ∈ C ↔ n ∈ J : by rw[(dec_trivial : C = J)] ... ↔ -2 ≤ n ∧ n < 3 : finset.mem_Ico ... ↔ - ((2 : ℕ) : ℤ) ≤ n ∧ n < (2 : ℕ) + 1 : by rw[e0,e1] ... ↔ - ((2 : ℕ) : ℤ) ≤ n ∧ n ≤ (2 : ℕ) : by rw[int.lt_succ_iff] ... ↔ - (nat.sqrt 8 : ℤ) ≤ n ∧ n ≤ nat.sqrt 8 : by rw[← sqrt_8] ... ↔ n ^ 2 < nat.succ 8 : by rw[e3] ... ↔ n ^ 2 < 9 : by rw[e2], end lemma D_spec (n : ℤ) : n ∈ D ↔ n ^ 2 ≤ 9 := begin have sqrt_9 : 3 = nat.sqrt 9 := nat.eq_sqrt.mpr ⟨dec_trivial,dec_trivial⟩, have e0 : (4 : ℤ) = ((3 : ℕ) : ℤ) + (1 : ℤ) := rfl, have e1 : (-3 : ℤ) = - ((3 : ℕ) : ℤ) := rfl, have e2 : ((9 : ℕ) : ℤ) = 9 := rfl, let e3 := @int.square_le 9 n, let J := finset.Ico (-3 : ℤ) (4 : ℤ), exact calc n ∈ D ↔ n ∈ J : by rw[(dec_trivial : D = J)] ... ↔ -3 ≤ n ∧ n < 4 : finset.mem_Ico ... ↔ - ((3 : ℕ) : ℤ) ≤ n ∧ n < (3 : ℕ) + 1 : by rw[e0,e1] ... ↔ - ((3 : ℕ) : ℤ) ≤ n ∧ n ≤ (3 : ℕ) : by rw[int.lt_succ_iff] ... ↔ - (nat.sqrt 9 : ℤ) ≤ n ∧ n ≤ nat.sqrt 9 : by rw[← sqrt_9] ... ↔ n ^ 2 ≤ (9 : ℕ) : by rw[e3] ... ↔ n ^ 2 ≤ 9 : by rw[e2] end end Q5 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q6 def A : finset ℕ := [1,2,4].to_finset def B : finset ℕ := [2,3,5].to_finset def C : finset ℕ := [1,2,3,4,5].to_finset def D : finset ℕ := [2].to_finset def E : finset ℕ := [3,4].to_finset lemma L1 : A ∪ B = C := dec_trivial lemma L2 : A ∩ B = D := dec_trivial lemma L3 : D ∩ E = ∅ := dec_trivial end Q6 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q7 local attribute [instance] classical.prop_decidable lemma L1 (U : Type) (A B : set U) : (A ∪ B)ᶜ = Aᶜ ∩ Bᶜ := by { simp } lemma L2 (U : Type) (A B : set U) : (A ∩ B)ᶜ = Aᶜ ∪ Bᶜ := begin ext x, rw[set.mem_union,set.mem_compl_iff,set.mem_compl_iff,set.mem_compl_iff], by_cases hA : (x ∈ A); by_cases hB : (x ∈ B); simp[hA,hB], end end Q7 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q8 end Q8 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q9 def even (n : ℤ) := ∃ k : ℤ, n = 2 * k def odd (n : ℤ) := ∃ k : ℤ, n = 2 * k + 1 lemma L1 (n : ℤ) : even n → even (n ^ 2) := begin rintro ⟨k,e⟩, use n * k, rw[e,pow_two],ring, end lemma L2 (n m : ℤ) : even n → even m → even (n + m) := begin rintros ⟨k,ek⟩ ⟨l,el⟩, use k + l, rw[ek,el], ring, end lemma L3 (n m : ℤ) : odd n → odd m → odd (n * m) := begin rintros ⟨k,ek⟩ ⟨l,el⟩, use k + l + 2 * k * l, rw[ek,el], ring, end /- Do the converses -/ end Q9 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q10 def f : ℝ → ℝ := λ x, x ^ 2 - 7 * x + 10 def f_alt : ℝ → ℝ := λ x, (x - 2) * (x - 5) lemma f_eq (x : ℝ) : f x = f_alt x := by {dsimp[f,f_alt],ring} lemma f_two : f 2 = 0 := by {dsimp[f],ring} lemma f_five : f 5 = 0 := by {dsimp[f],ring} lemma two_ne_five : (2 : ℝ) ≠ (5 : ℝ) := begin intro e, have h2 : (2 : ℝ) = ((2 : ℕ) : ℝ) := by {simp}, have h5 : (5 : ℝ) = ((5 : ℕ) : ℝ) := by {simp}, rw[h5,h2] at e, exact (dec_trivial : 2 ≠ 5) (nat.cast_inj.mp e), end def P1 (x : ℝ) : Prop := f x = 0 → x = 2 ∧ x = 5 def P2 (x : ℝ) : Prop := f x = 0 → x = 2 ∨ x = 5 lemma L1 : ¬ (∀ x : ℝ, P1 x) := begin intro h_P1, exact two_ne_five (h_P1 2 f_two).right, end lemma L2 : ∀ x : ℝ, P2 x := begin intros x fx, rw[f_eq x] at fx, dsimp[f_alt] at fx, rcases eq_zero_or_eq_zero_of_mul_eq_zero fx with x_eq_2 | x_eq_5, {exact or.inl (sub_eq_zero.mp x_eq_2)}, {exact or.inr (sub_eq_zero.mp x_eq_5)} end end Q10 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q11 end Q11 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q12 def f : ℚ → ℚ := λ x, x * (x + 1) * (2 * x + 1) / 6 lemma f_step (x : ℚ) : f (x + 1) = (f x) + (x + 1) ^ 2 := begin dsimp[f], apply sub_eq_zero.mp, rw[pow_two], ring, end lemma sum_of_squares : ∀ (n : ℕ), (((finset.range n.succ).sum (λ i, i ^ 2)) : ℚ) = f n | 0 := begin rw[finset.sum_range_succ,finset.sum_range_zero,f],simp, end | (n + 1) := begin rw[finset.sum_range_succ,sum_of_squares n], have : (((n + 1) : ℕ) : ℚ) = ((n + 1) : ℚ ) := by simp, rw[this,f_step n], end end Q12 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q13 end Q13 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q14 def f : ℚ → ℚ := λ x, (x + 1) / (2 * x) lemma f_step (x : ℚ) : x > 1 → (1 - 1 / (x ^ 2)) * f (x - 1) = f x := begin intro x_big, let d := 2 * (x - 1) * (x ^ 2) , let nz_2 : (2 : ℚ) ≠ 0 := by norm_num, /- Prove that all relevant denominators are nonzero -/ let nz_x : x ≠ 0 := (ne_of_lt (by linarith [x_big])).symm, let nz_2x : 2 * x ≠ 0 := mul_ne_zero nz_2 nz_x, let nz_x2 : x ^ 2 ≠ 0 := by {rw[pow_two], exact mul_ne_zero nz_x nz_x}, let nz_y : x - 1 ≠ 0 := (ne_of_lt (by linarith [x_big])).symm, let nz_2y : 2 * (x - 1) ≠ 0 := mul_ne_zero nz_2 nz_y, let nz_d : d ≠ 0 := mul_ne_zero nz_2y nz_x2, let e0 := calc (x ^ 2) * (1 - 1 / (x ^ 2)) = (x ^ 2) * 1 - (x ^ 2) * (1 / (x ^ 2)) : by rw[mul_sub] ... = x ^ 2 - 1 : by rw[mul_one,mul_div_cancel' 1 nz_x2], let e1 := calc d * (1 - 1 / (x ^ 2)) = (2 * (x - 1)) * ((x ^ 2) * (1 - 1 / (x ^ 2))) : by rw[mul_assoc] ... = (2 * (x - 1)) * (x ^ 2 - 1) : by rw[e0] ... = (x ^ 2 - 1) * (2 * (x - 1)) : by rw[mul_comm], let e2 : (x - 1) + 1 = x := by ring, let e3 := calc (2 * (x - 1)) * f (x - 1) = (2 * (x - 1)) * (((x - 1) + 1) / (2 * (x - 1))) : rfl ... = (2 * (x - 1)) * (x / (2 * (x - 1))) : by rw[e2] ... = x * (2 * (x - 1) / (2 * (x - 1))) : mul_div_left_comm (2 * (x - 1)) x (2 * (x - 1)) ... = x : by rw[div_self nz_2y,mul_one], let e4 := calc d * ((1 - 1 / (x ^ 2)) * f (x - 1)) = (d * (1 - 1 / (x ^ 2))) * f (x - 1) : by rw[← mul_assoc] ... = (x ^ 2 - 1) * (2 * (x - 1)) * f (x - 1) : by rw[e1] ... = (x ^ 2 - 1) * x : by rw[mul_assoc,e3] ... = (x ^ 2) * x - 1 * x : by rw[sub_mul] ... = x ^ 3 - x : by rw[← pow_succ',one_mul], let e5 : d = (x * x - x) * (2 * x) := by {dsimp[d],ring}, let e6 := calc d * f x = d * ((x + 1) / (2 * x)) : rfl ... = ((x * x - x) * (2 * x)) * ((x + 1) / (2 * x)) : by rw[e5] ... = (x * x - x) * ((2 * x) * ((x + 1) / (2 * x))) : by rw[mul_assoc] ... = (x * x - x) * (x + 1) : by rw[mul_div_left_comm,div_self nz_2x,mul_one] ... = x ^ 3 - x : by ring, exact (mul_right_inj' nz_d).mp (e4.trans e6.symm) end lemma product_formula : ∀ (n : ℕ), (finset.range n).prod (λ k, ((1 - 1 / ((k + 2) ^ 2)) : ℚ)) = f (n + 1) | 0 := by { rw[finset.prod_range_zero,f], norm_num } | (n + 1) := begin have e0 : 1 < n + 2 := by linarith, have e1 : (1 : ℚ) < ((n + 2) : ℕ) := by { have : (1 : ℚ) = (1 : ℕ) := by norm_num, rw[this], exact nat.cast_lt.mpr e0, }, rw[nat.cast_add,nat.cast_bit0,nat.cast_one] at e1, rw[finset.prod_range_succ,product_formula n], let e2 := f_step (n + 2) e1, have e3 : (n : ℚ) + 2 - 1 = n + 1 := by ring, have e4 : (((n + 1) : ℕ) : ℚ) + 1 = (n : ℚ) + 2 := by { rw[nat.cast_add,nat.cast_one],ring}, rw[e3] at e2, rw[mul_comm,e2,e4], end end Q14 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q15 end Q15 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q16 lemma nat.bodd_even (n : ℕ) : (2 * n).bodd = ff := by {rw[nat.bodd_mul,nat.bodd_two,band],} lemma nat.bodd_odd (n : ℕ) : (2 * n + 1).bodd = tt := by {rw[nat.bodd_add,nat.bodd_even],refl} lemma nat.div2_even : ∀ (n : ℕ), (2 * n).div2 = n | 0 := rfl | (n + 1) := begin have : 2 * (n + 1) = (2 * n + 1).succ := by ring_nf, rw[this,nat.div2_succ,nat.bodd_odd,bool.cond_tt], rw[nat.div2_succ,nat.bodd_even,bool.cond_ff], rw[nat.div2_even n], end lemma nat.div2_odd (n : ℕ) : (2 * n + 1).div2 = n := by {rw[nat.div2_succ,nat.bodd_even,bool.cond_ff,nat.div2_even]} lemma wf_lemma : ∀ (m : ℕ), m.succ.div2 < m.succ | 0 := dec_trivial | (nat.succ m) := begin rw[nat.div2_succ], cases m.succ.bodd; simp only[bool.cond_tt,bool.cond_ff], exact lt_trans (wf_lemma m) m.succ.lt_succ_self, exact nat.succ_lt_succ (wf_lemma m) end lemma wf_lemma' (m : ℕ) : cond (nat.bodd m) (nat.succ (nat.div2 m)) (nat.div2 m) < nat.succ m := begin cases m, {exact dec_trivial,}, let u := wf_lemma m, cases m.succ.bodd; simp only[bool.cond_tt,bool.cond_ff], exact lt_trans u m.succ.lt_succ_self, exact nat.succ_lt_succ u, end def f : bool → ℕ → ℕ | ff u := 4 * u + 1 | tt u := 9 * u + 2 def a : ℕ → ℕ | 0 := 0 | (nat.succ m) := have cond (nat.bodd m) (nat.succ (nat.div2 m)) (nat.div2 m) < nat.succ m := wf_lemma' m, f m.succ.bodd (a m.succ.div2) lemma a_even (n : ℕ) : n > 0 → a (2 * n) = 4 * (a n) + 1 := begin intro n_pos, let k := n.pred, have e0 : n = k + 1 := (nat.succ_pred_eq_of_pos n_pos).symm, let m := 2 * k + 1, have e1 : 2 * n = m.succ := calc 2 * n = 2 * (k + 1) : by rw[e0] ... = 2 * k + 2 : by rw[mul_add,mul_one] ... = m.succ : rfl, rw[e1,a,← e1,nat.bodd_even,nat.div2_even,f], end lemma a_odd (n : ℕ) : a (2 * n + 1) = 9 * (a n) + 2 := begin change a (2 * n).succ = 9 * (a n) + 2, rw[a,nat.bodd_odd,nat.div2_odd,f], end lemma a_even_step (n : ℕ) : n > 0 → n ^ 2 ≤ a n → (2 * n) ^ 2 ≤ a (2 * n) := begin intros n_pos ih, rw[a_even n n_pos], exact calc (2 * n) ^ 2 = 4 * n ^ 2 : by ring ... ≤ 4 * a n : nat.mul_le_mul_left 4 ih ... ≤ 4 * a n + 1 : nat.le_succ _ end lemma a_odd_step (n : ℕ) : n ^ 2 ≤ a n → (2 * n + 1) ^ 2 ≤ a (2 * n + 1) := begin intro ih, rw[a_odd n], exact calc (2 * n + 1) ^ 2 = 4 * n + (4 * n ^ 2 + 1) : by ring ... ≤ 4 * n ^ 2 + (4 * n ^ 2 + 1) : by {apply (nat.add_le_add_iff_le_right _ _ _).mpr, rw[pow_two], exact nat.mul_le_mul_left 4 (nat.le_mul_self n),} ... = 8 * n ^ 2 + 1 : by ring ... ≤ (8 * n ^ 2 + 1) + (n ^ 2 + 1) : le_self_add ... = 9 * n ^ 2 + 2 : by ring ... ≤ 9 * a n + 2 : by {apply (nat.add_le_add_iff_le_right _ _ _).mpr, exact nat.mul_le_mul_left 9 ih,} end lemma square_le : ∀ n, n ^ 2 ≤ a n | 0 := by { norm_num } | (nat.succ m) := have cond (nat.bodd m) (nat.succ (nat.div2 m)) (nat.div2 m) < nat.succ m := wf_lemma' m, begin let e := nat.bodd_add_div2 m.succ, rw[nat.bodd_succ] at e, rw[← e], rcases m.bodd; simp only[bnot,bool.cond_ff,bool.cond_tt,zero_add], {intros u0 u1, rw[nat.add_comm 1], exact a_odd_step m.succ.div2 (square_le m.succ.div2), },{ intros u0 u1, by_cases h : m.succ.div2 = 0, {exfalso,rw[h,mul_zero] at u0,exact nat.succ_ne_zero m u0.symm}, exact a_even_step m.succ.div2 (nat.pos_of_ne_zero h) (square_le m.succ.div2), } end end Q16 /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ /- --------------------------------------------------------- -/ namespace Q17 /- This is the basic definition of fibonacci numbers. It is not good for efficient evaluation. -/ def fibonacci : ℕ → ℕ | 0 := 0 | 1 := 1 | (n + 2) := (fibonacci n) + (fibonacci (n + 1)) /- We now do a more efficient version, and prove that it is consistent with the original one. -/ def fibonacci_step : ℕ × ℕ → ℕ × ℕ := λ ⟨a,b⟩, ⟨b, a + b⟩ def fibonacci_pair : ℕ → ℕ × ℕ | 0 := ⟨0,1⟩ | (n + 1) := fibonacci_step (fibonacci_pair n) lemma fibonacci_pair_spec : ∀ n , fibonacci_pair n = ⟨fibonacci n,fibonacci n.succ⟩ | 0 := rfl | (nat.succ n) := begin rw[fibonacci_pair,fibonacci_pair_spec n,fibonacci_step,fibonacci], ext,refl,refl, end lemma fibonacci_from_pair (n : ℕ) : fibonacci n = (fibonacci_pair n).fst := by rw[fibonacci_pair_spec n]. /- We now prove a fact about the fibonacci numbers mod 2. Later we will generalise this for an arbitrary modulus. -/ lemma fibonacci_bodd_step (n : ℕ) : (fibonacci (n + 3)).bodd = (fibonacci n).bodd := begin rw[fibonacci,fibonacci,nat.bodd_add,nat.bodd_add], cases (fibonacci (n + 1)).bodd; cases (fibonacci n).bodd; refl, end lemma fibonacci_bodd : ∀ n, (fibonacci n).bodd = bnot (n % 3 = 0) | 0 := rfl | 1 := rfl | 2 := rfl | (n + 3) := begin rw[fibonacci_bodd_step n,fibonacci_bodd n,nat.add_mod_right] end lemma F2013_even : (fibonacci 2013).bodd = ff := calc (fibonacci 2013).bodd = bnot (2013 % 3 = 0) : fibonacci_bodd _ ... = ff : by norm_num /- We now do a more general theory of modular periodicity of fibonacci numbers. For computational efficiency, we give an inductive definition of modular fibonacci numbers that does not require us to calculate the non-modular ones. We then prove that it is consistent with the original definition. -/ def pair_mod (p : ℕ) : ℕ × ℕ → ℕ × ℕ := λ ⟨a,b⟩, ⟨a % p,b % p⟩ lemma pair_mod_mod (p : ℕ) : ∀ (c : ℕ × ℕ), pair_mod p (pair_mod p c) = pair_mod p c := λ ⟨a,b⟩, by {simp[pair_mod,nat.mod_mod],} def fibonacci_pair_mod (p : ℕ) : ℕ → ℕ × ℕ | 0 := pair_mod p ⟨0,1⟩ | (n + 1) := pair_mod p (fibonacci_step (fibonacci_pair_mod n)) lemma fibonacci_pair_mod_mod (p : ℕ) : ∀ n, pair_mod p (fibonacci_pair_mod p n) = fibonacci_pair_mod p n | 0 := by {rw[fibonacci_pair_mod,pair_mod_mod],} | (n + 1) := by {rw[fibonacci_pair_mod,pair_mod_mod],} lemma mod_step_mod (p : ℕ) : ∀ (c : ℕ × ℕ), pair_mod p (fibonacci_step c) = pair_mod p (fibonacci_step (pair_mod p c)) := λ ⟨a,b⟩, begin change (⟨b % p,(a + b) % p⟩ : ℕ × ℕ) = ⟨b % p % p,(a % p + b % p) % p⟩, have e0 : b % p % p = b % p := nat.mod_mod b p, have e1 : (a % p + b % p) % p = (a + b) % p := nat.modeq.add (nat.mod_mod a p) (nat.mod_mod b p), rw[e0,e1] end lemma fibonacci_pair_mod_spec (p : ℕ) : ∀ n, fibonacci_pair_mod p n = pair_mod p (fibonacci_pair n) | 0 := rfl | (n + 1) := begin rw[fibonacci_pair_mod,fibonacci_pair,fibonacci_pair_mod_spec n], rw[← mod_step_mod], end lemma fibonacci_mod_spec (p : ℕ) (n : ℕ) : (fibonacci_pair_mod p n).fst = (fibonacci n) % p := begin rw[fibonacci_pair_mod_spec,fibonacci_pair_spec,pair_mod], refl, end lemma fibonacci_pair_period₀ {p : ℕ} {d : ℕ} (h : fibonacci_pair_mod p d = pair_mod p ⟨0,1⟩) : ∀ n, fibonacci_pair_mod p (n + d) = fibonacci_pair_mod p n | 0 := by {rw[zero_add,h,fibonacci_pair_mod],} | (n + 1) := by { rw[add_assoc,add_comm 1 d,← add_assoc], rw[fibonacci_pair_mod,fibonacci_pair_mod], rw[fibonacci_pair_period₀ n], } lemma fibonacci_pair_period₁ {p : ℕ} {d : ℕ} (h : fibonacci_pair_mod p d = pair_mod p ⟨0,1⟩) (m : ℕ) : ∀ n, fibonacci_pair_mod p (m + d * n) = fibonacci_pair_mod p m | 0 := by {rw[mul_zero,add_zero]} | (n + 1) := by { have : m + d * (n + 1) = (m + d * n) + d := by ring, rw[this,fibonacci_pair_period₀ h,fibonacci_pair_period₁], } lemma fibonacci_pair_period {p : ℕ} {d : ℕ} (h : fibonacci_pair_mod p d = pair_mod p ⟨0,1⟩) (n : ℕ) : fibonacci_pair_mod p n = fibonacci_pair_mod p (n % d) := calc fibonacci_pair_mod p n = fibonacci_pair_mod p (n % d + d * (n / d)) : congr_arg (fibonacci_pair_mod p) (nat.mod_add_div n d).symm ... = fibonacci_pair_mod p (n % d) : fibonacci_pair_period₁ h (n % d) (n / d) lemma fibonacci_period {p : ℕ} {d : ℕ} (h : fibonacci_pair_mod p d = pair_mod p ⟨0,1⟩) (n : ℕ) : (fibonacci n) ≡ (fibonacci (n % d)) [MOD p] := begin rw[nat.modeq,← fibonacci_mod_spec,← fibonacci_mod_spec], rw[fibonacci_pair_period], exact h, end lemma prime_89 : nat.prime 89 := by { norm_num, } lemma L89_dvd_F2013 : 89 ∣ (fibonacci 2013) := begin apply (nat.dvd_iff_mod_eq_zero _ _).mpr, have h0 : fibonacci_pair_mod 89 44 = ⟨0,1⟩ := by {unfold fibonacci_pair_mod fibonacci_step pair_mod; norm_num}, have h1 : fibonacci_pair_mod 89 33 = ⟨0,34⟩ := by {unfold fibonacci_pair_mod fibonacci_step pair_mod; norm_num}, have h2 : 2013 % 44 = 33 := by {norm_num}, let h3 := (fibonacci_mod_spec 89 2013).symm, let h4 := congr_arg prod.fst (fibonacci_pair_period h0 2013), let h5 := congr_arg prod.fst (congr_arg (fibonacci_pair_mod 89) h2), let h6 := congr_arg prod.fst h1, exact ((h3.trans h4).trans h5).trans h6, end end Q17 namespace Q18 variables (a b c d : ℤ) lemma L_i : a ∣ b → b ∣ c → a ∣ c := by { rintros ⟨uab,hab⟩ ⟨ubc,hbc⟩, use uab * ubc, rw[← mul_assoc,← hab,← hbc] } lemma L_ii : a ∣ b → a ∣ c → a ∣ (b + c) := by { rintros ⟨uab,hab⟩ ⟨uac,hac⟩, use uab + uac, rw[mul_add,hab,hac] } lemma L_iii_false : ¬ (∀ a b c : ℤ, (a ∣ (b + c)) → (a ∣ b) ∧ (a ∣ c)) := begin intro h₀, have h₁ : (2 : ℤ) ∣ 1 := (h₀ 2 1 1 dec_trivial).left, have h₂ : ¬ ((2 : ℤ) ∣ 1) := dec_trivial, exact h₂ h₁ end lemma L_iv : a ∣ b → a ∣ c → a ∣ (b * c) := by { rintros ⟨uab,hab⟩ ⟨uac,hac⟩, use uab * c, rw[← mul_assoc,hab] } lemma L_v_false : ¬ (∀ a b c : ℤ, (a ∣ (b * c)) → (a ∣ b) ∧ (a ∣ c)) := begin intro h₀, have h₁ : (4 : ℤ) ∣ 2 := (h₀ 4 2 2 dec_trivial).left, have h₂ : ¬ ((4 : ℤ) ∣ 2) := dec_trivial, exact h₂ h₁ end lemma L_vi : a ∣ b → c ∣ d → (a * c) ∣ (b * d) := by { rintros ⟨uab,hab⟩ ⟨ucd,hcd⟩, use uab * ucd, rw[hab,hcd], ring } end Q18 namespace Q19 def f (n : ℤ) : ℤ := n * (n + 1) * (n + 2) * (n + 3) lemma f_mod (p n₀ n₁ : ℤ) (h0 : n₀ ≡ n₁ [ZMOD p]) : f n₀ ≡ f n₁ [ZMOD p] := begin have h1 : n₀ + 1 ≡ n₁ + 1 [ZMOD p] := int.modeq.add h0 rfl, have h2 : n₀ + 2 ≡ n₁ + 2 [ZMOD p] := int.modeq.add h0 rfl, have h3 : n₀ + 3 ≡ n₁ + 3 [ZMOD p] := int.modeq.add h0 rfl, have h01 : n₀ * (n₀ + 1) ≡ n₁ * (n₁ + 1) [ZMOD p] := int.modeq.mul h0 h1, have h02 : n₀ * (n₀ + 1) * (n₀ + 2) ≡ n₁ * (n₁ + 1) * (n₁ + 2) [ZMOD p] := int.modeq.mul h01 h2, exact int.modeq.mul h02 h3, end lemma f_mod_3 (n : ℕ) : f n ≡ 0 [ZMOD 3] := begin have three_pos : (3 : ℤ) > 0 := dec_trivial, rcases int.exists_unique_equiv_nat n three_pos with ⟨r,⟨r_is_lt,r_equiv⟩⟩, let e := (f_mod 3 r n r_equiv).symm, suffices : f r ≡ 0 [ZMOD 3], {exact e.trans this,}, rcases r with _ | _ | _ | r0; rw[f]; try {refl}, {exfalso, have : (3 : ℤ) = ((3 : ℕ) : ℤ) := rfl, rw[this] at r_is_lt, let h0 := int.coe_nat_lt.mp r_is_lt, replace h0 := nat.lt_of_succ_lt_succ h0, replace h0 := nat.lt_of_succ_lt_succ h0, replace h0 := nat.lt_of_succ_lt_succ h0, exact nat.not_lt_zero r0 h0, } end lemma f_mod_8 (n : ℕ) : f n ≡ 0 [ZMOD 8] := begin have eight_pos : (8 : ℤ) > 0 := dec_trivial, rcases int.exists_unique_equiv_nat n eight_pos with ⟨r,⟨r_is_lt,r_equiv⟩⟩, let e := (f_mod 8 r n r_equiv).symm, suffices : f r ≡ 0 [ZMOD 8], {exact e.trans this,}, rcases r with _ | _ | _ | _ | _ | _ | _ | _ | r0; rw[int.modeq,f]; try {norm_num}, {exfalso, have : (8 : ℤ) = ((8 : ℕ) : ℤ) := rfl, rw[this] at r_is_lt, let h0 := int.coe_nat_lt.mp r_is_lt, repeat { replace h0 := nat.lt_of_succ_lt_succ h0 }, exact nat.not_lt_zero r0 h0, } end lemma f_mod_24 (n : ℕ) : f n ≡ 0 [ZMOD 24] := begin let i3 : ℤ := 3, let i8 : ℤ := 8, have : (24 : ℤ) = i3 * i8 := rfl, rw[this], have cp : nat.coprime i3.nat_abs i8.nat_abs := by {dsimp[i3,i8], norm_num}, exact (int.modeq_and_modeq_iff_modeq_mul cp).mp ⟨f_mod_3 n,f_mod_8 n⟩, end /- ----------- Part (ii) ------------- -/ def h {R : Type} [comm_ring R] (a b c d : R) : R := (a - b) * (a - c) * (a - d) * (b - c) * (b - d) * (c - d) lemma h_shift {R : Type} [comm_ring R] (a b c d : R) : h a b c d = h (a - d) (b - d) (c - d) 0 := begin have e : ∀ x y z : R, (x - z) - (y - z) = x - y := by {intros, ring}, dsimp[h], rw[sub_zero,sub_zero,sub_zero,e,e,e] end lemma h_zero_shift {R : Type} [comm_ring R] : (∀ a b c : R, h a b c 0 = 0) → (∀ a b c d : R, h a b c d = 0) := λ p a b c d, (h_shift a b c d).trans (p (a - d) (b - d) (c - d)) lemma h_zero_3 : ∀ a b c d : zmod 3, h a b c d = 0 := h_zero_shift dec_trivial lemma h_zero_4 : ∀ a b c d : zmod 4, h a b c d = 0 := h_zero_shift dec_trivial lemma h_map {R S : Type} [comm_ring R] [comm_ring S] (φ : R →+* S) (a b c d : R) : φ (h a b c d) = h (φ a) (φ b) (φ c) (φ d) := begin dsimp[h], let em := φ.map_mul, let es := φ.map_sub, rw[em,em,em,em,em,es,es,es,es,es,es] end lemma h_zero_mod (p : ℕ+) : (∀ a b c d : zmod p, h a b c d = 0) → (∀ a b c d : ℤ, h a b c d ≡ 0 [ZMOD p]) := begin intros e a b c d, have h₀ := eq_iff_modeq_int (zmod p) (p : ℕ), have : (p : ℤ) = ((p : ℕ) : ℤ) := by norm_cast, rw [← this] at h₀, rw[← h₀], let π : ℤ →+* (zmod p) := int.cast_ring_hom _, exact calc π (h a b c d) = h (π a) (π b) (π c) (π d) : by rw[h_map π] ... = 0 : e (π a) (π b) (π c) (π d), end lemma h_zero_12 : ∀ (a b c d : ℤ), h a b c d ≡ 0 [ZMOD 12] := begin intros, let i3 : ℤ := 3, let i4 : ℤ := 4, let h3 := h_zero_mod 3 h_zero_3 a b c d, let h4 := h_zero_mod 4 h_zero_4 a b c d, have : (12 : ℤ) = i3 * i4 := rfl, rw[this], have cp : nat.coprime i3.nat_abs i4.nat_abs := by {dsimp[i3,i4], norm_num}, exact (int.modeq_and_modeq_iff_modeq_mul cp).mp ⟨h3,h4⟩ end /- Here are partial results for a more general case -/ def π (m : ℕ+) : ℤ →+* (zmod m) := int.cast_ring_hom _ def F (n : ℕ) := { ij : (fin n) × (fin n) // ij.1.val < ij.2.val } instance (n : ℕ) : fintype (F n) := by { dsimp[F], apply_instance,} def g (n : ℕ) (u : (fin n) → ℤ) : ℤ := (@finset.univ (F n) _).prod (λ ij, (u ij.val.2) - (u ij.val.1)) def g_mod (n : ℕ) (m : ℕ+) (u : (fin n) → ℤ) : zmod m := (@finset.univ (F n) _).prod (λ ij, (π m (u ij.val.2)) - (π m (u ij.val.1))) lemma g_mod_spec (n : ℕ) (m : ℕ+) (u : (fin n) → ℤ) : π m (g n u) = g_mod n m u := begin dsimp[g,g_mod], let ms := (π m).map_sub, let ma := (π m).map_add, conv begin to_rhs, congr, skip, funext, rw[← ms], end, rw[ ← (π m).map_prod ], end lemma must_repeat (n : ℕ) (m : ℕ+) (m_lt_n : m.val < n) (u : fin n → ℤ) : ∃ i j : fin n, (i.val < j.val ∧ (π m (u i)) = (π m (u j))) := begin let P := { ij : (fin n) × (fin n) // ij.1 ≠ ij.2 }, let p : P → Prop := λ ij, π m (u ij.val.1) = π m (u ij.val.2), let q := exists ij, p ij, by_cases h : q, { rcases h with ⟨⟨⟨i,j⟩,i_ne_j⟩,eq_mod⟩, change i ≠ j at i_ne_j, let i_ne_j_val : i.val ≠ j.val := λ e,i_ne_j (fin.eq_of_veq e), change (π m (u i)) = (π m (u j)) at eq_mod, by_cases hij : i.val < j.val, {use i,use j,exact ⟨hij,eq_mod⟩}, { let hij' := lt_of_le_of_ne (le_of_not_gt hij) i_ne_j_val.symm, use j,use i,exact ⟨hij',eq_mod.symm⟩ } }, { exfalso, let v : fin n → zmod m := λ i, π m (u i), have v_inj : function.injective v := begin intros i j ev, by_cases hij : i = j, { exact hij }, { exfalso, exact h ⟨⟨⟨i,j⟩,hij⟩,ev⟩ } end, haveI : fact (0 < (m : ℕ)) := ⟨m.property⟩, let e := calc n = fintype.card (fin n) : (fintype.card_fin n).symm ... ≤ fintype.card (zmod m) : fintype.card_le_of_injective v v_inj ... = m : zmod.card m ... < n : m_lt_n, exact lt_irrefl _ e } end lemma g_mod_zero (n : ℕ) (m : ℕ+) (m_lt_n : m.val < n) (u : fin n → ℤ) : g_mod n m u = 0 := begin rcases must_repeat n m m_lt_n u with ⟨i,j,i_lt_j,e⟩, dsimp[π] at e, let ij : F n := ⟨⟨i,j⟩,i_lt_j⟩, dsimp[g_mod], apply finset.prod_eq_zero (finset.mem_univ ij), dsimp[ij], change π m (u i) = π m (u j) at e, rw[e,sub_self], end end Q19 namespace Q20 lemma L1 : nat.gcd 896 1200 = 16 := begin have e0 : 1200 % 896 = 304 := by norm_num, have e1 : 896 % 304 = 288 := by norm_num, have e2 : 304 % 288 = 16 := by norm_num, have e3 : 288 % 16 = 0 := by norm_num, exact calc nat.gcd 896 1200 = nat.gcd 304 896 : by rw[nat.gcd_rec,e0] ... = nat.gcd 288 304 : by rw[nat.gcd_rec,e1] ... = nat.gcd 16 288 : by rw[nat.gcd_rec,e2] ... = nat.gcd 0 16 : by rw[nat.gcd_rec,e3] ... = 16 : nat.gcd_zero_left 16 end lemma L2 : nat.gcd 123456789 987654321 = 9 := begin have e0 : 987654321 % 123456789 = 9 := by norm_num, have e1 : 123456789 % 9 = 0 := by norm_num, exact calc nat.gcd 123456789 987654321 = nat.gcd 9 123456789 : by rw[nat.gcd_rec,e0] ... = nat.gcd 0 9 : by rw[nat.gcd_rec,e1] ... = 9 : nat.gcd_zero_left 9 end end Q20 namespace Q21 def u (n : ℕ) : ℕ := 2 ^ n def a (n : ℕ) : ℕ := 2 ^ (u n) + 1 lemma u_ge_1 (n : ℕ) : u n ≥ 1 := by { let e := @nat.pow_le_pow_of_le_right 2 dec_trivial 0 n (nat.zero_le n), rw[pow_zero] at e, exact e, } lemma u_step (n : ℕ) : u (n + 1) = 2 * (u n) := by {dsimp[u],rw[pow_succ],} def a_pos (n : ℕ) : ℕ+ := ⟨a n,nat.zero_lt_succ _⟩ lemma a_step (n : ℕ) : a (n + 1) + 2 * (a n) = 2 + (a n) * (a n) := begin have h : ∀ (x : ℕ), x ^ 2 + 1 + 2 * (x + 1) = 2 + (x + 1) * (x + 1) := by {intro, ring,}, rw[a,a,u_step,mul_comm 2 (u n),pow_mul,h (2 ^ (u n))] end lemma a_ge_3 (n : ℕ) : a n ≥ 3 := begin let e := @nat.pow_le_pow_of_le_right 2 dec_trivial _ _ (u_ge_1 n), rw[pow_one] at e, exact nat.succ_le_succ e, end lemma a_ne_1 (n : ℕ) : a n ≠ 1 := ne_of_gt (lt_trans dec_trivial (a_ge_3 n)) lemma a_odd (n : ℕ) : (a n) % 2 = 1 := begin dsimp[a], rw[← nat.add_sub_of_le (u_ge_1 n),pow_add,pow_one], rw[add_comm _ 1,nat.add_mul_mod_self_left], refl, end lemma a_mod_a : ∀ (n m : ℕ), a (n + m + 1) ≡ 2 [MOD (a n)] | n 0 := begin rw[add_zero n], let e : (a (n + 1) + 2 * (a n)) % (a n) = (2 + (a n) * (a n)) % (a n) := congr_arg (λ i, i % (a n)) (a_step n), rw[nat.add_mul_mod_self_right] at e, rw[nat.add_mul_mod_self_right] at e, exact e, end | n (m + 1) := begin rw[← (add_assoc n m 1)], let e := a_step (n + m + 1), replace e : (a (n + m + 1 + 1) + 2 * a (n + m + 1)) % (a n) = (2 + a (n + m + 1) * a (n + m + 1)) % (a n) := by {rw[e]}, let ih := a_mod_a n m, let ih1 : 2 * a (n + m + 1) ≡ 4 [MOD (a n)] := nat.modeq.mul rfl ih, let ih2 : a (n + m + 1) * a (n + m + 1) ≡ 4 [MOD (a n)] := nat.modeq.mul ih ih, let ih3 : a (n + m + 1 + 1) + 2 * a (n + m + 1) ≡ a (n + m + 1 + 1) + 4 [MOD (a n)] := nat.modeq.add rfl ih1, let ih4 : 2 + a (n + m + 1) * a (n + m + 1) ≡ 2 + 4 [MOD (a n)] := nat.modeq.add rfl ih2, let e1 := (ih3.symm.trans e).trans ih4, exact nat.modeq.add_right_cancel rfl e1, end lemma a_coprime_aux (n m : ℕ) : nat.coprime (a n) (a (n + m + 1)) := begin let u := a n, let v := a (n + m + 1), change (nat.gcd u v) = 1, let q := v / u, let r := v % u, have e0 : r + u * q = v := nat.mod_add_div (a (n + m + 1)) (a n), have e1 : r = 2 % (a n) := a_mod_a n m, have e2 : 2 % (a n) = 2 := @nat.mod_eq_of_lt 2 (a n) (a_ge_3 n), rw[e2] at e1, have e3 : nat.gcd u v = nat.gcd r u := nat.gcd_rec u v, rw[e1] at e3, have e4 : nat.gcd 2 u = nat.gcd (u % 2) 2 := nat.gcd_rec 2 u, have e5 : u % 2 = 1 := a_odd n, have e6 : nat.gcd 1 2 = 1 := by norm_num, rw[e5,e6] at e4, rw[e4] at e3, exact e3, end lemma a_coprime {n m : ℕ} : n ≠ m → nat.coprime (a n) (a m) := begin cases (lt_or_ge n m) with h h, {let k := m - n.succ, have e0 : (n + 1) + k = m := add_tsub_cancel_of_le h, have : (n + 1) + k = n + k + 1 := by ring, rw[this] at e0, rw[← e0], intro, exact a_coprime_aux n k, },{ intro h0, let h1 := lt_of_le_of_ne h h0.symm, let k := n - m.succ, have e0 : (m + 1) + k = n := nat.add_sub_of_le h1, have : (m + 1) + k = m + k + 1 := by ring, rw[this] at e0, rw[← e0], exact (a_coprime_aux m k).symm, } end def b (n : ℕ) : ℕ := nat.min_fac (a n) def b_prime (n : ℕ) : nat.prime (b n) := nat.min_fac_prime (a_ne_1 n) lemma b_inj : function.injective b := begin intros i j e0, by_cases e1 : i = j, {assumption}, {exfalso, have e2 : nat.gcd (a i) (a j) = 1 := a_coprime e1, have e3 : (b i) ∣ (a i) := nat.min_fac_dvd (a i), have e4 : (b j) ∣ (a j) := nat.min_fac_dvd (a j), rw[← e0] at e4, let e5 := nat.dvd_gcd e3 e4, rw[e2] at e5, exact nat.prime.not_dvd_one (b_prime i) e5 } end end Q21 end exercises_1 end MAS114
46938bc6c463b33bd6dfe85e226ba9c6bb396281
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/wlog.lean
618096020358c10a552342d8b0c14dd9270fc681
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,134
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, Mario Carneiro, Johan Commelin, Reid Barton -/ import tactic.core import tactic.dependencies /-! # Without loss of generality tactic The tactic `wlog h : P` will add an assumption `h : P` to the main goal, and add a new goal that requires showing that the case `h : ¬ P` can be reduced to the case where `P` holds (typically by symmetry). The new goal will be placed at the top of the goal stack. -/ namespace tactic /-- A helper function to retrieve the names of the first `n` arguments to a Pi-expression. -/ meta def take_pi_args : nat → expr → list name | (n+1) (expr.pi h _ _ e) := h :: take_pi_args n e | _ _ := [] namespace interactive setup_tactic_parser /-- `wlog h : P` will add an assumption `h : P` to the main goal, and add a side goal that requires showing that the case `h : ¬ P` can be reduced to the case where `P` holds (typically by symmetry). The side goal will be at the top of the stack. In this side goal, there will be two assumptions: - `h : ¬ P`: the assumption that `P` does not hold - `this`: which is the statement that in the old context `P` suffices to prove the goal. By default, the name `this` is used, but the idiom `with H` can be added to specify the name: `wlog h : P with H`. Typically, it is useful to use the variant `wlog h : P generalizing x y`, to revert certain parts of the context before creating the new goal. In this way, the wlog-claim `this` can be applied to `x` and `y` in different orders (exploiting symmetry, which is the typical use case). By default, the entire context is reverted. -/ meta def wlog (H : parse ident) (t : parse (tk ":" *> texpr)) (revert : parse ((tk "generalizing" *> ((none <$ tk "*") <|> some <$> ident*)) <|> pure none)) (h : parse (tk "with" *> ident)?) : tactic unit := do -- if there is no `with` clause, use `this` as default name let h := h.get_or_else `this, t ← i_to_expr ``(%%t : Sort*), -- compute which constants must be reverted (by default: everything) (num_generalized, goal, rctx) ← retrieve (do assert_core H t, swap, -- use `revert_lst'` to ensure that the order of local constants in the context is preserved num_generalized ← match revert with | none := revert_all | some revert := prod.fst <$> (revert.mmap tactic.get_local >>= revert_lst') end, goal ← target, ctx ← local_context, return (num_generalized, goal, ctx)), ctx ← local_context, e ← tactic.assert h goal, goal ← target, (take_pi_args num_generalized goal).reverse.mmap' $ λ h, try (tactic.get_local h >>= tactic.clear), intron (num_generalized + 1), -- prove the easy branch of the side goal swap, tactic.by_cases t H, H ← tactic.get_local H, let L := ctx.filter (λ n, n ∉ rctx), tactic.exact $ (e.mk_app L).app H add_tactic_doc { name := "wlog", category := doc_category.tactic, decl_names := [`tactic.interactive.wlog], tags := ["logic"] } end interactive end tactic
9e1b73bce2a70815a27e59a37665af1a2c39a666
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/category_theory/limits/lattice.lean
aad26588aafa11bc7f36ccd9ac5a4bcda55eedfd
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,908
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.category.preorder import category_theory.limits.shapes.finite_limits import order.complete_lattice universes u open category_theory open category_theory.limits namespace category_theory.limits.complete_lattice variables {α : Type u} @[priority 100] -- see Note [lower instance priority] instance has_finite_limits_of_semilattice_inf_top [semilattice_inf_top α] : has_finite_limits α := ⟨λ J 𝒥₁ 𝒥₂, by exactI { has_limit := λ F, has_limit.mk { cone := { X := finset.univ.inf F.obj, π := { app := λ j, hom_of_le (finset.inf_le (fintype.complete _)) } }, is_limit := { lift := λ s, hom_of_le (finset.le_inf (λ j _, (s.π.app j).down.down)) } } }⟩ @[priority 100] -- see Note [lower instance priority] instance has_finite_colimits_of_semilattice_sup_bot [semilattice_sup_bot α] : has_finite_colimits α := ⟨λ J 𝒥₁ 𝒥₂, by exactI { has_colimit := λ F, has_colimit.mk { cocone := { X := finset.univ.sup F.obj, ι := { app := λ i, hom_of_le (finset.le_sup (fintype.complete _)) } }, is_colimit := { desc := λ s, hom_of_le (finset.sup_le (λ j _, (s.ι.app j).down.down)) } } }⟩ variables {J : Type u} [small_category J] /-- The limit cone over any functor into a complete lattice. -/ def limit_cone [complete_lattice α] (F : J ⥤ α) : limit_cone F := { cone := { X := infi F.obj, π := { app := λ j, hom_of_le (complete_lattice.Inf_le _ _ (set.mem_range_self _)) } }, is_limit := { lift := λ s, hom_of_le (complete_lattice.le_Inf _ _ begin rintros _ ⟨j, rfl⟩, exact (s.π.app j).le, end) } } /-- The colimit cocone over any functor into a complete lattice. -/ def colimit_cocone [complete_lattice α] (F : J ⥤ α) : colimit_cocone F := { cocone := { X := supr F.obj, ι := { app := λ j, hom_of_le (complete_lattice.le_Sup _ _ (set.mem_range_self _)) } }, is_colimit := { desc := λ s, hom_of_le (complete_lattice.Sup_le _ _ begin rintros _ ⟨j, rfl⟩, exact (s.ι.app j).le, end) } } -- It would be nice to only use the `Inf` half of the complete lattice, but -- this seems not to have been described separately. @[priority 100] -- see Note [lower instance priority] instance has_limits_of_complete_lattice [complete_lattice α] : has_limits α := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk (limit_cone F) } } @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_complete_lattice [complete_lattice α] : has_colimits α := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk (colimit_cocone F) } } noncomputable theory variables [complete_lattice α] (F : J ⥤ α) /-- The limit of a functor into a complete lattice is the infimum of the objects in the image. -/ def limit_iso_infi : limit F ≅ infi F.obj := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (limit_cone F).is_limit @[simp] lemma limit_iso_infi_hom (j : J) : (limit_iso_infi F).hom ≫ hom_of_le (infi_le _ j) = limit.π F j := by tidy @[simp] lemma limit_iso_infi_inv (j : J) : (limit_iso_infi F).inv ≫ limit.π F j = hom_of_le (infi_le _ j) := rfl /-- The colimit of a functor into a complete lattice is the supremum of the objects in the image. -/ def colimit_iso_supr : colimit F ≅ supr F.obj := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone F).is_colimit @[simp] lemma colimit_iso_supr_hom (j : J) : colimit.ι F j ≫ (colimit_iso_supr F).hom = hom_of_le (le_supr _ j) := rfl @[simp] lemma colimit_iso_supr_inv (j : J) : hom_of_le (le_supr _ j) ≫ (colimit_iso_supr F).inv = colimit.ι F j := by tidy end category_theory.limits.complete_lattice
8561c6693d0e34b1ec9b3affd58a452bc3a513f4
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/generator.lean
522630650fe3666055125bbd0611bad1b02b64a7
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
20,264
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.balanced import category_theory.limits.opposites import category_theory.limits.shapes.zero_morphisms import data.set.opposite /-! # Separating and detecting sets There are several non-equivalent notions of a generator of a category. Here, we consider two of them: * We say that `𝒢` is a separating set if the functors `C(G, -)` for `G ∈ 𝒢` are collectively faithful, i.e., if `h ≫ f = h ≫ g` for all `h` with domain in `𝒢` implies `f = g`. * We say that `𝒢` is a detecting set if the functors `C(G, -)` collectively reflect isomorphisms, i.e., if any `h` with domain in `𝒢` uniquely factors through `f`, then `f` is an isomorphism. There are, of course, also the dual notions of coseparating and codetecting sets. ## Main results We * define predicates `is_separating`, `is_coseparating`, `is_detecting` and `is_codetecting` on sets of objects; * show that separating and coseparating are dual notions; * show that detecting and codetecting are dual notions; * show that if `C` has equalizers, then detecting implies separating; * show that if `C` has coequalizers, then codetecting implies separating; * show that if `C` is balanced, then separating implies detecting and coseparating implies codetecting; * show that `∅` is separating if and only if `∅` is coseparating if and only if `C` is thin; * show that `∅` is detecting if and only if `∅` is codetecting if and only if `C` is a groupoid; * define predicates `is_separator`, `is_coseparator`, `is_detector` and `is_codetector` as the singleton counterparts to the definitions for sets above and restate the above results in this situation; * show that `G` is a separator if and only if `coyoneda.obj (op G)` is faithful (and the dual); * show that `G` is a detector if and only if `coyoneda.obj (op G)` reflects isomorphisms (and the dual). ## Future work * We currently don't have any examples yet. * We will want typeclasses `has_separator C` and similar. * To state the Special Adjoint Functor Theorem, we will need to be able to talk about *small* separating sets. -/ universes w v u open category_theory.limits opposite namespace category_theory variables {C : Type u} [category.{v} C] /-- We say that `𝒢` is a separating set if the functors `C(G, -)` for `G ∈ 𝒢` are collectively faithful, i.e., if `h ≫ f = h ≫ g` for all `h` with domain in `𝒢` implies `f = g`. -/ def is_separating (𝒢 : set C) : Prop := ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ (G ∈ 𝒢) (h : G ⟶ X), h ≫ f = h ≫ g) → f = g /-- We say that `𝒢` is a coseparating set if the functors `C(-, G)` for `G ∈ 𝒢` are collectively faithful, i.e., if `f ≫ h = g ≫ h` for all `h` with codomain in `𝒢` implies `f = g`. -/ def is_coseparating (𝒢 : set C) : Prop := ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ (G ∈ 𝒢) (h : Y ⟶ G), f ≫ h = g ≫ h) → f = g /-- We say that `𝒢` is a detecting set if the functors `C(G, -)` collectively reflect isomorphisms, i.e., if any `h` with domain in `𝒢` uniquely factors through `f`, then `f` is an isomorphism. -/ def is_detecting (𝒢 : set C) : Prop := ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ (G ∈ 𝒢) (h : G ⟶ Y), ∃! (h' : G ⟶ X), h' ≫ f = h) → is_iso f /-- We say that `𝒢` is a codetecting set if the functors `C(-, G)` collectively reflect isomorphisms, i.e., if any `h` with codomain in `G` uniquely factors through `f`, then `f` is an isomorphism. -/ def is_codetecting (𝒢 : set C) : Prop := ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ (G ∈ 𝒢) (h : X ⟶ G), ∃! (h' : Y ⟶ G), f ≫ h' = h) → is_iso f section dual lemma is_separating_op_iff (𝒢 : set C) : is_separating 𝒢.op ↔ is_coseparating 𝒢 := begin refine ⟨λ h𝒢 X Y f g hfg, _, λ h𝒢 X Y f g hfg, _⟩, { refine quiver.hom.op_inj (h𝒢 _ _ (λ G hG h, quiver.hom.unop_inj _)), simpa only [unop_comp, quiver.hom.unop_op] using hfg _ (set.mem_op.1 hG) _ }, { refine quiver.hom.unop_inj (h𝒢 _ _ (λ G hG h, quiver.hom.op_inj _)), simpa only [op_comp, quiver.hom.op_unop] using hfg _ (set.op_mem_op.2 hG) _ } end lemma is_coseparating_op_iff (𝒢 : set C) : is_coseparating 𝒢.op ↔ is_separating 𝒢 := begin refine ⟨λ h𝒢 X Y f g hfg, _, λ h𝒢 X Y f g hfg, _⟩, { refine quiver.hom.op_inj (h𝒢 _ _ (λ G hG h, quiver.hom.unop_inj _)), simpa only [unop_comp, quiver.hom.unop_op] using hfg _ (set.mem_op.1 hG) _ }, { refine quiver.hom.unop_inj (h𝒢 _ _ (λ G hG h, quiver.hom.op_inj _)), simpa only [op_comp, quiver.hom.op_unop] using hfg _ (set.op_mem_op.2 hG) _ } end lemma is_coseparating_unop_iff (𝒢 : set Cᵒᵖ) : is_coseparating 𝒢.unop ↔ is_separating 𝒢 := by rw [← is_separating_op_iff, set.unop_op] lemma is_separating_unop_iff (𝒢 : set Cᵒᵖ) : is_separating 𝒢.unop ↔ is_coseparating 𝒢 := by rw [← is_coseparating_op_iff, set.unop_op] lemma is_detecting_op_iff (𝒢 : set C) : is_detecting 𝒢.op ↔ is_codetecting 𝒢 := begin refine ⟨λ h𝒢 X Y f hf, _, λ h𝒢 X Y f hf, _⟩, { refine (is_iso_op_iff _).1 (h𝒢 _ (λ G hG h, _)), obtain ⟨t, ht, ht'⟩ := hf (unop G) (set.mem_op.1 hG) h.unop, exact ⟨t.op, quiver.hom.unop_inj ht, λ y hy, quiver.hom.unop_inj (ht' _ (quiver.hom.op_inj hy))⟩ }, { refine (is_iso_unop_iff _).1 (h𝒢 _ (λ G hG h, _)), obtain ⟨t, ht, ht'⟩ := hf (op G) (set.op_mem_op.2 hG) h.op, refine ⟨t.unop, quiver.hom.op_inj ht, λ y hy, quiver.hom.op_inj (ht' _ _)⟩, exact quiver.hom.unop_inj (by simpa only using hy) } end lemma is_codetecting_op_iff (𝒢 : set C) : is_codetecting 𝒢.op ↔ is_detecting 𝒢 := begin refine ⟨λ h𝒢 X Y f hf, _, λ h𝒢 X Y f hf, _⟩, { refine (is_iso_op_iff _).1 (h𝒢 _ (λ G hG h, _)), obtain ⟨t, ht, ht'⟩ := hf (unop G) (set.mem_op.1 hG) h.unop, exact ⟨t.op, quiver.hom.unop_inj ht, λ y hy, quiver.hom.unop_inj (ht' _ (quiver.hom.op_inj hy))⟩ }, { refine (is_iso_unop_iff _).1 (h𝒢 _ (λ G hG h, _)), obtain ⟨t, ht, ht'⟩ := hf (op G) (set.op_mem_op.2 hG) h.op, refine ⟨t.unop, quiver.hom.op_inj ht, λ y hy, quiver.hom.op_inj (ht' _ _)⟩, exact quiver.hom.unop_inj (by simpa only using hy) } end lemma is_detecting_unop_iff (𝒢 : set Cᵒᵖ) : is_detecting 𝒢.unop ↔ is_codetecting 𝒢 := by rw [← is_codetecting_op_iff, set.unop_op] lemma is_codetecting_unop_iff {𝒢 : set Cᵒᵖ} : is_codetecting 𝒢.unop ↔ is_detecting 𝒢 := by rw [← is_detecting_op_iff, set.unop_op] end dual lemma is_detecting.is_separating [has_equalizers C] {𝒢 : set C} (h𝒢 : is_detecting 𝒢) : is_separating 𝒢 := λ X Y f g hfg, have is_iso (equalizer.ι f g), from h𝒢 _ (λ G hG h, equalizer.exists_unique _ (hfg _ hG _)), by exactI eq_of_epi_equalizer section local attribute [instance] has_equalizers_opposite lemma is_codetecting.is_coseparating [has_coequalizers C] {𝒢 : set C} : is_codetecting 𝒢 → is_coseparating 𝒢 := by simpa only [← is_separating_op_iff, ← is_detecting_op_iff] using is_detecting.is_separating end lemma is_separating.is_detecting [balanced C] {𝒢 : set C} (h𝒢 : is_separating 𝒢) : is_detecting 𝒢 := begin intros X Y f hf, refine (is_iso_iff_mono_and_epi _).2 ⟨⟨λ Z g h hgh, h𝒢 _ _ (λ G hG i, _)⟩, ⟨λ Z g h hgh, _⟩⟩, { obtain ⟨t, -, ht⟩ := hf G hG (i ≫ g ≫ f), rw [ht (i ≫ g) (category.assoc _ _ _), ht (i ≫ h) (hgh.symm ▸ category.assoc _ _ _)] }, { refine h𝒢 _ _ (λ G hG i, _), obtain ⟨t, rfl, -⟩ := hf G hG i, rw [category.assoc, hgh, category.assoc] } end section local attribute [instance] balanced_opposite lemma is_coseparating.is_codetecting [balanced C] {𝒢 : set C} : is_coseparating 𝒢 → is_codetecting 𝒢 := by simpa only [← is_detecting_op_iff, ← is_separating_op_iff] using is_separating.is_detecting end lemma is_detecting_iff_is_separating [has_equalizers C] [balanced C] (𝒢 : set C) : is_detecting 𝒢 ↔ is_separating 𝒢 := ⟨is_detecting.is_separating, is_separating.is_detecting⟩ lemma is_codetecting_iff_is_coseparating [has_coequalizers C] [balanced C] {𝒢 : set C} : is_codetecting 𝒢 ↔ is_coseparating 𝒢 := ⟨is_codetecting.is_coseparating, is_coseparating.is_codetecting⟩ section mono lemma is_separating.mono {𝒢 : set C} (h𝒢 : is_separating 𝒢) {ℋ : set C} (h𝒢ℋ : 𝒢 ⊆ ℋ) : is_separating ℋ := λ X Y f g hfg, h𝒢 _ _ $ λ G hG h, hfg _ (h𝒢ℋ hG) _ lemma is_coseparating.mono {𝒢 : set C} (h𝒢 : is_coseparating 𝒢) {ℋ : set C} (h𝒢ℋ : 𝒢 ⊆ ℋ) : is_coseparating ℋ := λ X Y f g hfg, h𝒢 _ _ $ λ G hG h, hfg _ (h𝒢ℋ hG) _ lemma is_detecting.mono {𝒢 : set C} (h𝒢 : is_detecting 𝒢) {ℋ : set C} (h𝒢ℋ : 𝒢 ⊆ ℋ) : is_detecting ℋ := λ X Y f hf, h𝒢 _ $ λ G hG h, hf _ (h𝒢ℋ hG) _ lemma is_codetecting.mono {𝒢 : set C} (h𝒢 : is_codetecting 𝒢) {ℋ : set C} (h𝒢ℋ : 𝒢 ⊆ ℋ) : is_codetecting ℋ := λ X Y f hf, h𝒢 _ $ λ G hG h, hf _ (h𝒢ℋ hG) _ end mono section empty lemma thin_of_is_separating_empty (h : is_separating (∅ : set C)) (X Y : C) : subsingleton (X ⟶ Y) := ⟨λ f g, h _ _ $ λ G, false.elim⟩ lemma is_separating_empty_of_thin [∀ X Y : C, subsingleton (X ⟶ Y)] : is_separating (∅ : set C) := λ X Y f g hfg, subsingleton.elim _ _ lemma thin_of_is_coseparating_empty (h : is_coseparating (∅ : set C)) (X Y : C) : subsingleton (X ⟶ Y) := ⟨λ f g, h _ _ $ λ G, false.elim⟩ lemma is_coseparating_empty_of_thin [∀ X Y : C, subsingleton (X ⟶ Y)] : is_coseparating (∅ : set C) := λ X Y f g hfg, subsingleton.elim _ _ lemma groupoid_of_is_detecting_empty (h : is_detecting (∅ : set C)) {X Y : C} (f : X ⟶ Y) : is_iso f := h _ $ λ G, false.elim lemma is_detecting_empty_of_groupoid [∀ {X Y : C} (f : X ⟶ Y), is_iso f] : is_detecting (∅ : set C) := λ X Y f hf, infer_instance lemma groupoid_of_is_codetecting_empty (h : is_codetecting (∅ : set C)) {X Y : C} (f : X ⟶ Y) : is_iso f := h _ $ λ G, false.elim lemma is_codetecting_empty_of_groupoid [∀ {X Y : C} (f : X ⟶ Y), is_iso f] : is_codetecting (∅ : set C) := λ X Y f hf, infer_instance end empty /-- We say that `G` is a separator if the functor `C(G, -)` is faithful. -/ def is_separator (G : C) : Prop := is_separating ({G} : set C) /-- We say that `G` is a coseparator if the functor `C(-, G)` is faithful. -/ def is_coseparator (G : C) : Prop := is_coseparating ({G} : set C) /-- We say that `G` is a detector if the functor `C(G, -)` reflects isomorphisms. -/ def is_detector (G : C) : Prop := is_detecting ({G} : set C) /-- We say that `G` is a codetector if the functor `C(-, G)` reflects isomorphisms. -/ def is_codetector (G : C) : Prop := is_codetecting ({G} : set C) section dual lemma is_separator_op_iff (G : C) : is_separator (op G) ↔ is_coseparator G := by rw [is_separator, is_coseparator, ← is_separating_op_iff, set.singleton_op] lemma is_coseparator_op_iff (G : C) : is_coseparator (op G) ↔ is_separator G := by rw [is_separator, is_coseparator, ← is_coseparating_op_iff, set.singleton_op] lemma is_coseparator_unop_iff (G : Cᵒᵖ) : is_coseparator (unop G) ↔ is_separator G := by rw [is_separator, is_coseparator, ← is_coseparating_unop_iff, set.singleton_unop] lemma is_separator_unop_iff (G : Cᵒᵖ) : is_separator (unop G) ↔ is_coseparator G := by rw [is_separator, is_coseparator, ← is_separating_unop_iff, set.singleton_unop] lemma is_detector_op_iff (G : C) : is_detector (op G) ↔ is_codetector G := by rw [is_detector, is_codetector, ← is_detecting_op_iff, set.singleton_op] lemma is_codetector_op_iff (G : C) : is_codetector (op G) ↔ is_detector G := by rw [is_detector, is_codetector, ← is_codetecting_op_iff, set.singleton_op] lemma is_codetector_unop_iff (G : Cᵒᵖ) : is_codetector (unop G) ↔ is_detector G := by rw [is_detector, is_codetector, ← is_codetecting_unop_iff, set.singleton_unop] lemma is_detector_unop_iff (G : Cᵒᵖ) : is_detector (unop G) ↔ is_codetector G := by rw [is_detector, is_codetector, ← is_detecting_unop_iff, set.singleton_unop] end dual lemma is_detector.is_separator [has_equalizers C] {G : C} : is_detector G → is_separator G := is_detecting.is_separating lemma is_codetector.is_coseparator [has_coequalizers C] {G : C} : is_codetector G → is_coseparator G := is_codetecting.is_coseparating lemma is_separator.is_detector [balanced C] {G : C} : is_separator G → is_detector G := is_separating.is_detecting lemma is_cospearator.is_codetector [balanced C] {G : C} : is_coseparator G → is_codetector G := is_coseparating.is_codetecting lemma is_separator_def (G : C) : is_separator G ↔ ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ h : G ⟶ X, h ≫ f = h ≫ g) → f = g := ⟨λ hG X Y f g hfg, hG _ _ $ λ H hH h, by { obtain rfl := set.mem_singleton_iff.1 hH, exact hfg h }, λ hG X Y f g hfg, hG _ _ $ λ h, hfg _ (set.mem_singleton _) _⟩ lemma is_separator.def {G : C} : is_separator G → ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ h : G ⟶ X, h ≫ f = h ≫ g) → f = g := (is_separator_def _).1 lemma is_coseparator_def (G : C) : is_coseparator G ↔ ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ h : Y ⟶ G, f ≫ h = g ≫ h) → f = g := ⟨λ hG X Y f g hfg, hG _ _ $ λ H hH h, by { obtain rfl := set.mem_singleton_iff.1 hH, exact hfg h }, λ hG X Y f g hfg, hG _ _ $ λ h, hfg _ (set.mem_singleton _) _⟩ lemma is_coseparator.def {G : C} : is_coseparator G → ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), (∀ h : Y ⟶ G, f ≫ h = g ≫ h) → f = g := (is_coseparator_def _).1 lemma is_detector_def (G : C) : is_detector G ↔ ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : G ⟶ Y, ∃! h', h' ≫ f = h) → is_iso f := ⟨λ hG X Y f hf, hG _ $ λ H hH h, by { obtain rfl := set.mem_singleton_iff.1 hH, exact hf h }, λ hG X Y f hf, hG _ $ λ h, hf _ (set.mem_singleton _) _⟩ lemma is_detector.def {G : C} : is_detector G → ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : G ⟶ Y, ∃! h', h' ≫ f = h) → is_iso f := (is_detector_def _).1 lemma is_codetector_def (G : C) : is_codetector G ↔ ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : X ⟶ G, ∃! h', f ≫ h' = h) → is_iso f := ⟨λ hG X Y f hf, hG _ $ λ H hH h, by { obtain rfl := set.mem_singleton_iff.1 hH, exact hf h }, λ hG X Y f hf, hG _ $ λ h, hf _ (set.mem_singleton _) _⟩ lemma is_codetector.def {G : C} : is_codetector G → ∀ ⦃X Y : C⦄ (f : X ⟶ Y), (∀ h : X ⟶ G, ∃! h', f ≫ h' = h) → is_iso f := (is_codetector_def _).1 lemma is_separator_iff_faithful_coyoneda_obj (G : C) : is_separator G ↔ faithful (coyoneda.obj (op G)) := ⟨λ hG, ⟨λ X Y f g hfg, hG.def _ _ (congr_fun hfg)⟩, λ h, (is_separator_def _).2 $ λ X Y f g hfg, by exactI (coyoneda.obj (op G)).map_injective (funext hfg)⟩ lemma is_coseparator_iff_faithful_yoneda_obj (G : C) : is_coseparator G ↔ faithful (yoneda.obj G) := ⟨λ hG, ⟨λ X Y f g hfg, quiver.hom.unop_inj (hG.def _ _ (congr_fun hfg))⟩, λ h, (is_coseparator_def _).2 $ λ X Y f g hfg, quiver.hom.op_inj $ by exactI (yoneda.obj G).map_injective (funext hfg)⟩ section zero_morphisms variables [has_zero_morphisms C] lemma is_separator_coprod (G H : C) [has_binary_coproduct G H] : is_separator (G ⨿ H) ↔ is_separating ({G, H} : set C) := begin refine ⟨λ h X Y u v huv, _, λ h, (is_separator_def _).2 (λ X Y u v huv, h _ _ (λ Z hZ g, _))⟩, { refine h.def _ _ (λ g, coprod.hom_ext _ _), { simpa using huv G (by simp) (coprod.inl ≫ g) }, { simpa using huv H (by simp) (coprod.inr ≫ g) } }, { simp only [set.mem_insert_iff, set.mem_singleton_iff] at hZ, unfreezingI { rcases hZ with rfl|rfl }, { simpa using coprod.inl ≫= huv (coprod.desc g 0) }, { simpa using coprod.inr ≫= huv (coprod.desc 0 g) } } end lemma is_separator_coprod_of_is_separator_left (G H : C) [has_binary_coproduct G H] (hG : is_separator G) : is_separator (G ⨿ H) := (is_separator_coprod _ _).2 $ is_separating.mono hG $ by simp lemma is_separator_coprod_of_is_separator_right (G H : C) [has_binary_coproduct G H] (hH : is_separator H) : is_separator (G ⨿ H) := (is_separator_coprod _ _).2 $ is_separating.mono hH $ by simp lemma is_separator_sigma {β : Type w} (f : β → C) [has_coproduct f] : is_separator (∐ f) ↔ is_separating (set.range f) := begin refine ⟨λ h X Y u v huv, _, λ h, (is_separator_def _).2 (λ X Y u v huv, h _ _ (λ Z hZ g, _))⟩, { refine h.def _ _ (λ g, colimit.hom_ext (λ b, _)), simpa using huv (f b.as) (by simp) (colimit.ι (discrete.functor f) _ ≫ g) }, { obtain ⟨b, rfl⟩ := set.mem_range.1 hZ, classical, simpa using sigma.ι f b ≫= huv (sigma.desc (pi.single b g)) } end lemma is_separator_sigma_of_is_separator {β : Type w} (f : β → C) [has_coproduct f] (b : β) (hb : is_separator (f b)) : is_separator (∐ f) := (is_separator_sigma _).2 $ is_separating.mono hb $ by simp lemma is_coseparator_prod (G H : C) [has_binary_product G H] : is_coseparator (G ⨯ H) ↔ is_coseparating ({G, H} : set C) := begin refine ⟨λ h X Y u v huv, _, λ h, (is_coseparator_def _).2 (λ X Y u v huv, h _ _ (λ Z hZ g, _))⟩, { refine h.def _ _ (λ g, prod.hom_ext _ _), { simpa using huv G (by simp) (g ≫ limits.prod.fst) }, { simpa using huv H (by simp) (g ≫ limits.prod.snd) } }, { simp only [set.mem_insert_iff, set.mem_singleton_iff] at hZ, unfreezingI { rcases hZ with rfl|rfl }, { simpa using huv (prod.lift g 0) =≫ limits.prod.fst }, { simpa using huv (prod.lift 0 g) =≫ limits.prod.snd } } end lemma is_coseparator_prod_of_is_coseparator_left (G H : C) [has_binary_product G H] (hG : is_coseparator G) : is_coseparator (G ⨯ H) := (is_coseparator_prod _ _).2 $ is_coseparating.mono hG $ by simp lemma is_coseparator_prod_of_is_coseparator_right (G H : C) [has_binary_product G H] (hH : is_coseparator H) : is_coseparator (G ⨯ H) := (is_coseparator_prod _ _).2 $ is_coseparating.mono hH $ by simp lemma is_coseparator_pi {β : Type w} (f : β → C) [has_product f] : is_coseparator (∏ f) ↔ is_coseparating (set.range f) := begin refine ⟨λ h X Y u v huv, _, λ h, (is_coseparator_def _).2 (λ X Y u v huv, h _ _ (λ Z hZ g, _))⟩, { refine h.def _ _ (λ g, limit.hom_ext (λ b, _)), simpa using huv (f b.as) (by simp) (g ≫ limit.π (discrete.functor f) _ ) }, { obtain ⟨b, rfl⟩ := set.mem_range.1 hZ, classical, simpa using huv (pi.lift (pi.single b g)) =≫ pi.π f b } end lemma is_coseparator_pi_of_is_coseparator {β : Type w} (f : β → C) [has_product f] (b : β) (hb : is_coseparator (f b)) : is_coseparator (∏ f) := (is_coseparator_pi _).2 $ is_coseparating.mono hb $ by simp end zero_morphisms lemma is_detector_iff_reflects_isomorphisms_coyoneda_obj (G : C) : is_detector G ↔ reflects_isomorphisms (coyoneda.obj (op G)) := begin refine ⟨λ hG, ⟨λ X Y f hf, hG.def _ (λ h, _)⟩, λ h, (is_detector_def _).2 (λ X Y f hf, _)⟩, { rw [is_iso_iff_bijective, function.bijective_iff_exists_unique] at hf, exact hf h }, { suffices : is_iso ((coyoneda.obj (op G)).map f), { exactI @is_iso_of_reflects_iso _ _ _ _ _ _ _ (coyoneda.obj (op G)) _ h }, rwa [is_iso_iff_bijective, function.bijective_iff_exists_unique] } end lemma is_codetector_iff_reflects_isomorphisms_yoneda_obj (G : C) : is_codetector G ↔ reflects_isomorphisms (yoneda.obj G) := begin refine ⟨λ hG, ⟨λ X Y f hf, _ ⟩, λ h, (is_codetector_def _).2 (λ X Y f hf, _)⟩, { refine (is_iso_unop_iff _).1 (hG.def _ _), rwa [is_iso_iff_bijective, function.bijective_iff_exists_unique] at hf }, { rw ← is_iso_op_iff, suffices : is_iso ((yoneda.obj G).map f.op), { exactI @is_iso_of_reflects_iso _ _ _ _ _ _ _ (yoneda.obj G) _ h }, rwa [is_iso_iff_bijective, function.bijective_iff_exists_unique] } end end category_theory
fe1a986963642511756fea54929554e9d1c0da64
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/big_operators/multiset/lemmas.lean
8fe2c0c8224122a1f335e1a51ce4b269aa4f4fdb
[ "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
1,316
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Bhavik Mehta, Eric Wieser -/ import data.list.big_operators.lemmas import algebra.big_operators.multiset.basic /-! # Lemmas about `multiset.sum` and `multiset.prod` requiring extra algebra imports -/ variables {ι α β γ : Type*} namespace multiset lemma dvd_prod [comm_monoid α] {s : multiset α} {a : α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a @[to_additive] lemma prod_eq_one_iff [canonically_ordered_monoid α] {m : multiset α} : m.prod = 1 ↔ ∀ x ∈ m, x = (1 : α) := quotient.induction_on m $ λ l, by simpa using list.prod_eq_one_iff l end multiset open multiset namespace commute variables [non_unital_non_assoc_semiring α] {a : α} {s : multiset ι} {f : ι → α} lemma multiset_sum_right (s : multiset α) (a : α) (h : ∀ b ∈ s, commute a b) : commute a s.sum := begin induction s using quotient.induction_on, rw [quot_mk_to_coe, coe_sum], exact commute.list_sum_right _ _ h, end lemma multiset_sum_left (s : multiset α) (b : α) (h : ∀ a ∈ s, commute a b) : commute s.sum b := (commute.multiset_sum_right _ _ $ λ a ha, (h _ ha).symm).symm end commute
9519e584aea36a0f8caaeb5383d5a9a3644ee5cc
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Lean/Util/Path.lean
2bfeb1e7766a3c1d8bb0adf5d7e91a4aa83aa904
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,877
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, Sebastian Ullrich Management of the Lean search path (`LEAN_PATH`), which is a list of `pkg=path` mappings from package name to root path. An import `A.B.C` given an `A=path` entry resolves to `path/B/C.olean`. A package-only import `A` is normalized to `A.Default`. For the input file, we also need the reverse direction of finding a (unique) module path from a file path. -/ prelude import Init.System.IO import Init.System.FilePath import Init.Data.Array import Init.Data.List.Control import Init.Data.HashMap import Init.Data.Nat.Control import Init.Lean.Data.Name namespace Lean open System.FilePath (pathSeparator extSeparator) private def pathSep : String := toString pathSeparator def realPathNormalized (fname : String) : IO String := do fname ← IO.realPath fname; pure (System.FilePath.normalizePath fname) abbrev SearchPath := HashMap String String def mkSearchPathRef : IO (IO.Ref SearchPath) := IO.mkRef ∅ @[init mkSearchPathRef] constant searchPathRef : IO.Ref SearchPath := arbitrary _ def parseSearchPath (path : String) (sp : SearchPath := ∅) : IO SearchPath := do let ps := System.FilePath.splitSearchPath path; sp ← ps.foldlM (fun (sp : SearchPath) s => match s.splitOn "=" with | [pkg, path] => pure $ sp.insert pkg path | _ => throw $ IO.userError $ "ill-formed search path entry '" ++ s ++ "', should be of form 'pkg=path'") sp; pure sp def getBuiltinSearchPath : IO SearchPath := do appDir ← IO.appDir; let libDir := appDir ++ pathSep ++ ".." ++ pathSep ++ "src" ++ pathSep ++ "Init"; libDirExists ← IO.isDir libDir; if libDirExists then do path ← realPathNormalized libDir; pure $ HashMap.empty.insert "Init" path else do let installedLibDir := appDir ++ pathSep ++ ".." ++ pathSep ++ "lib" ++ pathSep ++ "lean" ++ pathSep ++ "library" ++ pathSep ++ "Init"; installedLibDirExists ← IO.isDir installedLibDir; if installedLibDirExists then do path ← realPathNormalized installedLibDir; pure $ HashMap.empty.insert "Init" path else pure ∅ def addSearchPathFromEnv (sp : SearchPath) : IO SearchPath := do val ← IO.getEnv "LEAN_PATH"; match val with | none => pure sp | some val => parseSearchPath val sp @[export lean_init_search_path] def initSearchPath (path : Option String := "") : IO Unit := match path with | some path => parseSearchPath path >>= searchPathRef.set | none => do sp ← getBuiltinSearchPath; sp ← addSearchPathFromEnv sp; searchPathRef.set sp def modPathToFilePath : Name → String | Name.str Name.anonymous h _ => h | Name.str p h _ => modPathToFilePath p ++ pathSep ++ h | Name.anonymous => "" | Name.num p _ _ => panic! "ill-formed import" /- Given `A.B.C, return ("A", `B.C). -/ def splitAtRoot : Name → String × Name | Name.str Name.anonymous s _ => (s, Name.anonymous) | Name.str n s _ => let (pkg, path) := splitAtRoot n; (pkg, mkNameStr path s) | _ => panic! "ill-formed import" def findOLean (mod : Name) : IO String := do sp ← searchPathRef.get; let (pkg, path) := splitAtRoot mod; some root ← pure $ sp.find? pkg | throw $ IO.userError $ "unknown package '" ++ pkg ++ "'"; let fname := root ++ pathSep ++ modPathToFilePath path ++ ".olean"; pure fname def findAtSearchPath (fname : String) : IO (Option (String × String)) := do fname ← realPathNormalized fname; sp ← searchPathRef.get; results ← sp.foldM (fun results pkg path => do path ← realPathNormalized path; pure $ if String.isPrefixOf path fname then (pkg, path) :: results else results) []; match results with | [res] => pure res | [] => pure none | _ => throw (IO.userError ("file '" ++ fname ++ "' is contained in multiple packages: " ++ ", ".intercalate (results.map Prod.fst))) @[export lean_module_name_of_file] def moduleNameOfFileName (fname : String) : IO (Option Name) := do some (pkg, path) ← findAtSearchPath fname | pure none; fname ← realPathNormalized fname; let fnameSuffix := fname.drop path.length; let fnameSuffix := if fnameSuffix.get 0 == pathSeparator then fnameSuffix.drop 1 else fnameSuffix; some extPos ← pure (fnameSuffix.revPosOf '.') | throw (IO.userError ("failed to convert file '" ++ fname ++ "' to module name, extension is missing")); let modNameStr := fnameSuffix.extract 0 extPos; let extStr := fnameSuffix.extract (extPos + 1) fnameSuffix.bsize; let parts := modNameStr.splitOn pathSep; let modName := parts.foldl mkNameStr pkg; pure modName -- normalize `A` to `A.Default` @[export lean_normalize_module_name] def normalizeModuleName : Name → Name | Name.str Name.anonymous pkg _ => mkNameSimple pkg ++ "Default" | m => m end Lean
495f8d573e827883d010d0249b4572dd0ace5fbb
4727251e0cd73359b15b664c3170e5d754078599
/archive/100-theorems-list/81_sum_of_prime_reciprocals_diverges.lean
a3631a5eb4bc12afe81aa35b9fd43eda460e90b5
[ "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
11,538
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import topology.instances.ennreal import algebra.squarefree /-! # Divergence of the Prime Reciprocal Series This file proves Theorem 81 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). The theorem states that the sum of the reciprocals of all prime numbers diverges. The formalization follows Erdős's proof by upper and lower estimates. ## Proof outline 1. Assume that the sum of the reciprocals of the primes converges. 2. Then there exists a `k : ℕ` such that, for any `x : ℕ`, the sum of the reciprocals of the primes between `k` and `x + 1` is less than 1/2 (`sum_lt_half_of_not_tendsto`). 3. For any `x : ℕ`, we can partition `range x` into two subsets (`range_sdiff_eq_bUnion`): * `M x k`, the subset of those `e` for which `e + 1` is a product of powers of primes smaller than or equal to `k`; * `U x k`, the subset of those `e` for which there is a prime `p > k` that divides `e + 1`. 4. Then `|U x k|` is bounded by the sum over the primes `p > k` of the number of multiples of `p` in `(k, x]`, which is at most `x / p`. It follows that `|U x k|` is at most `x` times the sum of the reciprocals of the primes between `k` and `x + 1`, which is less than 1/2 as noted in (2), so `|U x k| < x / 2` (`card_le_mul_sum`). 5. By factoring `e + 1 = (m + 1)² * (r + 1)`, `r + 1` squarefree and `m + 1 ≤ √x`, and noting that squarefree numbers correspond to subsets of `[1, k]`, we find that `|M x k| ≤ 2 ^ k * √x` (`card_le_two_pow_mul_sqrt`). 6. Finally, setting `x := (2 ^ (k + 1))²` (`√x = 2 ^ (k + 1)`), we find that `|M x k| ≤ 2 ^ k * 2 ^ (k + 1) = x / 2`. Combined with the strict bound for `|U k x|` from (4), `x = |M x k| + |U x k| < x / 2 + x / 2 = x`. ## References https://en.wikipedia.org/wiki/Divergence_of_the_sum_of_the_reciprocals_of_the_primes -/ open_locale big_operators open_locale classical open filter finset /-- The primes in `(k, x]`. -/ noncomputable def P (x k : ℕ) := {p ∈ range (x + 1) | k < p ∧ nat.prime p} /-- The union over those primes `p ∈ (k, x]` of the sets of `e < x` for which `e + 1` is a multiple of `p`, i.e., those `e < x` for which there is a prime `p ∈ (k, x]` that divides `e + 1`. -/ noncomputable def U (x k : ℕ) := finset.bUnion (P x k) (λ p, {e ∈ range x | p ∣ e + 1}) /-- Those `e < x` for which `e + 1` is a product of powers of primes smaller than or equal to `k`. -/ noncomputable def M (x k : ℕ) := {e ∈ range x | ∀ p : ℕ, (nat.prime p ∧ p ∣ e + 1) → p ≤ k} /-- If the sum of the reciprocals of the primes converges, there exists a `k : ℕ` such that the sum of the reciprocals of the primes greater than `k` is less than 1/2. More precisely, for any `x : ℕ`, the sum of the reciprocals of the primes between `k` and `x + 1` is less than 1/2. -/ lemma sum_lt_half_of_not_tendsto (h : ¬ tendsto (λ n, ∑ p in {p ∈ range n | nat.prime p}, (1 / (p : ℝ))) at_top at_top) : ∃ k, ∀ x, ∑ p in P x k, 1 / (p : ℝ) < 1 / 2 := begin have h0 : (λ n, ∑ p in {p ∈ range n | nat.prime p}, (1 / (p : ℝ))) = λ n, ∑ p in range n, ite (nat.prime p) (1 / (p : ℝ)) 0, { simp only [sum_filter, filter_congr_decidable, sep_def] }, have hf : ∀ n : ℕ, 0 ≤ ite (nat.prime n) (1 / (n : ℝ)) 0, { intro n, split_ifs, { simp only [one_div, inv_nonneg, nat.cast_nonneg] }, { exact le_rfl } }, rw [h0, ← summable_iff_not_tendsto_nat_at_top_of_nonneg hf, summable_iff_vanishing] at h, obtain ⟨s, h⟩ := h (set.Ioo (-1) (1/2)) (is_open_Ioo.mem_nhds (by norm_num)), obtain ⟨k, hk⟩ := exists_nat_subset_range s, use k, intro x, rw [P, sep_def, filter_congr_decidable, ←filter_filter, sum_filter], refine (h _ _).2, rw disjoint_iff_ne, simp_intros a ha b hb only [mem_filter], exact ((mem_range.mp (hk hb)).trans ha.2).ne', end /-- Removing from {0, ..., x - 1} those elements `e` for which `e + 1` is a product of powers of primes smaller than or equal to `k` leaves those `e` for which there is a prime `p > k` that divides `e + 1`, or the union over those primes `p > k` of the sets of `e`s for which `e + 1` is a multiple of `p`. -/ lemma range_sdiff_eq_bUnion {x k : ℕ} : range x \ M x k = U x k := begin ext e, simp only [mem_bUnion, not_and, mem_sdiff, sep_def, mem_filter, mem_range, U, M, P], push_neg, split, { rintros ⟨hex, hexh⟩, obtain ⟨p, ⟨hpp, hpe1⟩, hpk⟩ := hexh hex, refine ⟨p, _, ⟨hex, hpe1⟩⟩, exact ⟨(nat.le_of_dvd e.succ_pos hpe1).trans_lt (nat.succ_lt_succ hex), hpk, hpp⟩ }, { rintros ⟨p, hpfilter, ⟨hex, hpe1⟩⟩, rw imp_iff_right hex, exact ⟨hex, ⟨p, ⟨hpfilter.2.2, hpe1⟩, hpfilter.2.1⟩⟩ }, end /-- The number of `e < x` for which `e + 1` has a prime factor `p > k` is bounded by `x` times the sum of reciprocals of primes in `(k, x]`. -/ lemma card_le_mul_sum {x k : ℕ} : (card (U x k) : ℝ) ≤ x * ∑ p in P x k, 1 / p := begin let P := {p ∈ range (x + 1) | k < p ∧ nat.prime p}, let N := λ p, {e ∈ range x | p ∣ e + 1}, have h : card (finset.bUnion P N) ≤ ∑ p in P, card (N p) := card_bUnion_le, calc (card (finset.bUnion P N) : ℝ) ≤ ∑ p in P, card (N p) : by assumption_mod_cast ... ≤ ∑ p in P, x * (1 / p) : sum_le_sum (λ p hp, _) ... = x * ∑ p in P, 1 / p : mul_sum.symm, simp only [mul_one_div, N, sep_def, filter_congr_decidable, card_multiples, nat.cast_div_le], end /-- The number of `e < x` for which `e + 1` is a squarefree product of primes smaller than or equal to `k` is bounded by `2 ^ k`, the number of subsets of `[1, k]`. -/ lemma card_le_two_pow {x k : ℕ} : card {e ∈ M x k | squarefree (e + 1)} ≤ 2 ^ k := begin let M₁ := {e ∈ M x k | squarefree (e + 1)}, let f := λ s, finset.prod s (λ a, a) - 1, let K := powerset (image nat.succ (range k)), -- Take `e` in `M x k`. If `e + 1` is squarefree, then it is the product of a subset of `[1, k]`. -- It follows that `e` is one less than such a product. have h : M₁ ⊆ image f K, { intros m hm, simp only [M₁, M, sep_def, mem_filter, mem_range, mem_powerset, mem_image, exists_prop] at hm ⊢, obtain ⟨⟨-, hmp⟩, hms⟩ := hm, use (m + 1).factors, { rwa [multiset.coe_nodup, ← nat.squarefree_iff_nodup_factors m.succ_ne_zero] }, refine ⟨λ p, _, _⟩, { suffices : p ∈ (m + 1).factors → ∃ a : ℕ, a < k ∧ a.succ = p, { simpa }, simp_intros hp only [nat.mem_factors m.succ_ne_zero], exact ⟨p.pred, (nat.pred_lt (nat.prime.ne_zero hp.1)).trans_le ((hmp p) hp), nat.succ_pred_eq_of_pos (nat.prime.pos hp.1)⟩ }, { simp_rw f, simp [nat.prod_factors m.succ_ne_zero, m.succ_sub_one] } }, -- The number of elements of `M x k` with `e + 1` squarefree is bounded by the number of subsets -- of `[1, k]`. calc card M₁ ≤ card (image f K) : card_le_of_subset h ... ≤ card K : card_image_le ... ≤ 2 ^ card (image nat.succ (range k)) : by simp only [K, card_powerset] ... ≤ 2 ^ card (range k) : pow_le_pow one_le_two card_image_le ... = 2 ^ k : by rw card_range k, end /-- The number of `e < x` for which `e + 1` is a product of powers of primes smaller than or equal to `k` is bounded by `2 ^ k * nat.sqrt x`. -/ lemma card_le_two_pow_mul_sqrt {x k : ℕ} : card (M x k) ≤ 2 ^ k * nat.sqrt x := begin let M₁ := {e ∈ M x k | squarefree (e + 1)}, let M₂ := M (nat.sqrt x) k, let K := finset.product M₁ M₂, let f : ℕ × ℕ → ℕ := λ mn, (mn.2 + 1) ^ 2 * (mn.1 + 1) - 1, -- Every element of `M x k` is one less than the product `(m + 1)² * (r + 1)` with `r + 1` -- squarefree and `m + 1 ≤ √x`, and both `m + 1` and `r + 1` still only have prime powers -- smaller than or equal to `k`. have h1 : M x k ⊆ image f K, { intros m hm, simp only [M, M₁, M₂, mem_image, exists_prop, prod.exists, mem_product, sep_def, mem_filter, mem_range] at hm ⊢, have hm' := m.zero_lt_succ, obtain ⟨a, b, hab₁, hab₂⟩ := nat.sq_mul_squarefree_of_pos' hm', obtain ⟨ham, hbm⟩ := ⟨dvd.intro_left _ hab₁, dvd.intro _ hab₁⟩, refine ⟨a, b, ⟨⟨⟨_, λ p hp, _⟩, hab₂⟩, ⟨_, λ p hp, _⟩⟩, by simp_rw [f, hab₁, m.succ_sub_one]⟩, { exact (nat.succ_le_succ_iff.mp (nat.le_of_dvd hm' ham)).trans_lt hm.1 }, { exact hm.2 p ⟨hp.1, hp.2.trans ham⟩ }, { calc b < b + 1 : lt_add_one b ... ≤ (m + 1).sqrt : by simpa only [nat.le_sqrt, pow_two] using nat.le_of_dvd hm' hbm ... ≤ x.sqrt : nat.sqrt_le_sqrt (nat.succ_le_iff.mpr hm.1) }, { exact hm.2 p ⟨hp.1, hp.2.trans (nat.dvd_of_pow_dvd one_le_two hbm)⟩ } }, have h2 : card M₂ ≤ nat.sqrt x, { rw ← card_range (nat.sqrt x), apply card_le_of_subset, simp [M₂, M] }, calc card (M x k) ≤ card (image f K) : card_le_of_subset h1 ... ≤ card K : card_image_le ... = card M₁ * card M₂ : card_product M₁ M₂ ... ≤ 2 ^ k * x.sqrt : mul_le_mul' card_le_two_pow h2, end theorem real.tendsto_sum_one_div_prime_at_top : tendsto (λ n, ∑ p in {p ∈ range n | nat.prime p}, (1 / (p : ℝ))) at_top at_top := begin -- Assume that the sum of the reciprocals of the primes converges. by_contradiction h, -- Then there is a natural number `k` such that for all `x`, the sum of the reciprocals of primes -- between `k` and `x` is less than 1/2. obtain ⟨k, h1⟩ := sum_lt_half_of_not_tendsto h, -- Choose `x` sufficiently large for the argument below to work, and use a perfect square so we -- can easily take the square root. let x := 2 ^ (k + 1) * 2 ^ (k + 1), -- We will partition `range x` into two subsets: -- * `M`, the subset of those `e` for which `e + 1` is a product of powers of primes smaller -- than or equal to `k`; set M := M x k with hM, -- * `U`, the subset of those `e` for which there is a prime `p > k` that divides `e + 1`. let P := {p ∈ range (x + 1) | k < p ∧ nat.prime p}, set U := U x k with hU, -- This is indeed a partition, so `|U| + |M| = |range x| = x`. have h2 : x = card U + card M, { rw [← card_range x, hU, hM, ← range_sdiff_eq_bUnion], exact (card_sdiff_add_card_eq_card (finset.filter_subset _ _)).symm }, -- But for the `x` we have chosen above, both `|U|` and `|M|` are less than or equal to `x / 2`, -- and for U, the inequality is strict. have h3 := calc (card U : ℝ) ≤ x * ∑ p in P, 1 / p : card_le_mul_sum ... < x * (1 / 2) : mul_lt_mul_of_pos_left (h1 x) (by norm_num) ... = x / 2 : mul_one_div x 2, have h4 := calc (card M : ℝ) ≤ 2 ^ k * x.sqrt : by exact_mod_cast card_le_two_pow_mul_sqrt ... = 2 ^ k * ↑(2 ^ (k + 1)) : by rw nat.sqrt_eq ... = x / 2 : by field_simp [x, mul_right_comm, ← pow_succ'], refine lt_irrefl (x : ℝ) _, calc (x : ℝ) = (card U : ℝ) + (card M : ℝ) : by assumption_mod_cast ... < x / 2 + x / 2 : add_lt_add_of_lt_of_le h3 h4 ... = x : add_halves ↑x, end
5d0e80171d6155324ae2a0e930a9fbe8f42cc431
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/data/option2.lean
056cfc01210ece54b568d6d00ba2466225360a9f
[ "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
596
lean
import tactic.lint variables {α : Type*} /-- A property which determins whether this option is inhabited. -/ def option.is_some' : option α → Prop | (some _) := true | none := false instance option.is_some'.decide : decidable_pred (@option.is_some' α) | (some _) := decidable.true | none := decidable.false /-- Extract the value of an option, given a proof it exists. -/ def option.get' : ∀ {o : option α}, option.is_some' o → α | (some k) _ := k lemma option.eq_some_of_is_some' : ∀ {o : option α} (h : option.is_some' o), o = some (option.get' h) | (some x) _ := rfl #lint-
00d225c327ed95413e61a2de7b37e7c8848b1d55
e9078bde91465351e1b354b353c9f9d8b8a9c8c2
/superseded/two_quotient_special_case.hlean
fbb471febfad396dd4cdaee87db728123a5baa46
[ "Apache-2.0" ]
permissive
EgbertRijke/leansnippets
09fb7a9813477471532fbdd50c99be8d8fe3e6c4
1d9a7059784c92c0281fcc7ce66ac7b3619c8661
refs/heads/master
1,610,743,957,626
1,442,532,603,000
1,442,532,603,000
41,563,379
0
0
null
1,440,787,514,000
1,440,787,514,000
null
UTF-8
Lean
false
false
7,736
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 -/ import hit.circle eq2 open quotient eq circle sum sigma equiv function namespace two_quotient section parameters {A : Type} (R : A → A → Type) (Q : Π⦃a⦄, R a a → Type) variables {a a' : A} {r : R a a} {s : R a a'} local abbreviation B := A ⊎ Σ(a : A) (r : R a a), Q r inductive pre_two_quotient_rel : B → B → Type := | pre_Rmk {} : Π⦃a a'⦄ (r : R a a'), pre_two_quotient_rel (inl a) (inl a') --BUG: if {} not provided, the alias for pre_Rmk is wrong definition pre_two_quotient := quotient pre_two_quotient_rel open pre_two_quotient_rel local abbreviation C := quotient pre_two_quotient_rel private definition j [constructor] (a : A) : C := class_of pre_two_quotient_rel (inl a) private definition pre_aux [constructor] (q : Q r) : C := class_of pre_two_quotient_rel (inr ⟨a, r, q⟩) private definition e (s : R a a') : j a = j a' := eq_of_rel _ (pre_Rmk s) private definition f [unfold 7] (q : Q r) : S¹ → C := circle.elim (j a) (e r) private definition pre_rec [unfold 8] {P : C → Type} (Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : R a a⦄ (q : Q r), P (pre_aux q)) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') (x : C) : P x := begin induction x with p, { induction p, { apply Pj}, { induction a with a1 a2, induction a2, apply Pa}}, { induction H, esimp, apply Pe}, end private definition pre_elim [unfold 8] {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : R a a⦄, Q r → P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') (x : C) : P := pre_rec Pj Pa (λa a' s, pathover_of_eq (Pe s)) x private theorem rec_e {P : C → Type} (Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : R a a⦄ (q : Q r), P (pre_aux q)) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') ⦃a a' : A⦄ (s : R a a') : apdo (pre_rec Pj Pa Pe) (e s) = Pe s := !rec_eq_of_rel private theorem elim_e {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : R a a⦄, Q r → P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (s : R a a') : ap (pre_elim Pj Pa Pe) (e s) = Pe s := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (e s)), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑pre_elim,rec_e], end inductive two_quotient_rel : C → C → Type := | Rmk {} : Π{a : A} {r : R a a} (q : Q r) (x : circle), two_quotient_rel (f q x) (pre_aux q) open two_quotient_rel definition two_quotient := quotient two_quotient_rel local abbreviation D := two_quotient local abbreviation i := class_of two_quotient_rel definition incl0 (a : A) : D := i (j a) definition aux (q : Q r) : D := i (pre_aux q) definition incl1 (s : R a a') : incl0 a = incl0 a' := ap i (e s) definition incl2' (q : Q r) (x : S¹) : i (f q x) = aux q := eq_of_rel two_quotient_rel (Rmk q x) definition incl2 (q : Q r) : incl1 r = idp := (ap02 i (elim_loop (j a) (e r))⁻¹) ⬝ (ap_compose i (f q) loop)⁻¹ ⬝ ap_weakly_constant (incl2' q) loop ⬝ !con.right_inv local attribute two_quotient f i incl0 aux incl1 incl2' [reducible] local attribute i aux incl0 [constructor] protected definition elim {P : Type} (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : R a a⦄ (q : Q r), P1 r = idp) (x : D) : P := begin induction x, { refine (pre_elim _ _ _ a), { exact P0}, { intro a r q, exact P0 a}, { exact P1}}, { exact abstract begin induction H, induction x, { exact idpath (P0 a)}, { unfold f, apply eq_pathover, apply hdeg_square, exact abstract ap_compose (pre_elim P0 _ P1) (f q) loop ⬝ ap _ !elim_loop ⬝ !elim_e ⬝ P2 q ⬝ !ap_constant⁻¹ end} end end}, end local attribute elim [unfold 8] protected definition elim_on {P : Type} (x : D) (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : R a a⦄ (q : Q r), P1 r = idp) : P := elim P0 P1 P2 x definition elim_incl1 {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : R a a⦄ (q : Q r), P1 r = idp) ⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s := !ap_compose⁻¹ ⬝ !elim_e definition elim_incl2'_incl0 {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : R a a⦄ (q : Q r), P1 r = idp) ⦃a : A⦄ ⦃r : R a a⦄ (q : Q r) : ap (elim P0 P1 P2) (incl2' q base) = idpath (P0 a) := !elim_eq_of_rel -- set_option pp.implicit true theorem elim_incl2 {P : Type} (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : R a a⦄ (q : Q r), P1 r = idp) ⦃a : A⦄ ⦃r : R a a⦄ (q : Q r) : square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_incl1 P2 r) idp := begin check_expr empty, esimp [incl2,ap02], rewrite [+ap_con (ap _),▸*,-ap_compose (ap _) (ap i),+ap_inv], xrewrite [eq_top_of_square ((ap_compose_natural (elim P0 P1 P2) i (elim_loop (j a) (e r)))⁻¹ʰ⁻¹ᵛ ⬝h (ap_ap_compose (elim P0 P1 P2) i (f q) loop)⁻¹ʰ⁻¹ᵛ ⬝h ap_ap_weakly_constant (elim P0 P1 P2) (incl2' q) loop ⬝h ap_con_right_inv_sq (elim P0 P1 P2) (incl2' q base)), ↑[elim_incl1]], apply whisker_tl, check_expr empty, rewrite [ap_weakly_constant_eq], xrewrite [naturality_apdo_eq (λx, !elim_eq_of_rel) loop], rewrite [↑elim_2,rec_loop,square_of_pathover_concato_eq,square_of_pathover_eq_concato, eq_of_square_vconcat_eq,eq_of_square_eq_vconcat], check_expr empty, apply eq_vconcat, { apply ap (λx, _ ⬝ eq_con_inv_of_con_eq ((_ ⬝ x ⬝ _)⁻¹ ⬝ _) ⬝ _), transitivity _, apply ap eq_of_square, apply to_right_inv !eq_pathover_equiv_square (hdeg_square (elim_1 P A R Q P0 P1 a r q P2)), transitivity _, apply eq_of_square_hdeg_square, unfold elim_1, reflexivity}, check_expr empty, rewrite [+con_inv,whisker_left_inv,+inv_inv,-whisker_right_inv, con.assoc (whisker_left _ _),con.assoc _ (whisker_right _ _),▸*, whisker_right_con_whisker_left _ !ap_constant], xrewrite [-con.assoc _ _ (whisker_right _ _)], rewrite [con.assoc _ _ (whisker_left _ _),idp_con_whisker_left,▸*, con.assoc _ !ap_constant⁻¹,con.left_inv], xrewrite [eq_con_inv_of_con_eq_whisker_left,▸*], check_expr empty, rewrite [+con.assoc _ _ !con.right_inv, right_inv_eq_idp ( (λ(x : ap (elim P0 P1 P2) (incl2' q base) = idpath (elim P0 P1 P2 (class_of two_quotient_rel (f q base)))), x) (elim_incl2'_incl0 P2 q)), ↑[whisker_left]], xrewrite [con2_con_con2], rewrite [idp_con,↑elim_incl2'_incl0,con.left_inv,whisker_right_inv,↑whisker_right], xrewrite [con.assoc _ _ (_ ◾ _)], rewrite [con.left_inv,▸*,-+con.assoc,con.assoc _⁻¹,↑[elim,function.compose],con.left_inv, ▸*,↑j,con.left_inv,idp_con], check_expr empty, apply square_of_eq, reflexivity end end end two_quotient attribute two_quotient.incl0 [constructor] attribute /-two_quotient.rec-/ two_quotient.elim [unfold 8] [recursor 8] --attribute two_quotient.elim_type [unfold 9] attribute /-two_quotient.rec_on-/ two_quotient.elim_on [unfold 5] --attribute two_quotient.elim_type_on [unfold 6]
d88321fc11e4d0ccf2b65e38722705547523d400
4fa118f6209450d4e8d058790e2967337811b2b5
/src/sheaves/presheaf.lean
b3fdfa5c23af57a93b45f1cec59c323a2d6e55d4
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
1,942
lean
/- Presheaf (of types). https://stacks.math.columbia.edu/tag/006D Author: Ramon Fernandez Mir -/ import topology.basic import topology.opens universes u v -- Definition of a presheaf. open topological_space lattice structure presheaf (α : Type u) [topological_space α] := (F : opens α → Type v) (res : ∀ (U V) (HVU : V ⊆ U), F U → F V) (Hid : ∀ (U), res U U (set.subset.refl U) = id) (Hcomp : ∀ (U V W) (HWV : W ⊆ V) (HVU : V ⊆ U), res U W (set.subset.trans HWV HVU) = res V W HWV ∘ res U V HVU) namespace presheaf variables {α : Type u} [topological_space α] instance : has_coe_to_fun (presheaf α) := { F := λ _, opens α → Type v, coe := presheaf.F } -- Simplification lemmas for Hid and Hcomp. @[simp] lemma Hcomp' (F : presheaf α) : ∀ (U V W) (HWV : W ⊆ V) (HVU : V ⊆ U) (s : F U), (F.res U W (set.subset.trans HWV HVU)) s = (F.res V W HWV) ((F.res U V HVU) s) := λ U V W HWV HVU s, by rw F.Hcomp U V W HWV HVU @[simp] lemma Hid' (F : presheaf α) : ∀ (U) (s : F U), (F.res U U (set.subset.refl U)) s = s := λ U s, by rw F.Hid U; simp -- Morphism of presheaves. structure morphism (F G : presheaf α) := (map : ∀ (U), F U → G U) (commutes : ∀ (U V) (HVU : V ⊆ U), (G.res U V HVU) ∘ (map U) = (map V) ∘ (F.res U V HVU)) local infix `⟶`:80 := morphism section morphism def comp {F G H : presheaf α} (fg : F ⟶ G) (gh : G ⟶ H) : F ⟶ H := { map := λ U, gh.map U ∘ fg.map U, commutes := λ U V HVU, begin rw [←function.comp.assoc, gh.commutes U V HVU], symmetry, rw [function.comp.assoc, ←fg.commutes U V HVU] end } local infix `⊚`:80 := comp def id (F : presheaf α) : F ⟶ F := { map := λ U, id, commutes := λ U V HVU, by simp, } structure iso (F G : presheaf α) := (mor : F ⟶ G) (inv : G ⟶ F) (mor_inv_id : mor ⊚ inv = id F) (inv_mor_id : inv ⊚ mor = id G) end morphism end presheaf
33585901357588d0fb75473bd7fd570908402aae
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/autoBoundImplicits2.lean
b69c3883ee8a7fac2c1223b75cd84a6c87c39bb5
[ "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
1,057
lean
def f [Add α] (a : α) : α := a + a def BV (n : Nat) := { a : Array Bool // a.size = n } def allZero (bv : BV n) : Prop := ∀ i, i < n → bv.val[i] = false def foo (n : Nat) (h : allZero b) : BV n := b def optbind (x : Option α) (f : α → Option β) : Option β := match x with | none => none | some a => f a instance : Monad Option where bind := optbind pure := some inductive Mem : α → List α → Prop | head (a : α) (as : List α) : Mem a (a::as) def g1 {α : Type u} (a : α) : α := a #check g1 set_option autoBoundImplicitLocal false in def g2 {α : Type u /- Error -/} (a : α) : α := a def g3 {α : Type β /- Error greek letters are not valid auto names for universes -/} (a : α) : α := a def g4 {α : Type v} (a : α) : α := a def g5 {α : Type (v+1)} (a : α) : α := a def g6 {α : Type u} (a : α) := let β : Type u := α let x : β := a x inductive M (m : Type v → Type w) where | f (β : Type v) : M m variable {m : Type u → Type u} def h1 (a : m α) := a #print h1
12fd4bc196bae6f9b9b5813fe92b607853aa36f2
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/algebra/semigroup.lean
4b5cf947340796cea682d2a424ac9388a5b9ec39
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
4,752
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import topology.separation /-! # Idempotents in topological semigroups This file provides a sufficient condition for a semigroup `M` to contain an idempotent (i.e. an element `m` such that `m * m = m `), namely that `M` is a nonempty compact Hausdorff space where right-multiplication by constants is continuous. We also state a corresponding lemma guaranteeing that a subset of `M` contains an idempotent. -/ /-- Any nonempty compact Hausdorff semigroup where right-multiplication is continuous contains an idempotent, i.e. an `m` such that `m * m = m`. -/ @[to_additive "Any nonempty compact Hausdorff additive semigroup where right-addition is continuous contains an idempotent, i.e. an `m` such that `m + m = m`"] lemma exists_idempotent_of_compact_t2_of_continuous_mul_left {M} [nonempty M] [semigroup M] [topological_space M] [compact_space M] [t2_space M] (continuous_mul_left : ∀ r : M, continuous (* r)) : ∃ m : M, m * m = m := begin /- We apply Zorn's lemma to the poset of nonempty closed subsemigroups of `M`. It will turn out that any minimal element is `{m}` for an idempotent `m : M`. -/ let S : set (set M) := {N | is_closed N ∧ N.nonempty ∧ ∀ m m' ∈ N, m * m' ∈ N}, suffices : ∃ N ∈ S, ∀ N' ∈ S, N' ⊆ N → N' = N, { rcases this with ⟨N, ⟨N_closed, ⟨m, hm⟩, N_mul⟩, N_minimal⟩, use m, /- We now have an element `m : M` of a minimal subsemigroup `N`, and want to show `m + m = m`. We first show that every element of `N` is of the form `m' + m`.-/ have scaling_eq_self : (* m) '' N = N, { apply N_minimal, { refine ⟨(continuous_mul_left m).is_closed_map _ N_closed, ⟨_, ⟨m, hm, rfl⟩⟩, _⟩, rintros _ ⟨m'', hm'', rfl⟩ _ ⟨m', hm', rfl⟩, refine ⟨m'' * m * m', N_mul _ (N_mul _ hm'' _ hm) _ hm', mul_assoc _ _ _⟩ }, { rintros _ ⟨m', hm', rfl⟩, exact N_mul _ hm' _ hm } }, /- In particular, this means that `m' * m = m` for some `m'`. We now use minimality again to show that this holds for all `m' ∈ N`. -/ have absorbing_eq_self : N ∩ {m' | m' * m = m} = N, { apply N_minimal, { refine ⟨N_closed.inter ((t1_space.t1 m).preimage (continuous_mul_left m)), _, _⟩, { rwa ←scaling_eq_self at hm }, { rintros m'' ⟨mem'', eq'' : _ = m⟩ m' ⟨mem', eq' : _ = m⟩, refine ⟨N_mul _ mem'' _ mem', _⟩, rw [set.mem_set_of_eq, mul_assoc, eq', eq''] } }, apply set.inter_subset_left }, /- Thus `m * m = m` as desired. -/ rw ←absorbing_eq_self at hm, exact hm.2 }, refine zorn_superset _ (λ c hcs hc, _), refine ⟨⋂₀ c, ⟨is_closed_sInter $ λ t ht, (hcs ht).1, _, λ m hm m' hm', _⟩, λ s hs, set.sInter_subset_of_mem hs⟩, { obtain rfl | hcnemp := c.eq_empty_or_nonempty, { rw set.sInter_empty, apply set.univ_nonempty }, convert @is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ _ _ (set.nonempty_coe_sort.mpr hcnemp) (coe : c → set M) _ _ _ _, { simp only [subtype.range_coe_subtype, set.set_of_mem_eq] } , { refine directed_on.directed_coe (is_chain.directed_on hc.symm) }, exacts [λ i, (hcs i.prop).2.1, λ i, (hcs i.prop).1.is_compact, λ i, (hcs i.prop).1] }, { rw set.mem_sInter, exact λ t ht, (hcs ht).2.2 m (set.mem_sInter.mp hm t ht) m' (set.mem_sInter.mp hm' t ht) }, end /-- A version of `exists_idempotent_of_compact_t2_of_continuous_mul_left` where the idempotent lies in some specified nonempty compact subsemigroup. -/ @[to_additive exists_idempotent_in_compact_add_subsemigroup "A version of `exists_idempotent_of_compact_t2_of_continuous_add_left` where the idempotent lies in some specified nonempty compact additive subsemigroup."] lemma exists_idempotent_in_compact_subsemigroup {M} [semigroup M] [topological_space M] [t2_space M] (continuous_mul_left : ∀ r : M, continuous (* r)) (s : set M) (snemp : s.nonempty) (s_compact : is_compact s) (s_add : ∀ x y ∈ s, x * y ∈ s) : ∃ m ∈ s, m * m = m := begin let M' := {m // m ∈ s}, letI : semigroup M' := { mul := λ p q, ⟨p.1 * q.1, s_add _ p.2 _ q.2⟩, mul_assoc := λ p q r, subtype.eq (mul_assoc _ _ _) }, haveI : compact_space M' := is_compact_iff_compact_space.mp s_compact, haveI : nonempty M' := nonempty_subtype.mpr snemp, have : ∀ p : M', continuous (* p) := λ p, continuous_subtype_mk _ ((continuous_mul_left p.1).comp continuous_subtype_val), obtain ⟨⟨m, hm⟩, idem⟩ := exists_idempotent_of_compact_t2_of_continuous_mul_left this, exact ⟨m, hm, subtype.ext_iff.mp idem⟩ end
8b4eebe2b9b792a78364a2936be8402d796ca3ac
9dc8cecdf3c4634764a18254e94d43da07142918
/src/field_theory/cardinality.lean
4eca136d08f4eed6564b3378b2303c697389907f
[ "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
3,359
lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import algebra.ring.ulift import data.mv_polynomial.cardinal import data.rat.denumerable import field_theory.finite.galois_field import logic.equiv.transfer_instance import ring_theory.localization.cardinality import set_theory.cardinal.divisibility import data.nat.factorization.prime_pow /-! # Cardinality of Fields In this file we show all the possible cardinalities of fields. All infinite cardinals can harbour a field structure, and so can all types with prime power cardinalities, and this is sharp. ## Main statements * `fintype.nonempty_field_iff`: A `fintype` can be given a field structure iff its cardinality is a prime power. * `infinite.nonempty_field` : Any infinite type can be endowed a field structure. * `field.nonempty_iff` : There is a field structure on type iff its cardinality is a prime power. -/ local notation `‖` x `‖` := fintype.card x open_locale cardinal non_zero_divisors universe u /-- A finite field has prime power cardinality. -/ lemma fintype.is_prime_pow_card_of_field {α} [fintype α] [field α] : is_prime_pow (‖α‖) := begin casesI char_p.exists α with p _, haveI hp := fact.mk (char_p.char_is_prime α p), let b := is_noetherian.finset_basis (zmod p) α, rw [module.card_fintype b, zmod.card, is_prime_pow_pow_iff], { exact hp.1.is_prime_pow }, rw ←finite_dimensional.finrank_eq_card_basis b, exact finite_dimensional.finrank_pos.ne' end /-- A `fintype` can be given a field structure iff its cardinality is a prime power. -/ lemma fintype.nonempty_field_iff {α} [fintype α] : nonempty (field α) ↔ is_prime_pow (‖α‖) := begin refine ⟨λ ⟨h⟩, by exactI fintype.is_prime_pow_card_of_field, _⟩, rintros ⟨p, n, hp, hn, hα⟩, haveI := fact.mk (nat.prime_iff.mpr hp), exact ⟨(fintype.equiv_of_card_eq ((galois_field.card p n hn.ne').trans hα)).symm.field⟩, end lemma fintype.not_is_field_of_card_not_prime_pow {α} [fintype α] [ring α] : ¬ is_prime_pow (‖α‖) → ¬ is_field α := mt $ λ h, fintype.nonempty_field_iff.mp ⟨h.to_field⟩ /-- Any infinite type can be endowed a field structure. -/ lemma infinite.nonempty_field {α : Type u} [infinite α] : nonempty (field α) := begin letI K := fraction_ring (mv_polynomial α $ ulift.{u} ℚ), suffices : #α = #K, { obtain ⟨e⟩ := cardinal.eq.1 this, exact ⟨e.field⟩ }, rw ←is_localization.card (mv_polynomial α $ ulift.{u} ℚ)⁰ K le_rfl, apply le_antisymm, { refine ⟨⟨λ a, mv_polynomial.monomial (finsupp.single a 1) (1 : ulift.{u} ℚ), λ x y h, _⟩⟩, simpa [mv_polynomial.monomial_eq_monomial_iff, finsupp.single_eq_single_iff] using h }, { simp } end /-- There is a field structure on type if and only if its cardinality is a prime power. -/ lemma field.nonempty_iff {α : Type u} : nonempty (field α) ↔ is_prime_pow (#α) := begin rw cardinal.is_prime_pow_iff, casesI fintype_or_infinite α with h h, { simpa only [cardinal.mk_fintype, nat.cast_inj, exists_eq_left', (cardinal.nat_lt_aleph_0 _).not_le, false_or] using fintype.nonempty_field_iff }, { simpa only [← cardinal.infinite_iff, h, true_or, iff_true] using infinite.nonempty_field }, end