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
67ec6e30706011956302e7de49e290b51952f1ec
798dd332c1ad790518589a09bc82459fb12e5156
/category_theory/examples/topological_spaces.lean
2069f3e47444a363d5bd6c7ca685fe8ef82f4144
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,491
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Patrick Massot, Scott Morrison import category_theory.full_subcategory import analysis.topology.topological_space import analysis.topology.continuity open category_theory universe u namespace category_theory.examples /-- The category of topological spaces and continuous maps. -/ @[reducible] def Top : Type (u+1) := bundled topological_space instance (x : Top) : topological_space x := x.str namespace Top instance : concrete_category @continuous := ⟨@continuous_id, @continuous.comp⟩ -- local attribute [class] continuous -- instance {R S : Top} (f : R ⟶ S) : continuous (f : R → S) := f.2 end Top structure open_set (α : Type u) [X : topological_space α] : Type u := (s : set α) (is_open : topological_space.is_open X s) variables {α : Type*} [topological_space α] namespace open_set instance : has_coe (open_set α) (set α) := { coe := λ U, U.s } instance : has_subset (open_set α) := { subset := λ U V, U.s ⊆ V.s } instance : preorder (open_set α) := by refine { le := (⊆), .. } ; tidy instance open_sets : small_category (open_set α) := by apply_instance instance : has_mem α (open_set α) := { mem := λ a V, a ∈ V.s } def nbhd (x : α) := { U : open_set α // x ∈ U } def nbhds (x : α) : small_category (nbhd x) := begin unfold nbhd, apply_instance end end open_set end category_theory.examples
0e05687ef29ee0cc6df56fc58ff157551caf4c63
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0401.lean
6434f580e47f8f0fe0864676985a869d102ea497
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
69
lean
def foo : (ℕ → ℕ) → ℕ := λ f, f 0 #check foo #print foo
a993574f6c41af6446c79789977ca56841f04c1e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/split1.lean
d3112573453c0ed9285febda74bef30b09dde857
[ "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
553
lean
def f (xs : List Nat) : Nat := match xs with | [] => 1 | [a, b] => (a + b).succ | _ => 2 theorem ex1 (xs : List Nat) (hr : xs.reverse = xs) (ys : Nat) : ys > 0 → f xs > 0 := by simp [f] split next => intro hys; decide next => intro hys; apply Nat.zero_lt_succ next zs n₁ n₂ => intro hys; decide def g (xs : List Nat) : Nat := match xs with | [a, b, c, d, e] => a + e + 1 | _ => 1 theorem ex2 (xs : List Nat) : g xs > 0 := by simp [g] split next a b c d e => apply Nat.zero_lt_succ next h => decide
36afa985ba5febfe1221a9e0ff755e0a6e60c62f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/nat/dist.lean
800e4e0c6df4c4ef02307674811933ebcd42bec4
[ "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
4,501
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad -/ import data.nat.basic /-! # Distance function on ℕ This file defines a simple distance function on naturals from truncated substraction. -/ namespace nat /-- Distance (absolute value of difference) between natural numbers. -/ def dist (n m : ℕ) := (n - m) + (m - n) theorem dist.def (n m : ℕ) : dist n m = (n - m) + (m - n) := rfl theorem dist_comm (n m : ℕ) : dist n m = dist m n := by simp [dist.def, add_comm] @[simp] theorem dist_self (n : ℕ) : dist n n = 0 := by simp [dist.def, nat.sub_self] theorem eq_of_dist_eq_zero {n m : ℕ} (h : dist n m = 0) : n = m := have n - m = 0, from eq_zero_of_add_eq_zero_right h, have n ≤ m, from nat.le_of_sub_eq_zero this, have m - n = 0, from eq_zero_of_add_eq_zero_left h, have m ≤ n, from nat.le_of_sub_eq_zero this, le_antisymm ‹n ≤ m› ‹m ≤ n› theorem dist_eq_zero {n m : ℕ} (h : n = m) : dist n m = 0 := begin rw [h, dist_self] end theorem dist_eq_sub_of_le {n m : ℕ} (h : n ≤ m) : dist n m = m - n := begin rw [dist.def, sub_eq_zero_of_le h, zero_add] end theorem dist_eq_sub_of_le_right {n m : ℕ} (h : m ≤ n) : dist n m = n - m := begin rw [dist_comm], apply dist_eq_sub_of_le h end theorem dist_tri_left (n m : ℕ) : m ≤ dist n m + n := le_trans (nat.le_sub_add _ _) (add_le_add_right (le_add_left _ _) _) theorem dist_tri_right (n m : ℕ) : m ≤ n + dist n m := by rw add_comm; apply dist_tri_left theorem dist_tri_left' (n m : ℕ) : n ≤ dist n m + m := by rw dist_comm; apply dist_tri_left theorem dist_tri_right' (n m : ℕ) : n ≤ m + dist n m := by rw dist_comm; apply dist_tri_right theorem dist_zero_right (n : ℕ) : dist n 0 = n := eq.trans (dist_eq_sub_of_le_right (zero_le n)) (nat.sub_zero n) theorem dist_zero_left (n : ℕ) : dist 0 n = n := eq.trans (dist_eq_sub_of_le (zero_le n)) (nat.sub_zero n) theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n + k) - (m + k)) + ((m + k)-(n + k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : by rw nat.add_sub_add_right ... = (n - m) + (m - n) : by rw nat.add_sub_add_right theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := begin rw [add_comm k n, add_comm k m], apply dist_add_add_right end theorem dist_eq_intro {n m k l : ℕ} (h : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : by rw dist_add_add_right ... = dist (k + l) (k + m) : by rw h ... = dist l m : by rw dist_add_add_left protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := or.elim (le_total k m) (assume : k ≤ m, begin rw ←nat.add_sub_assoc this, apply nat.sub_le_sub_right, apply nat.le_sub_add end) (assume : k ≥ m, begin rw [sub_eq_zero_of_le this, add_zero], apply nat.sub_le_sub_left, exact this end) theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have dist n m + dist m k = (n - m) + (m - k) + ((k - m) + (m - n)), by simp [dist.def, add_comm, add_left_comm], begin rw [this, dist.def], apply add_le_add, repeat { apply nat.sub_lt_sub_add_sub } end theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := by rw [dist.def, dist.def, right_distrib, nat.mul_sub_right_distrib, nat.mul_sub_right_distrib] theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm] -- TODO(Jeremy): do when we have max and minx --theorem dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j := --sorry /- or.elim (lt_or_ge i j) (assume : i < j, by rw [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this]) (assume : i ≥ j, by rw [max_eq_left this , min_eq_right this, dist_eq_sub_of_le_right this]) -/ theorem dist_succ_succ {i j : nat} : dist (succ i) (succ j) = dist i j := by simp [dist.def, succ_sub_succ] theorem dist_pos_of_ne {i j : nat} : i ≠ j → 0 < dist i j := assume hne, nat.lt_by_cases (assume : i < j, begin rw [dist_eq_sub_of_le (le_of_lt this)], apply nat.sub_pos_of_lt this end) (assume : i = j, by contradiction) (assume : i > j, begin rw [dist_eq_sub_of_le_right (le_of_lt this)], apply nat.sub_pos_of_lt this end) end nat
8208a20db39da29457709025f3a6a42240883d58
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/category_theory/yoneda.lean
95ce9b0b533e8a0c0405aa94f09775312d38ea3f
[ "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
5,075
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison /- The Yoneda embedding, as a functor `yoneda : C ⥤ ((Cᵒᵖ) ⥤ (Type v₁))`, along with instances that it is `full` and `faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. -/ import category_theory.natural_transformation import category_theory.opposites import category_theory.types import category_theory.embedding import category_theory.natural_isomorphism namespace category_theory universes u₁ v₁ u₂ variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C] include 𝒞 def yoneda : C ⥤ ((Cᵒᵖ) ⥤ (Type v₁)) := { obj := λ X, { obj := λ Y : C, Y ⟶ X, map := λ Y Y' f g, f ≫ g, map_comp' := begin intros X_1 Y Z f g, ext1, dsimp at *, erw [category.assoc] end, map_id' := begin intros X_1, ext1, dsimp at *, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } } namespace yoneda @[simp] lemma obj_obj (X Y : C) : ((yoneda C).obj X).obj Y = (Y ⟶ X) := rfl @[simp] lemma obj_map (X : C) {Y Y' : C} (f : Y ⟶ Y') : ((yoneda C).obj X).map f = λ g, f ≫ g := rfl @[simp] lemma map_app {X X' : C} (f : X ⟶ X') (Y : C) : ((yoneda C).map f).app Y = λ g, g ≫ f := rfl lemma obj_map_id {X Y : Cᵒᵖ} (f : X ⟶ Y) : ((yoneda C).obj X).map f (𝟙 X) = ((yoneda C).map f).app Y (𝟙 Y) := by obviously @[simp] lemma naturality {X Y : C} (α : (yoneda C).obj X ⟶ (yoneda C).obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app Z' h = α.app Z (f ≫ h) := begin erw [functor_to_types.naturality], refl end instance full : full (yoneda C) := { preimage := λ X Y f, (f.app X) (𝟙 X) }. instance faithful : faithful (yoneda C) := begin fsplit, intros X Y f g p, injection p with h, convert (congr_fun (congr_fun h X) (𝟙 X)) ; simp end /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := @preimage_iso _ _ _ _ (yoneda C) _ _ _ _ (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category (((Cᵒᵖ) ⥤ Type v₁) × (Cᵒᵖ)) := category_theory.prod.{(max u₁ (v₁+1)) (max u₁ v₁) u₁ v₁} (Cᵒᵖ ⥤ Type v₁) (Cᵒᵖ) instance prod_category_instance_2 : category ((Cᵒᵖ) × ((Cᵒᵖ) ⥤ Type v₁)) := category_theory.prod.{u₁ v₁ (max u₁ (v₁+1)) (max u₁ v₁)} (Cᵒᵖ) (Cᵒᵖ ⥤ Type v₁) end yoneda open yoneda def yoneda_evaluation : (((Cᵒᵖ) ⥤ (Type v₁)) × (Cᵒᵖ)) ⥤ (Type (max u₁ v₁)) := (evaluation (Cᵒᵖ) (Type v₁)) ⋙ ulift_functor.{v₁ u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : (Cᵒᵖ ⥤ Type v₁) × (Cᵒᵖ)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = (α.1).app (Q.2) ((P.1).map (α.2) (x.down)) := rfl def yoneda_pairing : (((Cᵒᵖ) ⥤ (Type v₁)) × (Cᵒᵖ)) ⥤ (Type (max u₁ v₁)) := let F := (category_theory.prod.swap ((Cᵒᵖ) ⥤ (Type v₁)) (Cᵒᵖ)) in let G := (functor.prod ((yoneda C).op) (functor.id ((Cᵒᵖ) ⥤ (Type v₁)))) in let H := (functor.hom ((Cᵒᵖ) ⥤ (Type v₁))) in (F ⋙ G ⋙ H) @[simp] lemma yoneda_pairing_map (P Q : (Cᵒᵖ ⥤ Type v₁) × (Cᵒᵖ)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj (P.1, P.2)) : (yoneda_pairing C).map α β = (yoneda C).map (α.snd) ≫ β ≫ α.fst := rfl def yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C) := { hom := { app := λ F x, ulift.up ((x.app F.2) (𝟙 F.2)), naturality' := begin intros X Y f, ext1, ext1, cases f, cases Y, cases X, dsimp at *, simp at *, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end }, inv := { app := λ F x, { app := λ X a, (F.1.map a) x.down, naturality' := begin intros X Y f, ext1, cases x, cases F, dsimp at *, erw [functor_to_types.map_comp], refl end }, naturality' := begin intros X Y f, ext1, ext1, ext1, cases x, cases f, cases Y, cases X, dsimp at *, erw [←functor_to_types.naturality, functor_to_types.map_comp] end }, hom_inv_id' := begin ext1, ext1, ext1, ext1, cases X, dsimp at *, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end, inv_hom_id' := begin ext1, ext1, ext1, cases x, cases X, dsimp at *, erw [functor_to_types.map_id] end }. end category_theory
a09a9951b8a9e13cd956a8d59ae17ff064dadf9b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/setoid/partition.lean
dfba22d23e56c2c5a19776e8941ef7ebc7e49bb4
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
14,848
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen, Patrick Massot -/ import data.setoid.basic import data.set.lattice /-! # Equivalence relations: partitions This file comprises properties of equivalence relations viewed as partitions. There are two implementations of partitions here: * A collection `c : set (set α)` of sets is a partition of `α` if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. This is expressed as `is_partition c` * An indexed partition is a map `s : ι → α` whose image is a partition. This is expressed as `indexed_partition s`. Of course both implementations are related to `quotient` and `setoid`. ## Tags setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class -/ namespace setoid variables {α : Type*} /-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/ lemma eq_of_mem_eqv_class {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') : b = b' := (H x).unique2 hc hb hc' hb' /-- Makes an equivalence relation from a set of sets partitioning α. -/ def mk_classes (c : set (set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) : setoid α := ⟨λ x y, ∀ s ∈ c, x ∈ s → y ∈ s, ⟨λ _ _ _ hx, hx, λ x y h s hs hy, (H x).elim2 $ λ t ht hx _, have s = t, from eq_of_mem_eqv_class H hs hy ht (h t ht hx), this.symm ▸ hx, λ x y z h1 h2 s hs hx, (H y).elim2 $ λ t ht hy _, (H z).elim2 $ λ t' ht' hz _, have hst : s = t, from eq_of_mem_eqv_class H hs (h1 _ hs hx) ht hy, have htt' : t = t', from eq_of_mem_eqv_class H ht (h2 _ ht hy) ht' hz, (hst.trans htt').symm ▸ hz⟩⟩ /-- Makes the equivalence classes of an equivalence relation. -/ def classes (r : setoid α) : set (set α) := {s | ∃ y, s = {x | r.rel x y}} lemma mem_classes (r : setoid α) (y) : {x | r.rel x y} ∈ r.classes := ⟨y, rfl⟩ /-- Two equivalence relations are equal iff all their equivalence classes are equal. -/ lemma eq_iff_classes_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ ∀ x, {y | r₁.rel x y} = {y | r₂.rel x y} := ⟨λ h x, h ▸ rfl, λ h, ext' $ λ x, set.ext_iff.1 $ h x⟩ lemma rel_iff_exists_classes (r : setoid α) {x y} : r.rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c := ⟨λ h, ⟨_, r.mem_classes y, h, r.refl' y⟩, λ ⟨c, ⟨z, hz⟩, hx, hy⟩, by { subst c, exact r.trans' hx (r.symm' hy) }⟩ /-- Two equivalence relations are equal iff their equivalence classes are equal. -/ lemma classes_inj {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.classes = r₂.classes := ⟨λ h, h ▸ rfl, λ h, ext' $ λ a b, by simp only [rel_iff_exists_classes, exists_prop, h] ⟩ /-- The empty set is not an equivalence class. -/ lemma empty_not_mem_classes {r : setoid α} : ∅ ∉ r.classes := λ ⟨y, hy⟩, set.not_mem_empty y $ hy.symm ▸ r.refl' y /-- Equivalence classes partition the type. -/ lemma classes_eqv_classes {r : setoid α} (a) : ∃! b ∈ r.classes, a ∈ b := exists_unique.intro2 {x | r.rel x a} (r.mem_classes a) (r.refl' _) $ begin rintros _ ⟨y, rfl⟩ ha, ext x, exact ⟨λ hx, r.trans' hx (r.symm' ha), λ hx, r.trans' hx ha⟩ end /-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/ lemma eq_of_mem_classes {r : setoid α} {x b} (hc : b ∈ r.classes) (hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' := eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb' /-- The elements of a set of sets partitioning α are the equivalence classes of the equivalence relation defined by the set of sets. -/ lemma eq_eqv_class_of_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) : s = {x | (mk_classes c H).rel x y} := set.ext $ λ x, ⟨λ hs', symm' (mk_classes c H) $ λ b' hb' h', eq_of_mem_eqv_class H hs hy hb' h' ▸ hs', λ hx, (H x).elim2 $ λ b' hc' hb' h', (eq_of_mem_eqv_class H hs hy hc' $ hx b' hc' hb').symm ▸ hb'⟩ /-- The equivalence classes of the equivalence relation defined by a set of sets partitioning α are elements of the set of sets. -/ lemma eqv_class_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} : {x | (mk_classes c H).rel x y} ∈ c := (H y).elim2 $ λ b hc hy hb, eq_eqv_class_of_mem H hc hy ▸ hc lemma eqv_class_mem' {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x} : {y : α | (mk_classes c H).rel x y} ∈ c := by { convert setoid.eqv_class_mem H, ext, rw setoid.comm' } /-- Distinct elements of a set of sets partitioning α are disjoint. -/ lemma eqv_classes_disjoint {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) : set.pairwise_disjoint c := λ b₁ h₁ b₂ h₂ h, set.disjoint_left.2 $ λ x hx1 hx2, (H x).elim2 $ λ b hc hx hb, h $ eq_of_mem_eqv_class H h₁ hx1 h₂ hx2 /-- A set of disjoint sets covering α partition α (classical). -/ lemma eqv_classes_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) (a) : ∃! b ∈ c, a ∈ b := let ⟨b, hc, ha⟩ := set.mem_sUnion.1 $ show a ∈ _, by rw hu; exact set.mem_univ a in exists_unique.intro2 b hc ha $ λ b' hc' ha', H.elim hc' hc a ha' ha /-- Makes an equivalence relation from a set of disjoints sets covering α. -/ def setoid_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) : setoid α := setoid.mk_classes c $ eqv_classes_of_disjoint_union hu H /-- The equivalence relation made from the equivalence classes of an equivalence relation r equals r. -/ theorem mk_classes_classes (r : setoid α) : mk_classes r.classes classes_eqv_classes = r := ext' $ λ x y, ⟨λ h, r.symm' (h {z | r.rel z x} (r.mem_classes x) $ r.refl' x), λ h b hb hx, eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩ @[simp] theorem sUnion_classes (r : setoid α) : ⋃₀ r.classes = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 ⟨{ y | r.rel y x }, ⟨x, rfl⟩, setoid.refl _⟩ section partition /-- A collection `c : set (set α)` of sets is a partition of `α` into pairwise disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/ def is_partition (c : set (set α)) := ∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b /-- A partition of `α` does not contain the empty set. -/ lemma nonempty_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (h : s ∈ c) : s.nonempty := set.ne_empty_iff_nonempty.1 $ λ hs0, hc.1 $ hs0 ▸ h lemma is_partition_classes (r : setoid α) : is_partition r.classes := ⟨empty_not_mem_classes, classes_eqv_classes⟩ lemma is_partition.pairwise_disjoint {c : set (set α)} (hc : is_partition c) : c.pairwise_disjoint := eqv_classes_disjoint hc.2 lemma is_partition.sUnion_eq_univ {c : set (set α)} (hc : is_partition c) : ⋃₀ c = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 $ let ⟨t, ht⟩ := hc.2 x in ⟨t, by clear_aux_decl; finish⟩ /-- All elements of a partition of α are the equivalence class of some y ∈ α. -/ lemma exists_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (hs : s ∈ c) : ∃ y, s = {x | (mk_classes c hc.2).rel x y} := let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs in ⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩ /-- The equivalence classes of the equivalence relation defined by a partition of α equal the original partition. -/ theorem classes_mk_classes (c : set (set α)) (hc : is_partition c) : (mk_classes c hc.2).classes = c := set.ext $ λ s, ⟨λ ⟨y, hs⟩, (hc.2 y).elim2 $ λ b hm hb hy, by rwa (show s = b, from hs.symm ▸ set.ext (λ x, ⟨λ hx, symm' (mk_classes c hc.2) hx b hm hb, λ hx b' hc' hx', eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩)), exists_of_mem_partition hc⟩ /-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/ instance partition.le : has_le (subtype (@is_partition α)) := ⟨λ x y, mk_classes x.1 x.2.2 ≤ mk_classes y.1 y.2.2⟩ /-- Defining a partial order on partitions as the partial order on their induced equivalence relations. -/ instance partition.partial_order : partial_order (subtype (@is_partition α)) := { le := (≤), lt := λ x y, x ≤ y ∧ ¬y ≤ x, le_refl := λ _, @le_refl (setoid α) _ _, le_trans := λ _ _ _, @le_trans (setoid α) _ _ _ _, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ x y hx hy, let h := @le_antisymm (setoid α) _ _ _ hx hy in by rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2, ←classes_mk_classes y.1 y.2, h] } variables (α) /-- The order-preserving bijection between equivalence relations and partitions of sets. -/ def partition.rel_iso : setoid α ≃o subtype (@is_partition α) := { to_fun := λ r, ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩, inv_fun := λ x, mk_classes x.1 x.2.2, left_inv := mk_classes_classes, right_inv := λ x, by rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2], map_rel_iff' := λ x y, by { conv_rhs { rw [←mk_classes_classes x, ←mk_classes_classes y] }, refl } } variables {α} /-- A complete lattice instance for partitions; there is more infrastructure for the equivalent complete lattice on equivalence relations. -/ instance partition.complete_lattice : complete_lattice (subtype (@is_partition α)) := galois_insertion.lift_complete_lattice $ @rel_iso.to_galois_insertion _ (subtype (@is_partition α)) _ (partial_order.to_preorder _) $ partition.rel_iso α end partition end setoid /-- Constructive information associated with a partition of a type `α` indexed by another type `ι`, `s : ι → set α`. `indexed_partition.index` sends an element to its index, while `indexed_partition.some` sends an index to an element of the corresponding set. This type is primarily useful for definitional control of `s` - if this is not needed, then `setoid.ker index` by itself may be sufficient. -/ structure indexed_partition {ι α : Type*} (s : ι → set α) := (eq_of_mem : ∀ {x i j}, x ∈ s i → x ∈ s j → i = j) (some : ι → α) (some_mem : ∀ i, some i ∈ s i) (index : α → ι) (mem_index : ∀ x, x ∈ s (index x)) /-- The non-constructive constructor for `indexed_partition`. -/ noncomputable def indexed_partition.mk' {ι α : Type*} (s : ι → set α) (dis : ∀ i j, i ≠ j → disjoint (s i) (s j)) (nonempty : ∀ i, (s i).nonempty) (ex : ∀ x, ∃ i, x ∈ s i) : indexed_partition s := { eq_of_mem := λ x i j hxi hxj, classical.by_contradiction $ λ h, dis _ _ h ⟨hxi, hxj⟩, some := λ i, (nonempty i).some, some_mem := λ i, (nonempty i).some_spec, index := λ x, (ex x).some, mem_index := λ x, (ex x).some_spec } namespace indexed_partition open set variables {ι α : Type*} {s : ι → set α} (hs : indexed_partition s) /-- On a unique index set there is the obvious trivial partition -/ instance [unique ι] [inhabited α] : inhabited (indexed_partition (λ i : ι, (set.univ : set α))) := ⟨{ eq_of_mem := λ x i j hi hj, subsingleton.elim _ _, some := λ i, default α, some_mem := set.mem_univ, index := λ a, default ι, mem_index := set.mem_univ }⟩ attribute [simp] some_mem mem_index include hs lemma exists_mem (x : α) : ∃ i, x ∈ s i := ⟨hs.index x, hs.mem_index x⟩ lemma Union : (⋃ i, s i) = univ := by { ext x, simp [hs.exists_mem x] } lemma disjoint : ∀ {i j}, i ≠ j → disjoint (s i) (s j) := λ i j h x ⟨hxi, hxj⟩, h (hs.eq_of_mem hxi hxj) lemma mem_iff_index_eq {x i} : x ∈ s i ↔ hs.index x = i := ⟨λ hxi, (hs.eq_of_mem hxi (hs.mem_index x)).symm, λ h, h ▸ hs.mem_index _⟩ lemma eq (i) : s i = {x | hs.index x = i} := set.ext $ λ _, hs.mem_iff_index_eq /-- The equivalence relation associated to an indexed partition. Two elements are equivalent if they belong to the same set of the partition. -/ protected abbreviation setoid (hs : indexed_partition s) : setoid α := setoid.ker hs.index @[simp] lemma index_some (i : ι) : hs.index (hs.some i) = i := (mem_iff_index_eq _).1 $ hs.some_mem i lemma some_index (x : α) : hs.setoid.rel (hs.some (hs.index x)) x := hs.index_some (hs.index x) /-- The quotient associated to an indexed partition. -/ protected def quotient := quotient hs.setoid /-- The projection onto the quotient associated to an indexed partition. -/ def proj : α → hs.quotient := quotient.mk' instance [inhabited α] : inhabited (hs.quotient) := ⟨hs.proj (default α)⟩ lemma proj_eq_iff {x y : α} : hs.proj x = hs.proj y ↔ hs.index x = hs.index y := quotient.eq_rel @[simp] lemma proj_some_index (x : α) : hs.proj (hs.some (hs.index x)) = hs.proj x := quotient.eq'.2 (hs.some_index x) /-- The obvious equivalence between the quotient associated to an indexed partition and the indexing type. -/ def equiv_quotient : ι ≃ hs.quotient := (setoid.quotient_ker_equiv_of_right_inverse hs.index hs.some $ hs.index_some).symm @[simp] lemma equiv_quotient_index_apply (x : α) : hs.equiv_quotient (hs.index x) = hs.proj x := hs.proj_eq_iff.mpr (some_index hs x) @[simp] lemma equiv_quotient_symm_proj_apply (x : α) : hs.equiv_quotient.symm (hs.proj x) = hs.index x := rfl lemma equiv_quotient_index : hs.equiv_quotient ∘ hs.index = hs.proj := funext hs.equiv_quotient_index_apply /-- A map choosing a representative for each element of the quotient associated to an indexed partition. This is a computable version of `quotient.out'` using `indexed_partition.some`. -/ def out : hs.quotient ↪ α := hs.equiv_quotient.symm.to_embedding.trans ⟨hs.some, function.left_inverse.injective hs.index_some⟩ /-- This lemma is analogous to `quotient.mk_out'`. -/ @[simp] lemma out_proj (x : α) : hs.out (hs.proj x) = hs.some (hs.index x) := rfl /-- The indices of `quotient.out'` and `indexed_partition.out` are equal. -/ lemma index_out' (x : hs.quotient) : hs.index (x.out') = hs.index (hs.out x) := quotient.induction_on' x $ λ x, (setoid.ker_apply_mk_out' x).trans (hs.index_some _).symm /-- This lemma is analogous to `quotient.out_eq'`. -/ @[simp] lemma proj_out (x : hs.quotient) : hs.proj (hs.out x) = x := quotient.induction_on' x $ λ x, quotient.sound' $ hs.some_index x lemma class_of {x : α} : set_of (hs.setoid.rel x) = s (hs.index x) := set.ext $ λ y, eq_comm.trans hs.mem_iff_index_eq.symm lemma proj_fiber (x : hs.quotient) : hs.proj ⁻¹' {x} = s (hs.equiv_quotient.symm x) := quotient.induction_on' x $ λ x, begin ext y, simp only [set.mem_preimage, set.mem_singleton_iff, hs.mem_iff_index_eq], exact quotient.eq', end end indexed_partition
38da054a4b3822ee96fd7d9e1e0393a6ca056b3c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/fin/ops_auto.lean
b7f8c57edddf21897ccb2733b0fc849848b10199
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,401
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.nat.default import Mathlib.Lean3Lib.init.data.fin.basic namespace Mathlib namespace fin protected def succ {n : ℕ} : fin n → fin (Nat.succ n) := sorry def of_nat {n : ℕ} (a : ℕ) : fin (Nat.succ n) := { val := a % Nat.succ n, property := sorry } protected def add {n : ℕ} : fin n → fin n → fin n := sorry protected def mul {n : ℕ} : fin n → fin n → fin n := sorry protected def sub {n : ℕ} : fin n → fin n → fin n := sorry protected def mod {n : ℕ} : fin n → fin n → fin n := sorry protected def div {n : ℕ} : fin n → fin n → fin n := sorry protected instance has_zero {n : ℕ} : HasZero (fin (Nat.succ n)) := { zero := { val := 0, property := nat.succ_pos n } } protected instance has_one {n : ℕ} : HasOne (fin (Nat.succ n)) := { one := of_nat 1 } protected instance has_add {n : ℕ} : Add (fin n) := { add := fin.add } protected instance has_sub {n : ℕ} : Sub (fin n) := { sub := fin.sub } protected instance has_mul {n : ℕ} : Mul (fin n) := { mul := fin.mul } protected instance has_mod {n : ℕ} : Mod (fin n) := { mod := fin.mod } protected instance has_div {n : ℕ} : Div (fin n) := { div := fin.div } theorem of_nat_zero {n : ℕ} : of_nat 0 = 0 := rfl theorem add_def {n : ℕ} (a : fin n) (b : fin n) : subtype.val (a + b) = (subtype.val a + subtype.val b) % n := sorry theorem mul_def {n : ℕ} (a : fin n) (b : fin n) : subtype.val (a * b) = subtype.val a * subtype.val b % n := sorry theorem sub_def {n : ℕ} (a : fin n) (b : fin n) : subtype.val (a - b) = subtype.val a - subtype.val b := sorry theorem mod_def {n : ℕ} (a : fin n) (b : fin n) : subtype.val (a % b) = subtype.val a % subtype.val b := sorry theorem div_def {n : ℕ} (a : fin n) (b : fin n) : subtype.val (a / b) = subtype.val a / subtype.val b := sorry theorem lt_def {n : ℕ} (a : fin n) (b : fin n) : a < b = (subtype.val a < subtype.val b) := sorry theorem le_def {n : ℕ} (a : fin n) (b : fin n) : a ≤ b = (subtype.val a ≤ subtype.val b) := sorry theorem val_zero {n : ℕ} : subtype.val 0 = 0 := rfl def pred {n : ℕ} (i : fin (Nat.succ n)) : i ≠ 0 → fin n := sorry end Mathlib
540d85dd120880b42c4327e3150dae8191d914fc
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/MetavarContext.lean
bb77662da1405e45b357090344948f9b1a762b2a
[ "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
63,796
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.MonadCache import Lean.LocalContext namespace Lean /-! The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown above. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called "tmp" metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we may want to allow TC to invoke tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics in the future. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constraint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the synthesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variable `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contains `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction between temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ /-- `LocalInstance` represents a local typeclass instance registered by and for the elaborator. It stores the name of the typeclass in `className`, and the concrete typeclass instance in `fvar`. Note that the kernel does not care about this information, since typeclasses are entirely eliminated during elaboration. -/ structure LocalInstance where className : Name fvar : Expr deriving Inhabited abbrev LocalInstances := Array LocalInstance instance : BEq LocalInstance where beq i₁ i₂ := i₁.fvar == i₂.fvar /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts /-- A kind for the metavariable that determines its unification behaviour. For more information see the large comment at the beginning of this file. -/ inductive MetavarKind where /-- Normal unification behaviour -/ | natural /-- `isDefEq` avoids assignment -/ | synthetic /-- Never assigned by isDefEq -/ | syntheticOpaque deriving Inhabited, Repr def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false /-- Information about a metavariable. -/ structure MetavarDecl where /-- A user-friendly name for the metavariable. If anonymous then there is no such name. -/ userName : Name := Name.anonymous /-- The local context containing the free variables that the mvar is permitted to depend upon. -/ lctx : LocalContext /-- The type of the metavarible, in the given `lctx`. -/ type : Expr /-- The nesting depth of this metavariable. We do not want unification subproblems to influence the results of parent problems. The depth keeps track of this information and ensures that unification subproblems cannot leak information out, by unifying based on depth. -/ depth : Nat localInstances : LocalInstances kind : MetavarKind /-- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` -/ numScopeArgs : Nat := 0 /-- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext` -/ index : Nat deriving Inhabited /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => (mkMVar mvarIdPending))`. `mvarIdPending` is a `syntheticOpaque` metavariable that has not been synthesized yet. The delayed assignment becomes a real one as soon as `mvarIdPending` has been fully synthesized. `fvars` are variables in the `mvarIdPending` local context. See the comment below `assignDelayedMVar ` for the rationale of delayed assignments. Recall that we use a locally nameless approach when dealing with binders. Suppose we are trying to synthesize `?n` in the expression `e`, in the context of `(fun x => e)`. The metavariable `?n` might depend on the bound variable `x`. However, since we are locally nameless, the bound variable `x` is in fact represented by some free variable `fvar_x`. Thus, when we exit the scope, we must rebind the value of `fvar_x` in `?n` to the de-bruijn index of the bound variable `x`. -/ structure DelayedMetavarAssignment where fvars : Array Expr mvarIdPending : MVarId /-- The metavariable context is a set of metavariable declarations and their assignments. For more information on specifics see the comment in the file that `MetavarContext` is defined in. -/ structure MetavarContext where /-- Depth is used to control whether an mvar can be assigned in unification. -/ depth : Nat := 0 /-- Counter for setting the field `index` at `MetavarDecl` -/ mvarCounter : Nat := 0 lDepth : PersistentHashMap LMVarId Nat := {} /-- Metavariable declarations. -/ decls : PersistentHashMap MVarId MetavarDecl := {} /-- Index mapping user-friendly names to ids. -/ userNames : PersistentHashMap Name MVarId := {} /-- Assignment table for universe level metavariables.-/ lAssignment : PersistentHashMap LMVarId Level := {} /-- Assignment table for expression metavariables.-/ eAssignment : PersistentHashMap MVarId Expr := {} /-- Assignment table for delayed abstraction metavariables. For more information about delayed abstraction, see the docstring for `DelayedMetavarAssignment`. -/ dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {} /-- A monad with a stateful metavariable context, defining `getMCtx` and `modifyMCtx`. -/ class MonadMCtx (m : Type → Type) where getMCtx : m MetavarContext modifyMCtx : (MetavarContext → MetavarContext) → m Unit export MonadMCtx (getMCtx modifyMCtx) instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where getMCtx := liftM (getMCtx : m _) modifyMCtx := fun f => liftM (modifyMCtx f : m _) abbrev setMCtx [MonadMCtx m] (mctx : MetavarContext) : m Unit := modifyMCtx fun _ => mctx abbrev getLevelMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m (Option Level) := return (← getMCtx).lAssignment.find? mvarId def MetavarContext.getExprAssignmentCore? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId def getExprMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : MVarId) : m (Option Expr) := return (← getMCtx).getExprAssignmentCore? mvarId def getDelayedMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : MVarId) : m (Option DelayedMetavarAssignment) := return (← getMCtx).dAssignment.find? mvarId /-- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedMVarRoot [Monad m] [MonadMCtx m] (mvarId : MVarId) : m MVarId := do match (← getDelayedMVarAssignment? mvarId) with | some d => getDelayedMVarRoot d.mvarIdPending | none => return mvarId def isLevelMVarAssigned [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m Bool := return (← getMCtx).lAssignment.contains mvarId /-- Return `true` if the give metavariable is already assigned. -/ def _root_.Lean.MVarId.isAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := return (← getMCtx).eAssignment.contains mvarId @[deprecated MVarId.isAssigned] def isExprMVarAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isAssigned def _root_.Lean.MVarId.isDelayedAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := return (← getMCtx).dAssignment.contains mvarId @[deprecated MVarId.isDelayedAssigned] def isMVarDelayedAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isDelayedAssigned def isLevelMVarAssignable [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m Bool := do let mctx ← getMCtx match mctx.lDepth.find? mvarId with | some d => return d == mctx.depth | _ => panic! "unknown universe metavariable" def MetavarContext.getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def _root_.Lean.MVarId.isAssignable [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do let mctx ← getMCtx let decl := mctx.getDecl mvarId return decl.depth == mctx.depth @[deprecated MVarId.isAssignable] def isExprMVarAssignable [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isAssignable /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar [Monad m] [MonadMCtx m] : Level → m Bool | .succ lvl => pure lvl.hasMVar <&&> hasAssignedLevelMVar lvl | .max lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignedLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignedLevelMVar lvl₂) | .imax lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignedLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignedLevelMVar lvl₂) | .mvar mvarId => isLevelMVarAssigned mvarId | .zero => pure false | .param _ => pure false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar [Monad m] [MonadMCtx m] : Expr → m Bool | .const _ lvls => lvls.anyM hasAssignedLevelMVar | .sort lvl => hasAssignedLevelMVar lvl | .app f a => (pure f.hasMVar <&&> hasAssignedMVar f) <||> (pure a.hasMVar <&&> hasAssignedMVar a) | .letE _ t v b _ => (pure t.hasMVar <&&> hasAssignedMVar t) <||> (pure v.hasMVar <&&> hasAssignedMVar v) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .forallE _ d b _ => (pure d.hasMVar <&&> hasAssignedMVar d) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .lam _ d b _ => (pure d.hasMVar <&&> hasAssignedMVar d) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .fvar _ => return false | .bvar _ => return false | .lit _ => return false | .mdata _ e => pure e.hasMVar <&&> hasAssignedMVar e | .proj _ _ e => pure e.hasMVar <&&> hasAssignedMVar e | .mvar mvarId => mvarId.isAssigned <||> mvarId.isDelayedAssigned /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar [Monad m] [MonadMCtx m] : Level → m Bool | .succ lvl => pure lvl.hasMVar <&&> hasAssignableLevelMVar lvl | .max lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignableLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignableLevelMVar lvl₂) | .imax lvl₁ lvl₂ => (pure lvl₁.hasMVar <&&> hasAssignableLevelMVar lvl₁) <||> (pure lvl₂.hasMVar <&&> hasAssignableLevelMVar lvl₂) | .mvar mvarId => isLevelMVarAssignable mvarId | .zero => return false | .param _ => return false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar [Monad m] [MonadMCtx m] : Expr → m Bool | .const _ lvls => lvls.anyM hasAssignableLevelMVar | .sort lvl => hasAssignableLevelMVar lvl | .app f a => (pure f.hasMVar <&&> hasAssignableMVar f) <||> (pure a.hasMVar <&&> hasAssignableMVar a) | .letE _ t v b _ => (pure t.hasMVar <&&> hasAssignableMVar t) <||> (pure v.hasMVar <&&> hasAssignableMVar v) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .forallE _ d b _ => (pure d.hasMVar <&&> hasAssignableMVar d) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .lam _ d b _ => (pure d.hasMVar <&&> hasAssignableMVar d) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .fvar _ => return false | .bvar _ => return false | .lit _ => return false | .mdata _ e => pure e.hasMVar <&&> hasAssignableMVar e | .proj _ _ e => pure e.hasMVar <&&> hasAssignableMVar e | .mvar mvarId => mvarId.isAssignable /-- Add `mvarId := u` to the universe metavariable assignment. This method does not check whether `mvarId` is already assigned, nor it checks whether a cycle is being introduced. This is a low-level API, and it is safer to use `isLevelDefEq (mkLevelMVar mvarId) u`. -/ def assignLevelMVar [MonadMCtx m] (mvarId : LMVarId) (val : Level) : m Unit := modifyMCtx fun m => { m with lAssignment := m.lAssignment.insert mvarId val } /-- Add `mvarId := x` to the metavariable assignment. This method does not check whether `mvarId` is already assigned, nor it checks whether a cycle is being introduced, or whether the expression has the right type. This is a low-level API, and it is safer to use `isDefEq (mkMVar mvarId) x`. -/ def _root_.Lean.MVarId.assign [MonadMCtx m] (mvarId : MVarId) (val : Expr) : m Unit := modifyMCtx fun m => { m with eAssignment := m.eAssignment.insert mvarId val } @[deprecated MVarId.assign] def assignExprMVar [MonadMCtx m] (mvarId : MVarId) (val : Expr) : m Unit := mvarId.assign val def assignDelayedMVar [MonadMCtx m] (mvarId : MVarId) (fvars : Array Expr) (mvarIdPending : MVarId) : m Unit := modifyMCtx fun m => { m with dAssignment := m.dAssignment.insert mvarId { fvars, mvarIdPending } } /-! Notes on artificial eta-expanded terms due to metavariables. We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator. This kind of term may be generated when instantiating metavariable assignments. This module tries to avoid their generation because they often introduce unnecessary dependencies and may affect automation. When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y` are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression `fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`. We address this issue by create a synthetic metavariable `?n : Nat → Nat` and adding the delayed assignment `?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to `?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`. To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module. This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`. -/ partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level → m Level | lvl@(Level.succ lvl₁) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvl₂) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.imax lvl₁ lvl₂) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.mvar mvarId) => do match (← getLevelMVarAssignment? mvarId) with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl assignLevelMVar mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => do match e with | .proj _ _ s => return e.updateProj! (← instantiateExprMVars s) | .forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | .lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | .letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | .const _ lvls => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | .sort lvl => return e.updateSort! (← instantiateLevelMVars lvl) | .mdata _ b => return e.updateMData! (← instantiateExprMVars b) | .app .. => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT ExprStructEq Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | .mvar mvarId => match (← getDelayedMVarAssignment? mvarId) with | none => instApp | some { fvars, mvarIdPending } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars (mkMVar mvarIdPending) if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure result | _ => instApp | e@(.mvar mvarId) => checkCache { val := e : ExprStructEq } fun _ => do match (← getExprMVarAssignment? mvarId) with | some newE => do let newE' ← instantiateExprMVars newE mvarId.assign newE' pure newE' | none => pure e | e => pure e instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify def instantiateMVarsCore (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := let instantiate {ω} (e : Expr) : (MonadCacheT ExprStructEq Expr <| StateRefT MetavarContext (ST ω)) Expr := instantiateExprMVars e runST fun _ => instantiate e |>.run |>.run mctx def instantiateMVars [Monad m] [MonadMCtx m] (e : Expr) : m Expr := do if !e.hasMVar then return e else let (r, mctx) := instantiateMVarsCore (← getMCtx) e modifyMCtx fun _ => mctx return r def instantiateLCtxMVars [Monad m] [MonadMCtx m] (lctx : LocalContext) : m LocalContext := lctx.foldlM (init := {}) fun lctx ldecl => do match ldecl with | .cdecl _ fvarId userName type bi => let type ← instantiateMVars type return lctx.mkLocalDecl fvarId userName type bi | .ldecl _ fvarId userName type value nonDep => let type ← instantiateMVars type let value ← instantiateMVars value return lctx.mkLetDecl fvarId userName type value nonDep def instantiateMVarDeclMVars [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Unit := do let mvarDecl := (← getMCtx).getDecl mvarId let lctx ← instantiateLCtxMVars mvarDecl.lctx let type ← instantiateMVars mvarDecl.type modifyMCtx fun mctx => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx, type } } def instantiateLocalDeclMVars [Monad m] [MonadMCtx m] (localDecl : LocalDecl) : m LocalDecl := do match localDecl with | .cdecl idx id n type bi => return .cdecl idx id n (← instantiateMVars type) bi | .ldecl idx id n type val nonDep => return .ldecl idx id n (← instantiateMVars type) (← instantiateMVars val) nonDep namespace DependsOn structure State where visited : ExprSet := {} mctx : MetavarContext private abbrev M := StateM State instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } private def shouldVisit (e : Expr) : M Bool := do if !e.hasMVar && !e.hasFVar then return false else if (← get).visited.contains e then return false else modify fun s => { s with visited := s.visited.insert e } return true @[specialize] private partial def dep (pf : FVarId → Bool) (pm : MVarId → Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitApp : Expr → M Bool | .app f a .. => visitApp f <||> visit a | e => visit e, visitMain : Expr → M Bool | .proj _ _ s => visit s | .forallE _ d b _ => visit d <||> visit b | .lam _ d b _ => visit d <||> visit b | .letE _ t v b _ => visit t <||> visit v <||> visit b | .mdata _ b => visit b | e@(.app ..) => do let f := e.getAppFn if f.isMVar then let e' ← instantiateMVars e if e'.getAppFn != f then visitMain e' else if pm f.mvarId! then return true else visitApp e else visitApp e | .mvar mvarId => do match (← getExprMVarAssignment? mvarId) with | some a => visit a | none => if pm mvarId then return true else let lctx := (← getMCtx).getDecl mvarId |>.lctx return lctx.any fun decl => pf decl.fvarId | .fvar fvarId => return pf fvarId | _ => pure false visit e @[inline] partial def main (pf : FVarId → Bool) (pm : MVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep pf pm e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `pf x` is `true`, or an unassigned metavariable `?m` s.t. `pm ?m` is true. For each metavariable `?m` (that does not satisfy `pm` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn [Monad m] [MonadMCtx m] (e : Expr) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do let (result, { mctx, .. }) := DependsOn.main pf pm e |>.run { mctx := (← getMCtx) } setMCtx mctx return result /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `pf x` is `true` or an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ @[inline] def findLocalDeclDependsOn [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do match localDecl with | .cdecl (type := t) .. => findExprDependsOn t pf pm | .ldecl (type := t) (value := v) .. => let (result, { mctx, .. }) := (DependsOn.main pf pm t <||> DependsOn.main pf pm v).run { mctx := (← getMCtx) } setMCtx mctx return result def exprDependsOn [Monad m] [MonadMCtx m] (e : Expr) (fvarId : FVarId) : m Bool := findExprDependsOn e (fvarId == ·) /-- Return true iff `e` depends on the free variable `fvarId` -/ def dependsOn [Monad m] [MonadMCtx m] (e : Expr) (fvarId : FVarId) : m Bool := exprDependsOn e fvarId /-- Return true iff `e` depends on the free variable `fvarId` -/ def localDeclDependsOn [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (fvarId : FVarId) : m Bool := findLocalDeclDependsOn localDecl (fvarId == ·) /-- Similar to `exprDependsOn`, but `x` can be a free variable or an unassigned metavariable. -/ def exprDependsOn' [Monad m] [MonadMCtx m] (e : Expr) (x : Expr) : m Bool := if x.isFVar then findExprDependsOn e (x.fvarId! == ·) else if x.isMVar then findExprDependsOn e (pm := (x.mvarId! == ·)) else return false /-- Similar to `localDeclDependsOn`, but `x` can be a free variable or an unassigned metavariable. -/ def localDeclDependsOn' [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (x : Expr) : m Bool := if x.isFVar then findLocalDeclDependsOn localDecl (x.fvarId! == ·) else if x.isMVar then findLocalDeclDependsOn localDecl (pm := (x.mvarId! == ·)) else return false /-- Return true iff `e` depends on a free variable `x` s.t. `pf x`, or an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ def dependsOnPred [Monad m] [MonadMCtx m] (e : Expr) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := findExprDependsOn e pf pm /-- Return true iff the local declaration `localDecl` depends on a free variable `x` s.t. `pf x`, an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ def localDeclDependsOnPred [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (pf : FVarId → Bool := fun _ => false) (pm : MVarId → Bool := fun _ => false) : m Bool := do findLocalDeclDependsOn localDecl pf pm namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /-- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with mvarCounter := mctx.mvarCounter + 1 decls := mctx.decls.insert mvarId { depth := mctx.depth index := mctx.mvarCounter userName lctx localInstances type kind numScopeArgs } userNames := if userName.isAnonymous then mctx.userNames else mctx.userNames.insert userName mvarId } def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /-- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : LMVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := mctx.userNames.find? userName def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } /-- Set the metavariable user facing name. -/ def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } userNames := let userNames := mctx.userNames.erase decl.userName if userName.isAnonymous then userNames else userNames.insert userName mvarId } /-- Low-level version of `setMVarUserName`. It does not update the table `userNames`. Thus, `findUserName?` cannot see the modification. It is meant for `mkForallFVars'` where we temporarily set the user facing name of metavariables to get more meaningful binder names. -/ def setMVarUserNameTemporarily (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } } /-- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with type := type } } def findLevelDepth? (mctx : MetavarContext) (mvarId : LMVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : LMVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify namespace MkBinding inductive Exception where | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (varName : String) instance : ToString Exception where toString | Exception.revertFailure _ lctx toRevert varName => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString varName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString varName ++ "' from local context)" /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State where mctx : MetavarContext nextMacroScope : MacroScope ngen : NameGenerator cache : HashMap ExprStructEq Expr := {} structure Context where mainModule : Name preserveOrder : Bool /-- When creating binders for abstracted metavariables, we use the following `BinderInfo`. -/ binderInfoForMVars : BinderInfo := BinderInfo.implicit /-- Set of unassigned metavariables being abstracted. -/ mvarIdsToAbstract : MVarIdSet := {} abbrev MCore := EStateM Exception State abbrev M := ReaderT Context MCore instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } private def mkFreshBinderName (n : Name := `x) : M Name := do let fresh ← modifyGet fun s => (s.nextMacroScope, { s with nextMacroScope := s.nextMacroScope + 1 }) return addMacroScope (← read).mainModule n fresh def preserveOrder : M Bool := return (← read).preserveOrder instance : MonadHashMapCacheAdapter ExprStructEq Expr M where getCache := do let s ← get; pure s.cache modifyCache := fun f => modify fun s => { s with cache := f s.cache } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := Id.run do let mut d : LocalDecl := lctx.getFVar! xs[0]! for x in xs[1:] do if x.isFVar then let curr := lctx.getFVar! x if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ def collectForwardDeps (lctx : LocalContext) (toRevert : Array Expr) : M (Array Expr) := do if toRevert.size == 0 then pure toRevert else if (← preserveOrder) then -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i]! i.forM fun j => do let prevFVar := toRevert[j]! let prevDecl := lctx.getFVar! prevFVar if (← localDeclDependsOn prevDecl fvar.fvarId!) then throw (Exception.revertFailure (← getMCtx) lctx toRevert prevDecl.userName.toString) let newToRevert := if (← preserveOrder) then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => do if initSize.any fun i => decl.fvarId == newToRevert[i]!.fvarId! then return newToRevert else if toRevert.any fun x => decl.fvarId == x.fvarId! then return newToRevert.push decl.toExpr else if (← findLocalDeclDependsOn decl (newToRevert.any fun x => x.fvarId! == ·)) then return newToRevert.push decl.toExpr else return newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (init := lctx) fun x lctx => if x.isFVar then lctx.erase x.fvarId! else lctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (init := #[]) fun scope x => if !x.isFVar then scope else if lctx.contains x.fvarId! then scope.push x else scope /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache (x : M α) : M α := do let cache ← modifyGet fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (init := mvar) fun e x => if !x.isFVar then e else match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x mutual private partial def visit (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e private partial def elim (xs : Array Expr) (e : Expr) : M Expr := match e with | .proj _ _ s => return e.updateProj! (← visit xs s) | .forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b) | .lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b) | .letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b) | .mdata _ b => return e.updateMData! (← visit xs b) | .app .. => e.withApp fun f args => elimApp xs f args | .mvar _ => elimApp xs e #[] | e => return e private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (init := e) fun i e => do let x := xs[i]! if x.isFVar then match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => let type := type.headBeta let type ← abstractRangeAux xs i type return Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 return mkForall n BinderInfo.default type e | _ => pure e else let mvarDecl := (← get).mctx.getDecl x.mvarId! let type := mvarDecl.type.headBeta let type ← abstractRangeAux xs i type let id ← if mvarDecl.userName.isAnonymous then mkFreshBinderName else pure mvarDecl.userName return Lean.mkForall id (← read).binderInfoForMVars type e where abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim xs e pure (e.abstractRange i xs) private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do let mvarDecl := (← getMCtx).getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then let args ← args.mapM (visit xs) return (mkAppN (mkMVar mvarId) args, #[]) else /- `newMVarKind` is the kind for the new auxiliary metavariable. There is an alternative approach where we use ``` let newMVarKind := if !mctx.isExprAssignable mvarId || mvarDecl.isSyntheticOpaque then MetavarKind.syntheticOpaque else MetavarKind.natural ``` In this approach, we use the natural kind for the new auxiliary metavariable if the original metavariable is synthetic and assignable. Since we mainly use synthetic metavariables for pending type class (TC) resolution problems, this approach may minimize the number of TC resolution problems that may need to be resolved. A potential disadvantage is that `isDefEq` will not eagerly use `synthPending` for natural metavariables. That being said, we should try this approach as soon as we have an extensive test suite. -/ let newMVarKind := if !(← mvarId.isAssignable) then MetavarKind.syntheticOpaque else mvarDecl.kind let args ← args.mapM (visit xs) let toRevert ← collectForwardDeps mvarLCtx toRevert let newMVarLCtx := reduceLocalContext mvarLCtx toRevert -- Note that `toRevert` only contains free variables since it is the result of `getInScope` let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x -- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs` let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId := { name := (← get).ngen.curr } let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } if !mvarDecl.kind.isSyntheticOpaque then mvarId.assign result else /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := ?mvarPending`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, `newMVarId` is also `syntheticOpaque` and we add the delayed assignment delayed assignment ``` ?newMVar #[y_1, ..., y_m, x_1, ... x_n] := ?m ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectForwardDeps`. -/ let (mvarIdPending, nestedFVars) ← match (← getDelayedMVarAssignment? mvarId) with | none => pure (mvarId, #[]) | some { fvars, mvarIdPending } => pure (mvarIdPending, fvars) assignDelayedMVar newMVarId (toRevert ++ nestedFVars) mvarIdPending return (mkAppN result args, toRevert) private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId => match (← getExprMVarAssignment? mvarId) with | some newF => if newF.isLambda then let args ← args.mapM (visit xs) elim xs <| newF.betaRev args.reverse else elimApp xs newF args | none => if (← read).mvarIdsToAbstract.contains mvarId then return mkAppN f (← args.mapM (visit xs)) else return (← elimMVar xs mvarId args).1 | _ => return mkAppN (← visit xs f) (← args.mapM (visit xs)) end partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then return e else withFreshCache do elim xs e partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) := withFreshCache do elimMVar xs mvarId #[] /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` expressions are created only for used variables. If `usedLetOnly == false` then `let` expressions are created only for used (let-) variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr × Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (init := (e, 0)) fun i (e, num) => do let x := xs[i]! if x.isFVar then match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then return (Lean.mkLambda n bi type e, num + 1) else return (Lean.mkForall n bi type e, num + 1) else return (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => if !usedLetOnly || e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value return (mkLet n type value e nonDep, num + 1) else return (e.lowerLooseBVars 1 1, num) else let mvarDecl := (← get).mctx.getDecl x.mvarId! let type := mvarDecl.type.headBeta let type ← abstractRange xs i type let id ← if mvarDecl.userName.isAnonymous then mkFreshBinderName else pure mvarDecl.userName if isLambda then return (Lean.mkLambda id (← read).binderInfoForMVars type e, num + 1) else return (Lean.mkForall id (← read).binderInfoForMVars type e, num + 1) end MkBinding structure MkBindingM.Context where mainModule : Name lctx : LocalContext abbrev MkBindingM := ReaderT MkBindingM.Context MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun ctx => MkBinding.elimMVarDeps xs e { preserveOrder, mainModule := ctx.mainModule } def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun ctx => MkBinding.revert xs mvarId { preserveOrder, mainModule := ctx.mainModule } def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM (Expr × Nat) := fun ctx => let mvarIdsToAbstract := xs.foldl (init := {}) fun s x => if x.isMVar then s.insert x.mvarId! else s MkBinding.mkBinding isLambda ctx.lctx xs e usedOnly usedLetOnly { preserveOrder := false, binderInfoForMVars, mvarIdsToAbstract, mainModule := ctx.mainModule } @[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM Expr := return (← mkBinding (isLambda := true) xs e usedOnly usedLetOnly binderInfoForMVars).1 @[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM Expr := return (← mkBinding (isLambda := false) xs e usedOnly usedLetOnly binderInfoForMVars).1 @[inline] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MkBindingM Expr := fun ctx => MkBinding.abstractRange xs n e { preserveOrder := false, mainModule := ctx.mainModule } @[inline] def collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MkBindingM (Array Expr) := fun ctx => MkBinding.collectForwardDeps ctx.lctx toRevert { preserveOrder, mainModule := ctx.mainModule } /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed [Monad m] [MonadMCtx m] (lctx : LocalContext) : Expr → m Bool | .mdata _ e => isWellFormed lctx e | .proj _ _ e => isWellFormed lctx e | e@(.app f a) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx f <&&> isWellFormed lctx a) | e@(.lam _ d b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx d <&&> isWellFormed lctx b) | e@(.forallE _ d b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx d <&&> isWellFormed lctx b) | e@(.letE _ t v b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx t <&&> isWellFormed lctx v <&&> isWellFormed lctx b) | .const .. => return true | .bvar .. => return true | .sort .. => return true | .lit .. => return true | .mvar mvarId => do let mvarDecl := (← getMCtx).getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then return true else match (← getExprMVarAssignment? mvarId) with | none => return false | some v => isWellFormed lctx v | .fvar fvarId => return lctx.contains fvarId namespace LevelMVarToParam structure Context where paramNamePrefix : Name alreadyUsedPred : Name → Bool except : LMVarId → Bool structure State where mctx : MetavarContext paramNames : Array Name := #[] nextParamIdx : Nat cache : HashMap ExprStructEq Expr := {} abbrev M := ReaderT Context <| StateM State instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : MonadCache ExprStructEq Expr M where findCached? e := return (← get).cache.find? e cache e v := modify fun s => { s with cache := s.cache.insert e v } partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | .succ v => return u.updateSucc! (← visitLevel v) | .max v₁ v₂ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂) | .imax v₁ v₂ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂) | .zero => return u | .param .. => return u | .mvar mvarId => match (← getLevelMVarAssignment? mvarId) with | some v => visitLevel v | none => if (← read).except mvarId then return u else let p ← mkParamName let p := mkLevelParam p assignLevelMVar mvarId p return p partial def main (e : Expr) : M Expr := if !e.hasMVar then return e else checkCache { val := e : ExprStructEq } fun _ => do match e with | .proj _ _ s => return e.updateProj! (← main s) | .forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | .lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | .letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | .app .. => e.withApp fun f args => visitApp f args | .mdata _ b => return e.updateMData! (← main b) | .const _ us => return e.updateConst! (← us.mapM visitLevel) | .sort u => return e.updateSort! (← visitLevel u) | .mvar .. => visitApp e #[] | e => return e where visitApp (f : Expr) (args : Array Expr) : M Expr := do match f with | .mvar mvarId .. => match (← getExprMVarAssignment? mvarId) with | some v => return (← visitApp v args).headBeta | none => return mkAppN f (← args.mapM main) | _ => return mkAppN (← main f) (← args.mapM main) end LevelMVarToParam structure UnivMVarParamResult where mctx : MetavarContext newParamNames : Array Name nextParamIdx : Nat expr : Expr def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (except : LMVarId → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { except, paramNamePrefix, alreadyUsedPred } { mctx, nextParamIdx } { mctx := s.mctx newParamNames := s.paramNames nextParamIdx := s.nextParamIdx expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId end MetavarContext end Lean
28cf427f185e9d2a478789a00914fe0d61a902b5
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/tactic/auto_cases.lean
7c521f007566b99e7715e30d9bf56e15427da5b1
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
1,642
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import logic.basic import tactic.core import data.option.defs open tactic meta def auto_cases_at (h : expr) : tactic string := do t' ← infer_type h, t' ← whnf t', let use_cases := match t' with | `(empty) := tt | `(pempty) := tt | `(unit) := tt | `(punit) := tt | `(ulift _) := tt | `(plift _) := tt | `(prod _ _) := tt | `(and _ _) := tt | `(sigma _) := tt | `(subtype _) := tt | `(Exists _) := tt | `(fin 0) := tt | `(sum _ _) := tt -- This is perhaps dangerous! | `(or _ _) := tt -- This is perhaps dangerous! | `(iff _ _) := tt -- This is perhaps dangerous! | _ := ff end, if use_cases then do cases h, pp ← pp h, return ("cases " ++ pp.to_string) else match t' with -- `cases` can be dangerous on `eq` and `quot`, producing mysterious errors during type checking. -- instead we attempt `induction` | `(eq _ _) := do induction h, pp ← pp h, return ("induction " ++ pp.to_string) | `(quot _) := do induction h, pp ← pp h, return ("induction " ++ pp.to_string) | _ := failed end /-- Applies `cases` or `induction` on certain hypotheses. -/ meta def auto_cases : tactic string := do l ← local_context, results ← successes (l.reverse.map(λ h, auto_cases_at h)), when (results.empty) (fail "`auto_cases` did not find any hypotheses to apply `cases` or `induction` to"), return (string.intercalate ", " results)
371bade82dfbf5c6f43fe338c3de20505f0be311
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/units_auto.lean
083b9e00cf3526765ca08e3ef62410306706cb20
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,120
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.specific_limits import Mathlib.analysis.asymptotics import Mathlib.PostPort universes u_1 namespace Mathlib /-! # The group of units of a complete normed ring This file contains the basic theory for the group of units (invertible elements) of a complete normed ring (Banach algebras being a notable special case). ## Main results The constructions `one_sub`, `add` and `unit_of_nearby` state, in varying forms, that perturbations of a unit are units. The latter two are not stated in their optimal form; more precise versions would use the spectral radius. The first main result is `is_open`: the group of units of a complete normed ring is an open subset of the ring. The function `inverse` (defined in `algebra.ring`), for a ring `R`, sends `a : R` to `a⁻¹` if `a` is a unit and 0 if not. The other major results of this file (notably `inverse_add`, `inverse_add_norm` and `inverse_add_norm_diff_nth_order`) cover the asymptotic properties of `inverse (x + t)` as `t → 0`. -/ namespace units /-- In a complete normed ring, a perturbation of `1` by an element `t` of distance less than `1` from `1` is a unit. Here we construct its `units` structure. -/ def one_sub {R : Type u_1} [normed_ring R] [complete_space R] (t : R) (h : norm t < 1) : units R := mk (1 - t) (tsum fun (n : ℕ) => t ^ n) (mul_neg_geom_series t h) (geom_series_mul_neg t h) @[simp] theorem one_sub_coe {R : Type u_1} [normed_ring R] [complete_space R] (t : R) (h : norm t < 1) : ↑(one_sub t h) = 1 - t := rfl /-- In a complete normed ring, a perturbation of a unit `x` by an element `t` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ def add {R : Type u_1} [normed_ring R] [complete_space R] (x : units R) (t : R) (h : norm t < (norm ↑(x⁻¹)⁻¹)) : units R := x * one_sub (-(↑(x⁻¹) * t)) sorry @[simp] theorem add_coe {R : Type u_1} [normed_ring R] [complete_space R] (x : units R) (t : R) (h : norm t < (norm ↑(x⁻¹)⁻¹)) : ↑(add x t h) = ↑x + t := sorry /-- In a complete normed ring, an element `y` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/ def unit_of_nearby {R : Type u_1} [normed_ring R] [complete_space R] (x : units R) (y : R) (h : norm (y - ↑x) < (norm ↑(x⁻¹)⁻¹)) : units R := add x (y - ↑x) h @[simp] theorem unit_of_nearby_coe {R : Type u_1} [normed_ring R] [complete_space R] (x : units R) (y : R) (h : norm (y - ↑x) < (norm ↑(x⁻¹)⁻¹)) : ↑(unit_of_nearby x y h) = y := sorry /-- The group of units of a complete normed ring is an open subset of the ring. -/ theorem is_open {R : Type u_1} [normed_ring R] [complete_space R] : is_open (set_of fun (x : R) => is_unit x) := sorry theorem nhds {R : Type u_1} [normed_ring R] [complete_space R] (x : units R) : (set_of fun (x : R) => is_unit x) ∈ nhds ↑x := mem_nhds_sets is_open (eq.mpr (id (Eq._oldrec (Eq.refl (↑x ∈ set_of fun (x : R) => is_unit x)) set.mem_set_of_eq)) (is_unit_unit x)) end units namespace normed_ring theorem inverse_one_sub {R : Type u_1} [normed_ring R] [complete_space R] (t : R) (h : norm t < 1) : ring.inverse (1 - t) = ↑(units.one_sub t h⁻¹) := sorry /-- The formula `inverse (x + t) = inverse (1 + x⁻¹ * t) * x⁻¹` holds for `t` sufficiently small. -/ theorem inverse_add {R : Type u_1} [normed_ring R] [complete_space R] (x : units R) : filter.eventually (fun (t : R) => ring.inverse (↑x + t) = ring.inverse (1 + ↑(x⁻¹) * t) * ↑(x⁻¹)) (nhds 0) := sorry theorem inverse_one_sub_nth_order {R : Type u_1} [normed_ring R] [complete_space R] (n : ℕ) : filter.eventually (fun (t : R) => ring.inverse (1 - t) = (finset.sum (finset.range n) fun (i : ℕ) => t ^ i) + t ^ n * ring
48213fff6a321f8af3d32d54d15437dae2d0e8dc
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/subpp.lean
5f130a344d1a7f359ce626ccc53833c826c27a33
[ "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
29
lean
-- check {x : nat // x > 0 }
b195523912b0b945a1c945758ded6d25ddab6b1e
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/gcd_monoid/multiset.lean
01d4c1827a3a00cef7faa918608739af09117fb9
[ "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
5,187
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.lattice /-! # 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*} [comm_cancel_monoid_with_zero α] [nontrivial α] [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 variables [decidable_eq α] @[simp] lemma lcm_erase_dup (s : multiset α) : (erase_dup 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_erase_dup, erase_dup_ext.2, lcm_erase_dup, lcm_add], simp } @[simp] lemma lcm_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).lcm = gcd_monoid.lcm s₁.lcm s₂.lcm := by { rw [← lcm_erase_dup, erase_dup_ext.2, lcm_erase_dup, lcm_add], simp } @[simp] lemma lcm_ndinsert (a : α) (s : multiset α) : (ndinsert a s).lcm = gcd_monoid.lcm a s.lcm := by { rw [← lcm_erase_dup, erase_dup_ext.2, lcm_erase_dup, 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 variables [decidable_eq α] @[simp] lemma gcd_erase_dup (s : multiset α) : (erase_dup 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_erase_dup, erase_dup_ext.2, gcd_erase_dup, gcd_add], simp } @[simp] lemma gcd_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).gcd = gcd_monoid.gcd s₁.gcd s₂.gcd := by { rw [← gcd_erase_dup, erase_dup_ext.2, gcd_erase_dup, gcd_add], simp } @[simp] lemma gcd_ndinsert (a : α) (s : multiset α) : (ndinsert a s).gcd = gcd_monoid.gcd a s.gcd := by { rw [← gcd_erase_dup, erase_dup_ext.2, gcd_erase_dup, gcd_cons], simp } end gcd end multiset
25453f4326e191f3a35cf3b19f4700d050d884ae
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/covariant_and_contravariant.lean
d93372987695b429b4a495eed800f8df575ca262
[ "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
12,011
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.group.defs import order.basic /-! # Covariants and contravariants This file contains general lemmas and instances to work with the interactions between a relation and an action on a Type. The intended application is the splitting of the ordering from the algebraic assumptions on the operations in the `ordered_[...]` hierarchy. The strategy is to introduce two more flexible typeclasses, `covariant_class` and `contravariant_class`: * `covariant_class` models the implication `a ≤ b → c * a ≤ c * b` (multiplication is monotone), * `contravariant_class` models the implication `a * b < a * c → b < c`. Since `co(ntra)variant_class` takes as input the operation (typically `(+)` or `(*)`) and the order relation (typically `(≤)` or `(<)`), these are the only two typeclasses that I have used. The general approach is to formulate the lemma that you are interested in and prove it, with the `ordered_[...]` typeclass of your liking. After that, you convert the single typeclass, say `[ordered_cancel_monoid M]`, into three typeclasses, e.g. `[left_cancel_semigroup M] [partial_order M] [covariant_class M M (function.swap (*)) (≤)]` and have a go at seeing if the proof still works! Note that it is possible to combine several co(ntra)variant_class assumptions together. Indeed, the usual ordered typeclasses arise from assuming the pair `[covariant_class M M (*) (≤)] [contravariant_class M M (*) (<)]` on top of order/algebraic assumptions. A formal remark is that normally `covariant_class` uses the `(≤)`-relation, while `contravariant_class` uses the `(<)`-relation. This need not be the case in general, but seems to be the most common usage. In the opposite direction, the implication ```lean [semigroup α] [partial_order α] [contravariant_class α α (*) (≤)] => left_cancel_semigroup α ``` holds -- note the `co*ntra*` assumption on the `(≤)`-relation. # Formalization notes We stick to the convention of using `function.swap (*)` (or `function.swap (+)`), for the typeclass assumptions, since `function.swap` is slightly better behaved than `flip`. However, sometimes as a **non-typeclass** assumption, we prefer `flip (*)` (or `flip (+)`), as it is easier to use. -/ -- TODO: convert `has_exists_mul_of_le`, `has_exists_add_of_le`? -- TODO: relationship with `con/add_con` -- TODO: include equivalence of `left_cancel_semigroup` with -- `semigroup partial_order contravariant_class α α (*) (≤)`? -- TODO : use ⇒, as per Eric's suggestion? See -- https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/ordered.20stuff/near/236148738 -- for a discussion. open function section variants variables {M N : Type*} (μ : M → N → N) (r : N → N → Prop) variables (M N) /-- `covariant` is useful to formulate succintly statements about the interactions between an action of a Type on another one and a relation on the acted-upon Type. See the `covariant_class` doc-string for its meaning. -/ def covariant : Prop := ∀ (m) {n₁ n₂}, r n₁ n₂ → r (μ m n₁) (μ m n₂) /-- `contravariant` is useful to formulate succintly statements about the interactions between an action of a Type on another one and a relation on the acted-upon Type. See the `contravariant_class` doc-string for its meaning. -/ def contravariant : Prop := ∀ (m) {n₁ n₂}, r (μ m n₁) (μ m n₂) → r n₁ n₂ /-- Given an action `μ` of a Type `M` on a Type `N` and a relation `r` on `N`, informally, the `covariant_class` says that "the action `μ` preserves the relation `r`." More precisely, the `covariant_class` is a class taking two Types `M N`, together with an "action" `μ : M → N → N` and a relation `r : N → N → Prop`. Its unique field `elim` is the assertion that for all `m ∈ M` and all elements `n₁, n₂ ∈ N`, if the relation `r` holds for the pair `(n₁, n₂)`, then, the relation `r` also holds for the pair `(μ m n₁, μ m n₂)`, obtained from `(n₁, n₂)` by acting upon it by `m`. If `m : M` and `h : r n₁ n₂`, then `covariant_class.elim m h : r (μ m n₁) (μ m n₂)`. -/ @[protect_proj] class covariant_class : Prop := (elim : covariant M N μ r) /-- Given an action `μ` of a Type `M` on a Type `N` and a relation `r` on `N`, informally, the `contravariant_class` says that "if the result of the action `μ` on a pair satisfies the relation `r`, then the initial pair satisfied the relation `r`." More precisely, the `contravariant_class` is a class taking two Types `M N`, together with an "action" `μ : M → N → N` and a relation `r : N → N → Prop`. Its unique field `elim` is the assertion that for all `m ∈ M` and all elements `n₁, n₂ ∈ N`, if the relation `r` holds for the pair `(μ m n₁, μ m n₂)` obtained from `(n₁, n₂)` by acting upon it by `m`, then, the relation `r` also holds for the pair `(n₁, n₂)`. If `m : M` and `h : r (μ m n₁) (μ m n₂)`, then `contravariant_class.elim m h : r n₁ n₂`. -/ @[protect_proj] class contravariant_class : Prop := (elim : contravariant M N μ r) lemma rel_iff_cov [covariant_class M N μ r] [contravariant_class M N μ r] (m : M) {a b : N} : r (μ m a) (μ m b) ↔ r a b := ⟨contravariant_class.elim _, covariant_class.elim _⟩ section flip variables {M N μ r} lemma covariant.flip (h : covariant M N μ r) : covariant M N μ (flip r) := λ a b c hbc, h a hbc lemma contravariant.flip (h : contravariant M N μ r) : contravariant M N μ (flip r) := λ a b c hbc, h a hbc end flip section covariant variables {M N μ r} [covariant_class M N μ r] lemma act_rel_act_of_rel (m : M) {a b : N} (ab : r a b) : r (μ m a) (μ m b) := covariant_class.elim _ ab @[to_additive] lemma group.covariant_iff_contravariant [group N] : covariant N N (*) r ↔ contravariant N N (*) r := begin refine ⟨λ h a b c bc, _, λ h a b c bc, _⟩, { rw [← inv_mul_cancel_left a b, ← inv_mul_cancel_left a c], exact h a⁻¹ bc }, { rw [← inv_mul_cancel_left a b, ← inv_mul_cancel_left a c] at bc, exact h a⁻¹ bc } end @[to_additive] lemma group.covconv [group N] [covariant_class N N (*) r] : contravariant_class N N (*) r := ⟨group.covariant_iff_contravariant.mp covariant_class.elim⟩ section is_trans variables [is_trans N r] (m n : M) {a b c d : N} /- Lemmas with 3 elements. -/ lemma act_rel_of_rel_of_act_rel (ab : r a b) (rl : r (μ m b) c) : r (μ m a) c := trans (act_rel_act_of_rel m ab) rl lemma rel_act_of_rel_of_rel_act (ab : r a b) (rr : r c (μ m a)) : r c (μ m b) := trans rr (act_rel_act_of_rel _ ab) end is_trans end covariant /- Lemma with 4 elements. -/ section M_eq_N variables {M N μ r} {mu : N → N → N} [is_trans N r] [covariant_class N N mu r] [covariant_class N N (swap mu) r] {a b c d : N} lemma act_rel_act_of_rel_of_rel (ab : r a b) (cd : r c d) : r (mu a c) (mu b d) := trans (act_rel_act_of_rel c ab : _) (act_rel_act_of_rel b cd) end M_eq_N section contravariant variables {M N μ r} [contravariant_class M N μ r] lemma rel_of_act_rel_act (m : M) {a b : N} (ab : r (μ m a) (μ m b)) : r a b := contravariant_class.elim _ ab section is_trans variables [is_trans N r] (m n : M) {a b c d : N} /- Lemmas with 3 elements. -/ lemma act_rel_of_act_rel_of_rel_act_rel (ab : r (μ m a) b) (rl : r (μ m b) (μ m c)) : r (μ m a) c := trans ab (rel_of_act_rel_act m rl) lemma rel_act_of_act_rel_act_of_rel_act (ab : r (μ m a) (μ m b)) (rr : r b (μ m c)) : r a (μ m c) := trans (rel_of_act_rel_act m ab) rr end is_trans end contravariant lemma covariant_le_of_covariant_lt [partial_order N] : covariant M N μ (<) → covariant M N μ (≤) := begin refine λ h a b c bc, _, rcases le_iff_eq_or_lt.mp bc with rfl | bc, { exact rfl.le }, { exact (h _ bc).le } end lemma contravariant_lt_of_contravariant_le [partial_order N] : contravariant M N μ (≤) → contravariant M N μ (<) := begin refine λ h a b c bc, lt_iff_le_and_ne.mpr ⟨h a bc.le, _⟩, rintro rfl, exact lt_irrefl _ bc, end lemma covariant_le_iff_contravariant_lt [linear_order N] : covariant M N μ (≤) ↔ contravariant M N μ (<) := ⟨ λ h a b c bc, not_le.mp (λ k, not_le.mpr bc (h _ k)), λ h a b c bc, not_lt.mp (λ k, not_lt.mpr bc (h _ k))⟩ lemma covariant_lt_iff_contravariant_le [linear_order N] : covariant M N μ (<) ↔ contravariant M N μ (≤) := ⟨ λ h a b c bc, not_lt.mp (λ k, not_lt.mpr bc (h _ k)), λ h a b c bc, not_le.mp (λ k, not_le.mpr bc (h _ k))⟩ @[to_additive] lemma covariant_flip_mul_iff [comm_semigroup N] : covariant N N (flip (*)) (r) ↔ covariant N N (*) (r) := by rw is_symm_op.flip_eq @[to_additive] lemma contravariant_flip_mul_iff [comm_semigroup N] : contravariant N N (flip (*)) (r) ↔ contravariant N N (*) (r) := by rw is_symm_op.flip_eq @[to_additive] instance contravariant_mul_lt_of_covariant_mul_le [has_mul N] [linear_order N] [covariant_class N N (*) (≤)] : contravariant_class N N (*) (<) := { elim := (covariant_le_iff_contravariant_lt N N (*)).mp covariant_class.elim } @[to_additive] instance covariant_mul_lt_of_contravariant_mul_le [has_mul N] [linear_order N] [contravariant_class N N (*) (≤)] : covariant_class N N (*) (<) := { elim := (covariant_lt_iff_contravariant_le N N (*)).mpr contravariant_class.elim } @[to_additive] instance covariant_swap_mul_le_of_covariant_mul_le [comm_semigroup N] [has_le N] [covariant_class N N (*) (≤)] : covariant_class N N (swap (*)) (≤) := { elim := (covariant_flip_mul_iff N (≤)).mpr covariant_class.elim } @[to_additive] instance contravariant_swap_mul_le_of_contravariant_mul_le [comm_semigroup N] [has_le N] [contravariant_class N N (*) (≤)] : contravariant_class N N (swap (*)) (≤) := { elim := (contravariant_flip_mul_iff N (≤)).mpr contravariant_class.elim } @[to_additive] instance contravariant_swap_mul_lt_of_contravariant_mul_lt [comm_semigroup N] [has_lt N] [contravariant_class N N (*) (<)] : contravariant_class N N (swap (*)) (<) := { elim := (contravariant_flip_mul_iff N (<)).mpr contravariant_class.elim } @[to_additive] instance covariant_swap_mul_lt_of_covariant_mul_lt [comm_semigroup N] [has_lt N] [covariant_class N N (*) (<)] : covariant_class N N (swap (*)) (<) := { elim := (covariant_flip_mul_iff N (<)).mpr covariant_class.elim } @[to_additive] instance left_cancel_semigroup.covariant_mul_lt_of_covariant_mul_le [left_cancel_semigroup N] [partial_order N] [covariant_class N N (*) (≤)] : covariant_class N N (*) (<) := { elim := λ a b c bc, by { cases lt_iff_le_and_ne.mp bc with bc cb, exact lt_iff_le_and_ne.mpr ⟨covariant_class.elim a bc, (mul_ne_mul_right a).mpr cb⟩ } } @[to_additive] instance right_cancel_semigroup.covariant_swap_mul_lt_of_covariant_swap_mul_le [right_cancel_semigroup N] [partial_order N] [covariant_class N N (swap (*)) (≤)] : covariant_class N N (swap (*)) (<) := { elim := λ a b c bc, by { cases lt_iff_le_and_ne.mp bc with bc cb, exact lt_iff_le_and_ne.mpr ⟨covariant_class.elim a bc, (mul_ne_mul_left a).mpr cb⟩ } } @[to_additive] instance left_cancel_semigroup.contravariant_mul_le_of_contravariant_mul_lt [left_cancel_semigroup N] [partial_order N] [contravariant_class N N (*) (<)] : contravariant_class N N (*) (≤) := { elim := λ a b c bc, by { cases le_iff_eq_or_lt.mp bc with h h, { exact ((mul_right_inj a).mp h).le }, { exact (contravariant_class.elim _ h).le } } } @[to_additive] instance right_cancel_semigroup.contravariant_swap_mul_le_of_contravariant_swap_mul_lt [right_cancel_semigroup N] [partial_order N] [contravariant_class N N (swap (*)) (<)] : contravariant_class N N (swap (*)) (≤) := { elim := λ a b c bc, by { cases le_iff_eq_or_lt.mp bc with h h, { exact ((mul_left_inj a).mp h).le }, { exact (contravariant_class.elim _ h).le } } } end variants
0e8c641f69f603ec35b4f7d97d1c73f0cd5d9d08
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/indimp.lean
bc816e7bbfaf1195c04cd4193c16020571d6f210
[ "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
474
lean
prelude definition Prop := Type.{0} inductive nat | zero : nat | succ : nat → nat inductive list (A : Type) | nil {} : list | cons : A → list → list inductive list2 (A : Type) : Type | nil2 {} : list2 | cons2 : A → list2 → list2 inductive and (A B : Prop) : Prop | and_intro : A → B → and inductive cls {T1 : Type} (R1 : T1 → T1 → Prop) {T2 : Type} (R2 : T2 → T2 → Prop) (f : T1 → T2) | mk : (∀x y : T1, R1 x y → R2 (f x) (f y)) → cls
e222ce929fff5de119137ef0bc0249fb0d4a0f0f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/def6.lean
21737075aa1a4e644b922a1da399e0dfbbee9bba
[ "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
839
lean
open Nat inductive BV : Nat → Type | nil : BV 0 | cons : ∀ (n) (hd : Bool) (tl : BV n), BV (succ n) open BV variable (f : Bool → Bool → Bool) def map2 : {n : Nat} → BV n → BV n → BV n | .(0), nil, nil => nil | .(n+1), cons n b1 v1, cons .(n) b2 v2 => cons n (f b1 b2) (map2 v1 v2) theorem ex1 : map2 f nil nil = nil := rfl theorem ex2 (n : Nat) (b1 b2 : Bool) (v1 v2 : BV n) : map2 f (cons n b1 v1) (cons n b2 v2) = cons n (f b1 b2) (map2 f v1 v2) := rfl #print map2 def map2' : {n : Nat} → BV n → BV n → BV n | _, nil, nil => nil | _, cons _ b1 v1, cons _ b2 v2 => cons _ (f b1 b2) (map2' v1 v2) theorem ex3 : map2' f nil nil = nil := rfl theorem ex4 (n : Nat) (b1 b2 : Bool) (v1 v2 : BV n) : map2' f (cons n b1 v1) (cons n b2 v2) = cons n (f b1 b2) (map2' f v1 v2) := rfl
4b37da1be7ded1863136f93a04a3c8a7209aa5e2
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/continuous_function/ordered.lean
ce6e88b9f1c1aa371a485df34c3efacd46cd2534
[ "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
4,657
lean
/- Copyright © 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam -/ import topology.algebra.order.proj_Icc import topology.continuous_function.basic /-! # Bundled continuous maps into orders, with order-compatible topology -/ variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] namespace continuous_map section variables [linear_ordered_add_comm_group β] [order_topology β] /-- The pointwise absolute value of a continuous function as a continuous function. -/ def abs (f : C(α, β)) : C(α, β) := { to_fun := λ x, |f x|, } @[priority 100] -- see Note [lower instance priority] instance : has_abs C(α, β) := ⟨λf, abs f⟩ @[simp] lemma abs_apply (f : C(α, β)) (x : α) : |f| x = |f x| := rfl end /-! We now set up the partial order and lattice structure (given by pointwise min and max) on continuous functions. -/ section lattice instance partial_order [partial_order β] : partial_order C(α, β) := partial_order.lift (λ f, f.to_fun) (by tidy) lemma le_def [partial_order β] {f g : C(α, β)} : f ≤ g ↔ ∀ a, f a ≤ g a := pi.le_def lemma lt_def [partial_order β] {f g : C(α, β)} : f < g ↔ (∀ a, f a ≤ g a) ∧ (∃ a, f a < g a) := pi.lt_def instance has_sup [linear_order β] [order_closed_topology β] : has_sup C(α, β) := { sup := λ f g, { to_fun := λ a, max (f a) (g a), } } @[simp, norm_cast] lemma sup_coe [linear_order β] [order_closed_topology β] (f g : C(α, β)) : ((f ⊔ g : C(α, β)) : α → β) = (f ⊔ g : α → β) := rfl @[simp] lemma sup_apply [linear_order β] [order_closed_topology β] (f g : C(α, β)) (a : α) : (f ⊔ g) a = max (f a) (g a) := rfl instance [linear_order β] [order_closed_topology β] : semilattice_sup C(α, β) := { le_sup_left := λ f g, le_def.mpr (by simp [le_refl]), le_sup_right := λ f g, le_def.mpr (by simp [le_refl]), sup_le := λ f₁ f₂ g w₁ w₂, le_def.mpr (λ a, by simp [le_def.mp w₁ a, le_def.mp w₂ a]), ..continuous_map.partial_order, ..continuous_map.has_sup, } instance has_inf [linear_order β] [order_closed_topology β] : has_inf C(α, β) := { inf := λ f g, { to_fun := λ a, min (f a) (g a), } } @[simp, norm_cast] lemma inf_coe [linear_order β] [order_closed_topology β] (f g : C(α, β)) : ((f ⊓ g : C(α, β)) : α → β) = (f ⊓ g : α → β) := rfl @[simp] lemma inf_apply [linear_order β] [order_closed_topology β] (f g : C(α, β)) (a : α) : (f ⊓ g) a = min (f a) (g a) := rfl instance [linear_order β] [order_closed_topology β] : semilattice_inf C(α, β) := { inf_le_left := λ f g, le_def.mpr (by simp [le_refl]), inf_le_right := λ f g, le_def.mpr (by simp [le_refl]), le_inf := λ f₁ f₂ g w₁ w₂, le_def.mpr (λ a, by simp [le_def.mp w₁ a, le_def.mp w₂ a]), ..continuous_map.partial_order, ..continuous_map.has_inf, } instance [linear_order β] [order_closed_topology β] : lattice C(α, β) := { ..continuous_map.semilattice_inf, ..continuous_map.semilattice_sup } -- TODO transfer this lattice structure to `bounded_continuous_function` section sup' variables [linear_order γ] [order_closed_topology γ] lemma sup'_apply {ι : Type*} {s : finset ι} (H : s.nonempty) (f : ι → C(β, γ)) (b : β) : s.sup' H f b = s.sup' H (λ a, f a b) := finset.comp_sup'_eq_sup'_comp H (λ f : C(β, γ), f b) (λ i j, rfl) @[simp, norm_cast] lemma sup'_coe {ι : Type*} {s : finset ι} (H : s.nonempty) (f : ι → C(β, γ)) : ((s.sup' H f : C(β, γ)) : ι → β) = s.sup' H (λ a, (f a : β → γ)) := by { ext, simp [sup'_apply], } end sup' section inf' variables [linear_order γ] [order_closed_topology γ] lemma inf'_apply {ι : Type*} {s : finset ι} (H : s.nonempty) (f : ι → C(β, γ)) (b : β) : s.inf' H f b = s.inf' H (λ a, f a b) := @sup'_apply _ γᵒᵈ _ _ _ _ _ _ H f b @[simp, norm_cast] lemma inf'_coe {ι : Type*} {s : finset ι} (H : s.nonempty) (f : ι → C(β, γ)) : ((s.inf' H f : C(β, γ)) : ι → β) = s.inf' H (λ a, (f a : β → γ)) := @sup'_coe _ γᵒᵈ _ _ _ _ _ _ H f end inf' end lattice section extend variables [linear_order α] [order_topology α] {a b : α} (h : a ≤ b) /-- Extend a continuous function `f : C(set.Icc a b, β)` to a function `f : C(α, β)`. -/ def Icc_extend (f : C(set.Icc a b, β)) : C(α, β) := ⟨set.Icc_extend h f⟩ @[simp] lemma coe_Icc_extend (f : C(set.Icc a b, β)) : ((Icc_extend h f : C(α, β)) : α → β) = set.Icc_extend h f := rfl end extend end continuous_map
15e4beb0eccd80635b395431672df885c9a62643
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Data/Options.lean
e8f7371935c405b142d0a3aa1b9723f383301d1e
[ "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
5,915
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich and Leonardo de Moura -/ import Lean.ImportingFlag import Lean.Data.KVMap import Lean.Data.NameMap namespace Lean def Options := KVMap def Options.empty : Options := {} instance : Inhabited Options where default := {} instance : ToString Options := inferInstanceAs (ToString KVMap) instance : ForIn m Options (Name × DataValue) := inferInstanceAs (ForIn _ KVMap _) structure OptionDecl where defValue : DataValue group : String := "" descr : String := "" deriving Inhabited def OptionDecls := NameMap OptionDecl instance : Inhabited OptionDecls := ⟨({} : NameMap OptionDecl)⟩ private builtin_initialize optionDeclsRef : IO.Ref OptionDecls ← IO.mkRef (mkNameMap OptionDecl) @[export lean_register_option] def registerOption (name : Name) (decl : OptionDecl) : IO Unit := do unless (← initializing) do throw (IO.userError "failed to register option, options can only be registered during initialization") let decls ← optionDeclsRef.get if decls.contains name then throw $ IO.userError s!"invalid option declaration '{name}', option already exists" optionDeclsRef.set $ decls.insert name decl def getOptionDecls : IO OptionDecls := optionDeclsRef.get @[export lean_get_option_decls_array] def getOptionDeclsArray : IO (Array (Name × OptionDecl)) := do let decls ← getOptionDecls pure $ decls.fold (fun (r : Array (Name × OptionDecl)) k v => r.push (k, v)) #[] def getOptionDecl (name : Name) : IO OptionDecl := do let decls ← getOptionDecls let (some decl) ← pure (decls.find? name) | throw $ IO.userError s!"unknown option '{name}'" pure decl def getOptionDefaultValue (name : Name) : IO DataValue := do let decl ← getOptionDecl name pure decl.defValue def getOptionDescr (name : Name) : IO String := do let decl ← getOptionDecl name pure decl.descr def setOptionFromString (opts : Options) (entry : String) : IO Options := do let ps := (entry.splitOn "=").map String.trim let [key, val] ← pure ps | throw $ IO.userError "invalid configuration option entry, it must be of the form '<key> = <value>'" let key := Name.mkSimple key let defValue ← getOptionDefaultValue key match defValue with | DataValue.ofString _ => pure $ opts.setString key val | DataValue.ofBool _ => if key == `true then pure $ opts.setBool key true else if key == `false then pure $ opts.setBool key false else throw $ IO.userError s!"invalid Bool option value '{val}'" | DataValue.ofName _ => pure $ opts.setName key val.toName | DataValue.ofNat _ => match val.toNat? with | none => throw (IO.userError s!"invalid Nat option value '{val}'") | some v => pure $ opts.setNat key v | DataValue.ofInt _ => match val.toInt? with | none => throw (IO.userError s!"invalid Int option value '{val}'") | some v => pure $ opts.setInt key v | DataValue.ofSyntax _ => throw (IO.userError s!"invalid Syntax option value") class MonadOptions (m : Type → Type) where getOptions : m Options export MonadOptions (getOptions) instance [MonadLift m n] [MonadOptions m] : MonadOptions n where getOptions := liftM (getOptions : m _) variable [Monad m] [MonadOptions m] def getBoolOption (k : Name) (defValue := false) : m Bool := do let opts ← getOptions return opts.getBool k defValue def getNatOption (k : Name) (defValue := 0) : m Nat := do let opts ← getOptions return opts.getNat k defValue class MonadWithOptions (m : Type → Type) where withOptions (f : Options → Options) (x : m α) : m α export MonadWithOptions (withOptions) instance [MonadFunctor m n] [MonadWithOptions m] : MonadWithOptions n where withOptions f x := monadMap (m := m) (withOptions f) x /-! Remark: `_inPattern` is an internal option for communicating to the delaborator that the term being delaborated should be treated as a pattern. -/ def withInPattern [MonadWithOptions m] (x : m α) : m α := withOptions (fun o => o.setBool `_inPattern true) x def Options.getInPattern (o : Options) : Bool := o.getBool `_inPattern /-- A strongly-typed reference to an option. -/ protected structure Option (α : Type) where name : Name defValue : α deriving Inhabited namespace Option protected structure Decl (α : Type) where defValue : α group : String := "" descr : String := "" protected def get? [KVMap.Value α] (opts : Options) (opt : Lean.Option α) : Option α := opts.get? opt.name protected def get [KVMap.Value α] (opts : Options) (opt : Lean.Option α) : α := opts.get opt.name opt.defValue protected def set [KVMap.Value α] (opts : Options) (opt : Lean.Option α) (val : α) : Options := opts.set opt.name val /-- Similar to `set`, but update `opts` only if it doesn't already contains an setting for `opt.name` -/ protected def setIfNotSet [KVMap.Value α] (opts : Options) (opt : Lean.Option α) (val : α) : Options := if opts.contains opt.name then opts else opt.set opts val protected def register [KVMap.Value α] (name : Name) (decl : Lean.Option.Decl α) : IO (Lean.Option α) := do registerOption name { defValue := KVMap.Value.toDataValue decl.defValue, group := decl.group, descr := decl.descr } return { name := name, defValue := decl.defValue } macro (name := registerBuiltinOption) doc?:(docComment)? "register_builtin_option" name:ident " : " type:term " := " decl:term : command => `($[$doc?]? builtin_initialize $name : Lean.Option $type ← Lean.Option.register $(quote name.getId) $decl) macro (name := registerOption) doc?:(docComment)? "register_option" name:ident " : " type:term " := " decl:term : command => `($[$doc?]? initialize $name : Lean.Option $type ← Lean.Option.register $(quote name.getId) $decl) end Option end Lean
67bba83189120bb27958f515c5d5031e1def8333
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/specific_limits/normed.lean
e43964392760d5211acf720de2ecaa3843896a4d
[ "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
30,157
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Sébastien Gouëzel, Yury G. Kudryashov, Dylan MacKenzie, Patrick Massot -/ import algebra.order.field import analysis.asymptotics.asymptotics import analysis.specific_limits.basic /-! # A collection of specific limit computations This file contains important specific limit computations in (semi-)normed groups/rings/spaces, as as well as such computations in `ℝ` when the natural proof passes through a fact about normed spaces. -/ noncomputable theory open classical set function filter finset metric asymptotics open_locale classical topological_space nat big_operators uniformity nnreal ennreal variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top := tendsto_abs_at_top_at_top lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (∑ i in range n, |f i|)) at_top (𝓝 r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end /-! ### Powers -/ lemma tendsto_norm_zero' {𝕜 : Type*} [normed_group 𝕜] : tendsto (norm : 𝕜 → ℝ) (𝓝[≠] 0) (𝓝[>] 0) := tendsto_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx namespace normed_field lemma tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] : tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[≠] 0) at_top := (tendsto_inv_zero_at_top.comp tendsto_norm_zero').congr $ λ x, (norm_inv x).symm lemma tendsto_norm_zpow_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] {m : ℤ} (hm : m < 0) : tendsto (λ x : 𝕜, ∥x ^ m∥) (𝓝[≠] 0) at_top := begin rcases neg_surjective m with ⟨m, rfl⟩, rw neg_lt_zero at hm, lift m to ℕ using hm.le, rw int.coe_nat_pos at hm, simp only [norm_pow, zpow_neg, zpow_coe_nat, ← inv_pow], exact (tendsto_pow_at_top hm.ne').comp normed_field.tendsto_norm_inverse_nhds_within_0_at_top end /-- The (scalar) product of a sequence that tends to zero with a bounded one also tends to zero. -/ lemma tendsto_zero_smul_of_tendsto_zero_of_bounded {ι 𝕜 𝔸 : Type*} [normed_field 𝕜] [normed_group 𝔸] [normed_space 𝕜 𝔸] {l : filter ι} {ε : ι → 𝕜} {f : ι → 𝔸} (hε : tendsto ε l (𝓝 0)) (hf : filter.is_bounded_under (≤) l (norm ∘ f)) : tendsto (ε • f) l (𝓝 0) := begin rw ← is_o_one_iff 𝕜 at hε ⊢, simpa using is_o.smul_is_O hε (hf.is_O_const (one_ne_zero : (1 : 𝕜) ≠ 0)) end @[simp] lemma continuous_at_zpow {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {m : ℤ} {x : 𝕜} : continuous_at (λ x, x ^ m) x ↔ x ≠ 0 ∨ 0 ≤ m := begin refine ⟨_, continuous_at_zpow₀ _ _⟩, contrapose!, rintro ⟨rfl, hm⟩ hc, exact not_tendsto_at_top_of_tendsto_nhds (hc.tendsto.mono_left nhds_within_le_nhds).norm (tendsto_norm_zpow_nhds_within_0_at_top hm) end @[simp] lemma continuous_at_inv {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {x : 𝕜} : continuous_at has_inv.inv x ↔ x ≠ 0 := by simpa [(@zero_lt_one ℤ _ _).not_le] using @continuous_at_zpow _ _ (-1) x end normed_field lemma is_o_pow_pow_of_lt_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ < r₂) : (λ n : ℕ, r₁ ^ n) =o[at_top] (λ n, r₂ ^ n) := have H : 0 < r₂ := h₁.trans_lt h₂, is_o_of_tendsto (λ n hn, false.elim $ H.ne' $ pow_eq_zero hn) $ (tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg h₁ (h₁.trans h₂.le)) ((div_lt_one H).2 h₂)).congr (λ n, div_pow _ _ _) lemma is_O_pow_pow_of_le_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ ≤ r₂) : (λ n : ℕ, r₁ ^ n) =O[at_top] (λ n, r₂ ^ n) := h₂.eq_or_lt.elim (λ h, h ▸ is_O_refl _ _) (λ h, (is_o_pow_pow_of_lt_left h₁ h).is_O) lemma is_o_pow_pow_of_abs_lt_left {r₁ r₂ : ℝ} (h : |r₁| < |r₂|) : (λ n : ℕ, r₁ ^ n) =o[at_top] (λ n, r₂ ^ n) := begin refine (is_o.of_norm_left _).of_norm_right, exact (is_o_pow_pow_of_lt_left (abs_nonneg r₁) h).congr (pow_abs r₁) (pow_abs r₂) end /-- Various statements equivalent to the fact that `f n` grows exponentially slower than `R ^ n`. * 0: $f n = o(a ^ n)$ for some $-R < a < R$; * 1: $f n = o(a ^ n)$ for some $0 < a < R$; * 2: $f n = O(a ^ n)$ for some $-R < a < R$; * 3: $f n = O(a ^ n)$ for some $0 < a < R$; * 4: there exist `a < R` and `C` such that one of `C` and `R` is positive and $|f n| ≤ Ca^n$ for all `n`; * 5: there exists `0 < a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`; * 6: there exists `a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`; * 7: there exists `0 < a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`. NB: For backwards compatibility, if you add more items to the list, please append them at the end of the list. -/ lemma tfae_exists_lt_is_o_pow (f : ℕ → ℝ) (R : ℝ) : tfae [∃ a ∈ Ioo (-R) R, f =o[at_top] pow a, ∃ a ∈ Ioo 0 R, f =o[at_top] (pow a), ∃ a ∈ Ioo (-R) R, f =O[at_top] pow a, ∃ a ∈ Ioo 0 R, f =O[at_top] pow a, ∃ (a < R) C (h₀ : 0 < C ∨ 0 < R), ∀ n, |f n| ≤ C * a ^ n, ∃ (a ∈ Ioo 0 R) (C > 0), ∀ n, |f n| ≤ C * a ^ n, ∃ a < R, ∀ᶠ n in at_top, |f n| ≤ a ^ n, ∃ a ∈ Ioo 0 R, ∀ᶠ n in at_top, |f n| ≤ a ^ n] := begin have A : Ico 0 R ⊆ Ioo (-R) R, from λ x hx, ⟨(neg_lt_zero.2 (hx.1.trans_lt hx.2)).trans_le hx.1, hx.2⟩, have B : Ioo 0 R ⊆ Ioo (-R) R := subset.trans Ioo_subset_Ico_self A, -- First we prove that 1-4 are equivalent using 2 → 3 → 4, 1 → 3, and 2 → 1 tfae_have : 1 → 3, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 2 → 1, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, tfae_have : 3 → 2, { rintro ⟨a, ha, H⟩, rcases exists_between (abs_lt.2 ha) with ⟨b, hab, hbR⟩, exact ⟨b, ⟨(abs_nonneg a).trans_lt hab, hbR⟩, H.trans_is_o (is_o_pow_pow_of_abs_lt_left (hab.trans_le (le_abs_self b)))⟩ }, tfae_have : 2 → 4, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 4 → 3, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, -- Add 5 and 6 using 4 → 6 → 5 → 3 tfae_have : 4 → 6, { rintro ⟨a, ha, H⟩, rcases bound_of_is_O_nat_at_top H with ⟨C, hC₀, hC⟩, refine ⟨a, ha, C, hC₀, λ n, _⟩, simpa only [real.norm_eq_abs, abs_pow, abs_of_nonneg ha.1.le] using hC (pow_ne_zero n ha.1.ne') }, tfae_have : 6 → 5, from λ ⟨a, ha, C, H₀, H⟩, ⟨a, ha.2, C, or.inl H₀, H⟩, tfae_have : 5 → 3, { rintro ⟨a, ha, C, h₀, H⟩, rcases sign_cases_of_C_mul_pow_nonneg (λ n, (abs_nonneg _).trans (H n)) with rfl | ⟨hC₀, ha₀⟩, { obtain rfl : f = 0, by { ext n, simpa using H n }, simp only [lt_irrefl, false_or] at h₀, exact ⟨0, ⟨neg_lt_zero.2 h₀, h₀⟩, is_O_zero _ _⟩ }, exact ⟨a, A ⟨ha₀, ha⟩, is_O_of_le' _ (λ n, (H n).trans $ mul_le_mul_of_nonneg_left (le_abs_self _) hC₀.le)⟩ }, -- Add 7 and 8 using 2 → 8 → 7 → 3 tfae_have : 2 → 8, { rintro ⟨a, ha, H⟩, refine ⟨a, ha, (H.def zero_lt_one).mono (λ n hn, _)⟩, rwa [real.norm_eq_abs, real.norm_eq_abs, one_mul, abs_pow, abs_of_pos ha.1] at hn }, tfae_have : 8 → 7, from λ ⟨a, ha, H⟩, ⟨a, ha.2, H⟩, tfae_have : 7 → 3, { rintro ⟨a, ha, H⟩, have : 0 ≤ a, from nonneg_of_eventually_pow_nonneg (H.mono $ λ n, (abs_nonneg _).trans), refine ⟨a, A ⟨this, ha⟩, is_O.of_bound 1 _⟩, simpa only [real.norm_eq_abs, one_mul, abs_pow, abs_of_nonneg this] }, tfae_finish end /-- For any natural `k` and a real `r > 1` we have `n ^ k = o(r ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_const_pow_of_one_lt {R : Type*} [normed_ring R] (k : ℕ) {r : ℝ} (hr : 1 < r) : (λ n, n ^ k : ℕ → R) =o[at_top] (λ n, r ^ n) := begin have : tendsto (λ x : ℝ, x ^ k) (𝓝[>] 1) (𝓝 1), from ((continuous_id.pow k).tendsto' (1 : ℝ) 1 (one_pow _)).mono_left inf_le_left, obtain ⟨r' : ℝ, hr' : r' ^ k < r, h1 : 1 < r'⟩ := ((this.eventually (gt_mem_nhds hr)).and self_mem_nhds_within).exists, have h0 : 0 ≤ r' := zero_le_one.trans h1.le, suffices : (λ n, n ^ k : ℕ → R) =O[at_top] (λ n : ℕ, (r' ^ k) ^ n), from this.trans_is_o (is_o_pow_pow_of_lt_left (pow_nonneg h0 _) hr'), conv in ((r' ^ _) ^ _) { rw [← pow_mul, mul_comm, pow_mul] }, suffices : ∀ n : ℕ, ∥(n : R)∥ ≤ (r' - 1)⁻¹ * ∥(1 : R)∥ * ∥r' ^ n∥, from (is_O_of_le' _ this).pow _, intro n, rw mul_right_comm, refine n.norm_cast_le.trans (mul_le_mul_of_nonneg_right _ (norm_nonneg _)), simpa [div_eq_inv_mul, real.norm_eq_abs, abs_of_nonneg h0] using n.cast_le_pow_div_sub h1 end /-- For a real `r > 1` we have `n = o(r ^ n)` as `n → ∞`. -/ lemma is_o_coe_const_pow_of_one_lt {R : Type*} [normed_ring R] {r : ℝ} (hr : 1 < r) : (coe : ℕ → R) =o[at_top] (λ n, r ^ n) := by simpa only [pow_one] using @is_o_pow_const_const_pow_of_one_lt R _ 1 _ hr /-- If `∥r₁∥ < r₂`, then for any naturak `k` we have `n ^ k r₁ ^ n = o (r₂ ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_mul_const_pow_const_pow_of_norm_lt {R : Type*} [normed_ring R] (k : ℕ) {r₁ : R} {r₂ : ℝ} (h : ∥r₁∥ < r₂) : (λ n, n ^ k * r₁ ^ n : ℕ → R) =o[at_top] (λ n, r₂ ^ n) := begin by_cases h0 : r₁ = 0, { refine (is_o_zero _ _).congr' (mem_at_top_sets.2 $ ⟨1, λ n hn, _⟩) eventually_eq.rfl, simp [zero_pow (zero_lt_one.trans_le hn), h0] }, rw [← ne.def, ← norm_pos_iff] at h0, have A : (λ n, n ^ k : ℕ → R) =o[at_top] (λ n, (r₂ / ∥r₁∥) ^ n), from is_o_pow_const_const_pow_of_one_lt k ((one_lt_div h0).2 h), suffices : (λ n, r₁ ^ n) =O[at_top] (λ n, ∥r₁∥ ^ n), by simpa [div_mul_cancel _ (pow_pos h0 _).ne'] using A.mul_is_O this, exact is_O.of_bound 1 (by simpa using eventually_norm_pow_le r₁) end lemma tendsto_pow_const_div_const_pow_of_one_lt (k : ℕ) {r : ℝ} (hr : 1 < r) : tendsto (λ n, n ^ k / r ^ n : ℕ → ℝ) at_top (𝓝 0) := (is_o_pow_const_const_pow_of_one_lt k hr).tendsto_div_nhds_zero /-- If `|r| < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`. -/ lemma tendsto_pow_const_mul_const_pow_of_abs_lt_one (k : ℕ) {r : ℝ} (hr : |r| < 1) : tendsto (λ n, n ^ k * r ^ n : ℕ → ℝ) at_top (𝓝 0) := begin by_cases h0 : r = 0, { exact tendsto_const_nhds.congr' (mem_at_top_sets.2 ⟨1, λ n hn, by simp [zero_lt_one.trans_le hn, h0]⟩) }, have hr' : 1 < (|r|)⁻¹, from one_lt_inv (abs_pos.2 h0) hr, rw tendsto_zero_iff_norm_tendsto_zero, simpa [div_eq_mul_inv] using tendsto_pow_const_div_const_pow_of_one_lt k hr' end /-- If `0 ≤ r < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`. This is a specialized version of `tendsto_pow_const_mul_const_pow_of_abs_lt_one`, singled out for ease of application. -/ lemma tendsto_pow_const_mul_const_pow_of_lt_one (k : ℕ) {r : ℝ} (hr : 0 ≤ r) (h'r : r < 1) : tendsto (λ n, n ^ k * r ^ n : ℕ → ℝ) at_top (𝓝 0) := tendsto_pow_const_mul_const_pow_of_abs_lt_one k (abs_lt.2 ⟨neg_one_lt_zero.trans_le hr, h'r⟩) /-- If `|r| < 1`, then `n * r ^ n` tends to zero. -/ lemma tendsto_self_mul_const_pow_of_abs_lt_one {r : ℝ} (hr : |r| < 1) : tendsto (λ n, n * r ^ n : ℕ → ℝ) at_top (𝓝 0) := by simpa only [pow_one] using tendsto_pow_const_mul_const_pow_of_abs_lt_one 1 hr /-- If `0 ≤ r < 1`, then `n * r ^ n` tends to zero. This is a specialized version of `tendsto_self_mul_const_pow_of_abs_lt_one`, singled out for ease of application. -/ lemma tendsto_self_mul_const_pow_of_lt_one {r : ℝ} (hr : 0 ≤ r) (h'r : r < 1) : tendsto (λ n, n * r ^ n : ℕ → ℝ) at_top (𝓝 0) := by simpa only [pow_one] using tendsto_pow_const_mul_const_pow_of_lt_one 1 hr h'r /-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/ lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R} (h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) := begin apply squeeze_zero_norm' (eventually_norm_pow_le x), exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h, end lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : |r| < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := tendsto_pow_at_top_nhds_0_of_norm_lt_1 h /-! ### Geometric series-/ section geometric variables {K : Type*} [normed_field K] {ξ : K} lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ := begin have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] }, have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds, rw [has_sum_iff_tendsto_nat_of_summable_norm], { simpa [geom_sum_eq, xi_ne_one, neg_inv, div_eq_mul_inv] using A }, { simp [norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] } end lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) := ⟨_, has_sum_geometric_of_norm_lt_1 h⟩ lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : ∑'n:ℕ, ξ ^ n = (1 - ξ)⁻¹ := (has_sum_geometric_of_norm_lt_1 h).tsum_eq lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : |r| < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := has_sum_geometric_of_norm_lt_1 h lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : |r| < 1) : summable (λn:ℕ, r ^ n) := summable_geometric_of_norm_lt_1 h lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : |r| < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := tsum_geometric_of_norm_lt_1 h /-- A geometric series in a normed field is summable iff the norm of the common ratio is less than one. -/ @[simp] lemma summable_geometric_iff_norm_lt_1 : summable (λ n : ℕ, ξ ^ n) ↔ ∥ξ∥ < 1 := begin refine ⟨λ h, _, summable_geometric_of_norm_lt_1⟩, obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ := (h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists, simp only [norm_pow, dist_zero_right] at hk, rw [← one_pow k] at hk, exact lt_of_pow_lt_pow _ zero_le_one hk end end geometric section mul_geometric lemma summable_norm_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n : ℕ, ∥(n ^ k * r ^ n : R)∥) := begin rcases exists_between hr with ⟨r', hrr', h⟩, exact summable_of_is_O_nat (summable_geometric_of_lt_1 ((norm_nonneg _).trans hrr'.le) h) (is_o_pow_const_mul_const_pow_const_pow_of_norm_lt _ hrr').is_O.norm_left end lemma summable_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] [complete_space R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n, n ^ k * r ^ n : ℕ → R) := summable_of_summable_norm $ summable_norm_pow_mul_geometric_of_norm_lt_1 _ hr /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`, `has_sum` version. -/ lemma has_sum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : has_sum (λ n, n * r ^ n : ℕ → 𝕜) (r / (1 - r) ^ 2) := begin have A : summable (λ n, n * r ^ n : ℕ → 𝕜), by simpa using summable_pow_mul_geometric_of_norm_lt_1 1 hr, have B : has_sum (pow r : ℕ → 𝕜) (1 - r)⁻¹, from has_sum_geometric_of_norm_lt_1 hr, refine A.has_sum_iff.2 _, have hr' : r ≠ 1, by { rintro rfl, simpa [lt_irrefl] using hr }, set s : 𝕜 := ∑' n : ℕ, n * r ^ n, calc s = (1 - r) * s / (1 - r) : (mul_div_cancel_left _ (sub_ne_zero.2 hr'.symm)).symm ... = (s - r * s) / (1 - r) : by rw [sub_mul, one_mul] ... = ((0 : ℕ) * r ^ 0 + (∑' n : ℕ, (n + 1 : ℕ) * r ^ (n + 1)) - r * s) / (1 - r) : by rw ← tsum_eq_zero_add A ... = (r * (∑' n : ℕ, (n + 1) * r ^ n) - r * s) / (1 - r) : by simp [pow_succ, mul_left_comm _ r, tsum_mul_left] ... = r / (1 - r) ^ 2 : by simp [add_mul, tsum_add A B.summable, mul_add, B.tsum_eq, ← div_eq_mul_inv, sq, div_div] end /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`. -/ lemma tsum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : (∑' n : ℕ, n * r ^ n : 𝕜) = (r / (1 - r) ^ 2) := (has_sum_coe_mul_geometric_of_norm_lt_1 hr).tsum_eq end mul_geometric section summable_le_geometric variables [semi_normed_group α] {r C : ℝ} {f : ℕ → α} lemma semi_normed_group.cauchy_seq_of_le_geometric {C : ℝ} {r : ℝ} (hr : r < 1) {u : ℕ → α} (h : ∀ n, ∥u n - u (n + 1)∥ ≤ C*r^n) : cauchy_seq u := cauchy_seq_of_le_geometric r C hr (by simpa [dist_eq_norm] using h) lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) : dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n := begin rw [sum_range_succ, dist_eq_norm, ← norm_neg, neg_sub, add_sub_cancel'], exact hf n, end /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) : cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) := cauchy_seq_finset_of_norm_bounded _ (aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) {a : α} (ha : has_sum f a) (n : ℕ) : ∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) := begin rw ← dist_eq_norm, apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf), exact ha.tendsto_sum_nat end @[simp] lemma dist_partial_sum (u : ℕ → α) (n : ℕ) : dist (∑ k in range (n + 1), u k) (∑ k in range n, u k) = ∥u n∥ := by simp [dist_eq_norm, sum_range_succ] @[simp] lemma dist_partial_sum' (u : ℕ → α) (n : ℕ) : dist (∑ k in range n, u k) (∑ k in range (n+1), u k) = ∥u n∥ := by simp [dist_eq_norm', sum_range_succ] lemma cauchy_series_of_le_geometric {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1) (h : ∀ n, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range n, u k) := cauchy_seq_of_le_geometric r C hr (by simp [h]) lemma normed_group.cauchy_series_of_le_geometric' {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1) (h : ∀ n, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := (cauchy_series_of_le_geometric hr h).comp_tendsto $ tendsto_add_at_top_nat 1 lemma normed_group.cauchy_series_of_le_geometric'' {C : ℝ} {u : ℕ → α} {N : ℕ} {r : ℝ} (hr₀ : 0 < r) (hr₁ : r < 1) (h : ∀ n ≥ N, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin set v : ℕ → α := λ n, if n < N then 0 else u n, have hC : 0 ≤ C, from (zero_le_mul_right $ pow_pos hr₀ N).mp ((norm_nonneg _).trans $ h N $ le_refl N), have : ∀ n ≥ N, u n = v n, { intros n hn, simp [v, hn, if_neg (not_lt.mpr hn)] }, refine cauchy_seq_sum_of_eventually_eq this (normed_group.cauchy_series_of_le_geometric' hr₁ _), { exact C }, intro n, dsimp [v], split_ifs with H H, { rw norm_zero, exact mul_nonneg hC (pow_nonneg hr₀.le _) }, { push_neg at H, exact h _ H } end end summable_le_geometric section normed_ring_geometric variables {R : Type*} [normed_ring R] [complete_space R] open normed_space /-- A geometric series in a complete normed ring is summable. Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/ lemma normed_ring.summable_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) := begin have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h, refine summable_of_norm_bounded_eventually _ h1 _, rw nat.cofinite_eq_at_top, exact eventually_norm_pow_le x, end /-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the normed ring satisfies the axiom `∥1∥ = 1`. -/ lemma normed_ring.tsum_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : ∥∑' n:ℕ, x ^ n∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ := begin rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h), simp only [pow_zero], refine le_trans (norm_add_le _ _) _, have : ∥∑' b : ℕ, (λ n, x ^ (n + 1)) b∥ ≤ (1 - ∥x∥)⁻¹ - 1, { refine tsum_of_norm_bounded _ (λ b, norm_pow_le' _ (nat.succ_pos b)), convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h), simp }, linarith end lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) : (∑' i:ℕ, x ^ i) * (1 - x) = 1 := begin have := ((normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_right (1 - x)), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (𝓝 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←geom_sum_mul_neg, finset.sum_mul], end lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) : (1 - x) * ∑' i:ℕ, x ^ i = 1 := begin have := (normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_left (1 - x), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←mul_neg_geom_sum, finset.mul_sum] end end normed_ring_geometric /-! ### Summability tests based on comparison with geometric series -/ lemma summable_of_ratio_norm_eventually_le {α : Type*} [semi_normed_group α] [complete_space α] {f : ℕ → α} {r : ℝ} (hr₁ : r < 1) (h : ∀ᶠ n in at_top, ∥f (n+1)∥ ≤ r * ∥f n∥) : summable f := begin by_cases hr₀ : 0 ≤ r, { rw eventually_at_top at h, rcases h with ⟨N, hN⟩, rw ← @summable_nat_add_iff α _ _ _ _ N, refine summable_of_norm_bounded (λ n, ∥f N∥ * r^n) (summable.mul_left _ $ summable_geometric_of_lt_1 hr₀ hr₁) (λ n, _), conv_rhs {rw [mul_comm, ← zero_add N]}, refine le_geom hr₀ n (λ i _, _), convert hN (i + N) (N.le_add_left i) using 3, ac_refl }, { push_neg at hr₀, refine summable_of_norm_bounded_eventually 0 summable_zero _, rw nat.cofinite_eq_at_top, filter_upwards [h] with _ hn, by_contra' h, exact not_lt.mpr (norm_nonneg _) (lt_of_le_of_lt hn $ mul_neg_of_neg_of_pos hr₀ h), }, end lemma summable_of_ratio_test_tendsto_lt_one {α : Type*} [normed_group α] [complete_space α] {f : ℕ → α} {l : ℝ} (hl₁ : l < 1) (hf : ∀ᶠ n in at_top, f n ≠ 0) (h : tendsto (λ n, ∥f (n+1)∥/∥f n∥) at_top (𝓝 l)) : summable f := begin rcases exists_between hl₁ with ⟨r, hr₀, hr₁⟩, refine summable_of_ratio_norm_eventually_le hr₁ _, filter_upwards [eventually_le_of_tendsto_lt hr₀ h, hf] with _ _ h₁, rwa ← div_le_iff (norm_pos_iff.mpr h₁), end lemma not_summable_of_ratio_norm_eventually_ge {α : Type*} [semi_normed_group α] {f : ℕ → α} {r : ℝ} (hr : 1 < r) (hf : ∃ᶠ n in at_top, ∥f n∥ ≠ 0) (h : ∀ᶠ n in at_top, r * ∥f n∥ ≤ ∥f (n+1)∥) : ¬ summable f := begin rw eventually_at_top at h, rcases h with ⟨N₀, hN₀⟩, rw frequently_at_top at hf, rcases hf N₀ with ⟨N, hNN₀ : N₀ ≤ N, hN⟩, rw ← @summable_nat_add_iff α _ _ _ _ N, refine mt summable.tendsto_at_top_zero (λ h', not_tendsto_at_top_of_tendsto_nhds (tendsto_norm_zero.comp h') _), convert tendsto_at_top_of_geom_le _ hr _, { refine lt_of_le_of_ne (norm_nonneg _) _, intro h'', specialize hN₀ N hNN₀, simp only [comp_app, zero_add] at h'', exact hN h''.symm }, { intro i, dsimp only [comp_app], convert (hN₀ (i + N) (hNN₀.trans (N.le_add_left i))) using 3, ac_refl } end lemma not_summable_of_ratio_test_tendsto_gt_one {α : Type*} [semi_normed_group α] {f : ℕ → α} {l : ℝ} (hl : 1 < l) (h : tendsto (λ n, ∥f (n+1)∥/∥f n∥) at_top (𝓝 l)) : ¬ summable f := begin have key : ∀ᶠ n in at_top, ∥f n∥ ≠ 0, { filter_upwards [eventually_ge_of_tendsto_gt hl h] with _ hn hc, rw [hc, div_zero] at hn, linarith }, rcases exists_between hl with ⟨r, hr₀, hr₁⟩, refine not_summable_of_ratio_norm_eventually_ge hr₀ key.frequently _, filter_upwards [eventually_ge_of_tendsto_gt hr₁ h, key] with _ _ h₁, rwa ← le_div_iff (lt_of_le_of_ne (norm_nonneg _) h₁.symm) end section /-! ### Dirichlet and alternating series tests -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {b : ℝ} {f : ℕ → ℝ} {z : ℕ → E} /-- **Dirichlet's Test** for monotone sequences. -/ theorem monotone.cauchy_seq_series_mul_of_tendsto_zero_of_bounded (hfa : monotone f) (hf0 : tendsto f at_top (𝓝 0)) (hgb : ∀ n, ∥∑ i in range n, z i∥ ≤ b) : cauchy_seq (λ n, ∑ i in range (n + 1), (f i) • z i) := begin simp_rw [finset.sum_range_by_parts _ _ (nat.succ _), sub_eq_add_neg, nat.succ_sub_succ_eq_sub, tsub_zero], apply (normed_field.tendsto_zero_smul_of_tendsto_zero_of_bounded hf0 ⟨b, eventually_map.mpr $ eventually_of_forall $ λ n, hgb $ n+1⟩).cauchy_seq.add, apply (cauchy_seq_range_of_norm_bounded _ _ (_ : ∀ n, _ ≤ b * |f(n+1) - f(n)|)).neg, { exact normed_uniform_group }, { simp_rw [abs_of_nonneg (sub_nonneg_of_le (hfa (nat.le_succ _))), ← mul_sum], apply real.uniform_continuous_mul_const.comp_cauchy_seq, simp_rw [sum_range_sub, sub_eq_add_neg], exact (tendsto.cauchy_seq hf0).add_const }, { intro n, rw [norm_smul, mul_comm], exact mul_le_mul_of_nonneg_right (hgb _) (abs_nonneg _) }, end /-- **Dirichlet's test** for antitone sequences. -/ theorem antitone.cauchy_seq_series_mul_of_tendsto_zero_of_bounded (hfa : antitone f) (hf0 : tendsto f at_top (𝓝 0)) (hzb : ∀ n, ∥∑ i in range n, z i∥ ≤ b) : cauchy_seq (λ n, ∑ i in range (n+1), (f i) • z i) := begin have hfa': monotone (λ n, -f n) := λ _ _ hab, neg_le_neg $ hfa hab, have hf0': tendsto (λ n, -f n) at_top (𝓝 0) := by { convert hf0.neg, norm_num }, convert (hfa'.cauchy_seq_series_mul_of_tendsto_zero_of_bounded hf0' hzb).neg, funext, simp end lemma norm_sum_neg_one_pow_le (n : ℕ) : ∥∑ i in range n, (-1 : ℝ) ^ i∥ ≤ 1 := by { rw [neg_one_geom_sum], split_ifs; norm_num } /-- The **alternating series test** for monotone sequences. See also `tendsto_alternating_series_of_monotone_tendsto_zero`. -/ theorem monotone.cauchy_seq_alternating_series_of_tendsto_zero (hfa : monotone f) (hf0 : tendsto f at_top (𝓝 0)) : cauchy_seq (λ n, ∑ i in range (n+1), (-1) ^ i * f i) := begin simp_rw [mul_comm], exact hfa.cauchy_seq_series_mul_of_tendsto_zero_of_bounded hf0 norm_sum_neg_one_pow_le end /-- The **alternating series test** for monotone sequences. -/ theorem monotone.tendsto_alternating_series_of_tendsto_zero (hfa : monotone f) (hf0 : tendsto f at_top (𝓝 0)) : ∃ l, tendsto (λ n, ∑ i in range (n+1), (-1) ^ i * f i) at_top (𝓝 l) := cauchy_seq_tendsto_of_complete $ hfa.cauchy_seq_alternating_series_of_tendsto_zero hf0 /-- The **alternating series test** for antitone sequences. See also `tendsto_alternating_series_of_antitone_tendsto_zero`. -/ theorem antitone.cauchy_seq_alternating_series_of_tendsto_zero (hfa : antitone f) (hf0 : tendsto f at_top (𝓝 0)) : cauchy_seq (λ n, ∑ i in range (n+1), (-1) ^ i * f i) := begin simp_rw [mul_comm], exact hfa.cauchy_seq_series_mul_of_tendsto_zero_of_bounded hf0 norm_sum_neg_one_pow_le end /-- The **alternating series test** for antitone sequences. -/ theorem antitone.tendsto_alternating_series_of_tendsto_zero (hfa : antitone f) (hf0 : tendsto f at_top (𝓝 0)) : ∃ l, tendsto (λ n, ∑ i in range (n+1), (-1) ^ i * f i) at_top (𝓝 l) := cauchy_seq_tendsto_of_complete $ hfa.cauchy_seq_alternating_series_of_tendsto_zero hf0 end /-! ### Factorial -/ /-- The series `∑' n, x ^ n / n!` is summable of any `x : ℝ`. See also `exp_series_div_summable` for a version that also works in `ℂ`, and `exp_series_summable'` for a version that works in any normed algebra over `ℝ` or `ℂ`. -/ lemma real.summable_pow_div_factorial (x : ℝ) : summable (λ n, x ^ n / n! : ℕ → ℝ) := begin -- We start with trivial extimates have A : (0 : ℝ) < ⌊∥x∥⌋₊ + 1, from zero_lt_one.trans_le (by simp), have B : ∥x∥ / (⌊∥x∥⌋₊ + 1) < 1, from (div_lt_one A).2 (nat.lt_floor_add_one _), -- Then we apply the ratio test. The estimate works for `n ≥ ⌊∥x∥⌋₊`. suffices : ∀ n ≥ ⌊∥x∥⌋₊, ∥x ^ (n + 1) / (n + 1)!∥ ≤ ∥x∥ / (⌊∥x∥⌋₊ + 1) * ∥x ^ n / ↑n!∥, from summable_of_ratio_norm_eventually_le B (eventually_at_top.2 ⟨⌊∥x∥⌋₊, this⟩), -- Finally, we prove the upper estimate intros n hn, calc ∥x ^ (n + 1) / (n + 1)!∥ = (∥x∥ / (n + 1)) * ∥x ^ n / n!∥ : by rw [pow_succ, nat.factorial_succ, nat.cast_mul, ← div_mul_div_comm, norm_mul, norm_div, real.norm_coe_nat, nat.cast_succ] ... ≤ (∥x∥ / (⌊∥x∥⌋₊ + 1)) * ∥x ^ n / n!∥ : by mono* with [0 ≤ ∥x ^ n / n!∥, 0 ≤ ∥x∥]; apply norm_nonneg end lemma real.tendsto_pow_div_factorial_at_top (x : ℝ) : tendsto (λ n, x ^ n / n! : ℕ → ℝ) at_top (𝓝 0) := (real.summable_pow_div_factorial x).tendsto_at_top_zero
90819692e071c103e5858854be470567400b44ef
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/ring2_auto.lean
0594d4d07969e9bf38e65daf7f25cf751ca384f3
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
10,928
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.ring import Mathlib.data.num.lemmas import Mathlib.data.tree import Mathlib.PostPort universes u_1 l namespace Mathlib /-! # ring2 An experimental variant on the `ring` tactic that uses computational reflection instead of proof generation. Useful for kernel benchmarking. -/ namespace tree /-- `(reflect' t u α)` quasiquotes a tree `(t: tree expr)` of quoted values of type `α` at level `u` into an `expr` which reifies to a `tree α` containing the reifications of the `expr`s from the original `t`. -/ /-- Returns an element indexed by `n`, or zero if `n` isn't a valid index. See `tree.get`. -/ protected def get_or_zero {α : Type u_1} [HasZero α] (t : tree α) (n : pos_num) : α := get_or_else n t 0 end tree namespace tactic.ring2 /-- A reflected/meta representation of an expression in a commutative semiring. This representation is a direct translation of such expressions - see `horner_expr` for a normal form. -/ /- (atom n) is an opaque element of the csring. For example, inductive csring_expr where | atom : pos_num → csring_expr | const : num → csring_expr | add : csring_expr → csring_expr → csring_expr | mul : csring_expr → csring_expr → csring_expr | pow : csring_expr → num → csring_expr a local variable in the context. n indexes into a storage of such atoms - a `tree α`. -/ /- (const n) is technically the csring's one, added n times. Or the zero if n is 0. -/ namespace csring_expr protected instance inhabited : Inhabited csring_expr := { default := const 0 } /-- Evaluates a reflected `csring_expr` into an element of the original `comm_semiring` type `α`, retrieving opaque elements (atoms) from the tree `t`. -/ def eval {α : Type u_1} [comm_semiring α] (t : tree α) : csring_expr → α := sorry end csring_expr /-- An efficient representation of expressions in a commutative semiring using the sparse Horner normal form. This type admits non-optimal instantiations (e.g. `P` can be represented as `P+0+0`), so to get good performance out of it, care must be taken to maintain an optimal, *canonical* form. -/ /- (const n) is a constant n in the csring, similarly to the same inductive horner_expr where | const : znum → horner_expr | horner : horner_expr → pos_num → num → horner_expr → horner_expr constructor in `csring_expr`. This one, however, can be negative. -/ /- (horner a x n b) is a*xⁿ + b, where x is the x-th atom in the atom tree. -/ namespace horner_expr /-- True iff the `horner_expr` argument is a valid `csring_expr`. For that to be the case, all its constants must be non-negative. -/ def is_cs : horner_expr → Prop := sorry protected instance has_zero : HasZero horner_expr := { zero := const 0 } protected instance has_one : HasOne horner_expr := { one := const 1 } protected instance inhabited : Inhabited horner_expr := { default := 0 } /-- Represent a `csring_expr.atom` in Horner form. -/ def atom (n : pos_num) : horner_expr := horner 1 n 1 0 def to_string : horner_expr → string := sorry protected instance has_to_string : has_to_string horner_expr := has_to_string.mk to_string /-- Alternative constructor for (horner a x n b) which maintains canonical form by simplifying special cases of `a`. -/ def horner' (a : horner_expr) (x : pos_num) (n : num) (b : horner_expr) : horner_expr := sorry def add_const (k : znum) (e : horner_expr) : horner_expr := ite (k = 0) e (horner_expr.rec (fun (n : znum) => const (k + n)) (fun (a : horner_expr) (x : pos_num) (n : num) (b A B : horner_expr) => horner a x n B) e) def add_aux (a₁ : horner_expr) (A₁ : horner_expr → horner_expr) (x₁ : pos_num) : horner_expr → num → horner_expr → (horner_expr → horner_expr) → horner_expr := sorry def add : horner_expr → horner_expr → horner_expr := sorry /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact add_const n₁ e₂ }, exact match e₂ with e₂ := begin induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁; let e₁ := horner a₁ x₁ n₁ b₁, { exact add_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, exact match pos_num.cmp x₁ x₂ with | ordering.lt := horner a₁ x₁ n₁ (B₁ e₂) | ordering.gt := horner a₂ x₂ n₂ (B₂ n₁ b₁) | ordering.eq := match num.sub' n₁ n₂ with | znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂) | (znum.pos k) := horner (A₂ k 0) x₁ n₂ (B₁ b₂) | (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂) end end end end end-/ def neg (e : horner_expr) : horner_expr := horner_expr.rec (fun (n : znum) => const (-n)) (fun (a : horner_expr) (x : pos_num) (n : num) (b A B : horner_expr) => horner A x n B) e def mul_const (k : znum) (e : horner_expr) : horner_expr := ite (k = 0) 0 (ite (k = 1) e (horner_expr.rec (fun (n : znum) => const (n * k)) (fun (a : horner_expr) (x : pos_num) (n : num) (b A B : horner_expr) => horner A x n B) e)) def mul_aux (a₁ : horner_expr) (x₁ : pos_num) (n₁ : num) (b₁ : horner_expr) (A₁ : horner_expr → horner_expr) (B₁ : horner_expr → horner_expr) : horner_expr → horner_expr := sorry def mul : horner_expr → horner_expr → horner_expr := sorry /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact mul_const n₁ e₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂; let e₁ := horner a₁ x₁ n₁ b₁, { exact mul_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, cases pos_num.cmp x₁ x₂, { exact horner (A₁ e₂) x₁ n₁ (B₁ e₂) }, { let haa := horner' A₂ x₁ n₂ 0, exact if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) }, { exact horner A₂ x₂ n₂ B₂ } end-/ protected instance has_add : Add horner_expr := { add := add } protected instance has_neg : Neg horner_expr := { neg := neg } protected instance has_mul : Mul horner_expr := { mul := mul } def pow (e : horner_expr) : num → horner_expr := sorry def inv (e : horner_expr) : horner_expr := 0 /-- Brings expressions into Horner normal form. -/ def of_csexpr : csring_expr → horner_expr := sorry /-- Evaluates a reflected `horner_expr` - see `csring_expr.eval`. -/ def cseval {α : Type u_1} [comm_semiring α] (t : tree α) : horner_expr → α := sorry theorem cseval_atom {α : Type u_1} [comm_semiring α] (t : tree α) (n : pos_num) : is_cs (atom n) ∧ cseval t (atom n) = tree.get_or_zero t n := { left := { left := Exists.intro 1 rfl, right := Exists.intro 0 rfl }, right := Eq.symm (ring.horner_atom (tree.get_or_zero t n)) } theorem cseval_add_const {α : Type u_1} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : is_cs e) : is_cs (add_const (num.to_znum k) e) ∧ cseval t (add_const (num.to_znum k) e) = ↑k + cseval t e := sorry theorem cseval_horner' {α : Type u_1} [comm_semiring α] (t : tree α) (a : horner_expr) (x : pos_num) (n : num) (b : horner_expr) (h₁ : is_cs a) (h₂ : is_cs b) : is_cs (horner' a x n b) ∧ cseval t (horner' a x n b) = ring.horner (cseval t a) (tree.get_or_zero t x) (↑n) (cseval t b) := sorry theorem cseval_add {α : Type u_1} [comm_semiring α] (t : tree α) {e₁ : horner_expr} {e₂ : horner_expr} (cs₁ : is_cs e₁) (cs₂ : is_cs e₂) : is_cs (add e₁ e₂) ∧ cseval t (add e₁ e₂) = cseval t e₁ + cseval t e₂ := sorry theorem cseval_mul_const {α : Type u_1} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : is_cs e) : is_cs (mul_const (num.to_znum k) e) ∧ cseval t (mul_const (num.to_znum k) e) = cseval t e * ↑k := sorry theorem cseval_mul {α : Type u_1} [comm_semiring α] (t : tree α) {e₁ : horner_expr} {e₂ : horner_expr} (cs₁ : is_cs e₁) (cs₂ : is_cs e₂) : is_cs (mul e₁ e₂) ∧ cseval t (mul e₁ e₂) = cseval t e₁ * cseval t e₂ := sorry theorem cseval_pow {α : Type u_1} [comm_semiring α] (t : tree α) {x : horner_expr} (cs : is_cs x) (n : num) : is_cs (pow x n) ∧ cseval t (pow x n) = cseval t x ^ ↑n := sorry /-- For any given tree `t` of atoms and any reflected expression `r`, the Horner form of `r` is a valid csring expression, and under `t`, the Horner form evaluates to the same thing as `r`. -/ theorem cseval_of_csexpr {α : Type u_1} [comm_semiring α] (t : tree α) (r : csring_expr) : is_cs (of_csexpr r) ∧ cseval t (of_csexpr r) = csring_expr.eval t r := sorry end horner_expr /-- The main proof-by-reflection theorem. Given reflected csring expressions `r₁` and `r₂` plus a storage `t` of atoms, if both expressions go to the same Horner normal form, then the original non-reflected expressions are equal. `H` follows from kernel reduction and is therefore `rfl`. -/ theorem correctness {α : Type u_1} [comm_semiring α] (t : tree α) (r₁ : csring_expr) (r₂ : csring_expr) (H : horner_expr.of_csexpr r₁ = horner_expr.of_csexpr r₂) : csring_expr.eval t r₁ = csring_expr.eval t r₂ := sorry /-- Reflects a csring expression into a `csring_expr`, together with a dlist of atoms, i.e. opaque variables over which the expression is a polynomial. -/ /-| `(%%e₁ - %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.add r₂.neg, l₁ ++ l₂) | `(- %%e) := let (r, l) := reflect_expr e in (r.neg, l)-/ /-| `(has_inv.inv %%e) := let (r, l) := reflect_expr e in (r.neg, l) | `(%%e₁ / %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.mul r₂.inv, l₁ ++ l₂)-/ /-- In the output of `reflect_expr`, `atom`s are initialized with incorrect indices. The indices cannot be computed until the whole tree is built, so another pass over the expressions is needed - this is what `replace` does. The computation (expressed in the state monad) fixes up `atom`s to match their positions in the atom tree. The initial state is a list of all atom occurrences in the goal, left-to-right. -/ --| (csring_expr.neg x) := csring_expr.neg <$> x.replace --| (csring_expr.inv x) := csring_expr.inv <$> x.replace end tactic.ring2 namespace tactic namespace interactive /-- `ring2` solves equations in the language of rings. It supports only the commutative semiring operations, i.e. it does not normalize subtraction or division. This variant on the `ring` tactic uses kernel computation instead of proof generation. In general, you should use `ring` instead of `ring2`. -/ end Mathlib
3acdb7fba8527610413e7cd4190273ebc7d534e9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/sites/types.lean
1ac459a8079c4bf71fdc8612580ab4b9d26709be
[ "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
7,495
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import category_theory.sites.canonical /-! # Grothendieck Topology and Sheaves on the Category of Types In this file we define a Grothendieck topology on the category of types, and construct the canonical functor that sends a type to a sheaf over the category of types, and make this an equivalence of categories. Then we prove that the topology defined is the canonical topology. -/ universe u namespace category_theory open_locale category_theory.Type /-- A Grothendieck topology associated to the category of all types. A sieve is a covering iff it is jointly surjective. -/ def types_grothendieck_topology : grothendieck_topology (Type u) := { sieves := λ α S, ∀ x : α, S (λ _ : punit, x), top_mem' := λ α x, trivial, pullback_stable' := λ α β S f hs x, hs (f x), transitive' := λ α S hs R hr x, hr (hs x) punit.star } /-- The discrete sieve on a type, which only includes arrows whose image is a subsingleton. -/ @[simps] def discrete_sieve (α : Type u) : sieve α := { arrows := λ β f, ∃ x, ∀ y, f y = x, downward_closed' := λ β γ f ⟨x, hx⟩ g, ⟨x, λ y, hx $ g y⟩ } lemma discrete_sieve_mem (α : Type u) : discrete_sieve α ∈ types_grothendieck_topology α := λ x, ⟨x, λ y, rfl⟩ /-- The discrete presieve on a type, which only includes arrows whose domain is a singleton. -/ def discrete_presieve (α : Type u) : presieve α := λ β f, ∃ x : β, ∀ y : β, y = x lemma generate_discrete_presieve_mem (α : Type u) : sieve.generate (discrete_presieve α) ∈ types_grothendieck_topology α := λ x, ⟨punit, id, λ _, x, ⟨punit.star, λ _, subsingleton.elim _ _⟩, rfl⟩ open presieve theorem is_sheaf_yoneda' {α : Type u} : is_sheaf types_grothendieck_topology (yoneda.obj α) := λ β S hs x hx, ⟨λ y, x _ (hs y) punit.star, λ γ f h, funext $ λ z, have _ := congr_fun (hx (𝟙 _) (λ _, z) (hs $ f z) h rfl) punit.star, by { convert this, exact rfl }, λ f hf, funext $ λ y, by convert congr_fun (hf _ (hs y)) punit.star⟩ /-- The yoneda functor that sends a type to a sheaf over the category of types -/ @[simps] def yoneda' : Type u ⥤ SheafOfTypes types_grothendieck_topology := { obj := λ α, ⟨yoneda.obj α, is_sheaf_yoneda'⟩, map := λ α β f, yoneda.map f } @[simp] lemma yoneda'_comp : yoneda'.{u} ⋙ induced_functor _ = yoneda := rfl open opposite /-- Given a presheaf `P` on the category of types, construct a map `P(α) → (α → P(*))` for all type `α`. -/ def eval (P : (Type u)ᵒᵖ ⥤ Type u) (α : Type u) (s : P.obj (op α)) (x : α) : P.obj (op punit) := P.map (↾λ _, x).op s /-- Given a sheaf `S` on the category of types, construct a map `(α → S(*)) → S(α)` that is inverse to `eval`. -/ noncomputable def types_glue (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) (α : Type u) (f : α → S.obj (op punit)) : S.obj (op α) := (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem α)).amalgamate (λ β g hg, S.map (↾λ x, punit.star).op $ f $ g $ classical.some hg) (λ β γ δ g₁ g₂ f₁ f₂ hf₁ hf₂ h, (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem δ)).is_separated_for.ext $ λ ε g ⟨x, hx⟩, have f₁ (classical.some hf₁) = f₂ (classical.some hf₂), from classical.some_spec hf₁ (g₁ $ g x) ▸ classical.some_spec hf₂ (g₂ $ g x) ▸ congr_fun h _, by { simp_rw [← functor_to_types.map_comp_apply, this, ← op_comp], refl }) lemma eval_types_glue {S hs α} (f) : eval.{u} S α (types_glue S hs α f) = f := funext $ λ x, (is_sheaf_for.valid_glue _ _ _ $ by exact ⟨punit.star, λ _, subsingleton.elim _ _⟩).trans $ by { convert functor_to_types.map_id_apply _ _, rw ← op_id, congr } lemma types_glue_eval {S hs α} (s) : types_glue.{u} S hs α (eval S α s) = s := (hs.is_sheaf_for _ _ (generate_discrete_presieve_mem α)).is_separated_for.ext $ λ β f hf, (is_sheaf_for.valid_glue _ _ _ hf).trans $ (functor_to_types.map_comp_apply _ _ _ _).symm.trans $ by { rw ← op_comp, congr' 2, exact funext (λ x, congr_arg f (classical.some_spec hf x).symm) } /-- Given a sheaf `S`, construct an equivalence `S(α) ≃ (α → S(*))`. -/ @[simps] noncomputable def eval_equiv (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) (α : Type u) : S.obj (op α) ≃ (α → S.obj (op punit)) := { to_fun := eval S α, inv_fun := types_glue S hs α, left_inv := types_glue_eval, right_inv := eval_types_glue } lemma eval_map (S : (Type u)ᵒᵖ ⥤ Type u) (α β) (f : β ⟶ α) (s x) : eval S β (S.map f.op s) x = eval S α s (f x) := by { simp_rw [eval, ← functor_to_types.map_comp_apply, ← op_comp], refl } /-- Given a sheaf `S`, construct an isomorphism `S ≅ [-, S(*)]`. -/ @[simps] noncomputable def equiv_yoneda (S : (Type u)ᵒᵖ ⥤ Type u) (hs : is_sheaf types_grothendieck_topology S) : S ≅ yoneda.obj (S.obj (op punit)) := nat_iso.of_components (λ α, equiv.to_iso $ eval_equiv S hs $ unop α) $ λ α β f, funext $ λ s, funext $ λ x, eval_map S (unop α) (unop β) f.unop _ _ /-- Given a sheaf `S`, construct an isomorphism `S ≅ [-, S(*)]`. -/ @[simps] noncomputable def equiv_yoneda' (S : SheafOfTypes types_grothendieck_topology) : S ≅ yoneda'.obj (S.1.obj (op punit)) := { hom := (equiv_yoneda S.1 S.2).hom, inv := (equiv_yoneda S.1 S.2).inv, hom_inv_id' := (equiv_yoneda S.1 S.2).hom_inv_id, inv_hom_id' := (equiv_yoneda S.1 S.2).inv_hom_id } lemma eval_app (S₁ S₂ : SheafOfTypes.{u} types_grothendieck_topology) (f : S₁ ⟶ S₂) (α : Type u) (s : S₁.1.obj (op α)) (x : α) : eval S₂.1 α (f.app (op α) s) x = f.app (op punit) (eval S₁.1 α s x) := (congr_fun (f.2 (↾λ _ : punit, x).op) s).symm /-- `yoneda'` induces an equivalence of category between `Type u` and `Sheaf types_grothendieck_topology`. -/ @[simps] noncomputable def type_equiv : Type u ≌ SheafOfTypes types_grothendieck_topology := equivalence.mk yoneda' (induced_functor _ ⋙ (evaluation _ _).obj (op punit)) (nat_iso.of_components (λ α, /- α ≅ punit ⟶ α -/ { hom := λ x _, x, inv := λ f, f punit.star, hom_inv_id' := funext $ λ x, rfl, inv_hom_id' := funext $ λ f, funext $ λ y, punit.cases_on y rfl }) (λ α β f, rfl)) (iso.symm $ nat_iso.of_components (λ S, equiv_yoneda' S) (λ S₁ S₂ f, nat_trans.ext _ _ $ funext $ λ α, funext $ λ s, funext $ λ x, eval_app S₁ S₂ f (unop α) s x)) lemma subcanonical_types_grothendieck_topology : sheaf.subcanonical types_grothendieck_topology.{u} := sheaf.subcanonical.of_yoneda_is_sheaf _ (λ X, is_sheaf_yoneda') lemma types_grothendieck_topology_eq_canonical : types_grothendieck_topology.{u} = sheaf.canonical_topology (Type u) := le_antisymm subcanonical_types_grothendieck_topology $ Inf_le ⟨yoneda.obj (ulift bool), ⟨_, rfl⟩, grothendieck_topology.ext $ funext $ λ α, set.ext $ λ S, ⟨λ hs x, classical.by_contradiction $ λ hsx, have (λ _, ulift.up tt : (yoneda.obj (ulift bool)).obj (op punit)) = λ _, ulift.up ff := (hs punit (λ _, x)).is_separated_for.ext $ λ β f hf, funext $ λ y, hsx.elim $ S.2 hf $ λ _, y, bool.no_confusion $ ulift.up.inj $ (congr_fun this punit.star : _), λ hs β f, is_sheaf_yoneda' _ $ λ y, hs _⟩⟩ end category_theory
9239144294e7b4b8b939246fdb93dc1a592515fe
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/analysis/normed_space/operator_norm.lean
ee56bd5da6508f2940a7b19cea43c697e5246891
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,937
lean
/- Copyright (c) 2019 Jan-David Salchow. 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 -/ import linear_algebra.finite_dimensional import analysis.normed_space.riesz_lemma import analysis.asymptotics /-! # Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. -/ noncomputable theory open_locale classical variables {𝕜 : Type*} {E : Type*} {F : Type*} {G : Type*} [normed_group E] [normed_group F] [normed_group G] open metric continuous_linear_map lemma exists_pos_bound_of_bound {f : E → F} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ section normed_field /- Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality `∥f x∥ ≤ C ∥x∥` from the continuity of f. However, the other direction always holds. In this section, we just assume that `𝕜` is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) theorem linear_map.antilipschitz_of_bound {K : nnreal} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. The fact that the norm of the continuous linear map is then controlled is given in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, linear_map.continuous_of_bound f C h⟩ /-- Reinterpret a linear map `𝕜 →ₗ[𝕜] E` as a continuous linear map. This construction is generalized to the case of any finite dimensional domain in `linear_map.to_continuous_linear_map`. -/ def linear_map.to_continuous_linear_map₁ (f : 𝕜 →ₗ[𝕜] E) : 𝕜 →L[𝕜] E := f.mk_continuous (∥f 1∥) $ λ x, le_of_eq $ by { conv_lhs { rw ← mul_one x }, rw [← smul_eq_mul, f.map_smul, norm_smul, mul_comm] } /-- Construct a continuous linear map from a linear map and the existence of a bound on this linear map. If you have an explicit bound, use `linear_map.mk_continuous` instead, as a norm estimate will follow automatically in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous_of_exists_bound (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ lemma continuous_of_linear_of_bound {f : E → F} (h_add : ∀ x y, f (x + y) = f x + f y) (h_smul : ∀ (c : 𝕜) x, f (c • x) = c • f x) {C : ℝ} (h_bound : ∀ x, ∥f x∥ ≤ C*∥x∥) : continuous f := let φ : E →ₗ[𝕜] F := ⟨f, h_add, h_smul⟩ in φ.continuous_of_bound C h_bound @[simp, norm_cast] lemma linear_map.mk_continuous_coe (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous C h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_apply (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous C h x = f x := rfl @[simp, norm_cast] lemma linear_map.mk_continuous_of_exists_bound_coe (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous_of_exists_bound h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_of_exists_bound_apply (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous_of_exists_bound h x = f x := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_coe (f : 𝕜 →ₗ[𝕜] E) : (f.to_continuous_linear_map₁ : 𝕜 →ₗ[𝕜] E) = f := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_apply (f : 𝕜 →ₗ[𝕜] E) (x) : f.to_continuous_linear_map₁ x = f x := rfl lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (continuous_iff_is_closed.1 h) {0} (t1_space.t1 0), λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if `f = 0`, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if `f` is not zero, we use an element `x₀ ∉ ker f` such that `∥x₀∥ ≤ 2 ∥x₀ - y∥` for all `y ∈ ker f`, given by Riesz's lemma, and prove that `2 ∥f x₀∥ / ∥x₀∥` gives a bound on the operator norm of `f`. For this, start from an arbitrary `x` and note that `y = x₀ - (f x₀ / f x) x` belongs to the kernel of `f`. Applying the above inequality to `x₀` and `y` readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero_mem }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], norm_num }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg, norm_nonneg, inv_nonneg.2] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by simp [y] ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, normed_field.norm_mul, normed_field.norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 /-- A continuous linear map between normed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius `δ`. The nondiscreteness is then used to rescale any element into an element of norm in `[δ/C, δ]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₗ[𝕜] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin have : continuous_at f 0 := continuous_iff_continuous_at.1 hf _, rcases metric.tendsto_nhds_nhds.1 this 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, let δ := ε/2, have δ_pos : δ > 0 := half_pos ε_pos, have H : ∀{a}, ∥a∥ ≤ δ → ∥f a∥ ≤ 1, { assume a ha, have : dist (f a) (f 0) ≤ 1, { apply le_of_lt (hε _), rw [dist_eq_norm, sub_zero], exact lt_of_le_of_lt ha (half_lt_self ε_pos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨δ⁻¹ * ∥c∥, mul_pos (inv_pos.2 δ_pos) (lt_trans zero_lt_one hc), (λx, _)⟩, by_cases h : x = 0, { simp only [h, norm_zero, mul_zero, linear_map.map_zero] }, { rcases rescale_to_shell hc δ_pos h with ⟨d, hd, dxle, ledx, dinv⟩, calc ∥f x∥ = ∥f ((d⁻¹ * d) • x)∥ : by rwa [inv_mul_cancel, one_smul] ... = ∥d∥⁻¹ * ∥f (d • x)∥ : by rw [mul_smul, linear_map.map_smul, norm_smul, normed_field.norm_inv] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left (H dxle) (by { rw ← normed_field.norm_inv, exact norm_nonneg _ }) ... ≤ δ⁻¹ * ∥c∥ * ∥x∥ : by { rw mul_one, exact dinv } } end namespace continuous_linear_map theorem bound : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open asymptotics filter theorem is_O_id (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := f.bound in is_O_of_le' l hM theorem is_O_comp {α : Type*} (g : F →L[𝕜] G) (f : α → F) (l : filter α) : is_O (λ x', g (f x')) f l := (g.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_comp _ l /-- A linear map which is a homothety is a continuous linear map. Since the field `𝕜` need not have `ℝ` as a subfield, this theorem is not directly deducible from the corresponding theorem about isometries plus a theorem about scalar multiplication. Likewise for the other theorems about homotheties in this file. -/ def of_homothety (f : E →ₗ[𝕜] F) (a : ℝ) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E →L[𝕜] F := f.mk_continuous a (λ x, le_of_eq (hf x)) variable (𝕜) lemma to_span_singleton_homothety (x : E) (c : 𝕜) : ∥linear_map.to_span_singleton 𝕜 E x c∥ = ∥x∥ * ∥c∥ := by {rw mul_comm, exact norm_smul _ _} /-- Given an element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from `E` to the span of `x`.-/ def to_span_singleton (x : E) : 𝕜 →L[𝕜] E := of_homothety (linear_map.to_span_singleton 𝕜 E x) ∥x∥ (to_span_singleton_homothety 𝕜 x) end section op_norm open set real /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (E →L[𝕜] F) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : E →L[𝕜] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →L[𝕜] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := classical.by_cases (λ heq : x = 0, by { rw heq, simp }) (λ hne, have hlt : 0 < ∥x∥, from norm_pos_iff.2 hne, (div_le_iff hlt).mp ((le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc }))) theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_iff_of_nonneg_of_le (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := mul_one ∥f∥ ▸ f.le_op_norm_of_le /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : E →L[𝕜] F} {K : nnreal} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 lemma op_norm_le_of_ball {f : E →L[𝕜] F} {ε : ℝ} {C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) (hf : ∀ x ∈ ball (0 : E) ε, ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin apply f.op_norm_le_bound hC, intros x, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, by_cases hx : x = 0, { simp [hx] }, rcases rescale_to_shell hc (half_pos ε_pos) hx with ⟨δ, hδ, δxle, leδx, δinv⟩, have δx_in : δ • x ∈ ball (0 : E) ε, { rw [mem_ball, dist_eq_norm, sub_zero], linarith }, calc ∥f x∥ = ∥f ((1/δ) • δ • x)∥ : by simp [hδ, smul_smul] ... = ∥1/δ∥ * ∥f (δ • x)∥ : by simp [norm_smul] ... ≤ ∥1/δ∥ * (C*∥δ • x∥) : mul_le_mul_of_nonneg_left _ (norm_nonneg _) ... = C * ∥x∥ : by { rw norm_smul, field_simp [hδ], ring }, exact hf _ δx_in end lemma op_norm_eq_of_bounds {φ : E →L[𝕜] F} {M : ℝ} (M_nonneg : 0 ≤ M) (h_above : ∀ x, ∥φ x∥ ≤ M*∥x∥) (h_below : ∀ N ≥ 0, (∀ x, ∥φ x∥ ≤ N*∥x∥) → M ≤ N) : ∥φ∥ = M := le_antisymm (φ.op_norm_le_bound M_nonneg h_above) ((le_cInf_iff continuous_linear_map.bounds_bdd_below ⟨M, M_nonneg, h_above⟩).mpr $ λ N ⟨N_nonneg, hN⟩, h_below N N_nonneg hN) /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := show ∥f + g∥ ≤ (coe : nnreal → ℝ) (⟨_, f.op_norm_nonneg⟩ + ⟨_, g.op_norm_nonneg⟩), from op_norm_le_of_lipschitz (f.lipschitz.add g.lipschitz) /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥id 𝕜 E∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If a space is non-trivial, then the norm of the identity equals `1`. -/ lemma norm_id [nontrivial E] : ∥id 𝕜 E∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := exists_ne (0 : E) in have _ := (id 𝕜 E).ratio_le_op_norm x, by rwa [id_apply, div_self (ne_of_gt $ norm_pos_iff.2 hx)] at this @[simp] lemma norm_id_field : ∥id 𝕜 𝕜∥ = 1 := norm_id @[simp] lemma norm_id_field' : ∥(1 : 𝕜 →L[𝕜] 𝕜)∥ = 1 := norm_id_field lemma op_norm_smul_le : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (E →L[𝕜] F) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (E →L[𝕜] F) := ⟨op_norm_smul_le⟩ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →L[𝕜] F) : ∥h.comp f∥ ≤ ∥h∥ * ∥f∥ := (Inf_le _ bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) /-- Continuous linear maps form a normed ring with respect to the operator norm. -/ instance to_normed_ring : normed_ring (E →L[𝕜] E) := { norm_mul := op_norm_comp_le, .. continuous_linear_map.to_normed_group } /-- For a nonzero normed space `E`, continuous linear endomorphisms form a normed algebra with respect to the operator norm. -/ instance to_normed_algebra [nontrivial E] : normed_algebra 𝕜 (E →L[𝕜] E) := { norm_algebra_map_eq := λ c, show ∥c • id 𝕜 E∥ = ∥c∥, by {rw [norm_smul, norm_id], simp}, .. continuous_linear_map.algebra } /-- A continuous linear map is automatically uniformly continuous. -/ protected theorem uniform_continuous : uniform_continuous f := f.lipschitz.uniform_continuous variable {f} /-- A continuous linear map is an isometry if and only if it preserves the norm. -/ lemma isometry_iff_norm_image_eq_norm : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := begin rw isometry_emetric_iff_metric, split, { assume H x, have := H x 0, rwa [dist_eq_norm, dist_eq_norm, f.map_zero, sub_zero, sub_zero] at this }, { assume H x y, rw [dist_eq_norm, dist_eq_norm, ← f.map_sub, H] } end lemma homothety_norm [nontrivial E] (f : E →L[𝕜] F) {a : ℝ} (hf : ∀x, ∥f x∥ = a * ∥x∥) : ∥f∥ = a := begin obtain ⟨x, hx⟩ : ∃ (x : E), x ≠ 0 := exists_ne 0, have ha : 0 ≤ a, { apply nonneg_of_mul_nonneg_right, rw ← hf x, apply norm_nonneg, exact norm_pos_iff.mpr hx }, refine le_antisymm_iff.mpr ⟨_, _⟩, { exact continuous_linear_map.op_norm_le_bound f ha (λ y, le_of_eq (hf y)) }, { rw continuous_linear_map.norm_def, apply real.lb_le_Inf _ continuous_linear_map.bounds_nonempty, intros c h, rw mem_set_of_eq at h, apply (mul_le_mul_right (norm_pos_iff.mpr hx)).mp, rw ← hf x, exact h.2 x } end lemma to_span_singleton_norm (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := homothety_norm _ (to_span_singleton_homothety 𝕜 x) variable (f) theorem uniform_embedding_of_bound {K : nnreal} (hf : ∀ x, ∥x∥ ≤ K * ∥f x∥) : uniform_embedding f := (f.to_linear_map.antilipschitz_of_bound hf).uniform_embedding f.uniform_continuous /-- If a continuous linear map is a uniform embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_uniform_embedding (hf : uniform_embedding f) : ∃ K, antilipschitz_with K f := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { apply le_of_lt, apply hε, simp [dist_eq_norm], exact lt_of_le_of_lt hx (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨⟨δ⁻¹, _⟩ * nnnorm c, f.to_linear_map.antilipschitz_of_bound $ λx, _⟩, exact inv_nonneg.2 (le_of_lt δ_pos), by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxle, ledx, dinv⟩, have : ∥f (d • x)∥ ≤ δ, by simpa, have : ∥d • x∥ ≤ 1 := H this, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← normed_field.norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section completeness open_locale topological_space open filter /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. -/ instance [complete_space F] : complete_space (E →L[𝕜] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, clear hf, -- and establish that the evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∥v∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (norm_nonneg _) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (norm_nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is linear, let Glin : E →ₗ[𝕜] F := { to_fun := G, map_add' := λ v w, begin have A := hG (v + w), have B := (hG v).add (hG w), simp only [map_add] at A B, exact tendsto_nhds_unique A B, end, map_smul' := λ c v, begin have A := hG (c • v), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hG v), simp only [map_smul] at A B, exact tendsto_nhds_unique A B end }, -- and that `G` has norm at most `(b 0 + ∥f 0∥)`. have Gnorm : ∀ v, ∥G v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (norm_nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hG v).norm (eventually_of_forall A) }, -- Thus `G` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Gcont := Glin.mk_continuous _ Gnorm, use Gcont, -- Our last task is to establish convergence to `G` in norm. have : ∀ n, ∥f n - Gcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∥v∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (norm_nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Gcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hG v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] G) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →L[𝕜] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] G`. -/ def extend : G →L[𝕜] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, map_add' := begin refine h_dense.induction_on₂ _ _, { exact is_closed_eq (cont.comp continuous_add) ((cont.comp continuous_fst).add (cont.comp continuous_snd)) }, { assume x y, simp only [eq, ← e.map_add], exact f.map_add _ _ }, end, map_smul' := λk, begin refine (λ b, h_dense.induction_on b _ _), { exact is_closed_eq (cont.comp (continuous_const.smul continuous_id)) ((continuous_const.smul continuous_id).comp cont) }, { assume x, rw ← map_smul, simp only [eq], exact map_smul _ _ _ }, end, cont := cont } lemma extend_unique (g : G →L[𝕜] F) (H : g.comp e = f) : extend f e h_dense h_e = g := continuous_linear_map.coe_fn_injective $ uniformly_extend_unique h_e h_dense (continuous_linear_map.ext_iff.1 H) g.continuous @[simp] lemma extend_zero : extend (0 : E →L[𝕜] F) e h_dense h_e = 0 := extend_unique _ _ _ _ _ (zero_comp _) end section variables {N : nnreal} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm ↑N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm end continuous_linear_map /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma linear_map.mk_continuous_norm_le (f : E →ₗ[𝕜] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h namespace continuous_linear_map /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma norm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : ∥f∥ = 0, { rw h, simp [norm_nonneg] }, { have : 0 < ∥f∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm h), rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) (norm_nonneg f)) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥((smul_right c f) : E → F) x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end /-- Given `c : c : E →L[𝕜] 𝕜`, `c.smul_rightL` is the continuous linear map from `F` to `E →L[𝕜] F` sending `f` to `λ e, c e • f`. -/ def smul_rightL (c : E →L[𝕜] 𝕜) : F →L[𝕜] (E →L[𝕜] F) := (c.smul_rightₗ : F →ₗ[𝕜] (E →L[𝕜] F)).mk_continuous _ (λ f, le_of_eq $ c.norm_smul_right_apply f) @[simp] lemma norm_smul_rightL_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥c.smul_rightL f∥ = ∥c∥ * ∥f∥ := by simp [continuous_linear_map.smul_rightL, continuous_linear_map.smul_rightₗ] @[simp] lemma norm_smul_rightL (c : E →L[𝕜] 𝕜) [nontrivial F] : ∥(c.smul_rightL : F →L[𝕜] (E →L[𝕜] F))∥ = ∥c∥ := continuous_linear_map.homothety_norm _ c.norm_smul_right_apply variables (𝕜 F) /-- The linear map obtained by applying a continuous linear map at a given vector. -/ def applyₗ (v : E) : (E →L[𝕜] F) →ₗ[𝕜] F := { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v } lemma continuous_applyₗ (v : E) : continuous (continuous_linear_map.applyₗ 𝕜 F v) := begin apply (continuous_linear_map.applyₗ 𝕜 F v).continuous_of_bound, intro f, rw mul_comm, exact f.le_op_norm v, end /-- The continuous linear map obtained by applying a continuous linear map at a given vector. -/ def apply (v : E) : (E →L[𝕜] F) →L[𝕜] F := ⟨continuous_linear_map.applyₗ 𝕜 F v, continuous_linear_map.continuous_applyₗ _ _ _⟩ variables {𝕜 F} section multiplication_linear variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] /-- Left-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_left 𝕜 𝕜' x).mk_continuous ∥x∥ (λ y, by {rw algebra.lmul_left_apply, exact norm_mul_le x y}) /-- Right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_right : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_right 𝕜 𝕜' x).mk_continuous ∥x∥ (λ y, by {rw [algebra.lmul_right_apply, mul_comm], exact norm_mul_le y x}) /-- Simultaneous left- and right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left_right (vw : 𝕜' × 𝕜') : 𝕜' →L[𝕜] 𝕜' := (lmul_right 𝕜 𝕜' vw.2).comp (lmul_left 𝕜 𝕜' vw.1) @[simp] lemma lmul_left_apply (x y : 𝕜') : lmul_left 𝕜 𝕜' x y = x * y := rfl @[simp] lemma lmul_right_apply (x y : 𝕜') : lmul_right 𝕜 𝕜' x y = y * x := rfl @[simp] lemma lmul_left_right_apply (vw : 𝕜' × 𝕜') (x : 𝕜') : lmul_left_right 𝕜 𝕜' vw x = vw.1 * x * vw.2 := rfl end multiplication_linear section restrict_scalars variable (𝕜) variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E' : Type*} [normed_group E'] [normed_space 𝕜' E'] {F' : Type*} [normed_group F'] [normed_space 𝕜' F'] /-- `𝕜`-linear continuous function induced by a `𝕜'`-linear continuous function when `𝕜'` is a normed algebra over `𝕜`. -/ def restrict_scalars (f : E' →L[𝕜'] F') : (semimodule.restrict_scalars 𝕜 𝕜' E') →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F') := { cont := f.cont, ..linear_map.restrict_scalars 𝕜 (f.to_linear_map) } @[simp, norm_cast] lemma restrict_scalars_coe_eq_coe (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : (semimodule.restrict_scalars 𝕜 𝕜' E') →ₗ[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F')) = (f : E' →ₗ[𝕜'] F').restrict_scalars 𝕜 := rfl @[simp, norm_cast squash] lemma restrict_scalars_coe_eq_coe' (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' → F') = f := rfl end restrict_scalars section extend_scalars variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {F' : Type*} [normed_group F'] [normed_space 𝕜' F'] instance has_scalar_extend_scalars : has_scalar 𝕜' (E →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F')) := { smul := λ c f, (c • f.to_linear_map).mk_continuous (∥c∥ * ∥f∥) begin assume x, calc ∥c • (f x)∥ = ∥c∥ * ∥f x∥ : norm_smul c _ ... ≤ ∥c∥ * (∥f∥ * ∥x∥) : mul_le_mul_of_nonneg_left (le_op_norm f x) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : (mul_assoc _ _ _).symm end } instance module_extend_scalars : module 𝕜' (E →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F')) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } instance normed_space_extend_scalars : normed_space 𝕜' (E →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F')) := { norm_smul_le := λ c f, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ } /-- When `f` is a continuous linear map taking values in `S`, then `λb, f b • x` is a continuous linear map. -/ def smul_algebra_right (f : E →L[𝕜] 𝕜') (x : semimodule.restrict_scalars 𝕜 𝕜' F') : E →L[𝕜] (semimodule.restrict_scalars 𝕜 𝕜' F') := { cont := by continuity!, .. smul_algebra_right f.to_linear_map x } @[simp] theorem smul_algebra_right_apply (f : E →L[𝕜] 𝕜') (x : semimodule.restrict_scalars 𝕜 𝕜' F') (c : E) : smul_algebra_right f x c = f c • x := rfl end extend_scalars section has_sum variables {ι : Type*} /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma has_sum {f : ι → E} (φ : E →L[𝕜] F) {x : E} (hf : has_sum f x) : has_sum (λ (b:ι), φ (f b)) (φ x) := begin unfold has_sum, convert φ.continuous.continuous_at.tendsto.comp hf, ext s, rw [function.comp_app, finset.sum_hom s φ], end lemma has_sum_of_summable {f : ι → E} (φ : E →L[𝕜] F) (hf : summable f) : has_sum (λ (b:ι), φ (f b)) (φ (∑'b, f b)) := φ.has_sum hf.has_sum end has_sum end continuous_linear_map namespace continuous_linear_equiv variable (e : E ≃L[𝕜] F) protected lemma lipschitz : lipschitz_with (nnnorm (e : E →L[𝕜] F)) e := (e : E →L[𝕜] F).lipschitz protected lemma antilipschitz : antilipschitz_with (nnnorm (e.symm : F →L[𝕜] E)) e := e.symm.lipschitz.to_right_inverse e.left_inv theorem is_O_comp {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O (λ x', e (f x')) f l := (e : E →L[𝕜] F).is_O_comp f l theorem is_O_sub (l : filter E) (x : E) : asymptotics.is_O (λ x', e (x' - x)) (λ x', x' - x) l := (e : E →L[𝕜] F).is_O_sub l x theorem is_O_comp_rev {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O f (λ x', e (f x')) l := (e.symm.is_O_comp _ l).congr_left $ λ _, e.symm_apply_apply _ theorem is_O_sub_rev (l : filter E) (x : E) : asymptotics.is_O (λ x', x' - x) (λ x', e (x' - x)) l := e.is_O_comp_rev _ _ /-- A continuous linear equiv is a uniform embedding. -/ lemma uniform_embedding : uniform_embedding e := e.antilipschitz.uniform_embedding e.lipschitz.uniform_continuous lemma one_le_norm_mul_norm_symm [nontrivial E] : 1 ≤ ∥(e : E →L[𝕜] F)∥ * ∥(e.symm : F →L[𝕜] E)∥ := begin rw [mul_comm], convert (e.symm : F →L[𝕜] E).op_norm_comp_le (e : E →L[𝕜] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id] end lemma norm_pos [nontrivial E] : 0 < ∥(e : E →L[𝕜] F)∥ := pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma norm_symm_pos [nontrivial E] : 0 < ∥(e.symm : F →L[𝕜] E)∥ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma subsingleton_or_norm_symm_pos : subsingleton E ∨ 0 < ∥(e.symm : F →L[𝕜] E)∥ := begin rcases subsingleton_or_nontrivial E with _i|_i; resetI, { left, apply_instance }, { right, exact e.norm_symm_pos } end lemma subsingleton_or_nnnorm_symm_pos : subsingleton E ∨ 0 < (nnnorm $ (e.symm : F →L[𝕜] E)) := subsingleton_or_norm_symm_pos e lemma homothety_inverse (a : ℝ) (ha : 0 < a) (f : E ≃ₗ[𝕜] F) : (∀ (x : E), ∥f x∥ = a * ∥x∥) → (∀ (y : F), ∥f.symm y∥ = a⁻¹ * ∥y∥) := begin intros hf y, calc ∥(f.symm) y∥ = a⁻¹ * (a * ∥ (f.symm) y∥) : _ ... = a⁻¹ * ∥f ((f.symm) y)∥ : by rw hf ... = a⁻¹ * ∥y∥ : by simp, rw [← mul_assoc, inv_mul_cancel (ne_of_lt ha).symm, one_mul], end variable (𝕜) /-- A linear equivalence which is a homothety is a continuous linear equivalence. -/ def of_homothety (f : E ≃ₗ[𝕜] F) (a : ℝ) (ha : 0 < a) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := f, continuous_to_fun := f.to_linear_map.continuous_of_bound a (λ x, le_of_eq (hf x)), continuous_inv_fun := f.symm.to_linear_map.continuous_of_bound a⁻¹ (λ x, le_of_eq (homothety_inverse a ha f hf x)) } lemma to_span_nonzero_singleton_homothety (x : E) (h : x ≠ 0) (c : 𝕜) : ∥linear_equiv.to_span_nonzero_singleton 𝕜 E x h c∥ = ∥x∥ * ∥c∥ := continuous_linear_map.to_span_singleton_homothety _ _ _ /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear equivalence from `E` to the span of `x`.-/ def to_span_nonzero_singleton (x : E) (h : x ≠ 0) : 𝕜 ≃L[𝕜] (submodule.span 𝕜 ({x} : set E)) := of_homothety 𝕜 (linear_equiv.to_span_nonzero_singleton 𝕜 E x h) ∥x∥ (norm_pos_iff.mpr h) (to_span_nonzero_singleton_homothety 𝕜 x h) /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from the span of `x` to `𝕜`.-/ abbreviation coord (x : E) (h : x ≠ 0) : (submodule.span 𝕜 ({x} : set E)) →L[𝕜] 𝕜 := (to_span_nonzero_singleton 𝕜 x h).symm lemma coord_norm (x : E) (h : x ≠ 0) : ∥coord 𝕜 x h∥ = ∥x∥⁻¹ := begin have hx : 0 < ∥x∥ := (norm_pos_iff.mpr h), haveI : nontrivial (submodule.span 𝕜 ({x} : set E)) := submodule.nontrivial_span_singleton h, exact continuous_linear_map.homothety_norm _ (λ y, homothety_inverse _ hx _ (to_span_nonzero_singleton_homothety 𝕜 x h) _) end lemma coord_self (x : E) (h : x ≠ 0) : (coord 𝕜 x h) (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span 𝕜 ({x} : set E)) = 1 := linear_equiv.coord_self 𝕜 E x h end continuous_linear_equiv lemma linear_equiv.uniform_embedding (e : E ≃ₗ[𝕜] F) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := continuous_linear_equiv.uniform_embedding { continuous_to_fun := h₁, continuous_inv_fun := h₂, .. e } namespace continuous_linear_map variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[simp] lemma lmul_left_norm (v : 𝕜') : ∥lmul_left 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_left 𝕜 𝕜' v) (1:𝕜') } end @[simp] lemma lmul_right_norm (v : 𝕜') : ∥lmul_right 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_right 𝕜 𝕜' v) (1:𝕜') } end lemma lmul_left_right_norm_le (vw : 𝕜' × 𝕜') : ∥lmul_left_right 𝕜 𝕜' vw∥ ≤ ∥vw.1∥ * ∥vw.2∥ := by simpa [mul_comm] using op_norm_comp_le (lmul_right 𝕜 𝕜' vw.2) (lmul_left 𝕜 𝕜' vw.1) end continuous_linear_map
0841070c43f35cae99746738620b85b5c85bda2d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/sheaves/sheaf_of_functions.lean
7c17600cb0b207addaf053a15b3727397325f8bd
[ "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
4,220
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import topology.sheaves.presheaf_of_functions import topology.sheaves.sheaf_condition.unique_gluing import category_theory.limits.shapes.types import topology.local_homeomorph /-! # Sheaf conditions for presheaves of (continuous) functions. We show that * `Top.sheaf_condition.to_Type`: not-necessarily-continuous functions into a type form a sheaf * `Top.sheaf_condition.to_Types`: in fact, these may be dependent functions into a type family For * `Top.sheaf_condition.to_Top`: continuous functions into a topological space form a sheaf please see `topology/sheaves/local_predicate.lean`, where we set up a general framework for constructing sub(pre)sheaves of the sheaf of dependent functions. ## Future work Obviously there's more to do: * sections of a fiber bundle * various classes of smooth and structure preserving functions * functions into spaces with algebraic structure, which the sections inherit -/ open category_theory open category_theory.limits open topological_space open topological_space.opens universe u noncomputable theory variables (X : Top.{u}) open Top namespace Top.presheaf /-- We show that the presheaf of functions to a type `T` (no continuity assumptions, just plain functions) form a sheaf. In fact, the proof is identical when we do this for dependent functions to a type family `T`, so we do the more general case. -/ def to_Types (T : X → Type u) : sheaf_condition (presheaf_to_Types X T) := sheaf_condition_of_exists_unique_gluing _ $ λ ι U sf hsf, -- We use the sheaf condition in terms of unique gluing -- U is a family of open sets, indexed by `ι` and `sf` is a compatible family of sections. -- In the informal comments below, I'll just write `U` to represent the union. begin -- Our first goal is to define a function "lifted" to all of `U`. -- We do this one point at a time. Using the axiom of choice, we can pick for each -- `x : supr U` an index `i : ι` such that `x` lies in `U i` let index : supr U → ι := λ ⟨x,mem⟩, classical.some (opens.mem_supr.mp mem), have index_spec : ∀ x : supr U, x.1 ∈ U (index x) := by { rintro ⟨x,mem⟩, exact classical.some_spec (opens.mem_supr.mp mem), }, -- Using this data, we can glue our functions together to a single section let s : Π x : supr U, T x := λ x, sf (index x) ⟨x.1, index_spec x⟩, refine ⟨s,_,_⟩, { intro i, ext x, -- Now we need to verify that this lifted function restricts correctly to each set `U i`. -- Of course, the difficulty is that at any given point `x ∈ U i`, -- we may have used the axiom of choice to pick a differnt `j` with `x ∈ U j` -- when defining the function. -- Thus we'll need to use the fact that the restrictions are compatible. convert congr_fun (hsf (index ⟨x,_⟩) i) ⟨x,⟨index_spec ⟨x.1,_⟩,x.2⟩⟩, ext, refl }, { -- Now we just need to check that the lift we picked was the only possible one. -- So we suppose we had some other gluing `t` of our sections intros t ht, -- and observe that we need to check that it agrees with our choice -- for each `f : s .X` and each `x ∈ supr U`. ext x, convert congr_fun (ht (index x)) ⟨x.1,index_spec x⟩, ext, refl } end -- We verify that the non-dependent version is an immediate consequence: /-- The presheaf of not-necessarily-continuous functions to a target type `T` satsifies the sheaf condition. -/ def to_Type (T : Type u) : sheaf_condition (presheaf_to_Type X T) := to_Types X (λ _, T) end Top.presheaf namespace Top /-- The sheaf of not-necessarily-continuous functions on `X` with values in type family `T : X → Type u`. -/ def sheaf_to_Types (T : X → Type u) : sheaf (Type u) X := { presheaf := presheaf_to_Types X T, sheaf_condition := presheaf.to_Types _ _, } /-- The sheaf of not-necessarily-continuous functions on `X` with values in a type `T`. -/ def sheaf_to_Type (T : Type u) : sheaf (Type u) X := { presheaf := presheaf_to_Type X T, sheaf_condition := presheaf.to_Type _ _, } end Top
bce85a6ab6fd7cb118cb83b5d3ac92f54bda42e8
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Compiler/IR/Checker.lean
0b55cd354f1b98a3950414e4dc6f0b59de2ed884
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,419
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.Format namespace Lean.IR.Checker structure CheckerContext where env : Environment localCtx : LocalContext := {} decls : Array Decl structure CheckerState where foundVars : IndexSet := {} abbrev M := ReaderT CheckerContext (ExceptT String (StateT CheckerState Id)) def markIndex (i : Index) : M Unit := do let s ← get if s.foundVars.contains i then throw s!"variable / joinpoint index {i} has already been used" modify fun s => { s with foundVars := s.foundVars.insert i } def markVar (x : VarId) : M Unit := markIndex x.idx def markJP (j : JoinPointId) : M Unit := markIndex j.idx def getDecl (c : Name) : M Decl := do let ctx ← read match findEnvDecl' ctx.env c ctx.decls with | none => throw s!"unknown declaration '{c}'" | some d => pure d def checkVar (x : VarId) : M Unit := do let ctx ← read unless ctx.localCtx.isLocalVar x.idx || ctx.localCtx.isParam x.idx do throw s!"unknown variable '{x}'" def checkJP (j : JoinPointId) : M Unit := do let ctx ← read unless ctx.localCtx.isJP j.idx do throw s!"unknown join point '{j}'" def checkArg (a : Arg) : M Unit := match a with | Arg.var x => checkVar x | other => pure () def checkArgs (as : Array Arg) : M Unit := as.forM checkArg @[inline] def checkEqTypes (ty₁ ty₂ : IRType) : M Unit := do unless ty₁ == ty₂ do throw "unexpected type" @[inline] def checkType (ty : IRType) (p : IRType → Bool) : M Unit := do unless p ty do throw s!"unexpected type '{ty}'" def checkObjType (ty : IRType) : M Unit := checkType ty IRType.isObj def checkScalarType (ty : IRType) : M Unit := checkType ty IRType.isScalar def getType (x : VarId) : M IRType := do let ctx ← read match ctx.localCtx.getType x with | some ty => pure ty | none => throw s!"unknown variable '{x}'" @[inline] def checkVarType (x : VarId) (p : IRType → Bool) : M Unit := do let ty ← getType x; checkType ty p def checkObjVar (x : VarId) : M Unit := checkVarType x IRType.isObj def checkScalarVar (x : VarId) : M Unit := checkVarType x IRType.isScalar def checkFullApp (c : FunId) (ys : Array Arg) : M Unit := do let decl ← getDecl c unless ys.size == decl.params.size do throw s!"incorrect number of arguments to '{c}', {ys.size} provided, {decl.params.size} expected" checkArgs ys def checkPartialApp (c : FunId) (ys : Array Arg) : M Unit := do let decl ← getDecl c unless ys.size < decl.params.size do throw s!"too many arguments too partial application '{c}', num. args: {ys.size}, arity: {decl.params.size}" checkArgs ys def checkExpr (ty : IRType) : Expr → M Unit | Expr.pap f ys => checkPartialApp f ys *> checkObjType ty -- partial applications should always produce a closure object | Expr.ap x ys => checkObjVar x *> checkArgs ys | Expr.fap f ys => checkFullApp f ys | Expr.ctor c ys => when (!ty.isStruct && !ty.isUnion && c.isRef) (checkObjType ty) *> checkArgs ys | Expr.reset _ x => checkObjVar x *> checkObjType ty | Expr.reuse x i u ys => checkObjVar x *> checkArgs ys *> checkObjType ty | Expr.box xty x => checkObjType ty *> checkScalarVar x *> checkVarType x (fun t => t == xty) | Expr.unbox x => checkScalarType ty *> checkObjVar x | Expr.proj i x => do let xType ← getType x; match xType with | IRType.object => checkObjType ty | IRType.tobject => checkObjType ty | IRType.struct _ tys => if h : i < tys.size then checkEqTypes (tys.get ⟨i,h⟩) ty else throw "invalid proj index" | IRType.union _ tys => if h : i < tys.size then checkEqTypes (tys.get ⟨i,h⟩) ty else throw "invalid proj index" | other => throw s!"unexpected IR type '{xType}'" | Expr.uproj _ x => checkObjVar x *> checkType ty (fun t => t == IRType.usize) | Expr.sproj _ _ x => checkObjVar x *> checkScalarType ty | Expr.isShared x => checkObjVar x *> checkType ty (fun t => t == IRType.uint8) | Expr.isTaggedPtr x => checkObjVar x *> checkType ty (fun t => t == IRType.uint8) | Expr.lit (LitVal.str _) => checkObjType ty | Expr.lit _ => pure () @[inline] def withParams (ps : Array Param) (k : M Unit) : M Unit := do let ctx ← read let localCtx ← ps.foldlM (init := ctx.localCtx) fun (ctx : LocalContext) p => do markVar p.x pure $ ctx.addParam p withReader (fun _ => { ctx with localCtx := localCtx }) k partial def checkFnBody : FnBody → M Unit | FnBody.vdecl x t v b => do checkExpr t v; markVar x; let ctx ← read withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addLocal x t v }) (checkFnBody b) | FnBody.jdecl j ys v b => do markJP j; withParams ys (checkFnBody v); let ctx ← read withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addJP j ys v }) (checkFnBody b) | FnBody.set x _ y b => checkVar x *> checkArg y *> checkFnBody b | FnBody.uset x _ y b => checkVar x *> checkVar y *> checkFnBody b | FnBody.sset x _ _ y _ b => checkVar x *> checkVar y *> checkFnBody b | FnBody.setTag x _ b => checkVar x *> checkFnBody b | FnBody.inc x _ _ _ b => checkVar x *> checkFnBody b | FnBody.dec x _ _ _ b => checkVar x *> checkFnBody b | FnBody.del x b => checkVar x *> checkFnBody b | FnBody.mdata _ b => checkFnBody b | FnBody.jmp j ys => checkJP j *> checkArgs ys | FnBody.ret x => checkArg x | FnBody.case _ x _ alts => checkVar x *> alts.forM (fun alt => checkFnBody alt.body) | FnBody.unreachable => pure () def checkDecl : Decl → M Unit | Decl.fdecl f xs t b => withParams xs (checkFnBody b) | Decl.extern f xs t _ => withParams xs (pure ()) end Checker def checkDecl (decls : Array Decl) (decl : Decl) : CompilerM Unit := do let env ← getEnv match (Checker.checkDecl decl { env := env, decls := decls }).run' {} with | Except.error msg => throw s!"IR check failed at '{decl.name}', error: {msg}" | other => pure () def checkDecls (decls : Array Decl) : CompilerM Unit := decls.forM (checkDecl decls) end IR end Lean
bba48aca34cd66ec9d8a17178f2cbcb64ab37bc4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/WHNF.lean
d4cfa085d93825bb31049833bd6c882319d13a11
[ "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
37,672
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Structure import Lean.Util.Recognizers import Lean.Meta.GetUnfoldableConst import Lean.Meta.FunInfo import Lean.Meta.Match.MatcherInfo import Lean.Meta.Match.MatchPatternAttr namespace Lean.Meta -- =========================== /-! # Smart unfolding support -/ -- =========================== /-- Forward declaration. It is defined in the module `src/Lean/Elab/PreDefinition/Structural/Eqns.lean`. It is possible to avoid this hack if we move `Structural.EqnInfo` and `Structural.eqnInfoExt` to this module. -/ @[extern "lean_get_structural_rec_arg_pos"] opaque getStructuralRecArgPos? (declName : Name) : CoreM (Option Nat) def smartUnfoldingSuffix := "_sunfold" @[inline] def mkSmartUnfoldingNameFor (declName : Name) : Name := Name.mkStr declName smartUnfoldingSuffix def hasSmartUnfoldingDecl (env : Environment) (declName : Name) : Bool := env.contains (mkSmartUnfoldingNameFor declName) register_builtin_option smartUnfolding : Bool := { defValue := true descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion" } /-- Add auxiliary annotation to indicate the `match`-expression `e` must be reduced when performing smart unfolding. -/ def markSmartUnfoldingMatch (e : Expr) : Expr := mkAnnotation `sunfoldMatch e def smartUnfoldingMatch? (e : Expr) : Option Expr := annotation? `sunfoldMatch e /-- Add auxiliary annotation to indicate expression `e` (a `match` alternative rhs) was successfully reduced by smart unfolding. -/ def markSmartUnfoldingMatchAlt (e : Expr) : Expr := mkAnnotation `sunfoldMatchAlt e def smartUnfoldingMatchAlt? (e : Expr) : Option Expr := annotation? `sunfoldMatchAlt e -- =========================== /-! # Helper methods -/ -- =========================== def isAuxDef (constName : Name) : MetaM Bool := do let env ← getEnv return isAuxRecursor env constName || isNoConfusion env constName @[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α := match e with | Expr.const name lvls => do let (some cinfo) ← getUnfoldableConst? name | failK () k cinfo lvls | _ => failK () -- =========================== /-! # Helper functions for reducing recursors -/ -- =========================== private def getFirstCtor (d : Name) : MetaM (Option Name) := do let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getUnfoldableConstNoEx? d | pure none return some ctor private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := do match type.getAppFn with | Expr.const d lvls => let (some ctor) ← getFirstCtor d | pure none return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams) | _ => return none private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule := match major.getAppFn with | Expr.const fn _ => recVal.rules.find? fun r => r.ctor == fn | _ => none private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM Expr := do let majorType ← inferType major let majorType ← instantiateMVars (← whnf majorType) let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf recVal.getInduct then return major else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then return major else do let (some newCtorApp) ← mkNullaryCtor majorType recVal.numParams | pure major let newType ← inferType newCtorApp /- TODO: check whether changing reducibility to default hurts performance here. We do that to make sure auxiliary `Eq.rec` introduced by the `match`-compiler are reduced even when `TransparencyMode.reducible` (like in `simp`). We use `withNewMCtxDepth` to make sure metavariables at `majorType` are not assigned. For example, given `major : Eq ?x y`, we don't want to apply K by assigning `?x := y`. -/ if (← withAtLeastTransparency TransparencyMode.default <| withNewMCtxDepth <| isDefEq majorType newType) then return newCtorApp else return major /-- Create the `i`th projection `major`. It tries to use the auto-generated projection functions if available. Otherwise falls back to `Expr.proj`. -/ def mkProjFn (ctorVal : ConstructorVal) (us : List Level) (params : Array Expr) (i : Nat) (major : Expr) : CoreM Expr := do match getStructureInfo? (← getEnv) ctorVal.induct with | none => return mkProj ctorVal.induct i major | some info => match info.getProjFn? i with | none => return mkProj ctorVal.induct i major | some projFn => return mkApp (mkAppN (mkConst projFn us) params) major /-- If `major` is not a constructor application, and its type is a structure `C ...`, then return `C.mk major.1 ... major.n` \pre `inductName` is `C`. If `Meta.Config.etaStruct` is `false` or the condition above does not hold, this method just returns `major`. -/ private def toCtorWhenStructure (inductName : Name) (major : Expr) : MetaM Expr := do unless (← useEtaStruct inductName) do return major let env ← getEnv if !isStructureLike env inductName then return major else if let some _ := major.isConstructorApp? env then return major else let majorType ← inferType major let majorType ← instantiateMVars (← whnf majorType) let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf inductName then return major match majorType.getAppFn with | Expr.const d us => if (← whnfD (← inferType majorType)) == mkSort levelZero then return major -- We do not perform eta for propositions, see implementation in the kernel else let some ctorName ← getFirstCtor d | pure major let ctorInfo ← getConstInfoCtor ctorName let params := majorType.getAppArgs.shrink ctorInfo.numParams let mut result := mkAppN (mkConst ctorName us) params for i in [:ctorInfo.numFields] do result := mkApp result (← mkProjFn ctorInfo us params i major) return result | _ => return major -- Helper predicate that returns `true` for inductive predicates used to define functions by well-founded recursion. private def isWFRec (declName : Name) : Bool := declName == ``Acc.rec || declName == ``WellFounded.rec /-- Auxiliary function for reducing recursor applications. -/ private def reduceRec (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let mut major ← if isWFRec recVal.name && (← getTransparency) == TransparencyMode.default then -- If recursor is `Acc.rec` or `WellFounded.rec` and transparency is default, -- then we bump transparency to .all to make sure we can unfold defs defined by WellFounded recursion. -- We use this trick because we abstract nested proofs occurring in definitions. -- Alternative design: do not abstract nested proofs used to justify well-founded recursion. withTransparency .all <| whnf major else whnf major if recVal.k then major ← toCtorWhenK recVal major major := major.toCtorIfLit major ← toCtorWhenStructure recVal.getInduct major match getRecRuleFor recVal major with | some rule => let majorArgs := major.getAppArgs if recLvls.length != recVal.levelParams.length then failK () else let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls -- Apply parameters, motives and minor premises from recursor application. let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs /- The number of parameters in the constructor is not necessarily equal to the number of parameters in the recursor when we have nested inductive types. -/ let nparams := majorArgs.size - rule.nfields let rhs := mkAppRange rhs nparams majorArgs.size majorArgs let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs successK rhs | none => failK () else failK () -- =========================== /-! # Helper functions for reducing Quot.lift and Quot.ind -/ -- =========================== /-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/ private def reduceQuotRec (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let process (majorPos argPos : Nat) : MetaM α := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major match major with | Expr.app (Expr.app (Expr.app (Expr.const majorFn _) _) _) majorArg => do let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getUnfoldableConstNoEx? majorFn | failK () let f := recArgs[argPos]! let r := mkApp f majorArg let recArity := majorPos + 1 successK <| mkAppRange r recArity recArgs.size recArgs | _ => failK () else failK () match recVal.kind with | QuotKind.lift => process 5 3 | QuotKind.ind => process 4 3 | _ => failK () -- =========================== /-! # Helper function for extracting "stuck term" -/ -- =========================== mutual private partial def isRecStuck? (recVal : RecursorVal) (recArgs : Array Expr) : MetaM (Option MVarId) := if recVal.k then -- TODO: improve this case return none else do let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let major ← whnf major getStuckMVar? major else return none private partial def isQuotRecStuck? (recVal : QuotVal) (recArgs : Array Expr) : MetaM (Option MVarId) := let process? (majorPos : Nat) : MetaM (Option MVarId) := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major getStuckMVar? major else return none match recVal.kind with | QuotKind.lift => process? 5 | QuotKind.ind => process? 4 | _ => return none /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/ partial def getStuckMVar? (e : Expr) : MetaM (Option MVarId) := do match e with | .mdata _ e => getStuckMVar? e | .proj _ _ e => getStuckMVar? (← whnf e) | .mvar .. => let e ← instantiateMVars e match e with | .mvar mvarId => return some mvarId | _ => getStuckMVar? e | .app f .. => let f := f.getAppFn match f with | .mvar .. => let e ← instantiateMVars e match e.getAppFn with | .mvar mvarId => return some mvarId | _ => getStuckMVar? e | .const fName _ => match (← getUnfoldableConstNoEx? fName) with | some <| .recInfo recVal => isRecStuck? recVal e.getAppArgs | some <| .quotInfo recVal => isQuotRecStuck? recVal e.getAppArgs | _ => unless e.hasExprMVar do return none -- Projection function support let some projInfo ← getProjectionFnInfo? fName | return none -- This branch is relevant if `e` is a type class projection that is stuck because the instance has not been synthesized yet. unless projInfo.fromClass do return none let args := e.getAppArgs -- First check whether `e`s instance is stuck. if let some major := args.get? projInfo.numParams then if let some mvarId ← getStuckMVar? major then return mvarId /- Then, recurse on the explicit arguments We want to detect the stuck instance in terms such as `HAdd.hAdd Nat Nat Nat (instHAdd Nat instAddNat) n (OfNat.ofNat Nat 2 ?m)` See issue https://github.com/leanprover/lean4/issues/1408 for an example where this is needed. -/ let info ← getFunInfo f for pinfo in info.paramInfo, arg in args do if pinfo.isExplicit then if let some mvarId ← getStuckMVar? arg then return some mvarId return none | .proj _ _ e => getStuckMVar? (← whnf e) | _ => return none | _ => return none end -- =========================== /-! # Weak Head Normal Form auxiliary combinators -/ -- =========================== /-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/ @[specialize] partial def whnfEasyCases (e : Expr) (k : Expr → MetaM Expr) : MetaM Expr := do match e with | .forallE .. => return e | .lam .. => return e | .sort .. => return e | .lit .. => return e | .bvar .. => panic! "loose bvar in expression" | .letE .. => k e | .const .. => k e | .app .. => k e | .proj .. => k e | .mdata _ e => whnfEasyCases e k | .fvar fvarId => let decl ← fvarId.getDecl match decl with | .cdecl .. => return e | .ldecl (value := v) (nonDep := nonDep) .. => let cfg ← getConfig if nonDep && !cfg.zetaNonDep then return e else if cfg.trackZeta then modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId } whnfEasyCases v k | .mvar mvarId => match (← getExprMVarAssignment? mvarId) with | some v => whnfEasyCases v k | none => return e @[specialize] private def deltaDefinition (c : ConstantInfo) (lvls : List Level) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := do if c.levelParams.length != lvls.length then failK () else successK (← instantiateValueLevelParams c lvls) @[specialize] private def deltaBetaDefinition (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) (preserveMData := false) : MetaM α := do if c.levelParams.length != lvls.length then failK () else let val ← instantiateValueLevelParams c lvls let val := val.betaRev revArgs (preserveMData := preserveMData) successK val inductive ReduceMatcherResult where | reduced (val : Expr) | stuck (val : Expr) | notMatcher | partialApp /-- The "match" compiler uses `if-then-else` expressions and other auxiliary declarations to compile match-expressions such as ``` match v with | 'a' => 1 | 'b' => 2 | _ => 3 ``` because it is more efficient than using `casesOn` recursors. The method `reduceMatcher?` fails if these auxiliary definitions (e.g., `ite`) cannot be unfolded in the current transparency setting. This is problematic because tactics such as `simp` use `TransparencyMode.reducible`, and most users assume that expressions such as ``` match 0 with | 0 => 1 | 100 => 2 | _ => 3 ``` should reduce in any transparency mode. Thus, we define a custom `canUnfoldAtMatcher` predicate for `whnfMatcher`. This solution is not very modular because modifications at the `match` compiler require changes here. We claim this is defensible because it is reducing the auxiliary declaration defined by the `match` compiler. Alternative solution: tactics that use `TransparencyMode.reducible` should rely on the equations we generated for match-expressions. This solution is also not perfect because the match-expression above will not reduce during type checking when we are not using `TransparencyMode.default` or `TransparencyMode.all`. -/ def canUnfoldAtMatcher (cfg : Config) (info : ConstantInfo) : CoreM Bool := do match cfg.transparency with | TransparencyMode.all => return true | TransparencyMode.default => return !(← isIrreducible info.name) | _ => if (← isReducible info.name) || isGlobalInstance (← getEnv) info.name then return true else if hasMatchPatternAttribute (← getEnv) info.name then return true else return info.name == ``ite || info.name == ``dite || info.name == ``decEq || info.name == ``Nat.decEq || info.name == ``Char.ofNat || info.name == ``Char.ofNatAux || info.name == ``String.decEq || info.name == ``List.hasDecEq || info.name == ``Fin.ofNat || info.name == ``UInt8.ofNat || info.name == ``UInt8.decEq || info.name == ``UInt16.ofNat || info.name == ``UInt16.decEq || info.name == ``UInt32.ofNat || info.name == ``UInt32.decEq || info.name == ``UInt64.ofNat || info.name == ``UInt64.decEq /- Remark: we need to unfold the following two definitions because they are used for `Fin`, and lazy unfolding at `isDefEq` does not unfold projections. -/ || info.name == ``HMod.hMod || info.name == ``Mod.mod private def whnfMatcher (e : Expr) : MetaM Expr := do /- When reducing `match` expressions, if the reducibility setting is at `TransparencyMode.reducible`, we increase it to `TransparencyMode.instances`. We use the `TransparencyMode.reducible` in many places (e.g., `simp`), and this setting prevents us from reducing `match` expressions where the discriminants are terms such as `OfNat.ofNat α n inst`. For example, `simp [Int.div]` will not unfold the application `Int.div 2 1` occuring in the target. TODO: consider other solutions; investigate whether the solution above produces counterintuitive behavior. -/ let mut transparency ← getTransparency if transparency == TransparencyMode.reducible then transparency := TransparencyMode.instances withTransparency transparency <| withReader (fun ctx => { ctx with canUnfold? := canUnfoldAtMatcher }) do whnf e def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do match e.getAppFn with | Expr.const declName declLevels => let some info ← getMatcherInfo? declName | return ReduceMatcherResult.notMatcher let args := e.getAppArgs let prefixSz := info.numParams + 1 + info.numDiscrs if args.size < prefixSz + info.numAlts then return ReduceMatcherResult.partialApp else let constInfo ← getConstInfo declName let f ← instantiateValueLevelParams constInfo declLevels let auxApp := mkAppN f args[0:prefixSz] let auxAppType ← inferType auxApp forallBoundedTelescope auxAppType info.numAlts fun hs _ => do let auxApp ← whnfMatcher (mkAppN auxApp hs) let auxAppFn := auxApp.getAppFn let mut i := prefixSz for h in hs do if auxAppFn == h then let result := mkAppN args[i]! auxApp.getAppArgs let result := mkAppN result args[prefixSz + info.numAlts:args.size] return ReduceMatcherResult.reduced result.headBeta i := i + 1 return ReduceMatcherResult.stuck auxApp | _ => pure ReduceMatcherResult.notMatcher private def projectCore? (e : Expr) (i : Nat) : MetaM (Option Expr) := do let e := e.toCtorIfLit matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ => let numArgs := e.getAppNumArgs let idx := ctorVal.numParams + i if idx < numArgs then return some (e.getArg! idx) else return none def project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do projectCore? (← whnf e) i /-- Reduce kernel projection `Expr.proj ..` expression. -/ def reduceProj? (e : Expr) : MetaM (Option Expr) := do match e with | Expr.proj _ i c => project? c i | _ => return none /-- Auxiliary method for reducing terms of the form `?m t_1 ... t_n` where `?m` is delayed assigned. Recall that we can only expand a delayed assignment when all holes/metavariables in the assigned value have been "filled". -/ private def whnfDelayedAssigned? (f' : Expr) (e : Expr) : MetaM (Option Expr) := do if f'.isMVar then match (← getDelayedMVarAssignment? f'.mvarId!) with | none => return none | some { fvars, mvarIdPending } => let args := e.getAppArgs if fvars.size > args.size then -- Insufficient number of argument to expand delayed assignment return none else let newVal ← instantiateMVars (mkMVar mvarIdPending) if newVal.hasExprMVar then -- Delayed assignment still contains metavariables return none else let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args return mkAppRange result fvars.size args.size args else return none /-- Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction, expand let-expressions, expand assigned meta-variables. The parameter `deltaAtProj` controls how to reduce projections `s.i`. If `deltaAtProj == true`, then delta reduction is used to reduce `s` (i.e., `whnf` is used), otherwise `whnfCore`. If `simpleReduceOnly`, then `iota` and projection reduction are not performed. Note that the value of `deltaAtProj` is irrelevant if `simpleReduceOnly = true`. -/ partial def whnfCore (e : Expr) (deltaAtProj : Bool := true) (simpleReduceOnly := false) : MetaM Expr := go e where go (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do trace[Meta.whnf] e match e with | Expr.const .. => pure e | Expr.letE _ _ v b _ => go <| b.instantiate1 v | Expr.app f .. => let f := f.getAppFn let f' ← go f if f'.isLambda then let revArgs := e.getAppRevArgs go <| f'.betaRev revArgs else if let some eNew ← whnfDelayedAssigned? f' e then go eNew else let e := if f == f' then e else e.updateFn f' if simpleReduceOnly then return e else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced eNew => go eNew | ReduceMatcherResult.partialApp => pure e | ReduceMatcherResult.stuck _ => pure e | ReduceMatcherResult.notMatcher => matchConstAux f' (fun _ => return e) fun cinfo lvls => match cinfo with | ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs (fun _ => return e) go | ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs (fun _ => return e) go | c@(ConstantInfo.defnInfo _) => do if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => return e) go else return e | _ => return e | Expr.proj _ i c => if simpleReduceOnly then return e else let c ← if deltaAtProj then whnf c else whnfCore c match (← projectCore? c i) with | some e => go e | none => return e | _ => unreachable! /-- Recall that `_sunfold` auxiliary definitions contains the markers: `markSmartUnfoldingMatch` (*) and `markSmartUnfoldingMatchAlt` (**). For example, consider the following definition ``` def r (i j : Nat) : Nat := i + match j with | Nat.zero => 1 | Nat.succ j => i + match j with | Nat.zero => 2 | Nat.succ j => r i j ``` produces the following `_sunfold` auxiliary definition with the markers ``` def r._sunfold (i j : Nat) : Nat := i + (*) match j with | Nat.zero => (**) 1 | Nat.succ j => i + (*) match j with | Nat.zero => (**) 2 | Nat.succ j => (**) r i j ``` `match` expressions marked with `markSmartUnfoldingMatch` (*) must be reduced, otherwise the resulting term is not definitionally equal to the given expression. The recursion may be interrupted as soon as the annotation `markSmartUnfoldingAlt` (**) is reached. For example, the term `r i j.succ.succ` reduces to the definitionally equal term `i + i * r i j` -/ partial def smartUnfoldingReduce? (e : Expr) : MetaM (Option Expr) := go e |>.run where go (e : Expr) : OptionT MetaM Expr := do match e with | Expr.letE n t v b _ => withLetDecl n t (← go v) fun x => do mkLetFVars #[x] (← go (b.instantiate1 x)) | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← go b) | Expr.app f a .. => return mkApp (← go f) (← go a) | Expr.proj _ _ s => return e.updateProj! (← go s) | Expr.mdata _ b => if let some m := smartUnfoldingMatch? e then goMatch m else return e.updateMData! (← go b) | _ => return e goMatch (e : Expr) : OptionT MetaM Expr := do match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => if let some alt := smartUnfoldingMatchAlt? e then return alt else go e | ReduceMatcherResult.stuck e' => let mvarId ← getStuckMVar? e' /- Try to "unstuck" by resolving pending TC problems -/ if (← Meta.synthPending mvarId) then goMatch e else failure | _ => failure mutual /-- Auxiliary method for unfolding a class projection. -/ partial def unfoldProjInst? (e : Expr) : MetaM (Option Expr) := do match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { fromClass := true, .. } => match (← withDefault <| unfoldDefinition? e) with | none => return none | some e => match (← withReducibleAndInstances <| reduceProj? e.getAppFn) with | none => return none | some r => return mkAppN r e.getAppArgs |>.headBeta | _ => return none | _ => return none /-- Auxiliary method for unfolding a class projection. when transparency is set to `TransparencyMode.instances`. Recall that class instance projections are not marked with `[reducible]` because we want them to be in "reducible canonical form". -/ partial def unfoldProjInstWhenIntances? (e : Expr) : MetaM (Option Expr) := do if (← getTransparency) != TransparencyMode.instances then return none else unfoldProjInst? e /-- Unfold definition using "smart unfolding" if possible. -/ partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app f _ => matchConstAux f.getAppFn (fun _ => unfoldProjInstWhenIntances? e) fun fInfo fLvls => do if fInfo.levelParams.length != fLvls.length then return none else let unfoldDefault (_ : Unit) : MetaM (Option Expr) := if fInfo.hasValue then deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none if smartUnfolding.get (← getOptions) then match ((← getEnv).find? (mkSmartUnfoldingNameFor fInfo.name)) with | some fAuxInfo@(ConstantInfo.defnInfo _) => -- We use `preserveMData := true` to make sure the smart unfolding annotation are not erased in an over-application. deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (preserveMData := true) (fun _ => pure none) fun e₁ => do let some r ← smartUnfoldingReduce? e₁ | return none /- If `smartUnfoldingReduce?` succeeds, we should still check whether the argument the structural recursion is recursing on reduces to a constructor. This extra check is necessary in definitions (see issue #1081) such as ``` inductive Vector (α : Type u) : Nat → Type u where | nil : Vector α 0 | cons : α → Vector α n → Vector α (n+1) def Vector.insert (a: α) (i : Fin (n+1)) (xs : Vector α n) : Vector α (n+1) := match i, xs with | ⟨0, _⟩, xs => cons a xs | ⟨i+1, h⟩, cons x xs => cons x (xs.insert a ⟨i, Nat.lt_of_succ_lt_succ h⟩) ``` The structural recursion is being performed using the vector `xs`. That is, we used `Vector.brecOn` to define `Vector.insert`. Thus, an application `xs.insert a ⟨0, h⟩` is **not** definitionally equal to `Vector.cons a xs` because `xs` is not a constructor application (the `Vector.brecOn` application is blocked). Remark 1: performing structural recursion on `Fin (n+1)` is not an option here because it is a `Subtype` and and the repacking in recursive applications confuses the structural recursion module. Remark 2: the match expression reduces reduces to `cons a xs` when the discriminants are `⟨0, h⟩` and `xs`. Remark 3: this check is unnecessary in most cases, but we don't need dependent elimination to trigger the issue fixed by this extra check. Here is another example that triggers the issue fixed by this check. ``` def f : Nat → Nat → Nat | 0, y => y | x+1, y+1 => f (x-2) y | x+1, 0 => 0 theorem ex : f 0 y = y := rfl ``` Remark 4: the `return some r` in the following `let` is not a typo. Binport generated .olean files do not store the position of recursive arguments for definitions using structural recursion. Thus, we should keep `return some r` until Mathlib has been ported to Lean 3. Note that the `Vector` example above does not even work in Lean 3. -/ let some recArgPos ← getStructuralRecArgPos? fInfo.name | return some r let numArgs := e.getAppNumArgs if recArgPos >= numArgs then return none let recArg := e.getArg! recArgPos numArgs if !(← whnfMatcher recArg).isConstructorApp (← getEnv) then return none return some r | _ => if (← getMatcherInfo? fInfo.name).isSome then -- Recall that `whnfCore` tries to reduce "matcher" applications. return none else unfoldDefault () else unfoldDefault () | Expr.const declName lvls => do if smartUnfolding.get (← getOptions) && (← getEnv).contains (mkSmartUnfoldingNameFor declName) then return none else let some cinfo ← getUnfoldableConstNoEx? declName | pure none unless cinfo.hasValue do return none deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e)) | _ => return none end def unfoldDefinition (e : Expr) : MetaM Expr := do let some e ← unfoldDefinition? e | throwError "failed to unfold definition{indentExpr e}" return e @[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr := whnfEasyCases e fun e => do let e ← whnfCore e if (← pred e) then match (← unfoldDefinition? e) with | some e => whnfHeadPred e pred | none => return e else return e def whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do let e ← whnfHeadPred e (fun e => return !e.isAppOf declName) if e.isAppOf declName then return e else return none /-- Try to reduce matcher/recursor/quot applications. We say they are all "morally" recursor applications. -/ def reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do if !e.isApp then return none else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => return e | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do match cinfo with | ConstantInfo.recInfo «rec» => reduceRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | ConstantInfo.quotInfo «rec» => reduceQuotRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | c@(ConstantInfo.defnInfo _) => if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none | _ => return none unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName @[implemented_by reduceBoolNativeUnsafe] opaque reduceBoolNative (constName : Name) : MetaM Bool @[implemented_by reduceNatNativeUnsafe] opaque reduceNatNative (constName : Name) : MetaM Nat def reduceNative? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app (Expr.const fName _) (Expr.const argName _) => if fName == ``Lean.reduceBool then do return toExpr (← reduceBoolNative argName) else if fName == ``Lean.reduceNat then do return toExpr (← reduceNatNative argName) else return none | _ => return none @[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do let a ← whnf a match a with | Expr.const `Nat.zero _ => k 0 | Expr.lit (Literal.natVal v) => k v | _ => return none def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) := withNatValue a fun a => return mkRawNatLit <| f a def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) := withNatValue a fun a => withNatValue b fun b => do trace[Meta.isDefEq.whnf.reduceBinOp] "{a} op {b}" return mkRawNatLit <| f a b def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do withNatValue a fun a => withNatValue b fun b => return toExpr <| f a b def reduceNat? (e : Expr) : MetaM (Option Expr) := if e.hasFVar || e.hasMVar then return none else match e with | Expr.app (Expr.const fn _) a => if fn == ``Nat.succ then reduceUnaryNatOp Nat.succ a else return none | Expr.app (Expr.app (Expr.const fn _) a1) a2 => if fn == ``Nat.add then reduceBinNatOp Nat.add a1 a2 else if fn == ``Nat.sub then reduceBinNatOp Nat.sub a1 a2 else if fn == ``Nat.mul then reduceBinNatOp Nat.mul a1 a2 else if fn == ``Nat.div then reduceBinNatOp Nat.div a1 a2 else if fn == ``Nat.mod then reduceBinNatOp Nat.mod a1 a2 else if fn == ``Nat.beq then reduceBinNatPred Nat.beq a1 a2 else if fn == ``Nat.ble then reduceBinNatPred Nat.ble a1 a2 else return none | _ => return none @[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do -- We cache only closed terms without expr metavars. -- Potential refinement: cache if `e` is not stuck at a metavariable if e.hasFVar || e.hasExprMVar || (← read).canUnfold?.isSome then return false else match (← getConfig).transparency with | TransparencyMode.default => return true | TransparencyMode.all => return true | _ => return false @[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => return (← get).cache.whnfDefault.find? e | TransparencyMode.all => return (← get).cache.whnfAll.find? e | _ => unreachable! else return none private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r } | TransparencyMode.all => modify fun s => { s with cache.whnfAll := s.cache.whnfAll.insert e r } | _ => unreachable! return r @[export lean_whnf] partial def whnfImp (e : Expr) : MetaM Expr := withIncRecDepth <| whnfEasyCases e fun e => do checkMaxHeartbeats "whnf" let useCache ← useWHNFCache e match (← cached? useCache e) with | some e' => pure e' | none => let e' ← whnfCore e match (← reduceNat? e') with | some v => cache useCache e v | none => match (← reduceNative? e') with | some v => cache useCache e v | none => match (← unfoldDefinition? e') with | some e => whnfImp e | none => cache useCache e e' /-- If `e` is a projection function that satisfies `p`, then reduce it -/ def reduceProjOf? (e : Expr) (p : Name → Bool) : MetaM (Option Expr) := do if !e.isApp then pure none else match e.getAppFn with | Expr.const name .. => do let env ← getEnv match env.getProjectionStructureName? name with | some structName => if p structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none builtin_initialize registerTraceClass `Meta.whnf registerTraceClass `Meta.isDefEq.whnf.reduceBinOp end Lean.Meta
075f3396e1a0ffb2caf30fd2977c4a2f624c7e67
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/uniform_group.lean
53f5133dc0a6c3ada91d2d6e62dda249a72b5d93
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
11,680
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.uniform_embedding import Mathlib.topology.uniform_space.complete_separated import Mathlib.topology.algebra.group import Mathlib.tactic.abel import Mathlib.PostPort universes u_3 l u_1 u_2 u u_4 u_5 namespace Mathlib /-! # Uniform structure on topological groups * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) * `add_group_with_zero_nhd`: construct the topological structure from a group with a neighbourhood around zero. Then with `topological_add_group.to_uniform_space` one can derive a `uniform_space`. -/ /-- A uniform (additive) group is a group in which the addition and negation are uniformly continuous. -/ class uniform_add_group (α : Type u_3) [uniform_space α] [add_group α] where uniform_continuous_sub : uniform_continuous fun (p : α × α) => prod.fst p - prod.snd p theorem uniform_add_group.mk' {α : Type u_1} [uniform_space α] [add_group α] (h₁ : uniform_continuous fun (p : α × α) => prod.fst p + prod.snd p) (h₂ : uniform_continuous fun (p : α) => -p) : uniform_add_group α := sorry theorem uniform_continuous_sub {α : Type u_1} [uniform_space α] [add_group α] [uniform_add_group α] : uniform_continuous fun (p : α × α) => prod.fst p - prod.snd p := uniform_add_group.uniform_continuous_sub theorem uniform_continuous.sub {α : Type u_1} {β : Type u_2} [uniform_space α] [add_group α] [uniform_add_group α] [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous fun (x : β) => f x - g x := uniform_continuous.comp uniform_continuous_sub (uniform_continuous.prod_mk hf hg) theorem uniform_continuous.neg {α : Type u_1} {β : Type u_2} [uniform_space α] [add_group α] [uniform_add_group α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous fun (x : β) => -f x := sorry theorem uniform_continuous_neg {α : Type u_1} [uniform_space α] [add_group α] [uniform_add_group α] : uniform_continuous fun (x : α) => -x := uniform_continuous.neg uniform_continuous_id theorem uniform_continuous.add {α : Type u_1} {β : Type u_2} [uniform_space α] [add_group α] [uniform_add_group α] [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous fun (x : β) => f x + g x := sorry theorem uniform_continuous_add {α : Type u_1} [uniform_space α] [add_group α] [uniform_add_group α] : uniform_continuous fun (p : α × α) => prod.fst p + prod.snd p := uniform_continuous.add uniform_continuous_fst uniform_continuous_snd protected instance uniform_add_group.to_topological_add_group {α : Type u_1} [uniform_space α] [add_group α] [uniform_add_group α] : topological_add_group α := topological_add_group.mk (uniform_continuous.continuous uniform_continuous_neg) protected instance prod.uniform_add_group {α : Type u_1} {β : Type u_2} [uniform_space α] [add_group α] [uniform_add_group α] [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) := uniform_add_group.mk (uniform_continuous.prod_mk (uniform_continuous.sub (uniform_continuous.comp uniform_continuous_fst uniform_continuous_fst) (uniform_continuous.comp uniform_continuous_fst uniform_continuous_snd)) (uniform_continuous.sub (uniform_continuous.comp uniform_continuous_snd uniform_continuous_fst) (uniform_continuous.comp uniform_continuous_snd uniform_continuous_snd))) theorem uniformity_translate {α : Type u_1} [uniform_space α] [add_group α] [uniform_add_group α] (a : α) : filter.map (fun (x : α × α) => (prod.fst x + a, prod.snd x + a)) (uniformity α) = uniformity α := sorry theorem uniform_embedding_translate {α : Type u_1} [uniform_space α] [add_group α] [uniform_add_group α] (a : α) : uniform_embedding fun (x : α) => x + a := sorry theorem uniformity_eq_comap_nhds_zero (α : Type u_1) [uniform_space α] [add_group α] [uniform_add_group α] : uniformity α = filter.comap (fun (x : α × α) => prod.snd x - prod.fst x) (nhds 0) := sorry theorem group_separation_rel {α : Type u_1} [uniform_space α] [add_group α] [uniform_add_group α] (x : α) (y : α) : (x, y) ∈ Mathlib.separation_rel α ↔ x - y ∈ closure (singleton 0) := sorry theorem uniform_continuous_of_tendsto_zero {α : Type u_1} {β : Type u_2} [uniform_space α] [add_group α] [uniform_add_group α] [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : filter.tendsto f (nhds 0) (nhds 0)) : uniform_continuous f := sorry theorem uniform_continuous_of_continuous {α : Type u_1} {β : Type u_2} [uniform_space α] [add_group α] [uniform_add_group α] [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : continuous f) : uniform_continuous f := sorry /-- The right uniformity on a topological group. -/ def topological_add_group.to_uniform_space (G : Type u) [add_comm_group G] [topological_space G] [topological_add_group G] : uniform_space G := uniform_space.mk (uniform_space.core.mk (filter.comap (fun (p : G × G) => prod.snd p - prod.fst p) (nhds 0)) sorry sorry sorry) sorry theorem uniformity_eq_comap_nhds_zero' (G : Type u) [add_comm_group G] [topological_space G] [topological_add_group G] : uniformity G = filter.comap (fun (p : G × G) => prod.snd p - prod.fst p) (nhds 0) := rfl theorem topological_add_group_is_uniform {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G] : uniform_add_group G := sorry theorem to_uniform_space_eq {G : Type u} [u : uniform_space G] [add_comm_group G] [uniform_add_group G] : topological_add_group.to_uniform_space G = u := sorry namespace add_comm_group /- TODO: when modules are changed to have more explicit base ring, then change replace `is_Z_bilin` by using `is_bilinear_map ℤ` from `tensor_product`. -/ /-- `ℤ`-bilinearity for maps between additive commutative groups. -/ class is_Z_bilin {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) where add_left : ∀ (a a' : α) (b : β), f (a + a', b) = f (a, b) + f (a', b) add_right : ∀ (a : α) (b b' : β), f (a, b + b') = f (a, b) + f (a, b') theorem is_Z_bilin.comp_hom {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] {g : γ → δ} [add_comm_group δ] [is_add_group_hom g] : is_Z_bilin (g ∘ f) := sorry protected instance is_Z_bilin.comp_swap {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] : is_Z_bilin (f ∘ prod.swap) := is_Z_bilin.mk (fun (a a' : β) (b : α) => is_Z_bilin.add_right f b a a') fun (a : β) (b b' : α) => is_Z_bilin.add_left f b b' a theorem is_Z_bilin.zero_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] (b : β) : f (0, b) = 0 := sorry theorem is_Z_bilin.zero_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] (a : α) : f (a, 0) = 0 := is_Z_bilin.zero_left (f ∘ prod.swap) theorem is_Z_bilin.zero {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] : f (0, 0) = 0 := is_Z_bilin.zero_left f 0 theorem is_Z_bilin.neg_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] (a : α) (b : β) : f (-a, b) = -f (a, b) := sorry theorem is_Z_bilin.neg_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] (a : α) (b : β) : f (a, -b) = -f (a, b) := is_Z_bilin.neg_left (f ∘ prod.swap) b a theorem is_Z_bilin.sub_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] (a : α) (a' : α) (b : β) : f (a - a', b) = f (a, b) - f (a', b) := sorry theorem is_Z_bilin.sub_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [add_comm_group β] [add_comm_group γ] (f : α × β → γ) [is_Z_bilin f] (a : α) (b : β) (b' : β) : f (a, b - b') = f (a, b) - f (a, b') := is_Z_bilin.sub_left (f ∘ prod.swap) b b' a end add_comm_group -- α, β and G are abelian topological groups, G is a uniform space theorem is_Z_bilin.tendsto_zero_left {α : Type u_1} {β : Type u_2} [topological_space α] [add_comm_group α] [topological_space β] [add_comm_group β] {G : Type u_5} [uniform_space G] [add_comm_group G] {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : add_comm_group.is_Z_bilin ψ] (x₁ : α) : filter.tendsto ψ (nhds (x₁, 0)) (nhds 0) := sorry theorem is_Z_bilin.tendsto_zero_right {α : Type u_1} {β : Type u_2} [topological_space α] [add_comm_group α] [topological_space β] [add_comm_group β] {G : Type u_5} [uniform_space G] [add_comm_group G] {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : add_comm_group.is_Z_bilin ψ] (y₁ : β) : filter.tendsto ψ (nhds (0, y₁)) (nhds 0) := eq.mp (Eq._oldrec (Eq.refl (filter.tendsto ψ (nhds (0, y₁)) (nhds (ψ (0, y₁))))) (add_comm_group.is_Z_bilin.zero_left ψ y₁)) (continuous.tendsto hψ (0, y₁)) -- β is a dense subgroup of α, inclusion is denoted by e theorem tendsto_sub_comap_self {α : Type u_1} {β : Type u_2} [topological_space α] [add_comm_group α] [topological_add_group α] [topological_space β] [add_comm_group β] {e : β → α} [is_add_group_hom e] (de : dense_inducing e) (x₀ : α) : filter.tendsto (fun (t : β × β) => prod.snd t - prod.fst t) (filter.comap (fun (p : β × β) => (e (prod.fst p), e (prod.snd p))) (nhds (x₀, x₀))) (nhds 0) := sorry namespace dense_inducing -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense images into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {G : Type u_5} [topological_space α] [add_comm_group α] [topological_add_group α] [topological_space β] [add_comm_group β] [topological_add_group β] [topological_space γ] [add_comm_group γ] [topological_add_group γ] [topological_space δ] [add_comm_group δ] [topological_add_group δ] [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated_space G] [complete_space G] {e : β → α} [is_add_group_hom e] (de : dense_inducing e) {f : δ → γ} [is_add_group_hom f] (df : dense_inducing f) {φ : β × δ → G} (hφ : continuous φ) [bilin : add_comm_group.is_Z_bilin φ] : continuous (extend (dense_inducing.prod de df) φ) := sorry
fec072c7a5ebb80d8c5b8c425c3bcdae75d44dae
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/nat/div_auto.lean
9912663b459e7b3bff8ecd36e2d9b7af42033b81
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,050
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.wf import Mathlib.Lean3Lib.init.data.nat.basic namespace Mathlib namespace nat protected def div (x : ℕ) : ℕ → ℕ := well_founded.fix lt_wf div.F protected instance has_div : Div ℕ := { div := nat.div } theorem div_def_aux (x : ℕ) (y : ℕ) : x / y = dite (0 < y ∧ y ≤ x) (fun (h : 0 < y ∧ y ≤ x) => (x - y) / y + 1) fun (h : ¬(0 < y ∧ y ≤ x)) => 0 := congr_fun (well_founded.fix_eq lt_wf div.F x) y protected def mod (x : ℕ) : ℕ → ℕ := well_founded.fix lt_wf mod.F protected instance has_mod : Mod ℕ := { mod := nat.mod } theorem mod_def_aux (x : ℕ) (y : ℕ) : x % y = dite (0 < y ∧ y ≤ x) (fun (h : 0 < y ∧ y ≤ x) => (x - y) % y) fun (h : ¬(0 < y ∧ y ≤ x)) => x := congr_fun (well_founded.fix_eq lt_wf mod.F x) y end Mathlib
ee893870da8717717c7a2d43b0246f24f25eba3e
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Leanpkg.lean
101eb537e885111f7bb7333130c5b274d0bede97
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
8,883
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich -/ import Leanpkg.Resolve import Leanpkg.Git import Leanpkg.Build open System namespace Leanpkg def readManifest : IO Manifest := do let m ← Manifest.fromFile leanpkgTomlFn if m.leanVersion ≠ leanVersionString then IO.eprintln $ "\nWARNING: Lean version mismatch: installed version is " ++ leanVersionString ++ ", but package requires " ++ m.leanVersion ++ "\n" return m def writeManifest (manifest : Lean.Syntax) (fn : FilePath) : IO Unit := do IO.FS.writeFile fn manifest.reprint.get! def lockFileName : System.FilePath := ⟨".leanpkg-lock"⟩ partial def withLockFile (x : IO α) : IO α := do acquire try x finally IO.FS.removeFile lockFileName where acquire (firstTime := true) := try -- TODO: lock file should ideally contain PID if !System.Platform.isWindows then discard <| IO.FS.Handle.mkPrim lockFileName "wx" else -- `x` mode doesn't seem to work on Windows even though it's listed at -- https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfopen?view=msvc-160 -- ...? Let's use the slightly racy approach then. if ← lockFileName.pathExists then throw <| IO.Error.alreadyExists 0 "" discard <| IO.FS.Handle.mk lockFileName IO.FS.Mode.write catch | IO.Error.alreadyExists _ _ => do if firstTime then IO.eprintln s!"Waiting for prior leanpkg invocation to finish... (remove '{lockFileName}' if stuck)" IO.sleep (ms := 300) acquire (firstTime := false) | e => throw e def getRootPart (pkg : FilePath := ".") : IO Lean.Name := do let entries ← pkg.readDir match entries.filter (FilePath.extension ·.fileName == "lean") with | #[rootFile] => FilePath.withExtension rootFile.fileName "" |>.toString | #[] => throw <| IO.userError s!"no '.lean' file found in {← IO.FS.realPath "."}" | _ => throw <| IO.userError s!"{← IO.FS.realPath "."} must contain a unique '.lean' file as the package root" structure Configuration := leanPath : String leanSrcPath : String moreDeps : List FilePath def configure : IO Configuration := do let d ← readManifest IO.eprintln $ "configuring " ++ d.name ++ " " ++ d.version let assg ← solveDeps d let paths ← constructPath assg let mut moreDeps := [leanpkgTomlFn] for path in paths do unless path == FilePath.mk "." / "." do -- build recursively -- TODO: share build of common dependencies execCmd { cmd := (← IO.appPath).toString cwd := path args := #["build"] } moreDeps := (path / Build.buildPath / (← getRootPart path).toString |>.withExtension "olean") :: moreDeps return { leanPath := SearchPath.toString <| paths.map (· / Build.buildPath) leanSrcPath := SearchPath.toString paths moreDeps } def execMake (makeArgs : List String) (cfg : Build.Config) : IO Unit := withLockFile do let manifest ← readManifest let leanArgs := (match manifest.timeout with | some t => ["-T", toString t] | none => []) ++ cfg.leanArgs let mut spawnArgs := { cmd := "sh" cwd := manifest.effectivePath args := #["-c", s!"\"{← IO.appDir}/leanmake\" PKG={cfg.pkg} LEAN_OPTS=\"{" ".intercalate leanArgs}\" LEAN_PATH=\"{cfg.leanPath}\" {" ".intercalate makeArgs} MORE_DEPS+=\"{" ".intercalate (cfg.moreDeps.map toString)}\" >&2"] } execCmd spawnArgs def buildImports (imports : List String) (leanArgs : List String) : IO Unit := do unless ← leanpkgTomlFn.pathExists do return let manifest ← readManifest let cfg ← configure let imports := imports.map (·.toName) let root ← getRootPart let localImports := imports.filter (·.getRoot == root) if localImports != [] then let buildCfg : Build.Config := { pkg := root, leanArgs, leanPath := cfg.leanPath, moreDeps := cfg.moreDeps } if ← FilePath.pathExists "Makefile" then let oleans := localImports.map fun i => Lean.modToFilePath "build" i "olean" |>.toString execMake oleans buildCfg else Build.buildModules buildCfg localImports IO.println cfg.leanPath IO.println cfg.leanSrcPath def build (makeArgs leanArgs : List String) : IO Unit := do let cfg ← configure let root ← getRootPart let buildCfg : Build.Config := { pkg := root, leanArgs, leanPath := cfg.leanPath, moreDeps := cfg.moreDeps } if makeArgs != [] || (← FilePath.pathExists "Makefile") then execMake makeArgs buildCfg else Build.buildModules buildCfg [root] def initGitignoreContents := "/build " def initPkg (n : String) (fromNew : Bool) : IO Unit := do IO.FS.writeFile leanpkgTomlFn s!"[package] name = \"{n}\" version = \"0.1\" lean_version = \"{leanVersionString}\" " IO.FS.writeFile ⟨s!"{n.capitalize}.lean"⟩ "def main : IO Unit := IO.println \"Hello, world!\" " let h ← IO.FS.Handle.mk ⟨".gitignore"⟩ IO.FS.Mode.append (bin := false) h.putStr initGitignoreContents unless ← System.FilePath.isDir ⟨".git"⟩ do (do execCmd {cmd := "git", args := #["init", "-q"]} unless upstreamGitBranch = "master" do execCmd {cmd := "git", args := #["checkout", "-B", upstreamGitBranch]} ) <|> IO.eprintln "WARNING: failed to initialize git repository" def init (n : String) := initPkg n false def usage := "Lean package manager, version " ++ uiLeanVersionString ++ " Usage: leanpkg <command> init <name> create a Lean package in the current directory configure download and build dependencies build [<args>] configure and build *.olean files See `leanpkg help <command>` for more information on a specific command." def main : (cmd : String) → (leanpkgArgs leanArgs : List String) → IO Unit | "init", [Name], [] => init Name | "configure", [], [] => discard <| configure | "print-paths", leanpkgArgs, leanArgs => buildImports leanpkgArgs leanArgs | "build", makeArgs, leanArgs => build makeArgs leanArgs | "help", ["configure"], [] => IO.println "Download dependencies Usage: leanpkg configure This command sets up the `build/deps` directory. For each (transitive) git dependency, the specified commit is checked out into a sub-directory of `build/deps`. If there are dependencies on multiple versions of the same package, the version materialized is undefined. No copy is made of local dependencies." | "help", ["build"], [] => IO.println "download dependencies and build *.olean files Usage: leanpkg build [<leanmake-args>] [-- <lean-args>] This command invokes `leanpkg configure` followed by `leanmake <leanmake-args> LEAN_OPTS=<lean-args>`. If defined, the `package.timeout` configuration value is passed to Lean via its `-T` parameter. If no <lean-args> are given, only .olean files will be produced in `build/`. If `lib` or `bin` is passed instead, the extracted C code is compiled with `c++` and a static library in `build/lib` or an executable in `build/bin`, respectively, is created. `leanpkg build bin` requires a declaration of name `main` in the root namespace, which must return `IO Unit` or `IO UInt32` (the exit code) and may accept the program's command line arguments as a `List String` parameter. NOTE: building and linking dependent libraries currently has to be done manually, e.g. ``` $ (cd a; leanpkg build lib) $ (cd b; leanpkg build bin LINK_OPTS=../a/build/lib/libA.a) ```" | "help", ["init"], [] => IO.println "Create a new Lean package in the current directory Usage: leanpkg init <name> This command creates a new Lean package with the given name in the current directory." | "help", _, [] => IO.println usage | _, _, _ => throw <| IO.userError usage private def splitCmdlineArgsCore : List String → List String × List String | [] => ([], []) | (arg::args) => if arg == "--" then ([], args) else let (outerArgs, innerArgs) := splitCmdlineArgsCore args (arg::outerArgs, innerArgs) def splitCmdlineArgs : List String → IO (String × List String × List String) | [] => throw <| IO.userError usage | [cmd] => return (cmd, [], []) | (cmd::rest) => let (outerArgs, innerArgs) := splitCmdlineArgsCore rest return (cmd, outerArgs, innerArgs) end Leanpkg def main (args : List String) : IO UInt32 := do try Lean.initSearchPath none -- HACK let (cmd, outerArgs, innerArgs) ← Leanpkg.splitCmdlineArgs args Leanpkg.main cmd outerArgs innerArgs pure 0 catch e => IO.eprintln e -- avoid "uncaught exception: ..." pure 1
13c63b9dce08c6c6196285c16adff3fe7c6fbb74
57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5
/analysis/metric_space.lean
c7f86b0a6879473970172fae8348b9b3b3df3bf2
[ "Apache-2.0" ]
permissive
louisanu/mathlib
11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe
2bd5e2159d20a8f20d04fc4d382e65eea775ed39
refs/heads/master
1,617,706,993,439
1,523,163,654,000
1,523,163,654,000
124,519,997
0
0
Apache-2.0
1,520,588,283,000
1,520,588,283,000
null
UTF-8
Lean
false
false
18,422
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import data.real.basic analysis.topology.topological_structures open lattice set filter classical noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Construct a metric space from a distance function and metric space axioms -/ def metric_space.uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. -/ class metric_space (α : Type u) : Type u := (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (to_uniform_space : uniform_space α := metric_space.uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : uniformity = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) theorem uniformity_dist_of_mem_uniformity {U : filter (α × α)} (D : α → α → ℝ) (H : ∀ s, s ∈ U.sets ↔ ∃ε>0, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>0, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) variables [metric_space α] instance metric_space.to_uniform_space' : uniform_space α := metric_space.to_uniform_space α /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ def dist : α → α → ℝ := metric_space.dist @[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y @[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y := by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y) /- instantiate metric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ := (eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0, λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm theorem uniformity_dist : uniformity = (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}) := metric_space.uniformity_dist _ theorem uniformity_dist' : uniformity = (⨅ε:{ε:ℝ // ε>0}, principal {p:α×α | dist p.1 p.2 < ε.val}) := by simp [infi_subtype]; exact uniformity_dist theorem mem_uniformity_dist {s : set (α×α)} : s ∈ (@uniformity α _).sets ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := begin rw [uniformity_dist', infi_sets_eq], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff] {contextual := tt}⟩, exact ⟨⟨1, zero_lt_one⟩⟩ end theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ (@uniformity α _).sets := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_of_metric [metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_dist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ theorem uniform_embedding_of_metric [metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ theorem totally_bounded_of_metric {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ lemma cauchy_of_metric {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f.sets, ∀ x y ∈ t, dist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ theorem nhds_eq_metric : nhds x = (⨅ε:{ε:ℝ // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_dist', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, dist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff_metric : s ∈ (nhds x).sets ↔ ∃ε>0, ball x ε ⊆ s := begin rw [nhds_eq_metric, infi_sets_eq], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right] }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end theorem is_open_metric : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff_metric] theorem is_open_ball : is_open (ball x ε) := is_open_metric.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ (nhds x).sets := mem_nhds_sets is_open_ball (mem_ball_self ε0) theorem tendsto_nhds_of_metric [metric_space β] {f : α → β} {a b} : tendsto f (nhds a) (nhds b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := ⟨λ H ε ε0, mem_nhds_iff_metric.1 (H (ball_mem_nhds _ ε0)), λ H s hs, let ⟨ε, ε0, hε⟩ := mem_nhds_iff_metric.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_nhds_iff_metric.2 ⟨δ, δ0, λ x h, hε (hδ h)⟩⟩ theorem continuous_of_metric [metric_space β] {f : α → β} : continuous f ↔ ∀ {b} (ε > 0), ∃ δ > 0, ∀{a}, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_tendsto.trans $ forall_congr $ λ b, tendsto_nhds_of_metric theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) instance metric_space.to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-- Instantiate the reals as a metric space. -/ instance : metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, by rw [abs_sub], dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg instance : orderable_topology ℝ := orderable_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) }, { intros s h, rcases mem_nhds_iff_metric.1 h with ⟨ε, ε0, ss⟩, exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) }, end def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) : metric_space α := { dist := @dist _ m, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := U, uniformity_dist := H.trans (@uniformity_dist α _) } def metric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, to_uniform_space := uniform_space.vmap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_vmap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } theorem metric_space.induced_uniform_embedding {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : by haveI := metric_space.induced f hf m; exact uniform_embedding f := by let := metric_space.induced f hf m; exactI uniform_embedding_of_metric.2 ⟨hf, uniform_continuous_vmap, λ ε ε0, ⟨ε, ε0, λ a b, id⟩⟩ instance {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced subtype.val (λ x y, subtype.eq) t theorem subtype.dist_eq {p : α → Prop} [t : metric_space α] (x y : subtype p) : dist x y = dist x.1 y.1 := rfl instance prod.metric_space_max [metric_space β] : metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_dist := begin refine prod_uniformity.trans _, simp [uniformity_dist, vmap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, set_eq_def, max_lt_iff] end, to_uniform_space := prod.uniform_space } theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_of_metric.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous_dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := (hf.prod_mk hg).comp uniform_continuous_dist' theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist'.continuous theorem continuous_dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := (hf.prod_mk hg).comp continuous_dist' theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, dist (f x) (g x)) x (nhds (dist a b)) := have tendsto (λp:α×α, dist p.1 p.2) (nhds (a, b)) (nhds (dist a b)), from continuous_iff_tendsto.mp continuous_dist' (a, b), (hf.prod_mk hg).comp (by rw [nhds_prod_eq] at this; exact this) lemma nhds_vmap_dist (a : α) : (nhds (0 : ℝ)).vmap (λa', dist a' a) = nhds a := have h₁ : ∀ε, (λa', dist a' a) ⁻¹' ball 0 ε ⊆ ball a ε, by simp [subset_def, real.dist_0_eq_abs], have h₂ : tendsto (λa', dist a' a) (nhds a) (nhds (dist a a)), from tendsto_dist tendsto_id tendsto_const_nhds, le_antisymm (by simp [h₁, nhds_eq_metric, infi_le_infi, principal_mono, -le_principal_iff, -le_infi_iff]) (by simpa [map_le_iff_le_vmap.symm, tendsto] using h₂) lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (nhds a)) ↔ (tendsto (λb, dist (f b) a) x (nhds 0)) := by rw [← nhds_vmap_dist a, tendsto_vmap_iff] theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_dist continuous_id continuous_const) continuous_const
1cc5bf36c2419ce58c26ed29fc43d4a1d763b68b
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/linear_algebra/clifford_algebra/grading.lean
5be8b1cf42528566375549c79432c5f78c7b5c37
[ "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
9,225
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.clifford_algebra.basic import data.zmod.basic import ring_theory.graded_algebra.basic /-! # Results about the grading structure of the clifford algebra The main result is `clifford_algebra.graded_algebra`, which says that the clifford algebra is a ℤ₂-graded algebra (or "superalgebra"). -/ namespace clifford_algebra variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] variables {Q : quadratic_form R M} open_locale direct_sum variables (Q) /-- The even or odd submodule, defined as the supremum of the even or odd powers of `(ι Q).range`. `even_odd 0` is the even submodule, and `even_odd 1` is the odd submodule. -/ def even_odd (i : zmod 2) : submodule R (clifford_algebra Q) := ⨆ (j : {n : ℕ // ↑n = i}), (ι Q).range ^ (j : ℕ) lemma one_le_even_odd_zero : 1 ≤ even_odd Q 0 := begin refine le_trans _ (le_supr _ ⟨0, nat.cast_zero⟩), exact (pow_zero _).ge, end lemma range_ι_le_even_odd_one : (ι Q).range ≤ even_odd Q 1 := begin refine le_trans _ (le_supr _ ⟨1, nat.cast_one⟩), exact (pow_one _).ge, end lemma ι_mem_even_odd_one (m : M) : ι Q m ∈ even_odd Q 1 := range_ι_le_even_odd_one Q $ linear_map.mem_range_self _ m lemma ι_mul_ι_mem_even_odd_zero (m₁ m₂ : M) : ι Q m₁ * ι Q m₂ ∈ even_odd Q 0 := submodule.mem_supr_of_mem ⟨2, rfl⟩ begin rw [subtype.coe_mk, pow_two], exact submodule.mul_mem_mul ((ι Q).mem_range_self m₁) ((ι Q).mem_range_self m₂), end lemma even_odd_mul_le (i j : zmod 2) : even_odd Q i * even_odd Q j ≤ even_odd Q (i + j) := begin simp_rw [even_odd, submodule.supr_eq_span, submodule.span_mul_span], apply submodule.span_mono, intros z hz, obtain ⟨x, y, hx, hy, rfl⟩ := hz, obtain ⟨xi, hx'⟩ := set.mem_Union.mp hx, obtain ⟨yi, hy'⟩ := set.mem_Union.mp hy, refine set.mem_Union.mpr ⟨⟨xi + yi, by simp only [nat.cast_add, xi.prop, yi.prop]⟩, _⟩, simp only [subtype.coe_mk, nat.cast_add, pow_add], exact submodule.mul_mem_mul hx' hy', end instance even_odd.graded_monoid : set_like.graded_monoid (even_odd Q) := { one_mem := submodule.one_le.mp (one_le_even_odd_zero Q), mul_mem := λ i j p q hp hq, submodule.mul_le.mp (even_odd_mul_le Q _ _) _ hp _ hq } /-- A version of `clifford_algebra.ι` that maps directly into the graded structure. This is primarily an auxiliary construction used to provide `clifford_algebra.graded_algebra`. -/ def graded_algebra.ι : M →ₗ[R] ⨁ i : zmod 2, even_odd Q i := direct_sum.lof R (zmod 2) (λ i, ↥(even_odd Q i)) 1 ∘ₗ (ι Q).cod_restrict _ (ι_mem_even_odd_one Q) lemma graded_algebra.ι_apply (m : M) : graded_algebra.ι Q m = direct_sum.of (λ i, ↥(even_odd Q i)) 1 (⟨ι Q m, ι_mem_even_odd_one Q m⟩) := rfl lemma graded_algebra.ι_sq_scalar (m : M) : graded_algebra.ι Q m * graded_algebra.ι Q m = algebra_map R _ (Q m) := begin rw [graded_algebra.ι_apply Q, direct_sum.of_mul_of, direct_sum.algebra_map_apply], refine direct_sum.of_eq_of_graded_monoid_eq (sigma.subtype_ext rfl $ ι_sq_scalar _ _), end lemma graded_algebra.lift_ι_eq (i' : zmod 2) (x' : even_odd Q i') : lift Q ⟨by apply graded_algebra.ι Q, graded_algebra.ι_sq_scalar Q⟩ x' = direct_sum.of (λ i, even_odd Q i) i' x' := begin cases x' with x' hx', dsimp only [subtype.coe_mk, direct_sum.lof_eq_of], refine submodule.supr_induction' _ (λ i x hx, _) _ (λ x y hx hy ihx ihy, _) hx', { obtain ⟨i, rfl⟩ := i, dsimp only [subtype.coe_mk] at hx, refine submodule.pow_induction_on_left' _ (λ r, _) (λ x y i hx hy ihx ihy, _) (λ m hm i x hx ih, _) hx, { rw [alg_hom.commutes, direct_sum.algebra_map_apply], refl }, { rw [alg_hom.map_add, ihx, ihy, ←map_add], refl }, { obtain ⟨_, rfl⟩ := hm, rw [alg_hom.map_mul, ih, lift_ι_apply, graded_algebra.ι_apply Q, direct_sum.of_mul_of], refine direct_sum.of_eq_of_graded_monoid_eq (sigma.subtype_ext _ _); dsimp only [graded_monoid.mk, subtype.coe_mk], { rw [nat.succ_eq_add_one, add_comm, nat.cast_add, nat.cast_one] }, refl } }, { rw alg_hom.map_zero, apply eq.symm, apply dfinsupp.single_eq_zero.mpr, refl, }, { rw [alg_hom.map_add, ihx, ihy, ←map_add], refl }, end /-- The clifford algebra is graded by the even and odd parts. -/ instance graded_algebra : graded_algebra (even_odd Q) := graded_algebra.of_alg_hom (even_odd Q) -- while not necessary, the `by apply` makes this elaborate faster (lift Q ⟨by apply graded_algebra.ι Q, graded_algebra.ι_sq_scalar Q⟩) -- the proof from here onward is mostly similar to the `tensor_algebra` case, with some extra -- handling for the `supr` in `even_odd`. (begin ext m, dsimp only [linear_map.comp_apply, alg_hom.to_linear_map_apply, alg_hom.comp_apply, alg_hom.id_apply], rw [lift_ι_apply, graded_algebra.ι_apply Q, direct_sum.coe_alg_hom_of, subtype.coe_mk], end) (by apply graded_algebra.lift_ι_eq Q) lemma supr_ι_range_eq_top : (⨆ i : ℕ, (ι Q).range ^ i) = ⊤ := begin rw [← (direct_sum.decomposition.is_internal (even_odd Q)).submodule_supr_eq_top, eq_comm], calc (⨆ (i : zmod 2) (j : {n // ↑n = i}), (ι Q).range ^ ↑j) = (⨆ (i : Σ i : zmod 2, {n : ℕ // ↑n = i}), (ι Q).range ^ (i.2 : ℕ)) : by rw supr_sigma ... = (⨆ (i : ℕ), (ι Q).range ^ i) : function.surjective.supr_congr (λ i, i.2) (λ i, ⟨⟨_, i, rfl⟩, rfl⟩) (λ _, rfl), end lemma even_odd_is_compl : is_compl (even_odd Q 0) (even_odd Q 1) := (direct_sum.decomposition.is_internal (even_odd Q)).is_compl zero_ne_one $ begin have : (finset.univ : finset (zmod 2)) = {0, 1} := rfl, simpa using congr_arg (coe : finset (zmod 2) → set (zmod 2)) this, end /-- To show a property is true on the even or odd part, it suffices to show it is true on the scalars or vectors (respectively), closed under addition, and under left-multiplication by a pair of vectors. -/ @[elab_as_eliminator] lemma even_odd_induction (n : zmod 2) {P : Π x, x ∈ even_odd Q n → Prop} (hr : ∀ v (h : v ∈ (ι Q).range ^ n.val), P v (submodule.mem_supr_of_mem ⟨n.val, n.nat_cast_zmod_val⟩ h)) (hadd : ∀ {x y hx hy}, P x hx → P y hy → P (x + y) (submodule.add_mem _ hx hy)) (hιι_mul : ∀ m₁ m₂ {x hx}, P x hx → P (ι Q m₁ * ι Q m₂ * x) (zero_add n ▸ set_like.mul_mem_graded (ι_mul_ι_mem_even_odd_zero Q m₁ m₂) hx)) (x : clifford_algebra Q) (hx : x ∈ even_odd Q n) : P x hx := begin apply submodule.supr_induction' _ _ (hr 0 (submodule.zero_mem _)) @hadd, refine subtype.rec _, simp_rw [subtype.coe_mk, zmod.nat_coe_zmod_eq_iff, add_comm n.val], rintros n' ⟨k, rfl⟩ xv, simp_rw [pow_add, pow_mul], refine submodule.mul_induction_on' _ _, { intros a ha b hb, refine submodule.pow_induction_on_left' ((ι Q).range ^ 2) _ _ _ ha, { intro r, simp_rw ←algebra.smul_def, exact hr _ (submodule.smul_mem _ _ hb), }, { intros x y n hx hy, simp_rw add_mul, apply hadd, }, { intros x hx n y hy ihy, revert hx, simp_rw pow_two, refine submodule.mul_induction_on' _ _, { simp_rw linear_map.mem_range, rintros _ ⟨m₁, rfl⟩ _ ⟨m₂, rfl⟩, simp_rw mul_assoc _ y b, refine hιι_mul _ _ ihy, }, { intros x hx y hy ihx ihy, simp_rw add_mul, apply hadd ihx ihy } } }, { intros x y hx hy, apply hadd } end /-- To show a property is true on the even parts, it suffices to show it is true on the scalars, closed under addition, and under left-multiplication by a pair of vectors. -/ @[elab_as_eliminator] lemma even_induction {P : Π x, x ∈ even_odd Q 0 → Prop} (hr : ∀ r : R, P (algebra_map _ _ r) (set_like.algebra_map_mem_graded _ _)) (hadd : ∀ {x y hx hy}, P x hx → P y hy → P (x + y) (submodule.add_mem _ hx hy)) (hιι_mul : ∀ m₁ m₂ {x hx}, P x hx → P (ι Q m₁ * ι Q m₂ * x) (zero_add 0 ▸ set_like.mul_mem_graded (ι_mul_ι_mem_even_odd_zero Q m₁ m₂) hx)) (x : clifford_algebra Q) (hx : x ∈ even_odd Q 0) : P x hx := begin refine even_odd_induction Q 0 (λ rx, _) @hadd hιι_mul x hx, simp_rw [zmod.val_zero, pow_zero], rintro ⟨r, rfl⟩, exact hr r, end /-- To show a property is true on the odd parts, it suffices to show it is true on the vectors, closed under addition, and under left-multiplication by a pair of vectors. -/ @[elab_as_eliminator] lemma odd_induction {P : Π x, x ∈ even_odd Q 1 → Prop} (hι : ∀ v, P (ι Q v) (ι_mem_even_odd_one _ _)) (hadd : ∀ {x y hx hy}, P x hx → P y hy → P (x + y) (submodule.add_mem _ hx hy)) (hιι_mul : ∀ m₁ m₂ {x hx}, P x hx → P (ι Q m₁ * ι Q m₂ * x) (zero_add (1 : zmod 2) ▸ set_like.mul_mem_graded (ι_mul_ι_mem_even_odd_zero Q m₁ m₂) hx)) (x : clifford_algebra Q) (hx : x ∈ even_odd Q 1) : P x hx := begin refine even_odd_induction Q 1 (λ ιv, _) @hadd hιι_mul x hx, simp_rw [zmod.val_one, pow_one], rintro ⟨v, rfl⟩, exact hι v, end end clifford_algebra
4a0cd0a1aed86cb7a8262d565bbb9771cf807a79
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/tactic/restate_axiom.lean
9ab2098e68d71bee68837d3b0667322fd22bc5a3
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
1,557
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.buffer.parser open lean.parser tactic interactive parser /-- `restate_axiom` takes a structure field, and makes a new, definitionally simplified copy of it, appending `_lemma` to the name. The main application is to provide clean versions of structure fields that have been tagged with an auto_param. -/ meta def restate_axiom (d : declaration) (new_name : name) : tactic unit := do (levels, type, value, reducibility, trusted) ← pure (match d.to_definition with | declaration.defn name levels type value reducibility trusted := (levels, type, value, reducibility, trusted) | _ := undefined end), (s, u) ← mk_simp_set ff [] [], new_type ← (s.dsimplify [] type) <|> pure (type), updateex_env $ λ env, env.add (declaration.defn new_name levels new_type value reducibility trusted) private meta def name_lemma (n : name) := match n.components.reverse with | last :: most := mk_str_name n.get_prefix (last.to_string ++ "_lemma") | nil := undefined end @[user_command] meta def restate_axiom_cmd (meta_info : decl_meta_info) (_ : parse $ tk "restate_axiom") : lean.parser unit := do from_lemma ← ident, from_lemma_fully_qualified ← resolve_constant from_lemma, d ← get_decl from_lemma_fully_qualified <|> fail ("declaration " ++ to_string from_lemma ++ " not found"), do { restate_axiom d (name_lemma from_lemma_fully_qualified) }.
91be2f28091816957ab0aab0121bac6eb938724c
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/to_mathlib/localization/localization_of_iso.lean
8a07cc46f883ec4fef52526395ff4a796b3fb6b3
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
2,018
lean
/- If f : A → B has the localization property for a multiplicative S and g : B → C is a bijective ring homomorphism, then (g ∘ f) has the localization property for S too. -/ import algebra.ring import to_mathlib.localization.localization_alt universes u v w noncomputable theory open localization_alt variables {A : Type u} {B : Type v} {C : Type w} [comm_ring A] [comm_ring B] [comm_ring C] variables (S : set A) [is_submonoid S] (f : A → B) [is_ring_hom f] (Hloc : is_localization_data S f) variables (g : B → C) (Hg₁ : function.bijective g) (Hg₂ : is_ring_hom g) include Hloc Hg₁ Hg₂ lemma is_localization_data.of_iso.inverts_data : inverts_data S (g ∘ f) := begin rintros s, rcases (Hloc.inverts s) with ⟨w, Hw⟩, use (g w), rw [←is_ring_hom.map_mul g, Hw, is_ring_hom.map_one g], end lemma is_localization_data.of_iso.has_denom : has_denom S (g ∘ f) := begin intros x, rw function.bijective_iff_has_inverse at Hg₁, rcases Hg₁ with ⟨h, Hhleft, Hhright⟩, rcases (Hloc.has_denom (h x)) with ⟨pq, Hpq⟩, replace Hpq := congr_arg g Hpq, rw is_ring_hom.map_mul g at Hpq, rw Hhright at Hpq, use [pq, Hpq], end lemma is_localization_data.of_iso.has_denom_data : has_denom_data S (g ∘ f) := has_denom_some S (g ∘ f) (is_localization_data.of_iso.has_denom S f Hloc g Hg₁ Hg₂) lemma is_localization_data.of_iso.ker_le : ker (g ∘ f) ≤ submonoid_ann S := begin intros x Hx, rw function.bijective_iff_has_inverse at Hg₁, rcases Hg₁ with ⟨h, Hhleft, Hhright⟩, change g (f x) = 0 at Hx, replace Hx := congr_arg h Hx, rw ←is_ring_hom.map_zero g at Hx, iterate 2 { rw Hhleft at Hx, }, exact Hloc.ker_le Hx, end lemma is_localization_data.of_iso : is_localization_data S (g ∘ f) := { inverts := is_localization_data.of_iso.inverts_data S f Hloc g Hg₁ Hg₂, has_denom := is_localization_data.of_iso.has_denom_data S f Hloc g Hg₁ Hg₂, ker_le := is_localization_data.of_iso.ker_le S f Hloc g Hg₁ Hg₂, }
1003e0b85e269b51dd0f502a10d288c23a74bdc6
6db8061629f55e774dd3d03be5bf005ffb485e48
/BetterNumLits/OfRadix.lean
d578cad98814ac708413bd93d6894cfd93e3fac5
[]
no_license
tydeu/lean4-betterNumLits
21fd5717d1b62ecb021c73e8cfaa0e3d19005690
45e3b79214b3e1f81f8e034dd12257e993ddc578
refs/heads/master
1,683,103,070,685
1,621,717,131,000
1,621,717,131,000
369,368,844
0
0
null
null
null
null
UTF-8
Lean
false
false
691
lean
import BetterNumLits.Numerals universe u class OfRadix (A : Type u) (radix : Nat) (digits : Array (Fin radix)) where ofRadix : A abbrev ofRadix {A : Type u} (radix : Nat) (digits : Array (Fin radix)) [inst : OfRadix A radix digits] : A := inst.ofRadix @[defaultInstance low] instance {r : Nat} {ds : Array (Fin r)} : OfRadix Nat r ds := ⟨ds.foldl (fun n d => n * r + d) Nat.zero⟩ @[defaultInstance low + low] instance {r : Nat} {n : Fin r} : OfRadix (Fin r) r #[n] := ⟨n⟩ instance {A : Type u} {r : Nat} {ds : Array (Fin r)} [Zero A] [Mul A] [Add A] [CoeHTCT Nat A] [CoeHTCT (Fin r) A] : OfRadix A r ds := ⟨ds.foldl (fun n d => n * (coe r) + (coe d)) zero⟩
6ee7f7555491235c16cc74e6962d3026e44dca9d
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/standard/option.lean
3a71480ba220c249ce769269dbd3b19c2fa5d1cc
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
361
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import logic inductive option (A : Type) : Type := | none {} : option A | some : A → option A theorem inhabited_option [instance] (A : Type) : inhabited (option A) := inhabited_intro none
4ed80483792d079ca0fedcf4dc5b7fd71990d409
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/ring_theory/free_comm_ring.lean
f9671090dea3c2034a7b9d92abb93942c807b3ea
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
15,971
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import group_theory.free_abelian_group data.equiv.functor data.mv_polynomial import ring_theory.ideal_operations ring_theory.free_ring noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v variables (α : Type u) def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring instance : comm_ring (free_comm_ring α) := free_abelian_group.comm_ring _ instance : inhabited (free_comm_ring α) := ⟨0⟩ variables {α} def of (x : α) : free_comm_ring α := free_abelian_group.of ([x] : multiset α) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {β : Type v} [comm_ring β] (f : α → β) /-- Lift a map `α → R` to a ring homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : free_comm_ring α → β := free_abelian_group.lift $ λ s, (s.map f).prod @[simp] lemma lift_zero : lift f 0 = 0 := rfl @[simp] lemma lift_one : lift f 1 = 1 := free_abelian_group.lift.of _ _ @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_add (x y) : lift f (x + y) = lift f x + lift f y := free_abelian_group.lift.add _ _ _ @[simp] lemma lift_neg (x) : lift f (-x) = -lift f x := free_abelian_group.lift.neg _ _ @[simp] lemma lift_sub (x y) : lift f (x - y) = lift f x - lift f y := free_abelian_group.lift.sub _ _ _ @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros s2, conv { to_lhs, dsimp only [(*), mul_zero_class.mul, semiring.mul, ring.mul, semigroup.mul, comm_ring.mul] }, rw [free_abelian_group.lift.of, lift, free_abelian_group.lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros s1, iterate 3 { rw free_abelian_group.lift.of }, calc _ = multiset.prod ((multiset.map f s1) + (multiset.map f s2)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _ }, { intros s1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros s2 ih, rw [mul_neg_eq_neg_mul_symm, lift_neg, lift_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, lift_add, lift_add, mul_add, ih1, ih2] }, end /-- Lift of a map `f : α → β` to `free_comm_ring α` as a ring homomorphism. We don't use it as the canonical form because Lean fails to coerce it to a function. -/ def lift_hom : free_comm_ring α →+* β := ⟨lift f, lift_one f, lift_mul f, lift_zero f, lift_add f⟩ instance : is_ring_hom (lift f) := (lift_hom f).is_ring_hom @[simp] lemma coe_lift_hom : ⇑(lift_hom f : free_comm_ring α →+* β) = lift f := rfl @[simp] lemma lift_pow (x) (n : ℕ) : lift f (x ^ n) = lift f x ^ n := (lift_hom f).map_pow _ _ @[simp] lemma lift_comp_of (f : free_comm_ring α → β) [is_ring_hom f] : lift (f ∘ of) = f := funext $ λ x, free_comm_ring.induction_on x (by rw [lift_neg, lift_one, is_ring_hom.map_neg f, is_ring_hom.map_one f]) (lift_of _) (λ x y ihx ihy, by rw [lift_add, is_ring_hom.map_add f, ihx, ihy]) (λ x y ihx ihy, by rw [lift_mul, is_ring_hom.map_mul f, ihx, ihy]) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α → free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift_hom $ of ∘ f lemma map_zero : map f 0 = 0 := rfl lemma map_one : map f 1 = 1 := rfl lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ lemma map_add (x y) : map f (x + y) = map f x + map f y := lift_add _ _ _ lemma map_neg (x) : map f (-x) = -map f x := lift_neg _ _ lemma map_sub (x y) : map f (x - y) = map f x - map f y := lift_sub _ _ _ lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ lemma map_pow (x) (n : ℕ) : map f (x ^ n) = (map f x) ^ n := lift_pow _ _ _ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ ring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem _ _ _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero : is_supported 0 s := is_add_submonoid.zero_mem theorem is_supported_one : is_supported 1 s := is_submonoid.one_mem theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported def restriction (s : set α) [decidable_pred s] (x : free_comm_ring α) : free_comm_ring s := lift (λ p, if H : p ∈ s then of ⟨p, H⟩ else 0) x section restriction variables (s : set α) [decidable_pred s] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ @[simp] lemma restriction_zero : restriction s 0 = 0 := lift_zero _ @[simp] lemma restriction_one : restriction s 1 = 1 := lift_one _ @[simp] lemma restriction_add : restriction s (x + y) = restriction s x + restriction s y := lift_add _ _ _ @[simp] lemma restriction_neg : restriction s (-x) = -restriction s x := lift_neg _ _ @[simp] lemma restriction_sub : restriction s (x - y) = restriction s x - restriction s y := lift_sub _ _ _ @[simp] lemma restriction_mul : restriction s (x * y) = restriction s x * restriction s y := lift_mul _ _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, ring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin classical, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : polynomial ℤ) else polynomial.X) x = n, { intros x hx, refine ring.in_closure.rec_on hx _ _ _ _, { use 1, rw [lift_one], norm_cast }, { use -1, rw [lift_neg, lift_one], norm_cast }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [lift_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [lift_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw polynomial.int_cast_eq_C at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg one_ne_zero, polynomial.coeff_X, if_pos rfl] at this, apply_instance end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred s] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw restriction_one, refl }, { rw [restriction_neg, map_neg, restriction_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, restriction_of, dif_pos hps, map_mul, map_of, ih] }, { intros x y ihx ihy, rw [restriction_add, map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ finset.mem_singleton_self _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, set.finite_union hfs hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, set.finite_union hfs hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa finset.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) def to_free_comm_ring {α} : free_ring α → free_comm_ring α := free_ring.lift free_comm_ring.of instance to_free_comm_ring.is_ring_hom : is_ring_hom (@to_free_comm_ring α) := free_ring.is_ring_hom free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ instance coe.is_ring_hom : is_ring_hom (coe : free_ring α → free_comm_ring α) := free_ring.to_free_comm_ring.is_ring_hom _ @[simp] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := free_ring.lift_neg _ _ @[simp] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := free_ring.lift_add _ _ _ @[simp] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := free_ring.lift_sub _ _ _ @[simp] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := free_ring.lift_mul _ _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact free_ring.lift_add _ _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact free_ring.lift_mul _ _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := begin funext, apply @free_abelian_group.lift.ext _ _ _ (coe : free_ring α → free_comm_ring α) _ _ (free_abelian_group.lift.is_add_group_hom _), intros x, change free_ring.lift free_comm_ring.of (free_abelian_group.of x) = _, change _ = free_abelian_group.of (↑x), induction x with hd tl ih, {refl}, simp only [*, free_ring.lift, free_comm_ring.of, free_abelian_group.of, free_abelian_group.lift, free_group.of, free_group.to_group, free_group.to_group.aux, mul_one, free_group.quot_lift_mk, abelianization.lift.of, bool.cond_tt, list.prod_cons, cond, list.prod_nil, list.map] at *, refl end def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := @ring_equiv.of' (free_ring α) (free_comm_ring α) _ _ (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) $ begin delta functor.map_equiv, rw congr_arg is_ring_hom _, work_on_goal 2 { symmetry, exact coe_eq α }, apply_instance end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by rw [← (subsingleton_equiv_free_comm_ring α).left_inv (y * x), is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, mul_comm, ← is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, (subsingleton_equiv_free_comm_ring α).left_inv], .. free_ring.ring α } end free_ring def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := { to_fun := free_comm_ring.lift $ λ a, mv_polynomial.X a, inv_fun := mv_polynomial.eval₂ coe free_comm_ring.of, left_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, refine free_abelian_group.induction_on x rfl _ _ _, { intro s, refine multiset.induction_on s _ _, { unfold free_comm_ring.lift, rw [free_abelian_group.lift.of], exact mv_polynomial.eval₂_one _ _ }, { intros hd tl ih, show mv_polynomial.eval₂ coe free_comm_ring.of (free_comm_ring.lift (λ a, mv_polynomial.X a) (free_comm_ring.of hd * free_abelian_group.of tl)) = free_comm_ring.of hd * free_abelian_group.of tl, rw [free_comm_ring.lift_mul, free_comm_ring.lift_of, mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, ih] } }, { intros s ih, rw [free_comm_ring.lift_neg, ← neg_one_mul, mv_polynomial.eval₂_mul, ← mv_polynomial.C_1, ← mv_polynomial.C_neg, mv_polynomial.eval₂_C, int.cast_neg, int.cast_one, neg_one_mul, ih] }, { intros x₁ x₂ ih₁ ih₂, rw [free_comm_ring.lift_add, mv_polynomial.eval₂_add, ih₁, ih₂] } end, right_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, have : ∀ i : ℤ, free_comm_ring.lift (λ (a : α), mv_polynomial.X a) ↑i = mv_polynomial.C i, { exact λ i, int.induction_on i (by rw [int.cast_zero, free_comm_ring.lift_zero, mv_polynomial.C_0]) (λ i ih, by rw [int.cast_add, int.cast_one, free_comm_ring.lift_add, free_comm_ring.lift_one, ih, mv_polynomial.C_add, mv_polynomial.C_1]) (λ i ih, by rw [int.cast_sub, int.cast_one, free_comm_ring.lift_sub, free_comm_ring.lift_one, ih, mv_polynomial.C_sub, mv_polynomial.C_1]) }, apply mv_polynomial.induction_on x, { intro i, rw [mv_polynomial.eval₂_C, this] }, { intros p q ihp ihq, rw [mv_polynomial.eval₂_add, free_comm_ring.lift_add, ihp, ihq] }, { intros p a ih, rw [mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, free_comm_ring.lift_mul, free_comm_ring.lift_of, ih] } end, .. free_comm_ring.lift_hom $ λ a, mv_polynomial.X a } def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.pempty_ring_equiv _) def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.punit_ring_equiv _) open free_ring def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
95c41a776f2101328858aff85f53afa965bf2cfc
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/uniform_space/compact_separated.lean
b5fb044b4ad4f93d0872b025a91ebd9467444fbf
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
10,688
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.separation /-! # Compact separated uniform spaces ## Main statements * `compact_space_uniformity`: On a separated compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. * `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform structure. This uniform structure is described in the previous item. * Heine-Cantor theorem: continuous functions on compact separated uniform spaces with values in uniform spaces are automatically uniformly continuous. There are several variations, the main one is `compact_space.uniform_continuous_of_continuous`. ## Implementation notes The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly loop. ## tags uniform space, uniform continuity, compact space -/ open_locale classical uniformity topological_space filter open filter uniform_space set variables {α β : Type*} [uniform_space α] [uniform_space β] /-! ### Uniformity on compact separated spaces -/ lemma compact_space_uniformity [compact_space α] [separated_space α] : 𝓤 α = ⨆ x : α, 𝓝 (x, x) := begin symmetry, refine le_antisymm nhds_le_uniformity _, by_contra H, obtain ⟨V, hV, h⟩ : ∃ V : set (α × α), (∀ x : α, V ∈ 𝓝 (x, x)) ∧ 𝓤 α ⊓ 𝓟 Vᶜ ≠ ⊥, { rw le_iff_forall_inf_principal_compl at H, push_neg at H, simpa only [mem_supr_sets] using H }, let F := 𝓤 α ⊓ 𝓟 Vᶜ, obtain ⟨⟨x, y⟩, hx⟩ : ∃ (p : α × α), cluster_pt p F := cluster_point_of_compact h, have : cluster_pt (x, y) (𝓤 α) := hx.of_inf_left, have hxy : x = y := eq_of_uniformity_inf_nhds this, subst hxy, have : cluster_pt (x, x) (𝓟 Vᶜ) := hx.of_inf_right, have : (x, x) ∉ interior V, { have : (x, x) ∈ closure Vᶜ, by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have : (x, x) ∈ interior V, { rw mem_interior_iff_mem_nhds, exact hV x }, contradiction end lemma unique_uniformity_of_compact_t2 {α : Type*} [t : topological_space α] [compact_space α] [t2_space α] {u u' : uniform_space α} (h : u.to_topological_space = t) (h' : u'.to_topological_space = t) : u = u' := begin apply uniform_space_eq, change uniformity _ = uniformity _, haveI : @compact_space α u.to_topological_space := by rw h ; assumption, haveI : @compact_space α u'.to_topological_space := by rw h' ; assumption, haveI : @separated_space α u := by rwa [separated_iff_t2, h], haveI : @separated_space α u' := by rwa [separated_iff_t2, h'], rw [compact_space_uniformity, compact_space_uniformity, h, h'] end /-- The unique uniform structure inducing a given compact Hausdorff topological structure. -/ def uniform_space_of_compact_t2 {α : Type*} [topological_space α] [compact_space α] [t2_space α] : uniform_space α := { uniformity := ⨆ x, 𝓝 (x, x), refl := begin simp_rw [filter.principal_le_iff, mem_supr_sets], rintros V V_in ⟨x, _⟩ ⟨⟩, exact mem_of_nhds (V_in x), end, symm := begin refine le_of_eq _, rw map_supr, congr, ext1 x, erw [nhds_prod_eq, ← prod_comm], end, comp := begin /- This is the difficult part of the proof. We need to prove that, for each neighborhood W of the diagonal Δ, W ○ W is still a neighborhood of the diagonal. -/ set 𝓝Δ := ⨆ x : α, 𝓝 (x, x), -- The filter of neighborhoods of Δ set F := 𝓝Δ.lift' (λ (s : set (α × α)), s ○ s), -- Compositions of neighborhoods of Δ -- If this weren't true, then there would be V ∈ 𝓝Δ such that F ⊓ 𝓟 Vᶜ ≠ ⊥ rw le_iff_forall_inf_principal_compl, intros V V_in, by_contra H, -- Hence compactness would give us a cluster point (x, y) for F ⊓ 𝓟 Vᶜ obtain ⟨⟨x, y⟩, hxy⟩ : ∃ (p : α × α), cluster_pt p (F ⊓ 𝓟 Vᶜ) := cluster_point_of_compact H, -- In particular (x, y) is a cluster point of 𝓟 Vᶜ, hence is not in the interior of V, -- and a fortiori not in Δ, so x ≠ y have clV : cluster_pt (x, y) (𝓟 $ Vᶜ) := hxy.of_inf_right, have : (x, y) ∉ interior V, { have : (x, y) ∈ closure (Vᶜ), by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have diag_subset : diagonal α ⊆ interior V, { rw subset_interior_iff_nhds, rintros ⟨x, x⟩ ⟨⟩, exact (mem_supr_sets.mp V_in : _) x }, have x_ne_y : x ≠ y, { intro h, apply this, apply diag_subset, simp [h] }, -- Since α is compact and Hausdorff, it is normal, hence regular. haveI : normal_space α := normal_of_compact_t2, -- So there are closed neighboords V₁ and V₂ of x and y contained in disjoint open neighborhoods -- U₁ and U₂. obtain ⟨U₁, V₁, U₁_in, V₁_in, U₂, V₂, U₂_in₂, V₂_in, V₁_cl, V₂_cl, U₁_op, U₂_op, VU₁, VU₂, hU₁₂⟩ : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ U₁ ∩ U₂ = ∅ := disjoint_nested_nhds x_ne_y, -- We set U₃ := (V₁ ∪ V₂)ᶜ so that W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃) is an open -- neighborhood of Δ. let U₃ := (V₁ ∪ V₂)ᶜ, have U₃_op : is_open U₃ := is_open_compl_iff.mpr (is_closed_union V₁_cl V₂_cl), let W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃), have W_in : W ∈ 𝓝Δ, { rw mem_supr_sets, intros x, apply mem_nhds_sets (is_open_union (is_open_union _ _) _), { by_cases hx : x ∈ V₁ ∪ V₂, { left, cases hx with hx hx ; [left, right] ; split ; tauto }, { right, rw mem_prod, tauto }, }, all_goals { simp only [is_open_prod, *] } }, -- So W ○ W ∈ F by definition of F have : W ○ W ∈ F, { dsimp [F],-- Lean has weird elaboration trouble with this line exact mem_lift' W_in }, -- And V₁.prod V₂ ∈ 𝓝 (x, y) have hV₁₂ : V₁.prod V₂ ∈ 𝓝 (x, y) := prod_mem_nhds_sets V₁_in V₂_in, -- But (x, y) is also a cluster point of F so (V₁.prod V₂) ∩ (W ○ W) ≠ ∅ have clF : cluster_pt (x, y) F := hxy.of_inf_left, obtain ⟨p, p_in⟩ : ∃ p, p ∈ (V₁.prod V₂) ∩ (W ○ W) := cluster_pt_iff.mp clF hV₁₂ this, -- However the construction of W implies (V₁.prod V₂) ∩ (W ○ W) = ∅. -- Indeed assume for contradiction there is some (u, v) in the intersection. -- So u ∈ V₁, v ∈ V₂, and there exists some w such that (u, w) ∈ W and (w ,v) ∈ W. -- Because u is in V₁ which is disjoint from U₂ and U₃, (u, w) ∈ W forces (u, w) ∈ U₁.prod U₁. -- Similarly, because v ∈ V₂, (w ,v) ∈ W forces (w, v) ∈ U₂.prod U₂. -- Hence w ∈ U₁ ∩ U₂ which is empty. have inter_empty : (V₁.prod V₂) ∩ (W ○ W) = ∅, { rw eq_empty_iff_forall_not_mem, rintros ⟨u, v⟩ ⟨⟨u_in, v_in⟩, w, huw, hwv⟩, have uw_in : (u, w) ∈ U₁.prod U₁ := set.mem_prod.2 ((huw.resolve_right (λ h, (h.1 $ or.inl u_in))).resolve_right (λ h, have u ∈ U₁ ∩ U₂, from ⟨VU₁ u_in, h.1⟩, by rwa hU₁₂ at this)), have wv_in : (w, v) ∈ U₂.prod U₂ := set.mem_prod.2 ((hwv.resolve_right (λ h, (h.2 $ or.inr v_in))).resolve_left (λ h, have v ∈ U₁ ∩ U₂, from ⟨h.2, VU₂ v_in⟩, by rwa hU₁₂ at this)), have : w ∈ U₁ ∩ U₂ := ⟨uw_in.2, wv_in.1⟩, rwa hU₁₂ at this }, -- So we have a contradiction rwa inter_empty at p_in, end, is_open_uniformity := begin -- Here we need to prove the topology induced by the constructed uniformity is the -- topology we started with. suffices : ∀ x : α, comap (prod.mk x) (⨆ y, 𝓝 (y ,y)) = 𝓝 x, { intros s, change is_open s ↔ _, simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity_aux, this] }, intros x, simp_rw [comap_supr, nhds_prod_eq, comap_prod, show prod.fst ∘ prod.mk x = λ y : α, x, by ext ; simp, show prod.snd ∘ (prod.mk x) = (id : α → α), by ext ; refl, comap_id], rw [supr_split_single _ x, comap_const_of_mem (λ V, mem_of_nhds)], suffices : ∀ y ≠ x, comap (λ (y : α), x) (𝓝 y) ⊓ 𝓝 y ≤ 𝓝 x, by simpa, intros y hxy, simp [comap_const_of_not_mem (compl_singleton_mem_nhds hxy) (by simp)], end } /-! ### Heine-Cantor theorem -/ /-- Heine-Cantor: a continuous function on a compact separated uniform space is uniformly continuous. -/ lemma compact_space.uniform_continuous_of_continuous [compact_space α] [separated_space α] {f : α → β} (h : continuous f) : uniform_continuous f := begin calc map (prod.map f f) (𝓤 α) = map (prod.map f f) (⨆ x, 𝓝 (x, x)) : by rw compact_space_uniformity ... = ⨆ x, map (prod.map f f) (𝓝 (x, x)) : by rw map_supr ... ≤ ⨆ x, 𝓝 (f x, f x) : supr_le_supr (λ x, (h.prod_map h).continuous_at) ... ≤ ⨆ y, 𝓝 (y, y) : _ ... ≤ 𝓤 β : nhds_le_uniformity, rw ← supr_range, simp only [and_imp, supr_le_iff, prod.forall, supr_exists, mem_range, prod.mk.inj_iff], rintros _ _ ⟨y, rfl, rfl⟩, exact le_supr (λ x, 𝓝 (x, x)) (f y), end /-- Heine-Cantor: a continuous function on a compact separated set of a uniform space is uniformly continuous. -/ lemma compact.uniform_continuous_on_of_continuous' {s : set α} {f : α → β} (hs : compact s) (hs' : is_separated s) (hf : continuous_on f s) : uniform_continuous_on f s := begin rw uniform_continuous_on_iff_restrict, rw is_separated_iff_induced at hs', rw compact_iff_compact_space at hs, rw continuous_on_iff_continuous_restrict at hf, resetI, exact compact_space.uniform_continuous_of_continuous hf, end /-- Heine-Cantor: a continuous function on a compact set of a separated uniform space is uniformly continuous. -/ lemma compact.uniform_continuous_on_of_continuous [separated_space α] {s : set α} {f : α → β} (hs : compact s) (hf : continuous_on f s) : uniform_continuous_on f s := hs.uniform_continuous_on_of_continuous' (is_separated_of_separated_space s) hf
60e550690535b05cb32e5b2f7630e42b69023070
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/algebra/group/units_hom.lean
2b86b48d05952db67d684aed346c2037d7b5c656
[ "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
3,488
lean
/- Copyright (c) 2018 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes, Kevin Buzzard -/ import algebra.group.units import algebra.group.hom /-! # Lift monoid homomorphisms to group homomorphisms of their units subgroups. -/ universes u v w namespace units variables {M : Type u} {N : Type v} {P : Type w} [monoid M] [monoid N] [monoid P] /-- The group homomorphism on units induced by a `monoid_hom`. -/ @[to_additive "The `add_group` homomorphism on `add_unit`s induced by an `add_monoid_hom`."] def map (f : M →* N) : units M →* units N := monoid_hom.mk' (λ u, ⟨f u.val, f u.inv, by rw [← f.map_mul, u.val_inv, f.map_one], by rw [← f.map_mul, u.inv_val, f.map_one]⟩) (λ x y, ext (f.map_mul x y)) @[simp, to_additive] lemma coe_map (f : M →* N) (x : units M) : ↑(map f x) = f x := rfl @[simp, to_additive] lemma map_comp (f : M →* N) (g : N →* P) : map (g.comp f) = (map g).comp (map f) := rfl variables (M) @[simp, to_additive] lemma map_id : map (monoid_hom.id M) = monoid_hom.id (units M) := by ext; refl /-- Coercion `units M → M` as a monoid homomorphism. -/ @[to_additive "Coercion `add_units M → M` as an add_monoid homomorphism."] def coe_hom : units M →* M := ⟨coe, coe_one, coe_mul⟩ variable {M} @[simp, to_additive] lemma coe_hom_apply (x : units M) : coe_hom M x = ↑x := rfl /-- If a map `g : M → units N` agrees with a homomorphism `f : M →* N`, then this map is a monoid homomorphism too. -/ @[to_additive "If a map `g : M → add_units N` agrees with a homomorphism `f : M →+ N`, then this map is an add_monoid homomorphism too."] def lift_right (f : M →* N) (g : M → units N) (h : ∀ x, ↑(g x) = f x) : M →* units N := { to_fun := g, map_one' := units.ext $ (h 1).symm ▸ f.map_one, map_mul' := λ x y, units.ext $ by simp only [h, coe_mul, f.map_mul] } @[simp, to_additive] lemma coe_lift_right {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : (lift_right f g h x : N) = f x := h x @[simp, to_additive] lemma mul_lift_right_inv {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : f x * ↑(lift_right f g h x)⁻¹ = 1 := by rw [units.mul_inv_eq_iff_eq_mul, one_mul, coe_lift_right] @[simp, to_additive] lemma lift_right_inv_mul {f : M →* N} {g : M → units N} (h : ∀ x, ↑(g x) = f x) (x) : ↑(lift_right f g h x)⁻¹ * f x = 1 := by rw [units.inv_mul_eq_iff_eq_mul, mul_one, coe_lift_right] end units namespace monoid_hom /-- If `f` is a homomorphism from a group `G` to a monoid `M`, then its image lies in the units of `M`, and `f.to_hom_units` is the corresponding monoid homomorphism from `G` to `units M`. -/ @[to_additive "If `f` is a homomorphism from an additive group `G` to an additive monoid `M`, then its image lies in the `add_units` of `M`, and `f.to_hom_units` is the corresponding homomorphism from `G` to `add_units M`."] def to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) : G →* units M := { to_fun := λ g, ⟨f g, f (g⁻¹), by rw [← f.map_mul, mul_inv_self, f.map_one], by rw [← f.map_mul, inv_mul_self, f.map_one]⟩, map_one' := units.ext (f.map_one), map_mul' := λ _ _, units.ext (f.map_mul _ _) } @[simp] lemma coe_to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) (g : G): (f.to_hom_units g : M) = f g := rfl end monoid_hom
8a165a30e8435139b74ec7bd4f7063c75a72e53a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/fderiv/add.lean
459bb39412abe30e8c268b372482a443003af192
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
23,161
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.fderiv.linear import analysis.calculus.fderiv.comp /-! # Additive operations on derivatives > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. For detailed documentation of the Fréchet derivative, see the module docstring of `analysis/calculus/fderiv/basic.lean`. This file contains the usual formulas (and existence assertions) for the derivative of * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions -/ open filter asymptotics continuous_linear_map set metric open_locale topology classical nnreal filter asymptotics ennreal noncomputable theory section variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_add_comm_group G'] [normed_space 𝕜 G'] 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} section const_smul variables {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F] [has_continuous_const_smul R F] /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : R) : 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 : R) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h tendsto_map theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : R) : 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 : R) : 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 : R) : 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 : R) : 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 : R) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : R) : 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 : R) : 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 : R) : 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 only [linear_map.sub_apply, linear_map.add_apply, map_sub, map_add, add_apply], 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 only [linear_map.sub_apply, linear_map.add_apply, map_sub, map_add, add_apply], 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 @[simp] lemma differentiable_within_at_add_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ 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 @[simp] lemma differentiable_at_add_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ 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 @[simp] lemma differentiable_on_add_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c @[simp] lemma differentiable_add_const_iff (c : F) : differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := if hf : differentiable_within_at 𝕜 f s x then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf, fderiv_within_zero_of_not_differentiable_within_at], simpa } lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ] 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 @[simp] lemma differentiable_within_at_const_add_iff (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ 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 @[simp] lemma differentiable_at_const_add_iff (c : F) : differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ 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 @[simp] lemma differentiable_on_const_add_iff (c : F) : differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c @[simp] lemma differentiable_const_add_iff (c : F) : differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := by simpa only [add_comm] using fderiv_within_add_const hxs c lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] 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 tendsto_map 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_within_at_neg_iff : differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at @[simp] lemma differentiable_at_neg_iff : differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable_on_neg_iff : differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg @[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then h.has_fderiv_within_at.neg.fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa } @[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ] 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 := by simpa only [sub_eq_add_neg] using 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 := by simpa only [sub_eq_add_neg] using 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 := by simpa only [sub_eq_add_neg] using 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 := by simpa only [sub_eq_add_neg] using 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 @[simp] lemma differentiable_within_at_sub_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x := by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff] 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 @[simp] lemma differentiable_at_sub_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x := by simp only [sub_eq_add_neg, differentiable_at_add_const_iff] 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 @[simp] lemma differentiable_on_sub_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s := by simp only [sub_eq_add_neg, differentiable_on_add_const_iff] lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c @[simp] lemma differentiable_sub_const_iff (c : F) : differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_add_const_iff] lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_add_const hxs] lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] 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 := by simpa only [sub_eq_add_neg] using 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 := by simpa only [sub_eq_add_neg] using 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 @[simp] lemma differentiable_within_at_const_sub_iff (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x := by simp [sub_eq_add_neg] 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 @[simp] lemma differentiable_at_const_sub_iff (c : F) : differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x := by simp [sub_eq_add_neg] 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 @[simp] lemma differentiable_on_const_sub_iff (c : F) : differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s := by simp [sub_eq_add_neg] lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c @[simp] lemma differentiable_const_sub_iff (c : F) : differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f := by simp [sub_eq_add_neg] lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs] lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ] end sub end
527994c45351dbd12d3174f0185f2ac47b136338
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/sites/closed_auto.lean
ef48f2ebe730e119c7345e6cb93cbdea929d6039
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
10,289
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.sites.sheaf_of_types import Mathlib.order.closure import Mathlib.PostPort universes u namespace Mathlib /-! # Closed sieves A natural closure operator on sieves is a closure operator on `sieve X` for each `X` which commutes with pullback. We show that a Grothendieck topology `J` induces a natural closure operator, and define what the closed sieves are. The collection of `J`-closed sieves forms a presheaf which is a sheaf for `J`, and further this presheaf can be used to determine the Grothendieck topology from the sheaf predicate. Finally we show that a natural closure operator on sieves induces a Grothendieck topology, and hence that natural closure operators are in bijection with Grothendieck topologies. ## Main definitions * `category_theory.grothendieck_topology.close`: Sends a sieve `S` on `X` to the set of arrows which it covers. This has all the usual properties of a closure operator, as well as commuting with pullback. * `category_theory.grothendieck_topology.closure_operator`: The bundled `closure_operator` given by `category_theory.grothendieck_topology.close`. * `category_theory.grothendieck_topology.closed`: A sieve `S` on `X` is closed for the topology `J` if it contains every arrow it covers. * `category_theory.functor.closed_sieves`: The presheaf sending `X` to the collection of `J`-closed sieves on `X`. This is additionally shown to be a sheaf for `J`, and if this is a sheaf for a different topology `J'`, then `J' ≤ J`. * `category_theory.grothendieck_topology.topology_of_closure_operator`: A closure operator on the set of sieves on every object which commutes with pullback additionally induces a Grothendieck topology, giving a bijection with `category_theory.grothendieck_topology.closure_operator`. ## Tags closed sieve, closure, Grothendieck topology ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] -/ namespace category_theory namespace grothendieck_topology /-- The `J`-closure of a sieve is the collection of arrows which it covers. -/ def close {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} (S : sieve X) : sieve X := sieve.mk (fun (Y : C) (f : Y ⟶ X) => covers J₁ S f) sorry /-- Any sieve is smaller than its closure. -/ theorem le_close {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} (S : sieve X) : S ≤ close J₁ S := fun (Y : C) (g : Y ⟶ X) (hg : coe_fn S Y g) => covering_of_eq_top J₁ (sieve.pullback_eq_top_of_mem S hg) /-- A sieve is closed for the Grothendieck topology if it contains every arrow it covers. In the case of the usual topology on a topological space, this means that the open cover contains every open set which it covers. Note this has no relation to a closed subset of a topological space. -/ def is_closed {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} (S : sieve X) := ∀ {Y : C} (f : Y ⟶ X), covers J₁ S f → coe_fn S Y f /-- If `S` is `J₁`-closed, then `S` covers exactly the arrows it contains. -/ theorem covers_iff_mem_of_closed {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} {S : sieve X} (h : is_closed J₁ S) {Y : C} (f : Y ⟶ X) : covers J₁ S f ↔ coe_fn S Y f := { mp := h f, mpr := arrow_max J₁ f S } /-- Being `J`-closed is stable under pullback. -/ theorem is_closed_pullback {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} {Y : C} (f : Y ⟶ X) (S : sieve X) : is_closed J₁ S → is_closed J₁ (sieve.pullback f S) := sorry /-- The closure of a sieve `S` is the largest closed sieve which contains `S` (justifying the name "closure"). -/ theorem le_close_of_is_closed {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} {S : sieve X} {T : sieve X} (h : S ≤ T) (hT : is_closed J₁ T) : close J₁ S ≤ T := fun (Y : C) (f : Y ⟶ X) (hf : coe_fn (close J₁ S) Y f) => hT f (superset_covering J₁ (sieve.pullback_monotone f h) hf) /-- The closure of a sieve is closed. -/ theorem close_is_closed {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} (S : sieve X) : is_closed J₁ (close J₁ S) := fun (Y : C) (g : Y ⟶ X) (hg : covers J₁ (close J₁ S) g) => arrow_trans J₁ g (close J₁ S) S hg fun (Z : C) (h : Z ⟶ X) (hS : coe_fn (close J₁ S) Z h) => hS /-- The sieve `S` is closed iff its closure is equal to itself. -/ theorem is_closed_iff_close_eq_self {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} (S : sieve X) : is_closed J₁ S ↔ close J₁ S = S := sorry theorem close_eq_self_of_is_closed {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} {S : sieve X} (hS : is_closed J₁ S) : close J₁ S = S := iff.mp (is_closed_iff_close_eq_self J₁ S) hS /-- Closing under `J` is stable under pullback. -/ theorem pullback_close {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} {Y : C} (f : Y ⟶ X) (S : sieve X) : close J₁ (sieve.pullback f S) = sieve.pullback f (close J₁ S) := sorry theorem monotone_close {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} : monotone (close J₁) := fun (S₁ S₂ : sieve X) (h : S₁ ≤ S₂) => le_close_of_is_closed J₁ (has_le.le.trans h (le_close J₁ S₂)) (close_is_closed J₁ S₂) @[simp] theorem close_close {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} (S : sieve X) : close J₁ (close J₁ S) = close J₁ S := le_antisymm (le_close_of_is_closed J₁ (le_refl (close J₁ S)) (close_is_closed J₁ S)) (monotone_close J₁ (le_close J₁ S)) /-- The sieve `S` is in the topology iff its closure is the maximal sieve. This shows that the closure operator determines the topology. -/ theorem close_eq_top_iff_mem {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} (S : sieve X) : close J₁ S = ⊤ ↔ S ∈ coe_fn J₁ X := sorry /-- A Grothendieck topology induces a natural family of closure operators on sieves. -/ @[simp] theorem closure_operator_to_preorder_hom_to_fun_apply {C : Type u} [small_category C] (J₁ : grothendieck_topology C) (X : C) (S : sieve X) (Y : C) (f : Y ⟶ X) : coe_fn (coe_fn (closure_operator.to_preorder_hom (closure_operator J₁ X)) S) Y f = covers J₁ S f := Eq.refl (coe_fn (coe_fn (closure_operator.to_preorder_hom (closure_operator J₁ X)) S) Y f) @[simp] theorem closed_iff_closed {C : Type u} [small_category C] (J₁ : grothendieck_topology C) {X : C} (S : sieve X) : S ∈ closure_operator.closed (closure_operator J₁ X) ↔ is_closed J₁ S := iff.symm (is_closed_iff_close_eq_self J₁ S) end grothendieck_topology /-- The presheaf sending each object to the set of `J`-closed sieves on it. This presheaf is a `J`-sheaf (and will turn out to be a subobject classifier for the category of `J`-sheaves). -/ @[simp] theorem functor.closed_sieves_map_coe {C : Type u} [small_category C] (J₁ : grothendieck_topology C) (X : Cᵒᵖ) (Y : Cᵒᵖ) (f : X ⟶ Y) (S : Subtype fun (S : sieve (opposite.unop X)) => grothendieck_topology.is_closed J₁ S) : ↑(functor.map (functor.closed_sieves J₁) f S) = sieve.pullback (has_hom.hom.unop f) (subtype.val S) := Eq.refl ↑(functor.map (functor.closed_sieves J₁) f S) /-- The presheaf of `J`-closed sieves is a `J`-sheaf. The proof of this is adapted from [MM92], Chatper III, Section 7, Lemma 1. -/ theorem classifier_is_sheaf {C : Type u} [small_category C] (J₁ : grothendieck_topology C) : presieve.is_sheaf J₁ (functor.closed_sieves J₁) := sorry /-- If presheaf of `J₁`-closed sieves is a `J₂`-sheaf then `J₁ ≤ J₂`. Note the converse is true by `classifier_is_sheaf` and `is_sheaf_of_le`. -/ theorem le_topology_of_closed_sieves_is_sheaf {C : Type u} [small_category C] {J₁ : grothendieck_topology C} {J₂ : grothendieck_topology C} (h : presieve.is_sheaf J₁ (functor.closed_sieves J₂)) : J₁ ≤ J₂ := sorry /-- If being a sheaf for `J₁` is equivalent to being a sheaf for `J₂`, then `J₁ = J₂`. -/ theorem topology_eq_iff_same_sheaves {C : Type u} [small_category C] {J₁ : grothendieck_topology C} {J₂ : grothendieck_topology C} : J₁ = J₂ ↔ ∀ (P : Cᵒᵖ ⥤ Type u), presieve.is_sheaf J₁ P ↔ presieve.is_sheaf J₂ P := sorry /-- A closure (increasing, inflationary and idempotent) operation on sieves that commutes with pullback induces a Grothendieck topology. In fact, such operations are in bijection with Grothendieck topologies. -/ @[simp] theorem topology_of_closure_operator_sieves {C : Type u} [small_category C] (c : (X : C) → closure_operator (sieve X)) (hc : ∀ {X Y : C} (f : Y ⟶ X) (S : sieve X), coe_fn (c Y) (sieve.pullback f S) = sieve.pullback f (coe_fn (c X) S)) (X : C) : coe_fn (topology_of_closure_operator c hc) X = set_of fun (S : sieve X) => coe_fn (c X) S = ⊤ := Eq.refl (coe_fn (topology_of_closure_operator c hc) X) /-- The topology given by the closure operator `J.close` on a Grothendieck topology is the same as `J`. -/ theorem topology_of_closure_operator_self {C : Type u} [small_category C] (J₁ : grothendieck_topology C) : (topology_of_closure_operator (grothendieck_topology.closure_operator J₁) fun (X Y : C) => grothendieck_topology.pullback_close J₁) = J₁ := grothendieck_topology.ext (funext fun (X : C) => set.ext fun (S : sieve X) => grothendieck_topology.close_eq_top_iff_mem J₁ S) theorem topology_of_closure_operator_close {C : Type u} [small_category C] (c : (X : C) → closure_operator (sieve X)) (pb : ∀ {X Y : C} (f : Y ⟶ X) (S : sieve X), coe_fn (c Y) (sieve.pullback f S) = sieve.pullback f (coe_fn (c X) S)) (X : C) (S : sieve X) : grothendieck_topology.close (topology_of_closure_operator c pb) S = coe_fn (c X) S := sorry end Mathlib
1dd4f37892964d2fb67fb21b512c25127059a26c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/preadditive/functor_category.lean
617fe29b98439cf49e87f3cd407359f4a13d0aa3
[ "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
2,705
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import category_theory.preadditive.default /-! # Preadditive structure on functor categories If `C` and `D` are categories and `D` is preadditive, then `C ⥤ D` is also preadditive. -/ open_locale big_operators namespace category_theory open category_theory.limits preadditive variables {C D : Type*} [category C] [category D] [preadditive D] instance functor_category_preadditive : preadditive (C ⥤ D) := { hom_group := λ F G, { add := λ α β, { app := λ X, α.app X + β.app X, naturality' := by { intros, rw [comp_add, add_comp, α.naturality, β.naturality] } }, zero := { app := λ X, 0, naturality' := by { intros, rw [zero_comp, comp_zero] } }, neg := λ α, { app := λ X, -α.app X, naturality' := by { intros, rw [comp_neg, neg_comp, α.naturality] } }, sub := λ α β, { app := λ X, α.app X - β.app X, naturality' := by { intros, rw [comp_sub, sub_comp, α.naturality, β.naturality] } }, add_assoc := by { intros, ext, apply add_assoc }, zero_add := by { intros, ext, apply zero_add }, add_zero := by { intros, ext, apply add_zero }, sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg }, add_left_neg := by { intros, ext, apply add_left_neg }, add_comm := by { intros, ext, apply add_comm } }, add_comp' := by { intros, ext, apply add_comp }, comp_add' := by { intros, ext, apply comp_add } } namespace nat_trans variables {F G : C ⥤ D} /-- Application of a natural transformation at a fixed object, as group homomorphism -/ @[simps] def app_hom (X : C) : (F ⟶ G) →+ (F.obj X ⟶ G.obj X) := { to_fun := λ α, α.app X, map_zero' := rfl, map_add' := λ _ _, rfl } @[simp] lemma app_zero (X : C) : (0 : F ⟶ G).app X = 0 := rfl @[simp] lemma app_add (X : C) (α β : F ⟶ G) : (α + β).app X = α.app X + β.app X := rfl @[simp] lemma app_sub (X : C) (α β : F ⟶ G) : (α - β).app X = α.app X - β.app X := rfl @[simp] lemma app_neg (X : C) (α : F ⟶ G) : (-α).app X = -α.app X := rfl @[simp] lemma app_nsmul (X : C) (α : F ⟶ G) (n : ℕ) : (n • α).app X = n • α.app X := (app_hom X).map_nsmul α n @[simp] lemma app_zsmul (X : C) (α : F ⟶ G) (n : ℤ) : (n • α).app X = n • α.app X := (app_hom X : (F ⟶ G) →+ (F.obj X ⟶ G.obj X)).map_zsmul α n @[simp] lemma app_sum {ι : Type*} (s : finset ι) (X : C) (α : ι → (F ⟶ G)) : (∑ i in s, α i).app X = ∑ i in s, ((α i).app X) := by { rw [← app_hom_apply, add_monoid_hom.map_sum], refl } end nat_trans end category_theory
833f3230c52bf24b1d1d142091ff2df7f8a93175
e953c38599905267210b87fb5d82dcc3e52a4214
/hott/types/sigma.hlean
75cc004c2c0a87c150d11e5150c209d533dc6438
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
15,247
hlean
/- Copyright (c) 2014-15 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about sigma-types (dependent sums) -/ import types.prod open eq sigma sigma.ops equiv is_equiv function namespace sigma variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {u v w : Σa, B a} definition destruct := @sigma.cases_on protected definition eta : Π (u : Σa, B a), ⟨u.1 , u.2⟩ = u | eta ⟨u₁, u₂⟩ := idp definition eta2 : Π (u : Σa b, C a b), ⟨u.1, u.2.1, u.2.2⟩ = u | eta2 ⟨u₁, u₂, u₃⟩ := idp definition eta3 : Π (u : Σa b c, D a b c), ⟨u.1, u.2.1, u.2.2.1, u.2.2.2⟩ = u | eta3 ⟨u₁, u₂, u₃, u₄⟩ := idp definition dpair_eq_dpair (p : a = a') (q : b =[p] b') : ⟨a, b⟩ = ⟨a', b'⟩ := by induction q; reflexivity definition sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) : u = v := by induction u; induction v; exact (dpair_eq_dpair p q) /- Projections of paths from a total space -/ definition eq_pr1 (p : u = v) : u.1 = v.1 := ap pr1 p postfix `..1`:(max+1) := eq_pr1 definition eq_pr2 (p : u = v) : u.2 =[p..1] v.2 := by induction p; exact idpo postfix `..2`:(max+1) := eq_pr2 definition dpair_sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) : ⟨(sigma_eq p q)..1, (sigma_eq p q)..2⟩ = ⟨p, q⟩ := by induction u; induction v;esimp at *;induction q;esimp definition sigma_eq_pr1 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..1 = p := (dpair_sigma_eq p q)..1 definition sigma_eq_pr2 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..2 =[sigma_eq_pr1 p q] q := (dpair_sigma_eq p q)..2 definition sigma_eq_eta (p : u = v) : sigma_eq (p..1) (p..2) = p := by induction p; induction u; reflexivity definition tr_pr1_sigma_eq {B' : A → Type} (p : u.1 = v.1) (q : u.2 =[p] v.2) : transport (λx, B' x.1) (sigma_eq p q) = transport B' p := by induction u; induction v; esimp at *;induction q; reflexivity /- the uncurried version of sigma_eq. We will prove that this is an equivalence -/ definition sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), u = v | sigma_eq_unc ⟨pq₁, pq₂⟩ := sigma_eq pq₁ pq₂ definition dpair_sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), ⟨(sigma_eq_unc pq)..1, (sigma_eq_unc pq)..2⟩ = pq | dpair_sigma_eq_unc ⟨pq₁, pq₂⟩ := dpair_sigma_eq pq₁ pq₂ definition sigma_eq_pr1_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : (sigma_eq_unc pq)..1 = pq.1 := (dpair_sigma_eq_unc pq)..1 definition sigma_eq_pr2_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : (sigma_eq_unc pq)..2 =[sigma_eq_pr1_unc pq] pq.2 := (dpair_sigma_eq_unc pq)..2 definition sigma_eq_eta_unc (p : u = v) : sigma_eq_unc ⟨p..1, p..2⟩ = p := sigma_eq_eta p definition tr_sigma_eq_pr1_unc {B' : A → Type} (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : transport (λx, B' x.1) (@sigma_eq_unc A B u v pq) = transport B' pq.1 := destruct pq tr_pr1_sigma_eq definition is_equiv_sigma_eq [instance] (u v : Σa, B a) : is_equiv (@sigma_eq_unc A B u v) := adjointify sigma_eq_unc (λp, ⟨p..1, p..2⟩) sigma_eq_eta_unc dpair_sigma_eq_unc definition sigma_eq_equiv (u v : Σa, B a) : (u = v) ≃ (Σ(p : u.1 = v.1), u.2 =[p] v.2) := (equiv.mk sigma_eq_unc _)⁻¹ᵉ definition dpair_eq_dpair_con (p1 : a = a' ) (q1 : b =[p1] b' ) (p2 : a' = a'') (q2 : b' =[p2] b'') : dpair_eq_dpair (p1 ⬝ p2) (q1 ⬝o q2) = dpair_eq_dpair p1 q1 ⬝ dpair_eq_dpair p2 q2 := by induction q1; induction q2; reflexivity definition sigma_eq_con (p1 : u.1 = v.1) (q1 : u.2 =[p1] v.2) (p2 : v.1 = w.1) (q2 : v.2 =[p2] w.2) : sigma_eq (p1 ⬝ p2) (q1 ⬝o q2) = sigma_eq p1 q1 ⬝ sigma_eq p2 q2 := by induction u; induction v; induction w; apply dpair_eq_dpair_con local attribute dpair_eq_dpair [reducible] definition dpair_eq_dpair_con_idp (p : a = a') (q : b =[p] b') : dpair_eq_dpair p q = dpair_eq_dpair p !pathover_tr ⬝ dpair_eq_dpair idp (pathover_idp_of_eq (tr_eq_of_pathover q)) := by induction q; reflexivity /- eq_pr1 commutes with the groupoid structure. -/ definition eq_pr1_idp (u : Σa, B a) : (refl u) ..1 = refl (u.1) := idp definition eq_pr1_con (p : u = v) (q : v = w) : (p ⬝ q) ..1 = (p..1) ⬝ (q..1) := !ap_con definition eq_pr1_inv (p : u = v) : p⁻¹ ..1 = (p..1)⁻¹ := !ap_inv /- Applying dpair to one argument is the same as dpair_eq_dpair with reflexivity in the first place. -/ definition ap_dpair (q : b₁ = b₂) : ap (sigma.mk a) q = dpair_eq_dpair idp (pathover_idp_of_eq q) := by induction q; reflexivity /- Dependent transport is the same as transport along a sigma_eq. -/ definition transportD_eq_transport (p : a = a') (c : C a b) : p ▸D c = transport (λu, C (u.1) (u.2)) (dpair_eq_dpair p !pathover_tr) c := by induction p; reflexivity definition sigma_eq_eq_sigma_eq {p1 q1 : a = a'} {p2 : b =[p1] b'} {q2 : b =[q1] b'} (r : p1 = q1) (s : p2 =[r] q2) : sigma_eq p1 p2 = sigma_eq q1 q2 := by induction s; reflexivity /- A path between paths in a total space is commonly shown component wise. -/ definition sigma_eq2 {p q : u = v} (r : p..1 = q..1) (s : p..2 =[r] q..2) : p = q := begin revert q r s, induction p, induction u with u1 u2, intro q r s, transitivity sigma_eq q..1 q..2, apply sigma_eq_eq_sigma_eq r s, apply sigma_eq_eta, end definition sigma_eq2_unc {p q : u = v} (rs : Σ(r : p..1 = q..1), p..2 =[r] q..2) : p = q := destruct rs sigma_eq2 /- Transport -/ /- The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD]. In particular, this indicates why `transport` alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? -/ definition sigma_transport (p : a = a') (bc : Σ(b : B a), C a b) : p ▸ bc = ⟨p ▸ bc.1, p ▸D bc.2⟩ := by induction p; induction bc; reflexivity /- The special case when the second variable doesn't depend on the first is simpler. -/ definition sigma_transport_nondep {B : Type} {C : A → B → Type} (p : a = a') (bc : Σ(b : B), C a b) : p ▸ bc = ⟨bc.1, p ▸ bc.2⟩ := by induction p; induction bc; reflexivity /- Or if the second variable contains a first component that doesn't depend on the first. -/ definition sigma_transport2_nondep {C : A → Type} {D : Π a:A, B a → C a → Type} (p : a = a') (bcd : Σ(b : B a) (c : C a), D a b c) : p ▸ bcd = ⟨p ▸ bcd.1, p ▸ bcd.2.1, p ▸D2 bcd.2.2⟩ := begin induction p, induction bcd with b cd, induction cd, reflexivity end /- Pathovers -/ definition eta_pathover (p : a = a') (bc : Σ(b : B a), C a b) : bc =[p] ⟨p ▸ bc.1, p ▸D bc.2⟩ := by induction p; induction bc; apply idpo definition sigma_pathover (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b) (r : u.1 =[p] v.1) (s : u.2 =[apo011 C p r] v.2) : u =[p] v := begin induction u, induction v, esimp at *, induction r, esimp [apo011] at s, induction s using idp_rec_on, apply idpo end /- TODO: * define the projections from the type u =[p] v * show that the uncurried version of sigma_pathover is an equivalence -/ /- Functorial action -/ variables (f : A → A') (g : Πa, B a → B' (f a)) definition sigma_functor [unfold 7] (u : Σa, B a) : Σa', B' a' := ⟨f u.1, g u.1 u.2⟩ /- Equivalences -/ definition is_equiv_sigma_functor [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : is_equiv (sigma_functor f g) := adjointify (sigma_functor f g) (sigma_functor f⁻¹ (λ(a' : A') (b' : B' a'), ((g (f⁻¹ a'))⁻¹ (transport B' (right_inv f a')⁻¹ b')))) begin intro u', induction u' with a' b', apply sigma_eq (right_inv f a'), rewrite [▸*,right_inv (g (f⁻¹ a')),▸*], apply tr_pathover end begin intro u, induction u with a b, apply (sigma_eq (left_inv f a)), apply pathover_of_tr_eq, rewrite [▸*,adj f,-(fn_tr_eq_tr_fn (left_inv f a) (λ a, (g a)⁻¹)), ▸*,tr_compose B' f,tr_inv_tr,left_inv] end definition sigma_equiv_sigma_of_is_equiv [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : (Σa, B a) ≃ (Σa', B' a') := equiv.mk (sigma_functor f g) !is_equiv_sigma_functor definition sigma_equiv_sigma (Hf : A ≃ A') (Hg : Π a, B a ≃ B' (to_fun Hf a)) : (Σa, B a) ≃ (Σa', B' a') := sigma_equiv_sigma_of_is_equiv (to_fun Hf) (λ a, to_fun (Hg a)) definition sigma_equiv_sigma_id {B' : A → Type} (Hg : Π a, B a ≃ B' a) : (Σa, B a) ≃ Σa, B' a := sigma_equiv_sigma equiv.refl Hg definition ap_sigma_functor_eq_dpair (p : a = a') (q : b =[p] b') : ap (sigma_functor f g) (sigma_eq p q) = sigma_eq (ap f p) (pathover.rec_on q idpo) := by induction q; reflexivity -- definition ap_sigma_functor_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) -- : ap (sigma_functor f g) (sigma_eq p q) = -- sigma_eq (ap f p) -- ((tr_compose B' f p (g u.1 u.2))⁻¹ ⬝ (fn_tr_eq_tr_fn p g u.2)⁻¹ ⬝ ap (g v.1) q) := -- by induction u; induction v; apply ap_sigma_functor_eq_dpair /- definition 3.11.9(i): Summing up a contractible family of types does nothing. -/ open is_trunc definition is_equiv_pr1 [instance] (B : A → Type) [H : Π a, is_contr (B a)] : is_equiv (@pr1 A B) := adjointify pr1 (λa, ⟨a, !center⟩) (λa, idp) (λu, sigma_eq idp (pathover_idp_of_eq !center_eq)) definition sigma_equiv_of_is_contr_pr2 [H : Π a, is_contr (B a)] : (Σa, B a) ≃ A := equiv.mk pr1 _ /- definition 3.11.9(ii): Dually, summing up over a contractible type does nothing. -/ definition sigma_equiv_of_is_contr_pr1 (B : A → Type) [H : is_contr A] : (Σa, B a) ≃ B (center A) := equiv.mk _ (adjointify (λu, (center_eq u.1)⁻¹ ▸ u.2) (λb, ⟨!center, b⟩) (λb, ap (λx, x ▸ b) !hprop_eq_of_is_contr) (λu, sigma_eq !center_eq !tr_pathover)) /- Associativity -/ --this proof is harder than in Coq because we don't have eta definitionally for sigma definition sigma_assoc_equiv (C : (Σa, B a) → Type) : (Σa b, C ⟨a, b⟩) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨⟨av.1, av.2.1⟩, av.2.2⟩) (λuc, ⟨uc.1.1, uc.1.2, !sigma.eta⁻¹ ▸ uc.2⟩) begin intro uc, induction uc with u c, induction u, reflexivity end begin intro av, induction av with a v, induction v, reflexivity end) open prod prod.ops definition assoc_equiv_prod (C : (A × A') → Type) : (Σa a', C (a,a')) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨(av.1, av.2.1), av.2.2⟩) (λuc, ⟨pr₁ (uc.1), pr₂ (uc.1), !prod.eta⁻¹ ▸ uc.2⟩) proof (λuc, destruct uc (λu, prod.destruct u (λa b c, idp))) qed proof (λav, destruct av (λa v, destruct v (λb c, idp))) qed) /- Symmetry -/ definition comm_equiv_unc (C : A × A' → Type) : (Σa a', C (a, a')) ≃ (Σa' a, C (a, a')) := calc (Σa a', C (a, a')) ≃ Σu, C u : assoc_equiv_prod ... ≃ Σv, C (flip v) : sigma_equiv_sigma !prod_comm_equiv (λu, prod.destruct u (λa a', equiv.refl)) ... ≃ (Σa' a, C (a, a')) : assoc_equiv_prod definition sigma_comm_equiv (C : A → A' → Type) : (Σa a', C a a') ≃ (Σa' a, C a a') := comm_equiv_unc (λu, C (prod.pr1 u) (prod.pr2 u)) definition equiv_prod (A B : Type) : (Σ(a : A), B) ≃ A × B := equiv.mk _ (adjointify (λs, (s.1, s.2)) (λp, ⟨pr₁ p, pr₂ p⟩) proof (λp, prod.destruct p (λa b, idp)) qed proof (λs, destruct s (λa b, idp)) qed) definition comm_equiv_nondep (A B : Type) : (Σ(a : A), B) ≃ Σ(b : B), A := calc (Σ(a : A), B) ≃ A × B : equiv_prod ... ≃ B × A : prod_comm_equiv ... ≃ Σ(b : B), A : equiv_prod /- ** Universal mapping properties -/ /- *** The positive universal property. -/ section definition is_equiv_sigma_rec [instance] (C : (Σa, B a) → Type) : is_equiv (sigma.rec : (Πa b, C ⟨a, b⟩) → Πab, C ab) := adjointify _ (λ g a b, g ⟨a, b⟩) (λ g, proof eq_of_homotopy (λu, destruct u (λa b, idp)) qed) (λ f, refl f) definition equiv_sigma_rec (C : (Σa, B a) → Type) : (Π(a : A) (b: B a), C ⟨a, b⟩) ≃ (Πxy, C xy) := equiv.mk sigma.rec _ /- *** The negative universal property. -/ protected definition coind_unc (fg : Σ(f : Πa, B a), Πa, C a (f a)) (a : A) : Σ(b : B a), C a b := ⟨fg.1 a, fg.2 a⟩ protected definition coind (f : Π a, B a) (g : Π a, C a (f a)) (a : A) : Σ(b : B a), C a b := sigma.coind_unc ⟨f, g⟩ a --is the instance below dangerous? --in Coq this can be done without function extensionality definition is_equiv_coind [instance] (C : Πa, B a → Type) : is_equiv (@sigma.coind_unc _ _ C) := adjointify _ (λ h, ⟨λa, (h a).1, λa, (h a).2⟩) (λ h, proof eq_of_homotopy (λu, !sigma.eta) qed) (λfg, destruct fg (λ(f : Π (a : A), B a) (g : Π (x : A), C x (f x)), proof idp qed)) definition sigma_pi_equiv_pi_sigma : (Σ(f : Πa, B a), Πa, C a (f a)) ≃ (Πa, Σb, C a b) := equiv.mk sigma.coind_unc _ end /- ** Subtypes (sigma types whose second components are hprops) -/ /- To prove equality in a subtype, we only need equality of the first component. -/ definition subtype_eq [H : Πa, is_hprop (B a)] (u v : Σa, B a) : u.1 = v.1 → u = v := sigma_eq_unc ∘ inv pr1 definition is_equiv_subtype_eq [H : Πa, is_hprop (B a)] (u v : Σa, B a) : is_equiv (subtype_eq u v) := !is_equiv_compose local attribute is_equiv_subtype_eq [instance] definition equiv_subtype [H : Πa, is_hprop (B a)] (u v : Σa, B a) : (u.1 = v.1) ≃ (u = v) := equiv.mk !subtype_eq _ /- truncatedness -/ definition is_trunc_sigma (B : A → Type) (n : trunc_index) [HA : is_trunc n A] [HB : Πa, is_trunc n (B a)] : is_trunc n (Σa, B a) := begin revert A B HA HB, induction n with n IH, { intro A B HA HB, fapply is_trunc_equiv_closed_rev, apply sigma_equiv_of_is_contr_pr1}, { intro A B HA HB, apply is_trunc_succ_intro, intro u v, apply is_trunc_equiv_closed_rev, apply sigma_eq_equiv, exact IH _ _ _ _} end end sigma attribute sigma.is_trunc_sigma [instance] [priority 1490]
20205c08e32ef67a50c6d0e2460c5eca833c6311
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/group_theory/sylow.lean
7846dc1c9d348386afb02e6d881bae6de8cc5773
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,066
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import group_theory.group_action import group_theory.quotient_group import group_theory.order_of_element import data.zmod.basic import data.fintype.card import data.list.rotate /-! # Sylow theorems The Sylow theorems are the following results for every finite group `G` and every prime number `p`. * There exists a Sylow `p`-subgroup of `G`. * All Sylow `p`-subgroups of `G` are conjugate to each other. * Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow `p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow `p`-subgroup in `G`. In this file, currently only the first of these results is proven. ## Main statements * `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of `G` there exists an element of order `p` in `G`. This is known as Cauchy`s theorem. * `exists_subgroup_card_pow_prime`: A generalisation of the first of the Sylow theorems: For every prime power `pⁿ` dividing `G`, there exists a subgroup of `G` of order `pⁿ`. ## TODO * Prove the second and third of the Sylow theorems. * Sylow theorems for infinite groups -/ open equiv fintype finset mul_action function open equiv.perm subgroup list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end variable (α) lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] {p : ℕ} {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (sigma_preimage_equiv (@quotient.mk' _ (orbit_rel G α))).symm ... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _ ... ≡ ∑ a : fixed_points G α, 1 [MOD p] : begin rw [←zmod.eq_iff_modeq_nat p, nat.cast_sum, nat.cast_sum], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)], exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp.1).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, pow_zero]⟩, mem_univ _, _, rfl⟩, rw [nat.cast_one], exact one_ne_zero } end ... = _ : by simp; refl /-- If a p-group acts on `α` and the cardinality of `α` is not a multiple of `p` then the action has a fixed point. -/ lemma nonempty_fixed_point_of_prime_not_dvd_card [fintype α] [fintype G] [fintype (fixed_points G α)] {p : ℕ} {n : ℕ} [hp : fact p.prime] (hG : card G = p ^ n) (hp : ¬ p ∣ fintype.card α) : (fixed_points G α).nonempty := @set.nonempty_of_nonempty_subtype _ _ begin rw [← fintype.card_pos_iff, pos_iff_ne_zero], assume h, have := card_modeq_card_fixed_points α hG, rw [h, nat.modeq.modeq_zero_iff] at this, contradiction end /-- If a p-group acts on `α` and the cardinality of `α` is a multiple of `p`, and the action has one fixed point, then it has another fixed point. -/ lemma exists_fixed_point_of_prime_dvd_card_of_fixed_point [fintype α] [fintype G] [fintype (fixed_points G α)] {p : ℕ} {n : ℕ} [hp : fact p.prime] (hG : card G = p ^ n) (hpα : p ∣ fintype.card α) {a : α} (ha : a ∈ fixed_points G α) : ∃ b, b ∈ fixed_points G α ∧ a ≠ b := have hpf : p ∣ fintype.card (fixed_points G α), from nat.modeq.modeq_zero_iff.1 $ (card_modeq_card_fixed_points α hG).symm.trans (nat.modeq.modeq_zero_iff.2 hpα), have hα : 1 < fintype.card (fixed_points G α), from lt_of_lt_of_le hp.out.one_lt (nat.le_of_dvd (fintype.card_pos_iff.2 ⟨⟨a, ha⟩⟩) hpf), let ⟨⟨b, hb⟩, hba⟩ := exists_ne_of_one_lt_card hα ⟨a, ha⟩ in ⟨b, hb, λ hab, hba $ by simp [hab]⟩ end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G) (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ ::ᵥ v lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := begin intro v, apply subtype.eq, apply vector.eq _ _, show rotate _ (0 : zmod n).val = _, rw zmod.val_zero, exact rotate_zero v.1.to_list end, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- **Cauchy's theorem** -/ lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := have hcard : card (vectors_prod_eq_one G p) = card G ^ (p - 1), by conv_lhs { rw [← nat.sub_add_cancel hp.out.pos, set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector] }, have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1, by { rw pow_one p, exact zmod.card p }, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G p) := calc p ∣ card G ^ 1 : by rwa pow_one ... ∣ card G ^ (p - 1) : pow_dvd_pow _ (nat.le_sub_left_of_add_le hp.out.two_le) ... = card (vectors_prod_eq_one G p) : hcard.symm, let ⟨⟨⟨x, hxl⟩, hx1⟩, hx, h1x⟩ := mul_action.exists_fixed_point_of_prime_dvd_card_of_fixed_point (vectors_prod_eq_one G p) hzmod hdvdcard (one_mem_fixed_points_rotate _) in have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p).val = x := subtype.mk.inj (subtype.mk.inj (hx (n : zmod p))), by rwa [zmod.val_nat_cast, ← hxl, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hxp1 : x.prod = 1 := hx1, have ha1: a ≠ 1, from λ h, h1x (subtype.ext $ subtype.ext $ by rw [subtype.coe_mk, subtype.coe_mk, subtype.coe_mk, ha, hxl, h, vector.repeat, subtype.coe_mk]), have a ^ p = 1, by rwa [ha, list.prod_repeat, hxl] at hxp1, (hp.1.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open subgroup submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G} [fintype ((H : set G) : Type u)] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H), have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)), show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv} )), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] : mul_action.fixed_points H (quotient H) ≃ quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := @subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _) (λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm) (by intros; refl) /-- The first of the **Sylow theorems** -/ theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime] (hdvd : p ^ n ∣ card G), ∃ H : subgroup G, fintype.card H = p ^ n | 0 := λ _ _, ⟨(⊥ : subgroup G), by convert card_bot⟩ | (n+1) := λ hp hdvd, let ⟨H, hH2⟩ := @exists_subgroup_card_pow_prime _ hp (dvd.trans (pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in have hcard : card (quotient H) = s * p := (nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, H.one_mem⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH2, hs, pow_succ', mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ @card_modeq_card_fixed_points _ _ _ _ _ _ _ p _ hp hH2, have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) := ⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, -- begin proof of ∃ H : subgroup G, fintype.card H = p ^ n ⟨subgroup.map ((normalizer H).subtype) (subgroup.comap (quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)), begin show card ↥(map H.normalizer.subtype (comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1), suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x)) : set (↥(H.normalizer)))) = p^(n+1), { convert this using 2 }, rw [set.card_image_of_injective (subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x) : set (H.normalizer)) subtype.val_injective, pow_succ', ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod], exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _) end⟩ end sylow
ca2fb7b1993442b49692fdd17ac8c9a631a4ec62
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/ioRandomBytes.lean
7943dffed4ee96d5c5474b295229588f914b9394
[ "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
54
lean
#eval IO.getRandomBytes 0 #eval IO.getRandomBytes 256
bccbe68b10dfb4bea2dddd840672b4ac8d908bc4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/reassoc_axiom_auto.lean
a3da1f167474c9301559d84152233bc4a69dcdc0
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,417
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.category.default import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Tools to reformulate category-theoretic axioms in a more associativity-friendly way ## The `reassoc` attribute The `reassoc` attribute can be applied to a lemma ```lean @[reassoc] lemma some_lemma : foo ≫ bar = baz := ... ``` and produce ```lean lemma some_lemma_assoc {Y : C} (f : X ⟶ Y) : foo ≫ bar ≫ f = baz ≫ f := ... ``` The name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If `simp` is added first, the generated lemma will also have the `simp` attribute. ## The `reassoc_axiom` command When declaring a class of categories, the axioms can be reformulated to be more amenable to manipulation in right associated expressions: ```lean class some_class (C : Type) [category C] := (foo : Π X : C, X ⟶ X) (bar : ∀ {X Y : C} (f : X ⟶ Y), foo X ≫ f = f ≫ foo Y) reassoc_axiom some_class.bar ``` Here too, the `reassoc` attribute can be used instead. It works well when combined with `simp`: ```lean attribute [simp, reassoc] some_class.bar ``` -/ namespace tactic /-- From an expression `f ≫ g`, extract the expression representing the category instance. -/ /-- (internals for `@[reassoc]`) Given a lemma of the form `f ≫ g = h`, proves a new lemma of the form `h : ∀ {W} (k), f ≫ (g ≫ k) = h ≫ k`, and returns the type and proof of this lemma. -/ /-- (implementation for `@[reassoc]`) Given a declaration named `n` of the form `f ≫ g = h`, proves a new lemma named `n'` of the form `∀ {W} (k), f ≫ (g ≫ k) = h ≫ k`. -/ /-- The `reassoc` attribute can be applied to a lemma ```lean @[reassoc] lemma some_lemma : foo ≫ bar = baz := ... ``` to produce ```lean lemma some_lemma_assoc {Y : C} (f : X ⟶ Y) : foo ≫ bar ≫ f = baz ≫ f := ... ``` The name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If `simp` is added first, the generated lemma will also have the `simp` attribute. -/ /-- When declaring a class of categories, the axioms can be reformulated to be more amenable to manipulation in right associated expressions: ```lean class some_class (C : Type) [category C] := (foo : Π X : C, X ⟶ X) (bar : ∀ {X Y : C} (f : X ⟶ Y), foo X ≫ f = f ≫ foo Y) reassoc_axiom some_class.bar ``` The above will produce: ```lean lemma some_class.bar_assoc {Z : C} (g : Y ⟶ Z) : foo X ≫ f ≫ g = f ≫ foo Y ≫ g := ... ``` Here too, the `reassoc` attribute can be used instead. It works well when combined with `simp`: ```lean attribute [simp, reassoc] some_class.bar ``` -/ namespace interactive /-- `reassoc h`, for assumption `h : x ≫ y = z`, creates a new assumption `h : ∀ {W} (f : Z ⟶ W), x ≫ y ≫ f = z ≫ f`. `reassoc! h`, does the same but deletes the initial `h` assumption. (You can also add the attribute `@[reassoc]` to lemmas to generate new declarations generalized in this way.) -/ end interactive def calculated_Prop {α : Sort u_1} (β : Prop) (hh : α) := β end tactic /-- With `h : x ≫ y ≫ z = x` (with universal quantifiers tolerated), `reassoc_of h : ∀ {X'} (f : W ⟶ X'), x ≫ y ≫ z ≫ f = x ≫ f`. The type and proof of `reassoc_of h` is generated by `tactic.derive_reassoc_proof` which make `reassoc_of` meta-programming adjacent. It is not called as a tactic but as an expression. The goal is to avoid creating assumptions that are dismissed after one use: ```lean example (X Y Z W : C) (x : X ⟶ Y) (y : Y ⟶ Z) (z z' : Z ⟶ W) (w : X ⟶ Z) (h : x ≫ y = w) (h' : y ≫ z = y ≫ z') : x ≫ y ≫ z = w ≫ z' := begin rw [h',reassoc_of h], end ``` -/ theorem category_theory.reassoc_of {α : Sort u_1} (hh : α) {β : Prop} (x : autoParam (tactic.calculated_Prop β hh) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.derive_reassoc_proof") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "derive_reassoc_proof") [])) : β := x /-- `reassoc_of h` takes local assumption `h` and add a ` ≫ f` term on the right of end Mathlib
889a1a8b30adee0c8579ffc03c96da1a8d1a84ae
63abd62053d479eae5abf4951554e1064a4c45b4
/src/set_theory/ordinal.lean
f60747bf6037c0c59d27dde8d603f395fe698bf9
[ "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
56,608
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import set_theory.cardinal /-! # Ordinals Ordinals are defined as equivalences of well-ordered sets under order isomorphism. They are endowed with a total order, where an ordinal is smaller than another one if it embeds into it as an initial segment (or, equivalently, in any way). This total order is well founded. ## Main definitions * `initial_seg r s`: type of order embeddings of `r` into `s` for which the range is an initial segment (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). It is denoted by `r ≼i s`. * `principal_seg r s`: Type of order embeddings of `r` into `s` for which the range is a principal segment, i.e., an interval of the form `(-∞, top)` for some element `top`. It is denoted by `r ≺i s`. * `ordinal`: the type of ordinals (in a given universe) * `type r`: given a well-founded order `r`, this is the corresponding ordinal * `typein r a`: given a well-founded order `r` on a type `α`, and `a : α`, the ordinal corresponding to all elements smaller than `a`. * `enum r o h`: given a well-order `r` on a type `α`, and an ordinal `o` strictly smaller than the ordinal corresponding to `r` (this is the assumption `h`), returns the `o`-th element of `α`. In other words, the elements of `α` can be enumerated using ordinals up to `type r`. * `card o`: the cardinality of an ordinal `o`. * `lift` lifts an ordinal in universe `u` to an ordinal in universe `max u v`. For a version registering additionally that this is an initial segment embedding, see `lift.initial_seg`. For a version regiserting that it is a principal segment embedding if `u < v`, see `lift.principal_seg`. * `omega` is the first infinite ordinal. It is the order type of `ℕ`. * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. The main properties of addition (and the other operations on ordinals) are stated and proved in `ordinal_arithmetic.lean`. Here, we only introduce it and prove its basic properties to deduce the fact that the order on ordinals is total (and well founded). * `succ o` is the successor of the ordinal `o`. * `min`: the minimal element of a nonempty indexed family of ordinals * `omin` : the minimal element of a nonempty set of ordinals * `ord c`: when `c` is a cardinal, `ord c` is the smallest ordinal with this cardinality. It is the canonical way to represent a cardinal with an ordinal. ## Notations * `r ≼i s`: the type of initial segment embeddings of `r` into `s`. * `r ≺i s`: the type of principal segment embeddings of `r` into `s`. * `ω` is a notation for the first infinite ordinal in the locale ordinal. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-! ### Initial segments Order embeddings whose range is an initial segment of `s` (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). The type of these embeddings from `r` to `s` is called `initial_seg r s`, and denoted by `r ≼i s`. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≼i s` is an order embedding whose range is an initial segment. That is, whenever `b < f a` in `β` then `b` is in the range of `f`. -/ @[nolint has_inhabited_instance] structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (init : ∀ a b, s b (to_rel_embedding a) → ∃ a', to_rel_embedding a' = b) local infix ` ≼i `:25 := initial_seg namespace initial_seg instance : has_coe (r ≼i s) (r ↪r s) := ⟨initial_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≼i s) := ⟨λ _, α → β, λ f x, (f : r ↪r s) x⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (o) : (@initial_seg.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≼i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ↪r s) : α → β) = f := rfl theorem init' (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b := f.init _ _ theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r ↪r s).map_rel_iff.2 (e.symm ▸ h)⟩, λ ⟨a', e, h⟩, e ▸ (f : r ↪r s).map_rel_iff.1 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃r s) : r ≼i s := ⟨f, λ a b h, ⟨f.symm b, rel_iso.apply_symm_apply f _⟩⟩ /-- The identity function shows that `≼i` is reflexive -/ @[refl] protected def refl (r : α → α → Prop) : r ≼i r := ⟨rel_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩ /-- Composition of functions shows that `≼i` is transitive -/ @[trans] protected def trans (f : r ≼i s) (g : s ≼i t) : r ≼i t := ⟨f.1.trans g.1, λ a c h, begin simp at h ⊢, rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.1.map_rel_iff.2 h, rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼i s) (g : s ≼i t) (a : α) : (f.trans g) a = g (f a) := rfl theorem unique_of_extensional [is_extensional β s] : well_founded r → subsingleton (r ≼i s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : α → β) = g, { cases f, cases g, congr, exact rel_embedding.coe_fn_inj this }, funext a, have := h a, induction this with a H IH, refine @is_extensional.ext _ s _ _ _ (λ x, ⟨λ h, _, λ h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r ↪r s).map_rel_iff.1 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r ↪r s).map_rel_iff.1 h' } end⟩ instance [is_well_order β s] : subsingleton (r ≼i s) := ⟨λ a, @subsingleton.elim _ (unique_of_extensional (@rel_embedding.well_founded _ _ r s a is_well_order.wf)) a⟩ protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f := initial_seg.eq (f.trans g) (initial_seg.refl _) /-- If we have order embeddings between `α` and `β` whose images are initial segments, and `β` is a well-order then `α` and `β` are order-isomorphic. -/ def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃r s := by haveI := f.to_rel_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.map_rel_iff'⟩ @[simp] theorem antisymm_to_fun [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl @[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f := rel_iso.injective_coe_fn rfl theorem eq_or_principal [is_well_order β s] (f : r ≼i s) : surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x := or_iff_not_imp_right.2 $ λ h b, acc.rec_on (is_well_order.wf.apply b : acc s b) $ λ x H IH, not_forall_not.1 $ λ hn, h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (λ hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p := ⟨rel_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- Initial segment embedding of an order `r` into the disjoint union of `r` and `s`. -/ def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s := ⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, sum.lex_inl_inl.symm⟩, λ a b, by cases b; [exact λ _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩ @[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg /-! ### Principal segments Order embeddings whose range is a principal segment of `s` (i.e., an interval of the form `(-∞, top)` for some element `top` of `β`). The type of these embeddings from `r` to `s` is called `principal_seg r s`, and denoted by `r ≺i s`. Principal segments are in particular initial segments. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≺i s` is an order embedding whose range is an open interval `(-∞, top)` for some element `top` of `β`. Such order embeddings are called principal segments -/ @[nolint has_inhabited_instance] structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (top : β) (down : ∀ b, s b top ↔ ∃ a, to_rel_embedding a = b) local infix ` ≺i `:25 := principal_seg namespace principal_seg instance : has_coe (r ≺i s) (r ↪r s) := ⟨principal_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≺i s) := ⟨λ _, α → β, λ f, f⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (t o) : (@principal_seg.mk _ _ r s f t o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≺i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≺i s) : ((f : r ↪r s) : α → β) = f := rfl theorem down' (f : r ≺i s) {b : β} : s b f.top ↔ ∃ a, f a = b := f.down _ theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.down'.2 ⟨_, rfl⟩ theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b := f.down'.1 $ trans h $ f.lt_top _ /-- A principal segment is in particular an initial segment. -/ instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) := ⟨λ f, ⟨f.to_rel_embedding, λ a b, f.init⟩⟩ theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := @initial_seg.init_iff α β r s f a b theorem irrefl (r : α → α → Prop) [is_well_order α r] (f : r ≺i r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end /-- Composition of a principal segment with an initial segment, as a principal segment -/ def lt_le (f : r ≺i s) (g : s ≼i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, λ a, by simp only [g.init_iff, f.down', exists_and_distrib_left.symm, exists_swap, rel_embedding.trans_apply, exists_eq_right']; refl⟩ @[simp] theorem lt_le_apply (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl /-- Composition of two principal segments as a principal segment -/ @[trans] protected def trans [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t := lt_le f g @[simp] theorem trans_apply [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl /-- Composition of an order isomorphism with a principal segment, as a principal segment -/ def equiv_lt (f : r ≃r s) (g : s ≺i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g.top, λ c, suffices (∃ (a : β), g a = c) ↔ ∃ (a : α), g (f a) = c, by simpa [g.down], ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, rel_iso.apply_symm_apply, rel_iso.coe_coe_fn]⟩, λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩ /-- Composition of a principal segment with an order isomorphism, as a principal segment -/ def lt_equiv {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : principal_seg r s) (g : s ≃r t) : principal_seg r t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, begin intro x, rw [← g.apply_symm_apply x, ← g.map_rel_iff, f.down', exists_congr], intro y, exact ⟨congr_arg g, λ h, g.to_equiv.bijective.1 h⟩ end⟩ @[simp] theorem equiv_lt_apply (f : r ≃r s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem equiv_lt_top (f : r ≃r s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl /-- Given a well order `s`, there is a most one principal segment embedding of `r` into `s`. -/ instance [is_well_order β s] : subsingleton (r ≺i s) := ⟨λ f g, begin have ef : (f : α → β) = g, { show ((f : r ≼i s) : α → β) = g, rw @subsingleton.elim _ _ (f : r ≼i s) g, refl }, have et : f.top = g.top, { refine @is_extensional.ext _ s _ _ _ (λ x, _), simp only [f.down, g.down, ef, coe_fn_to_rel_embedding] }, cases f, cases g, have := rel_embedding.coe_fn_inj ef; congr' end⟩ theorem top_eq [is_well_order γ t] (e : r ≃r s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl lemma top_lt_top {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} [is_well_order γ t] (f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top := by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top } /-- Any element of a well order yields a principal segment -/ def of_element {α : Type*} (r : α → α → Prop) (a : α) : subrel r {b | r b a} ≺i r := ⟨subrel.rel_embedding _ _, a, λ b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) (a : α) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) (a : α) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set β) (f : r ≺i s) (H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p := ⟨rel_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩, f.down'.trans $ exists_congr $ λ a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl end principal_seg /-! ### Properties of initial and principal segments -/ /-- To an initial segment taking values in a well order, one can associate either a principal segment (if the range is not everything, hence one can take as top the minimum of the complement of the range) or an order isomorphism (if the range is everything). -/ def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) : (r ≺i s) ⊕ (r ≃r s) := if h : surjective f then sum.inr (rel_iso.of_surjective f h) else have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ theorem initial_seg.lt_or_eq_apply_left [is_well_order β s] (f : r ≼i s) (g : r ≺i s) (a : α) : g a = f a := @initial_seg.eq α β r s _ g f a theorem initial_seg.lt_or_eq_apply_right [is_well_order β s] (f : r ≼i s) (g : r ≃r s) (a : α) : g a = f a := initial_seg.eq (initial_seg.of_iso g) f a /-- Composition of an initial segment taking values in a well order and a principal segment. -/ def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left] }, { simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right] } end namespace rel_embedding /-- Given an order embedding into a well order, collapse the order embedding by filling the gaps, to obtain an initial segment. Here, we construct the collapsed order embedding pointwise, but the proof of the fact that it is an initial segment will be given in `collapse`. -/ def collapse_F [is_well_order β s] (f : r ↪r s) : Π a, {b // ¬ s (f a) b} := (rel_embedding.well_founded f $ is_well_order.wf).fix $ λ a IH, begin let S := {b | ∀ a h, s (IH a h).1 b}, have : f a ∈ S, from λ a' h, ((trichotomous _ _) .resolve_left $ λ h', (IH a' h).2 $ trans (f.map_rel_iff.1 h) h') .resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.map_rel_iff.1 h, exact ⟨is_well_order.wf.min S ⟨_, this⟩, is_well_order.wf.not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order β s] (f : r ↪r s) {a : α} : ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order β s] (f : r ↪r s) (a : α) {b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding into a well order, by collapsing it to fill the gaps. -/ def collapse [is_well_order β s] (f : r ↪r s) : r ≼i s := by haveI := rel_embedding.is_well_order f; exact ⟨rel_embedding.of_monotone (λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f), λ a b, acc.rec_on (is_well_order.wf.apply b : acc s b) (λ b H IH a h, begin let S := {a | ¬ s (collapse_F f a).1 b}, have : S.nonempty := ⟨_, asymm h⟩, existsi (is_well_order.wf : well_founded r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_order.wf : well_founded r).min_mem S this }, { refine collapse_F.not_lt f _ (λ a' h', _), by_contradiction hn, exact is_well_order.wf.not_lt_min S this hn h' } end) a⟩ theorem collapse_apply [is_well_order β s] (f : r ↪r s) (a) : collapse f a = (collapse_F f a).1 := rfl end rel_embedding /-! ### Well order on an arbitrary type -/ section well_ordering_thm parameter {σ : Type u} open function theorem nonempty_embedding_to_cardinal : nonempty (σ ↪ cardinal.{u}) := embedding.total.resolve_left $ λ ⟨⟨f, hf⟩⟩, let g : σ → cardinal.{u} := inv_fun f in let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in have g x ≤ sum g, from le_sum.{u u} g x, not_le_of_gt (by rw hx; exact cantor _) this /-- An embedding of any type to the set of cardinals. -/ def embedding_to_cardinal : σ ↪ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal /-- Any type can be endowed with a well order, obtained by pulling back the well order over cardinals by some embedding. -/ def well_ordering_rel : σ → σ → Prop := embedding_to_cardinal ⁻¹'o (<) instance well_ordering_rel.is_well_order : is_well_order σ well_ordering_rel := (rel_embedding.preimage _ _).is_well_order end well_ordering_thm /-! ### Definition of ordinals -/ /-- Bundled structure registering a well order on a type. Ordinals will be defined as a quotient of this type. -/ structure Well_order : Type (u+1) := (α : Type u) (r : α → α → Prop) (wo : is_well_order α r) attribute [instance] Well_order.wo namespace Well_order instance : inhabited Well_order := ⟨⟨pempty, _, empty_relation.is_well_order⟩⟩ end Well_order /-- Equivalence relation on well orders on arbitrary types in universe `u`, given by order isomorphism. -/ instance ordinal.is_equivalent : setoid Well_order := { r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃r s), iseqv := ⟨λ⟨α, r, _⟩, ⟨rel_iso.refl _⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `ordinal.{u}` is the type of well orders in `Type u`, up to order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent namespace ordinal /-- The order type of a well order is an ordinal. -/ def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal := ⟦⟨α, r, wo⟩⟧ /-- The order type of an element inside a well order. For the embedding as a principal segment, see `typein.principal_seg`. -/ def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal := type (subrel r {b | r b a}) theorem type_def (r : α → α → Prop) [wo : is_well_order α r] : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl @[simp] theorem type_def' (r : α → α → Prop) [is_well_order α r] {wo} : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r = type s ↔ nonempty (r ≃r s) := quotient.eq @[simp] lemma type_out (o : ordinal) : type o.out.r = o := by { refine eq.trans _ (by rw [←quotient.out_eq o]), cases quotient.out o, refl } @[elab_as_eliminator] theorem induction_on {C : ordinal → Prop} (o : ordinal) (H : ∀ α r [is_well_order α r], by exactI C (type r)) : C o := quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo /-! ### The order on ordinals -/ /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≤ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ protected def le (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, propext ⟨ λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩ instance : has_le ordinal := ⟨ordinal.le⟩ theorem type_le {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl theorem type_le' {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ↪r s) := ⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩ /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ def lt (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, by exactI propext ⟨ λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩ instance : has_lt ordinal := ⟨ordinal.lt⟩ @[simp] theorem type_lt {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r < type s ↔ nonempty (r ≺i s) := iff.rfl instance : partial_order ordinal := { le := (≤), lt := (<), le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl _⟩, λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩) (λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := λ x b, show x ≤ b → b ≤ x → x = b, from quotient.induction_on₂ x b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩, by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ } /-- Given two ordinals `α ≤ β`, then `initial_seg_out α β` is the initial segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def initial_seg_out {α β : ordinal} (h : α ≤ β) : initial_seg α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α < β`, then `principal_seg_out α β` is the principal segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def principal_seg_out {α β : ordinal} (h : α < β) : principal_seg α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α = β`, then `rel_iso_out α β` is the order isomorphism between two model types for `α` and `β`. -/ def rel_iso_out {α β : ordinal} (h : α = β) : rel_iso α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice ∘ quotient.exact end theorem typein_lt_type (r : α → α → Prop) [is_well_order α r] (a : α) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ @[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≺i s) : typein s f.top = type r := eq.symm $ quot.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ f f.lt_top) (λ ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ ((subrel.rel_embedding _ _).trans f) (λ ⟨x, h⟩, by rw [rel_embedding.trans_apply]; exact f.to_rel_embedding.map_rel_iff.1 h)) (λ ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_rel_embedding.map_rel_iff.2 h⟩, subtype.eq $ rel_embedding.trans_apply _ _ _⟩)⟩ @[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r] {a b : α} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, exact this }, rw ← this, exact f.top.2 end, λ h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : ∃ a, typein r a = o := induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h lemma typein_injective (r : α → α → Prop) [is_well_order α r] : injective (typein r) := injective_of_increasing r (<) (typein r) (λ x y, (typein_lt_typein r).2) theorem typein_inj (r : α → α → Prop) [is_well_order α r] {a b} : typein r a = typein r b ↔ a = b := injective.eq_iff (typein_injective r) /-! ### Enumerating elements in a well-order with ordinals. -/ /-- `enum r o h` is the `o`-th element of `α` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `α`. -/ def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α := quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $ λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (λ (H₂ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : ∀ {o e} (H : o < type r), @@eq.rec (λ (o : ordinal), o < type r → α) (λ (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this H₂).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice H₂)) end theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : s ≺i r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (rel_iso.refl _) _ _ @[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α) {h : typein r a < type r} : enum r (typein r a) h = a := enum_type (principal_seg.of_element r a) @[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; rw enum_typein /-- A well order `r` is order isomorphic to the set of ordinals strictly smaller than the ordinal version of `r`. -/ def typein_iso (r : α → α → Prop) [is_well_order α r] : r ≃r subrel (<) (< type r) := ⟨⟨λ x, ⟨typein r x, typein_lt_type r x⟩, λ x, enum r x.1 x.2, λ y, enum_typein r y, λ ⟨y, hy⟩, subtype.eq (typein_enum r hy)⟩, λ a b, (typein_lt_typein r).symm⟩ theorem enum_lt {r : α → α → Prop} [is_well_order α r] {o₁ o₂ : ordinal} (h₁ : o₁ < type r) (h₂ : o₂ < type r) : r (enum r o₁ h₁) (enum r o₂ h₂) ↔ o₁ < o₂ := by rw [← typein_lt_typein r, typein_enum, typein_enum] lemma rel_iso_enum' {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : rel_iso r s) (o : ordinal) : ∀(hr : o < type r) (hs : o < type s), f (enum r o hr) = enum s o hs := begin refine induction_on o _, rintros γ t wo ⟨g⟩ ⟨h⟩, resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl end lemma rel_iso_enum {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : rel_iso r s) (o : ordinal) (hr : o < type r) : f (enum r o hr) = enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) := rel_iso_enum' _ _ _ _ theorem wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ λ α r wo, by exactI suffices ∀ a, acc (<) (typein r a), from ⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩, λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), wf⟩ /-- Principal segment version of the `typein` function, embedding a well order into ordinals as a principal segment. -/ def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] : @principal_seg α ordinal.{u} r (<) := ⟨rel_embedding.of_monotone (typein r) (λ a b, (typein_lt_typein r).2), type r, λ b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] : (typein.principal_seg r : α → ordinal) = typein r := rfl /-! ### Cardinality of ordinals -/ /-- The cardinal of an ordinal is the cardinal of any set with that order type. -/ def card (o : ordinal) : cardinal := quot.lift_on o (λ ⟨α, r, _⟩, mk α) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩ @[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] : card (type r) = mk α := rfl lemma card_typein {r : α → α → Prop} [wo : is_well_order α r] (x : α) : mk {y // r y x} = (typein r x).card := rfl theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ instance : has_zero ordinal := ⟨⟦⟨pempty, empty_relation, by apply_instance⟩⟧⟩ instance : inhabited ordinal := ⟨0⟩ theorem zero_eq_type_empty : 0 = @type empty empty_relation _ := quotient.sound ⟨⟨empty_equiv_pempty.symm, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_zero : card 0 = 0 := rfl theorem zero_le (o : ordinal) : 0 ≤ o := induction_on o $ λ α r _, ⟨⟨⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim, λ a, a.elim⟩, λ a, a.elim⟩⟩ @[simp] theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 := by simp only [le_antisymm_iff, zero_le, and_true] theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 := by simp only [lt_iff_le_and_ne, zero_le, true_and, ne.def, eq_comm] instance : has_one ordinal := ⟨⟦⟨punit, empty_relation, by apply_instance⟩⟧⟩ theorem one_eq_type_unit : 1 = @type unit empty_relation _ := quotient.sound ⟨⟨punit_equiv_punit, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_one : card 1 = 1 := rfl /-! ### Lifting ordinals to a higher universe -/ /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. For the initial segment version, see `lift.initial_seg`. -/ def lift (o : ordinal.{u}) : ordinal.{max u v} := quotient.lift_on o (λ ⟨α, r, wo⟩, @type _ _ (@rel_embedding.is_well_order _ _ (@equiv.ulift.{v} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{v} r) wo)) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩ theorem lift_type {α} (r : α → α → Prop) [is_well_order α r] : ∃ wo', lift (type r) = @type _ (@equiv.ulift.{v} α ⁻¹'o r) wo' := ⟨_, rfl⟩ theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift r).trans (rel_iso.preimage equiv.ulift r).symm⟩ theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ λ α r _, quotient.sound ⟨rel_iso.preimage equiv.ulift r⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : ordinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans $ (rel_iso.preimage equiv.ulift _).trans (rel_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) ≤ lift.{v (max u w)} (type s) ↔ nonempty (r ≼i s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) = lift.{v (max u w)} (type s) ↔ nonempty (r ≃r s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).symm.trans $ f.trans (rel_iso.preimage equiv.ulift s)⟩, λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) < lift.{v (max u w)} (type s) ↔ nonempty (r ≺i s) := by haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max v w)} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{(max v w)} r) _; haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max u w)} β ⁻¹'o s) s (rel_iso.preimage equiv.ulift.{(max u w)} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b := induction_on a $ λ α r _, induction_on b $ λ β s _, by rw ← lift_umax; exactI lift_type_le @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp only [le_antisymm_iff, lift_le] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp only [lt_iff_le_not_le, lift_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨pempty_equiv_pempty, λ a b, iff.rfl⟩⟩ theorem zero_eq_lift_type_empty : 0 = lift.{0 u} (@type empty empty_relation _) := by rw [← zero_eq_type_empty, lift_zero] @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨punit_equiv_punit, λ a b, iff.rfl⟩⟩ theorem one_eq_lift_type_unit : 1 = lift.{0 u} (@type unit empty_relation _) := by rw [← one_eq_type_unit, lift_one] @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ λ α r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≤ a.lift) : ∃ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in quotient.induction_on c (λ α, induction_on b $ λ β s _ e', begin resetI, rw [mk_def, card_type, ← cardinal.lift_id'.{(max u v) u} (mk β), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := rel_iso.preimage f s, haveI := (g : ⇑f ⁻¹'o s ↪r s).is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≤ lift a) : ∃ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ /-- Initial segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as an initial segment when `u ≤ v`. -/ def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{u v}, λ a b, lift_inj.1⟩, λ a b, lift_lt.symm⟩, λ a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl /-! ### The first infinite ordinal `omega` -/ /-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/ def omega : ordinal.{u} := lift $ @type ℕ (<) _ localized "notation `ω` := ordinal.omega.{0}" in ordinal theorem card_omega : card omega = cardinal.omega := rfl @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /-! ### Definition and first properties of addition on ordinals In this paragraph, we introduce the addition on ordinals, and prove just enough properties to deduce that the order on ordinals is total (and therefore well-founded). Further properties of the addition, together with properties of the other operations, are proved in `ordinal_arithmetic.lean`. -/ /-- `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. -/ instance : has_add ordinal.{u} := ⟨λo₁ o₂, quotient.lift_on₂ o₁ o₂ (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α ⊕ β, sum.lex r s, by exactI sum.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.sum_lex_congr f g⟩⟩ @[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl @[simp] theorem card_nat (n : ℕ) : card.{u} n = n := by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]] @[simp] theorem type_add {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r + type s = type (sum.lex r s) := rfl /-- The ordinal successor is the smallest ordinal larger than `o`. It is defined as `o + 1`. -/ def succ (o : ordinal) : ordinal := o + 1 theorem succ_eq_add_one (o) : succ o = o + 1 := rfl instance : add_monoid ordinal.{u} := { add := (+), zero := 0, zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(pempty_sum α).symm, λ a b, sum.lex_inr_inr.symm⟩⟩, add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(sum_pempty α).symm, λ a b, sum.lex_inl_inl.symm⟩⟩, add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨sum_assoc _ _ _, λ a b, begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp only [sum_assoc_apply_in1, sum_assoc_apply_in2, sum_assoc_apply_in3, sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ } theorem add_le_add_left {a b : ordinal} : a ≤ b → ∀ c, c + a ≤ c + b := induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s _, ⟨⟨⟨(embedding.refl _).sum_map f, λ a b, match a, b with | sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm | sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep | sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl | sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm end⟩, λ a b H, match a, b, H with | _, sum.inl b, _ := ⟨sum.inl b, rfl⟩ | sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim | sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in ⟨sum.inr w, congr_arg sum.inr h⟩ end⟩⟩ theorem le_add_right (a b : ordinal) : a ≤ a + b := by simpa only [add_zero] using add_le_add_left (zero_le b) a theorem add_le_add_right {a b : ordinal} : a ≤ b → ∀ c, a + c ≤ b + c := induction_on a $ λ α₁ r₁ hr₁, induction_on b $ λ α₂ r₂ hr₂ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s hs, (@type_le' _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr₁ hs) (@sum.lex.is_well_order _ _ _ _ hr₂ hs)).2 ⟨⟨f.sum_map (embedding.refl _), λ a b, begin split; intro H, { cases H; constructor; [rwa ← fo, assumption] }, { cases a with a a; cases b with b b; cases H; constructor; [rwa fo, assumption] } end⟩⟩ theorem le_add_left (a b : ordinal) : a ≤ b + a := by simpa only [zero_add] using add_le_add_right (zero_le b) a theorem lt_succ_self (o : ordinal.{u}) : o < succ o := induction_on o $ λ α r _, ⟨⟨⟨⟨λ x, sum.inl x, λ _ _, sum.inl.inj⟩, λ _ _, sum.lex_inl_inl.symm⟩, sum.inr punit.star, λ b, sum.rec_on b (λ x, ⟨λ _, ⟨x, rfl⟩, λ _, sum.lex.sep _ _⟩) (λ x, sum.lex_inr_inr.trans ⟨false.elim, λ ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩ theorem succ_le {a b : ordinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), induction_on a $ λ α r hr, induction_on b $ λ β s hs ⟨⟨f, t, hf⟩⟩, begin refine ⟨⟨@rel_embedding.of_monotone (α ⊕ punit) β _ _ (@sum.lex.is_well_order _ _ _ _ hr _).1.1 (@is_asymm_of_is_trans_of_is_irrefl _ _ hs.1.2.2 hs.1.2.1) (sum.rec _ _) (λ a b, _), λ a b, _⟩⟩, { exact f }, { exact λ _, t }, { rcases a with a|_; rcases b with b|_, { simpa only [sum.lex_inl_inl] using f.map_rel_iff.1 }, { intro _, rw hf, exact ⟨_, rfl⟩ }, { exact false.elim ∘ sum.lex_inr_inl }, { exact false.elim ∘ sum.lex_inr_inr.1 } }, { rcases a with a|_, { intro h, have := @principal_seg.init _ _ _ _ hs.1.2.2 ⟨f, t, hf⟩ _ _ h, cases this with w h, exact ⟨sum.inl w, h⟩ }, { intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } } end⟩ theorem le_total (a b : ordinal) : a ≤ b ∨ b ≤ a := match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h; [exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)] end) h₁ h₂ end instance : linear_order ordinal := { le_total := le_total, decidable_le := classical.dec_rel _, ..ordinal.partial_order } instance : is_well_order ordinal (<) := ⟨wf⟩ @[simp] lemma typein_le_typein (r : α → α → Prop) [is_well_order α r] {x x' : α} : typein r x ≤ typein r x' ↔ ¬r x' x := by rw [←not_lt, typein_lt_typein] lemma enum_le_enum (r : α → α → Prop) [is_well_order α r] {o o' : ordinal} (ho : o < type r) (ho' : o' < type r) : ¬r (enum r o' ho') (enum r o ho) ↔ o ≤ o' := by rw [←@not_lt _ _ o' o, enum_lt ho'] /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ def univ := lift.{(u+1) v} (@type ordinal.{u} (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ /-- Principal segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as a principal segment when `u < v`. -/ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := ⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine λ b, induction_on b _, introsI β s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊢, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, introsI α r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(rel_iso.of_surjective (rel_embedding.of_monotone _ _) _).symm⟩, { exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine λ a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.map_rel_iff.1 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, introsI α r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal → ordinal) = lift.{u (max (u+1) v)} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ := by simp only [lift.principal_seg_top, univ_id] /-! ### Minimum -/ /-- The minimal element of a nonempty family of ordinals -/ def min {ι} (I : nonempty ι) (f : ι → ordinal) : ordinal := wf.min (set.range f) (let ⟨i⟩ := I in ⟨_, set.mem_range_self i⟩) theorem min_eq {ι} (I) (f : ι → ordinal) : ∃ i, min I f = f i := let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩ theorem min_le {ι I} (f : ι → ordinal) (i) : min I f ≤ f i := le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i) theorem le_min {ι I} {f : ι → ordinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ /-- The minimal element of a nonempty set of ordinals -/ def omin (S : set ordinal.{u}) (H : ∃ x, x ∈ S) : ordinal.{u} := @min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val theorem omin_mem (S H) : omin S H ∈ S := let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in (show omin S H = i, from e).symm ▸ h theorem le_omin {S H a} : a ≤ omin S H ↔ ∀ i ∈ S, a ≤ i := le_min.trans set_coe.forall theorem omin_le {S H i} (h : i ∈ S) : omin S H ≤ i := le_omin.1 (le_refl _) _ h @[simp] theorem lift_min {ι} (I) (f : ι → ordinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) end ordinal /-! ### Representing a cardinal with an ordinal -/ namespace cardinal open ordinal /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. For the order-embedding version, see `ord.order_embedding`. -/ def ord (c : cardinal) : ordinal := begin let ι := λ α, {r // is_well_order α r}, have : Π α, ι α := λ α, ⟨well_ordering_rel, by apply_instance⟩, let F := λ α, ordinal.min ⟨this _⟩ (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧), refine quot.lift_on c F _, suffices : ∀ {α β}, α ≈ β → F α ≤ F β, from λ α β h, le_antisymm (this h) (this (setoid.symm h)), intros α β h, cases h with f, refine ordinal.le_min.2 (λ i, _), haveI := @rel_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(rel_iso.preimage f i.1) i.2, rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from quot.sound ⟨rel_iso.preimage f i.1⟩, exact ordinal.min_le (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩ end @[nolint def_lemma doc_blame] -- TODO: This should be a theorem but Lean fails to synthesize the placeholder def ord_eq_min (α : Type u) : ord (mk α) = @ordinal.min _ _ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) := rfl theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r], ord (mk α) = @type α r wo := let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) in ⟨r, wo, h⟩ theorem ord_le_type (r : α → α → Prop) [is_well_order α r] : ord (mk α) ≤ ordinal.type r := @ordinal.min_le {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩ theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card := quotient.induction_on c $ λ α, induction_on o $ λ β s _, let ⟨r, _, e⟩ := ord_eq α in begin resetI, simp only [mk_def, card_type], split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := rel_embedding.preimage f s, haveI := rel_embedding.is_well_order g, exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) } end theorem lt_ord {c o} : o < ord c ↔ o.card < c := by rw [← not_le, ← not_le, ord_le] @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ λ α, let ⟨r, _, e⟩ := ord_eq α in by simp only [mk_def, e, card_type] theorem ord_card_le (o : ordinal) : o.card.ord ≤ o := ord_le.2 (le_refl _) lemma lt_ord_succ_card (o : ordinal) : o < o.card.succ.ord := by { rw [lt_ord], apply cardinal.lt_succ_self } @[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ := by simp only [ord_le, card_ord] @[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ := by simp only [lt_ord, card_ord] @[simp] theorem ord_zero : ord 0 = 0 := le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _) @[simp] theorem ord_nat (n : ℕ) : ord n = n := le_antisymm (ord_le.2 $ by simp only [card_nat]) $ begin induction n with n IH, { apply ordinal.zero_le }, { exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := eq_of_forall_ge_iff $ λ o, le_iff_le_iff_lt_iff_lt.2 $ begin split; intro h, { rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩, rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] }, { rw lt_ord at h, rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩, rw [← lift_card, lift_lt] at h, rwa [ordinal.lift_lt, lt_ord] } end lemma mk_ord_out (c : cardinal) : mk c.ord.out.α = c := by rw [←card_type c.ord.out.r, type_out, card_ord] lemma card_typein_lt (r : α → α → Prop) [is_well_order α r] (x : α) (h : ord (mk α) = type r) : card (typein r x) < mk α := by { rw [←ord_lt_ord, h], refine lt_of_le_of_lt (ord_card_le _) (typein_lt_type r x) } lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.α) : card (typein c.ord.out.r x) < c := by { convert card_typein_lt c.ord.out.r x _, rw [mk_ord_out], rw [type_out, mk_ord_out] } lemma ord_injective : injective ord := by { intros c c' h, rw [←card_ord c, ←card_ord c', h] } /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. This is the order-embedding version. For the regular function, see `ord`. -/ def ord.order_embedding : cardinal ↪o ordinal := rel_embedding.order_embedding_of_lt_embedding (rel_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2) @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal → ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ def univ := lift.{(u+1) v} (mk ordinal) theorem univ_id : univ.{u (u+1)} = mk ordinal := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{u (u+1)} c < univ.{u (u+1)} := by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{u (max (u+1) v)} c < univ.{u v} := by simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down'.1 (by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩, simp only [lift.principal_seg_coe], rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{u (u+1)} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down'.1 (by simpa only [lift.principal_seg_top]) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{u (max (u+1) v)} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp only [e.symm, lift_lift]⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩ end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl end ordinal
e9f03ec46585d69aa069b1a1ee05d2ab79b73067
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/limits/shapes/finite_limits.lean
c6706bd92296733e84618ab8cf5cf60e9213250b
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
1,941
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.limits.shapes.products import category_theory.discrete_category import data.fintype universes v u open category_theory namespace category_theory.limits /-- A category with a `fintype` of objects, and a `fintype` for each morphism space. -/ class fin_category (J : Type v) [small_category J] := (decidable_eq_obj : decidable_eq J . tactic.apply_instance) (fintype_obj : fintype J . tactic.apply_instance) (decidable_eq_hom : Π (j j' : J), decidable_eq (j ⟶ j') . tactic.apply_instance) (fintype_hom : Π (j j' : J), fintype (j ⟶ j') . tactic.apply_instance) attribute [instance] fin_category.decidable_eq_obj fin_category.fintype_obj fin_category.decidable_eq_hom fin_category.fintype_hom -- We need a `decidable_eq` instance here to construct `fintype` on the morphism spaces. instance fin_category_discrete_of_decidable_fintype (J : Type v) [fintype J] [decidable_eq J] : fin_category (discrete J) := { } variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 class has_finite_limits := (has_limits_of_shape : Π (J : Type v) [small_category J] [fin_category J], has_limits_of_shape.{v} J C) class has_finite_colimits := (has_colimits_of_shape : Π (J : Type v) [small_category J] [fin_category J], has_colimits_of_shape.{v} J C) attribute [instance] has_finite_limits.has_limits_of_shape has_finite_colimits.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance [has_limits.{v} C] : has_finite_limits.{v} C := { has_limits_of_shape := λ J _ _, by { resetI, apply_instance } } @[priority 100] -- see Note [lower instance priority] instance [has_colimits.{v} C] : has_finite_colimits.{v} C := { has_colimits_of_shape := λ J _ _, by { resetI, apply_instance } } end category_theory.limits
699d5fd5f93df142d633a2cf15e19df31c9578a4
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/lie/cartan_subalgebra.lean
0c1204888eb1a13614b8ca0787638108129acfed
[ "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
5,457
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.nilpotent /-! # Cartan subalgebras Cartan subalgebras are one of the most important concepts in Lie theory. We define them here. The standard example is the set of diagonal matrices in the Lie algebra of matrices. ## Main definitions * `lie_subalgebra.normalizer` * `lie_subalgebra.le_normalizer_of_ideal` * `lie_subalgebra.is_cartan_subalgebra` ## Tags lie subalgebra, normalizer, idealizer, cartan subalgebra -/ universes u v w w₁ w₂ variables {R : Type u} {L : Type v} variables [comm_ring R] [lie_ring L] [lie_algebra R L] (H : lie_subalgebra R L) namespace lie_subalgebra /-- The normalizer of a Lie subalgebra `H` is the set of elements of the Lie algebra whose bracket with any element of `H` lies in `H`. It is the Lie algebra equivalent of the group-theoretic normalizer (see `subgroup.normalizer`) and is an idealizer in the sense of abstract algebra. -/ def normalizer : lie_subalgebra R L := { carrier := { x : L | ∀ (y : L), (y ∈ H) → ⁅x, y⁆ ∈ H }, zero_mem' := λ y hy, by { rw zero_lie y, exact H.zero_mem, }, add_mem' := λ z₁ z₂ h₁ h₂ y hy, by { rw add_lie, exact H.add_mem (h₁ y hy) (h₂ y hy), }, smul_mem' := λ t y hy z hz, by { rw smul_lie, exact H.smul_mem t (hy z hz), }, lie_mem' := λ z₁ z₂ h₁ h₂ y hy, by { rw lie_lie, exact H.sub_mem (h₁ _ (h₂ y hy)) (h₂ _ (h₁ y hy)), }, } lemma mem_normalizer_iff (x : L) : x ∈ H.normalizer ↔ ∀ (y : L), (y ∈ H) → ⁅x, y⁆ ∈ H := iff.rfl lemma mem_normalizer_iff' (x : L) : x ∈ H.normalizer ↔ ∀ (y : L), (y ∈ H) → ⁅y, x⁆ ∈ H := forall₂_congr $ λ y hy, by rw [← lie_skew, neg_mem_iff] lemma le_normalizer : H ≤ H.normalizer := λ x hx, show ∀ (y : L), y ∈ H → ⁅x,y⁆ ∈ H, from λ y, H.lie_mem hx variables {H} lemma lie_mem_sup_of_mem_normalizer {x y z : L} (hx : x ∈ H.normalizer) (hy : y ∈ (R ∙ x) ⊔ ↑H) (hz : z ∈ (R ∙ x) ⊔ ↑H) : ⁅y, z⁆ ∈ (R ∙ x) ⊔ ↑H := begin rw submodule.mem_sup at hy hz, obtain ⟨u₁, hu₁, v, hv : v ∈ H, rfl⟩ := hy, obtain ⟨u₂, hu₂, w, hw : w ∈ H, rfl⟩ := hz, obtain ⟨t, rfl⟩ := submodule.mem_span_singleton.mp hu₁, obtain ⟨s, rfl⟩ := submodule.mem_span_singleton.mp hu₂, apply submodule.mem_sup_right, simp only [lie_subalgebra.mem_coe_submodule, smul_lie, add_lie, zero_add, lie_add, smul_zero, lie_smul, lie_self], refine H.add_mem (H.smul_mem s _) (H.add_mem (H.smul_mem t _) (H.lie_mem hv hw)), exacts [(H.mem_normalizer_iff' x).mp hx v hv, (H.mem_normalizer_iff x).mp hx w hw], end /-- A Lie subalgebra is an ideal of its normalizer. -/ lemma ideal_in_normalizer : ∀ {x y : L}, x ∈ H.normalizer → y ∈ H → ⁅x,y⁆ ∈ H := λ x y h, h y /-- A Lie subalgebra `H` is an ideal of any Lie subalgebra `K` containing `H` and contained in the normalizer of `H`. -/ lemma exists_nested_lie_ideal_of_le_normalizer {K : lie_subalgebra R L} (h₁ : H ≤ K) (h₂ : K ≤ H.normalizer) : ∃ (I : lie_ideal R K), (I : lie_subalgebra R K) = of_le h₁ := begin rw exists_nested_lie_ideal_coe_eq_iff, exact λ x y hx hy, ideal_in_normalizer (h₂ hx) hy, end /-- The normalizer of a Lie subalgebra `H` is the maximal Lie subalgebra in which `H` is a Lie ideal. -/ lemma le_normalizer_of_ideal {N : lie_subalgebra R L} (h : ∀ (x y : L), x ∈ N → y ∈ H → ⁅x,y⁆ ∈ H) : N ≤ H.normalizer := λ x hx y, h x y hx variables (H) lemma normalizer_eq_self_iff : H.normalizer = H ↔ (lie_module.max_triv_submodule R H $ L ⧸ H.to_lie_submodule) = ⊥ := begin rw lie_submodule.eq_bot_iff, refine ⟨λ h, _, λ h, le_antisymm (λ x hx, _) H.le_normalizer⟩, { rintros ⟨x⟩ hx, suffices : x ∈ H, by simpa, rw [← h, H.mem_normalizer_iff'], intros y hy, replace hx : ⁅_, lie_submodule.quotient.mk' _ x⁆ = 0 := hx ⟨y, hy⟩, rwa [← lie_module_hom.map_lie, lie_submodule.quotient.mk_eq_zero] at hx, }, { let y := lie_submodule.quotient.mk' H.to_lie_submodule x, have hy : y ∈ lie_module.max_triv_submodule R H (L ⧸ H.to_lie_submodule), { rintros ⟨z, hz⟩, rw [← lie_module_hom.map_lie, lie_submodule.quotient.mk_eq_zero, coe_bracket_of_module, submodule.coe_mk, mem_to_lie_submodule], exact (H.mem_normalizer_iff' x).mp hx z hz, }, simpa using h y hy, }, end /-- A Cartan subalgebra is a nilpotent, self-normalizing subalgebra. -/ class is_cartan_subalgebra : Prop := (nilpotent : lie_algebra.is_nilpotent R H) (self_normalizing : H.normalizer = H) end lie_subalgebra @[simp] lemma lie_ideal.normalizer_eq_top {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) : (I : lie_subalgebra R L).normalizer = ⊤ := begin ext x, simpa only [lie_subalgebra.mem_normalizer_iff, lie_subalgebra.mem_top, iff_true] using λ y hy, I.lie_mem hy end open lie_ideal /-- A nilpotent Lie algebra is its own Cartan subalgebra. -/ instance lie_algebra.top_is_cartan_subalgebra_of_nilpotent [lie_algebra.is_nilpotent R L] : lie_subalgebra.is_cartan_subalgebra (⊤ : lie_subalgebra R L) := { nilpotent := infer_instance, self_normalizing := by { rw [← top_coe_lie_subalgebra, normalizer_eq_top, top_coe_lie_subalgebra], }, }
9617bf37e636074750be84df8cb5d98301c17237
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_342.lean
9d8e5b873635bf4620e2f945680211c5ce4701cc
[]
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
230
lean
import data.real.basic variables (f g : ℝ → ℝ) -- BEGIN example (mf : monotone f) (mg : monotone g) : monotone (λ x, f x + g x) := begin intros a b aleb, apply add_le_add, apply mf aleb, apply mg aleb end -- END
b097bbefd3cb43c598deda0053b85b76ad6440b9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/dimension.lean
f17c68d567b16a03fb9b5ecf79d536e984c838d6
[ "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
53,175
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen, Scott Morrison -/ import algebra.module.big_operators import linear_algebra.dfinsupp import linear_algebra.invariant_basis_number import linear_algebra.isomorphisms import linear_algebra.std_basis import set_theory.cardinal.cofinality /-! # Dimension of modules and vector spaces ## Main definitions * The rank of a module is defined as `module.rank : cardinal`. This is defined as the supremum of the cardinalities of linearly independent subsets. * The rank of a linear map is defined as the rank of its range. ## Main statements * `linear_map.dim_le_of_injective`: the source of an injective linear map has dimension at most that of the target. * `linear_map.dim_le_of_surjective`: the target of a surjective linear map has dimension at most that of that source. * `basis_fintype_of_finite_spans`: the existence of a finite spanning set implies that any basis is finite. * `infinite_basis_le_maximal_linear_independent`: if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. For modules over rings satisfying the rank condition * `basis.le_span`: the cardinality of a basis is bounded by the cardinality of any spanning set For modules over rings satisfying the strong rank condition * `linear_independent_le_span`: For any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. * `linear_independent_le_basis`: If `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. For modules over rings with invariant basis number (including all commutative rings and all noetherian rings) * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. For vector spaces (i.e. modules over a field), we have * `dim_quotient_add_dim`: if `V₁` is a submodule of `V`, then `module.rank (V/V₁) + module.rank V₁ = module.rank V`. * `dim_range_add_dim_ker`: the rank-nullity theorem. ## Implementation notes There is a naming discrepancy: most of the theorem names refer to `dim`, even though the definition is of `module.rank`. This reflects that `module.rank` was originally called `dim`, and only defined for vector spaces. Many theorems in this file are not universe-generic when they relate dimensions in different universes. They should be as general as they can be without inserting `lift`s. The types `V`, `V'`, ... all live in different universes, and `V₁`, `V₂`, ... all live in the same universe. -/ noncomputable theory universes u v v' v'' u₁' w w' variables {K : Type u} {V V₁ V₂ V₃ : Type v} {V' V'₁ : Type v'} {V'' : Type v''} variables {ι : Type w} {ι' : Type w'} {η : Type u₁'} {φ : η → Type*} open_locale classical big_operators cardinal open basis submodule function set section module section variables [semiring K] [add_comm_monoid V] [module K V] include K variables (K V) /-- The rank of a module, defined as a term of type `cardinal`. We define this as the supremum of the cardinalities of linearly independent subsets. For a free module over any ring satisfying the strong rank condition (e.g. left-noetherian rings, commutative rings, and in particular division rings and fields), this is the same as the dimension of the space (i.e. the cardinality of any basis). In particular this agrees with the usual notion of the dimension of a vector space. The definition is marked as protected to avoid conflicts with `_root_.rank`, the rank of a linear map. -/ protected def module.rank : cardinal := ⨆ ι : {s : set V // linear_independent K (coe : s → V)}, #ι.1 end section variables {R : Type u} [ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {M' : Type v'} [add_comm_group M'] [module R M'] variables {M₁ : Type v} [add_comm_group M₁] [module R M₁] theorem linear_map.lift_dim_le_of_injective (f : M →ₗ[R] M') (i : injective f) : cardinal.lift.{v'} (module.rank R M) ≤ cardinal.lift.{v} (module.rank R M') := begin dsimp [module.rank], rw [cardinal.lift_supr (cardinal.bdd_above_range.{v' v'} _), cardinal.lift_supr (cardinal.bdd_above_range.{v v} _)], apply csupr_mono' (cardinal.bdd_above_range.{v' v} _), rintro ⟨s, li⟩, refine ⟨⟨f '' s, _⟩, cardinal.lift_mk_le'.mpr ⟨(equiv.set.image f s i).to_embedding⟩⟩, exact (li.map' _ $ linear_map.ker_eq_bot.mpr i).image, end theorem linear_map.dim_le_of_injective (f : M →ₗ[R] M₁) (i : injective f) : module.rank R M ≤ module.rank R M₁ := cardinal.lift_le.1 (f.lift_dim_le_of_injective i) theorem dim_le {n : ℕ} (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) : module.rank R M ≤ n := begin apply csupr_le', rintro ⟨s, li⟩, exact linear_independent_bounded_of_finset_linear_independent_bounded H _ li, end lemma lift_dim_range_le (f : M →ₗ[R] M') : cardinal.lift.{v} (module.rank R f.range) ≤ cardinal.lift.{v'} (module.rank R M) := begin dsimp [module.rank], rw [cardinal.lift_supr (cardinal.bdd_above_range.{v' v'} _)], apply csupr_le', rintro ⟨s, li⟩, apply le_trans, swap 2, apply cardinal.lift_le.mpr, refine (le_csupr (cardinal.bdd_above_range.{v v} _) ⟨range_splitting f '' s, _⟩), { apply linear_independent.of_comp f.range_restrict, convert li.comp (equiv.set.range_splitting_image_equiv f s) (equiv.injective _) using 1, }, { exact (cardinal.lift_mk_eq'.mpr ⟨equiv.set.range_splitting_image_equiv f s⟩).ge, }, end lemma dim_range_le (f : M →ₗ[R] M₁) : module.rank R f.range ≤ module.rank R M := by simpa using lift_dim_range_le f lemma lift_dim_map_le (f : M →ₗ[R] M') (p : submodule R M) : cardinal.lift.{v} (module.rank R (p.map f)) ≤ cardinal.lift.{v'} (module.rank R p) := begin have h := lift_dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_map_le (f : M →ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map f) ≤ module.rank R p := by simpa using lift_dim_map_le f p lemma dim_le_of_submodule (s t : submodule R M) (h : s ≤ t) : module.rank R s ≤ module.rank R t := (of_le h).dim_le_of_injective $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq /-- Two linearly equivalent vector spaces have the same dimension, a version with different universes. -/ theorem linear_equiv.lift_dim_eq (f : M ≃ₗ[R] M') : cardinal.lift.{v'} (module.rank R M) = cardinal.lift.{v} (module.rank R M') := begin apply le_antisymm, { exact f.to_linear_map.lift_dim_le_of_injective f.injective, }, { exact f.symm.to_linear_map.lift_dim_le_of_injective f.symm.injective, }, end /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : M ≃ₗ[R] M₁) : module.rank R M = module.rank R M₁ := cardinal.lift_inj.1 f.lift_dim_eq lemma dim_eq_of_injective (f : M →ₗ[R] M₁) (h : injective f) : module.rank R M = module.rank R f.range := (linear_equiv.of_injective f h).dim_eq /-- Pushforwards of submodules along a `linear_equiv` have the same dimension. -/ lemma linear_equiv.dim_map_eq (f : M ≃ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map (f : M →ₗ[R] M₁)) = module.rank R p := (f.submodule_map p).dim_eq.symm variables (R M) @[simp] lemma dim_top : module.rank R (⊤ : submodule R M) = module.rank R M := begin have : (⊤ : submodule R M) ≃ₗ[R] M := linear_equiv.of_top ⊤ rfl, rw this.dim_eq, end variables {R M} lemma dim_range_of_surjective (f : M →ₗ[R] M') (h : surjective f) : module.rank R f.range = module.rank R M' := by rw [linear_map.range_eq_top.2 h, dim_top] lemma dim_submodule_le (s : submodule R M) : module.rank R s ≤ module.rank R M := begin rw ←dim_top R M, exact dim_le_of_submodule _ _ le_top, end lemma linear_map.dim_le_of_surjective (f : M →ₗ[R] M₁) (h : surjective f) : module.rank R M₁ ≤ module.rank R M := begin rw ←dim_range_of_surjective f h, apply dim_range_le, end theorem dim_quotient_le (p : submodule R M) : module.rank R (M ⧸ p) ≤ module.rank R M := (mkq p).dim_le_of_surjective (surjective_quot_mk _) variables [nontrivial R] lemma {m} cardinal_lift_le_dim_of_linear_independent {ι : Type w} {v : ι → M} (hv : linear_independent R v) : cardinal.lift.{max v m} (#ι) ≤ cardinal.lift.{max w m} (module.rank R M) := begin apply le_trans, { exact cardinal.lift_mk_le.mpr ⟨(equiv.of_injective _ hv.injective).to_embedding⟩, }, { simp only [cardinal.lift_le], apply le_trans, swap, exact le_csupr (cardinal.bdd_above_range.{v v} _) ⟨range v, hv.coe_range⟩, exact le_rfl, }, end lemma cardinal_lift_le_dim_of_linear_independent' {ι : Type w} {v : ι → M} (hv : linear_independent R v) : cardinal.lift.{v} (#ι) ≤ cardinal.lift.{w} (module.rank R M) := cardinal_lift_le_dim_of_linear_independent.{u v w 0} hv lemma cardinal_le_dim_of_linear_independent {ι : Type v} {v : ι → M} (hv : linear_independent R v) : #ι ≤ module.rank R M := by simpa using cardinal_lift_le_dim_of_linear_independent hv lemma cardinal_le_dim_of_linear_independent' {s : set M} (hs : linear_independent R (λ x, x : s → M)) : #s ≤ module.rank R M := cardinal_le_dim_of_linear_independent hs variables (R M) @[simp] lemma dim_punit : module.rank R punit = 0 := begin apply le_bot_iff.mp, apply csupr_le', rintro ⟨s, li⟩, apply le_bot_iff.mpr, apply cardinal.mk_emptyc_iff.mpr, simp only [subtype.coe_mk], by_contradiction h, have ne : s.nonempty := ne_empty_iff_nonempty.mp h, simpa using linear_independent.ne_zero (⟨_, ne.some_mem⟩ : s) li, end @[simp] lemma dim_bot : module.rank R (⊥ : submodule R M) = 0 := begin have : (⊥ : submodule R M) ≃ₗ[R] punit := bot_equiv_punit, rw [this.dim_eq, dim_punit], end variables {R M} /-- A linearly-independent family of vectors in a module over a non-trivial ring must be finite if the module is Noetherian. -/ lemma linear_independent.finite_of_is_noetherian [is_noetherian R M] {v : ι → M} (hv : linear_independent R v) : finite ι := begin have hwf := is_noetherian_iff_well_founded.mp (by apply_instance : is_noetherian R M), refine complete_lattice.well_founded.finite_of_independent hwf hv.independent_span_singleton (λ i contra, _), apply hv.ne_zero i, have : v i ∈ R ∙ v i := submodule.mem_span_singleton_self (v i), rwa [contra, submodule.mem_bot] at this, end lemma linear_independent.set_finite_of_is_noetherian [is_noetherian R M] {s : set M} (hi : linear_independent R (coe : s → M)) : s.finite := @set.to_finite _ _ hi.finite_of_is_noetherian /-- Over any nontrivial ring, the existence of a finite spanning set implies that any basis is finite. -/ -- One might hope that a finite spanning set implies that any linearly independent set is finite. -- While this is true over a division ring -- (simply because any linearly independent set can be extended to a basis), -- I'm not certain what more general statements are possible. def basis_fintype_of_finite_spans (w : set M) [fintype w] (s : span R w = ⊤) {ι : Type w} (b : basis ι R M) : fintype ι := begin -- We'll work by contradiction, assuming `ι` is infinite. apply fintype_of_not_infinite _, introI i, -- Let `S` be the union of the supports of `x ∈ w` expressed as linear combinations of `b`. -- This is a finite set since `w` is finite. let S : finset ι := finset.univ.sup (λ x : w, (b.repr x).support), let bS : set M := b '' S, have h : ∀ x ∈ w, x ∈ span R bS, { intros x m, rw [←b.total_repr x, finsupp.span_image_eq_map_total, submodule.mem_map], use b.repr x, simp only [and_true, eq_self_iff_true, finsupp.mem_supported], change (b.repr x).support ≤ S, convert (finset.le_sup (by simp : (⟨x, m⟩ : w) ∈ finset.univ)), refl, }, -- Thus this finite subset of the basis elements spans the entire module. have k : span R bS = ⊤ := eq_top_iff.2 (le_trans s.ge (span_le.2 h)), -- Now there is some `x : ι` not in `S`, since `ι` is infinite. obtain ⟨x, nm⟩ := infinite.exists_not_mem_finset S, -- However it must be in the span of the finite subset, have k' : b x ∈ span R bS, { rw k, exact mem_top, }, -- giving the desire contradiction. refine b.linear_independent.not_mem_span_image _ k', exact nm, end /-- Over any ring `R`, if `b` is a basis for a module `M`, and `s` is a maximal linearly independent set, then the union of the supports of `x ∈ s` (when written out in the basis `b`) is all of `b`. -/ -- From [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] lemma union_support_maximal_linear_independent_eq_range_basis {ι : Type w} (b : basis ι R M) {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : (⋃ k, ((b.repr (v k)).support : set ι)) = univ := begin -- If that's not the case, by_contradiction h, simp only [←ne.def, ne_univ_iff_exists_not_mem, mem_Union, not_exists_not, finsupp.mem_support_iff, finset.mem_coe] at h, -- We have some basis element `b b'` which is not in the support of any of the `v i`. obtain ⟨b', w⟩ := h, -- Using this, we'll construct a linearly independent family strictly larger than `v`, -- by also using this `b b'`. let v' : option κ → M := λ o, o.elim (b b') v, have r : range v ⊆ range v', { rintro - ⟨k, rfl⟩, use some k, refl, }, have r' : b b' ∉ range v, { rintro ⟨k, p⟩, simpa [w] using congr_arg (λ m, (b.repr m) b') p, }, have r'' : range v ≠ range v', { intro e, have p : b b' ∈ range v', { use none, refl, }, rw ←e at p, exact r' p, }, have inj' : injective v', { rintros (_|k) (_|k) z, { refl, }, { exfalso, exact r' ⟨k, z.symm⟩, }, { exfalso, exact r' ⟨k, z⟩, }, { congr, exact i.injective z, }, }, -- The key step in the proof is checking that this strictly larger family is linearly independent. have i' : linear_independent R (coe : range v' → M), { rw [linear_independent_subtype_range inj', linear_independent_iff], intros l z, rw [finsupp.total_option] at z, simp only [v', option.elim] at z, change _ + finsupp.total κ M R v l.some = 0 at z, -- We have some linear combination of `b b'` and the `v i`, which we want to show is trivial. -- We'll first show the coefficient of `b b'` is zero, -- by expressing the `v i` in the basis `b`, and using that the `v i` have no `b b'` term. have l₀ : l none = 0, { rw ←eq_neg_iff_add_eq_zero at z, replace z := eq_neg_of_eq_neg z, apply_fun (λ x, b.repr x b') at z, simp only [repr_self, linear_equiv.map_smul, mul_one, finsupp.single_eq_same, pi.neg_apply, finsupp.smul_single', linear_equiv.map_neg, finsupp.coe_neg] at z, erw finsupp.congr_fun (finsupp.apply_total R (b.repr : M →ₗ[R] ι →₀ R) v l.some) b' at z, simpa [finsupp.total_apply, w] using z, }, -- Then all the other coefficients are zero, because `v` is linear independent. have l₁ : l.some = 0, { rw [l₀, zero_smul, zero_add] at z, exact linear_independent_iff.mp i _ z, }, -- Finally we put those facts together to show the linear combination is trivial. ext (_|a), { simp only [l₀, finsupp.coe_zero, pi.zero_apply], }, { erw finsupp.congr_fun l₁ a, simp only [finsupp.coe_zero, pi.zero_apply], }, }, dsimp [linear_independent.maximal] at m, specialize m (range v') i' r, exact r'' m, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ lemma infinite_basis_le_maximal_linear_independent' {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.lift.{w'} (#ι) ≤ cardinal.lift.{w} (#κ) := begin let Φ := λ k : κ, (b.repr (v k)).support, have w₁ : #ι ≤ #(set.range Φ), { apply cardinal.le_range_of_union_finset_eq_top, exact union_support_maximal_linear_independent_eq_range_basis b v i m, }, have w₂ : cardinal.lift.{w'} (#(set.range Φ)) ≤ cardinal.lift.{w} (#κ) := cardinal.mk_range_le_lift, exact (cardinal.lift_le.mpr w₁).trans w₂, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ -- (See `infinite_basis_le_maximal_linear_independent'` for the more general version -- where the index types can live in different universes.) lemma infinite_basis_le_maximal_linear_independent {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : #ι ≤ #κ := cardinal.lift_le.mp (infinite_basis_le_maximal_linear_independent' b v i m) lemma complete_lattice.independent.subtype_ne_bot_le_rank [no_zero_smul_divisors R M] {V : ι → submodule R M} (hV : complete_lattice.independent V) : cardinal.lift.{v} (#{i : ι // V i ≠ ⊥}) ≤ cardinal.lift.{w} (module.rank R M) := begin set I := {i : ι // V i ≠ ⊥}, have hI : ∀ i : I, ∃ v ∈ V i, v ≠ (0:M), { intros i, rw ← submodule.ne_bot_iff, exact i.prop }, choose v hvV hv using hI, have : linear_independent R v, { exact (hV.comp subtype.coe_injective).linear_independent _ hvV hv }, exact cardinal_lift_le_dim_of_linear_independent' this end end section rank_zero variables {R : Type u} {M : Type v} variables [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] lemma dim_zero_iff_forall_zero : module.rank R M = 0 ↔ ∀ x : M, x = 0 := begin refine ⟨λ h, _, λ h, _⟩, { contrapose! h, obtain ⟨x, hx⟩ := h, suffices : 1 ≤ module.rank R M, { intro h, exact this.not_lt (h.symm ▸ zero_lt_one) }, suffices : linear_independent R (λ (y : ({x} : set M)), ↑y), { simpa using (cardinal_le_dim_of_linear_independent this), }, exact linear_independent_singleton hx }, { have : (⊤ : submodule R M) = ⊥, { ext x, simp [h x] }, rw [←dim_top, this, dim_bot] } end lemma dim_zero_iff : module.rank R M = 0 ↔ subsingleton M := dim_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm lemma dim_pos_iff_exists_ne_zero : 0 < module.rank R M ↔ ∃ x : M, x ≠ 0 := begin rw ←not_iff_not, simpa using dim_zero_iff_forall_zero end lemma dim_pos_iff_nontrivial : 0 < module.rank R M ↔ nontrivial M := dim_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm lemma dim_pos [h : nontrivial M] : 0 < module.rank R M := dim_pos_iff_nontrivial.2 h end rank_zero section invariant_basis_number variables {R : Type u} [ring R] [invariant_basis_number R] variables {M : Type v} [add_comm_group M] [module R M] /-- The dimension theorem: if `v` and `v'` are two bases, their index types have the same cardinalities. -/ theorem mk_eq_mk_of_basis (v : basis ι R M) (v' : basis ι' R M) : cardinal.lift.{w'} (#ι) = cardinal.lift.{w} (#ι') := begin haveI := nontrivial_of_invariant_basis_number R, casesI fintype_or_infinite ι, { -- `v` is a finite basis, so by `basis_fintype_of_finite_spans` so is `v'`. haveI : fintype (range v) := set.fintype_range v, haveI := basis_fintype_of_finite_spans _ v.span_eq v', -- We clean up a little: rw [cardinal.mk_fintype, cardinal.mk_fintype], simp only [cardinal.lift_nat_cast, cardinal.nat_cast_inj], -- Now we can use invariant basis number to show they have the same cardinality. apply card_eq_of_lequiv R, exact (((finsupp.linear_equiv_fun_on_finite R R ι).symm.trans v.repr.symm) ≪≫ₗ v'.repr) ≪≫ₗ (finsupp.linear_equiv_fun_on_finite R R ι'), }, { -- `v` is an infinite basis, -- so by `infinite_basis_le_maximal_linear_independent`, `v'` is at least as big, -- and then applying `infinite_basis_le_maximal_linear_independent` again -- we see they have the same cardinality. have w₁ := infinite_basis_le_maximal_linear_independent' v _ v'.linear_independent v'.maximal, rcases cardinal.lift_mk_le'.mp w₁ with ⟨f⟩, haveI : infinite ι' := infinite.of_injective f f.2, have w₂ := infinite_basis_le_maximal_linear_independent' v' _ v.linear_independent v.maximal, exact le_antisymm w₁ w₂, } end /-- Given two bases indexed by `ι` and `ι'` of an `R`-module, where `R` satisfies the invariant basis number property, an equiv `ι ≃ ι' `. -/ def basis.index_equiv (v : basis ι R M) (v' : basis ι' R M) : ι ≃ ι' := nonempty.some (cardinal.lift_mk_eq.1 (cardinal.lift_umax_eq.2 (mk_eq_mk_of_basis v v'))) theorem mk_eq_mk_of_basis' {ι' : Type w} (v : basis ι R M) (v' : basis ι' R M) : #ι = #ι' := cardinal.lift_inj.1 $ mk_eq_mk_of_basis v v' end invariant_basis_number section rank_condition variables {R : Type u} [ring R] [rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] /-- An auxiliary lemma for `basis.le_span`. If `R` satisfies the rank condition, then for any finite basis `b : basis ι R M`, and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma basis.le_span'' {ι : Type*} [fintype ι] (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : fintype.card ι ≤ fintype.card w := begin -- We construct an surjective linear map `(w → R) →ₗ[R] (ι → R)`, -- by expressing a linear combination in `w` as a linear combination in `ι`. fapply card_le_of_surjective' R, { exact b.repr.to_linear_map.comp (finsupp.total w M R coe), }, { apply surjective.comp, apply linear_equiv.surjective, rw [←linear_map.range_eq_top, finsupp.range_total], simpa using s, }, end /-- Another auxiliary lemma for `basis.le_span`, which does not require assuming the basis is finite, but still assumes we have a finite spanning set. -/ lemma basis_le_span' {ι : Type*} (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : #ι ≤ fintype.card w := begin haveI := nontrivial_of_invariant_basis_number R, haveI := basis_fintype_of_finite_spans w s b, rw cardinal.mk_fintype ι, simp only [cardinal.nat_cast_le], exact basis.le_span'' b s, end /-- If `R` satisfies the rank condition, then the cardinality of any basis is bounded by the cardinality of any spanning set. -/ -- Note that if `R` satisfies the strong rank condition, -- this also follows from `linear_independent_le_span` below. theorem basis.le_span {J : set M} (v : basis ι R M) (hJ : span R J = ⊤) : #(range v) ≤ #J := begin haveI := nontrivial_of_invariant_basis_number R, casesI fintype_or_infinite J, { rw [←cardinal.lift_le, cardinal.mk_range_eq_of_injective v.injective, cardinal.mk_fintype J], convert cardinal.lift_le.{w v}.2 (basis_le_span' v hJ), simp, }, { have := cardinal.mk_range_eq_of_injective v.injective, let S : J → set ι := λ j, ↑(v.repr j).support, let S' : J → set M := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span R J ≤ comap v.repr.to_linear_map (finsupp.supported R R (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : v.repr (v i) ∈ (finsupp.supported R R (⋃ j, S j)) := this trivial, rw [v.repr_self, finsupp.mem_supported, finsupp.support_single_ne_zero _ one_ne_zero] at this, { subst b, rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩, exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ }, { apply_instance } }, refine le_of_not_lt (λ IJ, _), suffices : #(⋃ j, S' j) < #(range v), { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, ℵ₀) _)) _, { exact λ j, (cardinal.lt_aleph_0_of_finite _).le }, { simpa } }, end end rank_condition section strong_rank_condition variables {R : Type u} [ring R] [strong_rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] open submodule -- An auxiliary lemma for `linear_independent_le_span'`, -- with the additional assumption that the linearly independent family is finite. lemma linear_independent_le_span_aux' {ι : Type*} [fintype ι] (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype.card ι ≤ fintype.card w := begin -- We construct an injective linear map `(ι → R) →ₗ[R] (w → R)`, -- by thinking of `f : ι → R` as a linear combination of the finite family `v`, -- and expressing that (using the axiom of choice) as a linear combination over `w`. -- We can do this linearly by constructing the map on a basis. fapply card_le_of_injective' R, { apply finsupp.total, exact λ i, span.repr R w ⟨v i, s (mem_range_self i)⟩, }, { intros f g h, apply_fun finsupp.total w M R coe at h, simp only [finsupp.total_total, submodule.coe_mk, span.finsupp_total_repr] at h, rw [←sub_eq_zero, ←linear_map.map_sub] at h, exact sub_eq_zero.mp (linear_independent_iff.mp i _ h), }, end /-- If `R` satisfies the strong rank condition, then any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, is itself finite. -/ def linear_independent_fintype_of_le_span_fintype {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype ι := fintype_of_finset_card_le (fintype.card w) (λ t, begin let v' := λ x : (t : set ι), v x, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have s' : range v' ≤ span R w := (range_comp_subset_range _ _).trans s, simpa using linear_independent_le_span_aux' v' i' w s', end) /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span' {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : #ι ≤ fintype.card w := begin haveI : fintype ι := linear_independent_fintype_of_le_span_fintype v i w s, rw cardinal.mk_fintype, simp only [cardinal.nat_cast_le], exact linear_independent_le_span_aux' v i w s, end /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : span R w = ⊤) : #ι ≤ fintype.card w := begin apply linear_independent_le_span' v i w, rw s, exact le_top, end /-- An auxiliary lemma for `linear_independent_le_basis`: we handle the case where the basis `b` is infinite. -/ lemma linear_independent_le_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) : #κ ≤ #ι := begin by_contradiction, rw [not_le, ← cardinal.mk_finset_of_infinite ι] at h, let Φ := λ k : κ, (b.repr (v k)).support, obtain ⟨s, w : infinite ↥(Φ ⁻¹' {s})⟩ := cardinal.exists_infinite_fiber Φ h (by apply_instance), let v' := λ k : Φ ⁻¹' {s}, v k, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have w' : fintype (Φ ⁻¹' {s}), { apply linear_independent_fintype_of_le_span_fintype v' i' (s.image b), rintros m ⟨⟨p,⟨rfl⟩⟩,rfl⟩, simp only [set_like.mem_coe, subtype.coe_mk, finset.coe_image], apply basis.mem_span_repr_support, }, exactI w.false, end /-- Over any ring `R` satisfying the strong rank condition, if `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. -/ lemma linear_independent_le_basis {ι : Type*} (b : basis ι R M) {κ : Type*} (v : κ → M) (i : linear_independent R v) : #κ ≤ #ι := begin -- We split into cases depending on whether `ι` is infinite. cases fintype_or_infinite ι; resetI, { -- When `ι` is finite, we have `linear_independent_le_span`, rw cardinal.mk_fintype ι, haveI : nontrivial R := nontrivial_of_invariant_basis_number R, rw fintype.card_congr (equiv.of_injective b b.injective), exact linear_independent_le_span v i (range b) b.span_eq, }, { -- and otherwise we have `linear_indepedent_le_infinite_basis`. exact linear_independent_le_infinite_basis b v i, }, end /-- In an `n`-dimensional space, the rank is at most `m`. -/ lemma basis.card_le_card_of_linear_independent_aux {R : Type*} [ring R] [strong_rank_condition R] (n : ℕ) {m : ℕ} (v : fin m → fin n → R) : linear_independent R v → m ≤ n := λ h, by simpa using (linear_independent_le_basis (pi.basis_fun R (fin n)) v h) /-- Over any ring `R` satisfying the strong rank condition, if `b` is an infinite basis for a module `M`, then every maximal linearly independent set has the same cardinality as `b`. This proof (along with some of the lemmas above) comes from [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] -/ -- When the basis is not infinite this need not be true! lemma maximal_linear_independent_eq_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : #κ = #ι := begin apply le_antisymm, { exact linear_independent_le_basis b v i, }, { haveI : nontrivial R := nontrivial_of_invariant_basis_number R, exact infinite_basis_le_maximal_linear_independent b v i m, } end theorem basis.mk_eq_dim'' {ι : Type v} (v : basis ι R M) : #ι = module.rank R M := begin haveI := nontrivial_of_invariant_basis_number R, apply le_antisymm, { transitivity, swap, apply le_csupr (cardinal.bdd_above_range.{v v} _), exact ⟨set.range v, by { convert v.reindex_range.linear_independent, ext, simp }⟩, exact (cardinal.mk_range_eq v v.injective).ge, }, { apply csupr_le', rintro ⟨s, li⟩, apply linear_independent_le_basis v _ li, }, end -- By this stage we want to have a complete API for `module.rank`, -- so we set it `irreducible` here, to keep ourselves honest. attribute [irreducible] module.rank theorem basis.mk_range_eq_dim (v : basis ι R M) : #(range v) = module.rank R M := v.reindex_range.mk_eq_dim'' /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] (h : basis ι R M) : module.rank R M = fintype.card ι := by {haveI := nontrivial_of_invariant_basis_number R, rw [←h.mk_range_eq_dim, cardinal.mk_fintype, set.card_range_of_injective h.injective] } lemma basis.card_le_card_of_linear_independent {ι : Type*} [fintype ι] (b : basis ι R M) {ι' : Type*} [fintype ι'] {v : ι' → M} (hv : linear_independent R v) : fintype.card ι' ≤ fintype.card ι := begin letI := nontrivial_of_invariant_basis_number R, simpa [dim_eq_card_basis b, cardinal.mk_fintype] using cardinal_lift_le_dim_of_linear_independent' hv end lemma basis.card_le_card_of_submodule (N : submodule R M) [fintype ι] (b : basis ι R M) [fintype ι'] (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι := b.card_le_card_of_linear_independent (b'.linear_independent.map' N.subtype N.ker_subtype) lemma basis.card_le_card_of_le {N O : submodule R M} (hNO : N ≤ O) [fintype ι] (b : basis ι R O) [fintype ι'] (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι := b.card_le_card_of_linear_independent (b'.linear_independent.map' (submodule.of_le hNO) (N.ker_of_le O _)) theorem basis.mk_eq_dim (v : basis ι R M) : cardinal.lift.{v} (#ι) = cardinal.lift.{w} (module.rank R M) := begin haveI := nontrivial_of_invariant_basis_number R, rw [←v.mk_range_eq_dim, cardinal.mk_range_eq_of_injective v.injective] end theorem {m} basis.mk_eq_dim' (v : basis ι R M) : cardinal.lift.{max v m} (#ι) = cardinal.lift.{max w m} (module.rank R M) := by simpa using v.mk_eq_dim /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ lemma basis.nonempty_fintype_index_of_dim_lt_aleph_0 {ι : Type*} (b : basis ι R M) (h : module.rank R M < ℵ₀) : nonempty (fintype ι) := by rwa [← cardinal.lift_lt, ← b.mk_eq_dim, -- ensure `aleph_0` has the correct universe cardinal.lift_aleph_0, ← cardinal.lift_aleph_0.{u_1 v}, cardinal.lift_lt, cardinal.lt_aleph_0_iff_fintype] at h /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ noncomputable def basis.fintype_index_of_dim_lt_aleph_0 {ι : Type*} (b : basis ι R M) (h : module.rank R M < ℵ₀) : fintype ι := classical.choice (b.nonempty_fintype_index_of_dim_lt_aleph_0 h) /-- If a module has a finite dimension, all bases are indexed by a finite set. -/ lemma basis.finite_index_of_dim_lt_aleph_0 {ι : Type*} {s : set ι} (b : basis s R M) (h : module.rank R M < ℵ₀) : s.finite := finite_def.2 (b.nonempty_fintype_index_of_dim_lt_aleph_0 h) lemma dim_span {v : ι → M} (hv : linear_independent R v) : module.rank R ↥(span R (range v)) = #(range v) := begin haveI := nontrivial_of_invariant_basis_number R, rw [←cardinal.lift_inj, ← (basis.span hv).mk_eq_dim, cardinal.mk_range_eq_of_injective (@linear_independent.injective ι R M v _ _ _ _ hv)] end lemma dim_span_set {s : set M} (hs : linear_independent R (λ x, x : s → M)) : module.rank R ↥(span R s) = #s := by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs } /-- If `N` is a submodule in a free, finitely generated module, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank [is_domain R] [fintype ι] (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (N : submodule R M) : P N := submodule.induction_on_rank_aux b P ih (fintype.card ι) N (λ s hs hli, by simpa using b.card_le_card_of_linear_independent hli) /-- If `S` a finite-dimensional ring extension of `R` which is free as an `R`-module, then the rank of an ideal `I` of `S` over `R` is the same as the rank of `S`. -/ lemma ideal.rank_eq {R S : Type*} [comm_ring R] [strong_rank_condition R] [ring S] [is_domain S] [algebra R S] {n m : Type*} [fintype n] [fintype m] (b : basis n R S) {I : ideal S} (hI : I ≠ ⊥) (c : basis m R I) : fintype.card m = fintype.card n := begin obtain ⟨a, ha⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr hI), have : linear_independent R (λ i, b i • a), { have hb := b.linear_independent, rw fintype.linear_independent_iff at ⊢ hb, intros g hg, apply hb g, simp only [← smul_assoc, ← finset.sum_smul, smul_eq_zero] at hg, exact hg.resolve_right ha }, exact le_antisymm (b.card_le_card_of_linear_independent (c.linear_independent.map' (submodule.subtype I) (linear_map.ker_eq_bot.mpr subtype.coe_injective))) (c.card_le_card_of_linear_independent this), end variables (R) @[simp] lemma dim_self : module.rank R R = 1 := by rw [←cardinal.lift_inj, ← (basis.singleton punit R).mk_eq_dim, cardinal.mk_punit] end strong_rank_condition section division_ring variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables {K V} /-- If a vector space has a finite dimension, the index set of `basis.of_vector_space` is finite. -/ lemma basis.finite_of_vector_space_index_of_dim_lt_aleph_0 (h : module.rank K V < ℵ₀) : (basis.of_vector_space_index K V).finite := finite_def.2 $ (basis.of_vector_space K V).nonempty_fintype_index_of_dim_lt_aleph_0 h variables [add_comm_group V'] [module K V'] /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_lift_dim_eq (cond : cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin let B := basis.of_vector_space K V, let B' := basis.of_vector_space K V', have : cardinal.lift.{v' v} (#_) = cardinal.lift.{v v'} (#_), by rw [B.mk_eq_dim'', cond, B'.mk_eq_dim''], exact (cardinal.lift_mk_eq.{v v' 0}.1 this).map (B.equiv B') end /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_dim_eq (cond : module.rank K V = module.rank K V₁) : nonempty (V ≃ₗ[K] V₁) := nonempty_linear_equiv_of_lift_dim_eq $ congr_arg _ cond section variables (V V' V₁) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_lift_dim_eq (cond : cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) : V ≃ₗ[K] V' := classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_dim_eq (cond : module.rank K V = module.rank K V₁) : V ≃ₗ[K] V₁ := classical.choice (nonempty_linear_equiv_of_dim_eq cond) end /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq : nonempty (V ≃ₗ[K] V') ↔ cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V') := ⟨λ ⟨h⟩, linear_equiv.lift_dim_eq h, λ h, nonempty_linear_equiv_of_lift_dim_eq h⟩ /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_dim_eq : nonempty (V ≃ₗ[K] V₁) ↔ module.rank K V = module.rank K V₁ := ⟨λ ⟨h⟩, linear_equiv.dim_eq h, λ h, nonempty_linear_equiv_of_dim_eq h⟩ -- TODO how far can we generalise this? -- When `s` is finite, we could prove this for any ring satisfying the strong rank condition -- using `linear_independent_le_span'` lemma dim_span_le (s : set V) : module.rank K (span K s) ≤ #s := begin obtain ⟨b, hb, hsab, hlib⟩ := exists_linear_independent K s, convert cardinal.mk_le_mk_of_subset hb, rw [← hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : module.rank K (span K (↑s : set V)) < ℵ₀ := calc module.rank K (span K (↑s : set V)) ≤ #(↑s : set V) : dim_span_le ↑s ... = s.card : by rw [finset.coe_sort_coe, cardinal.mk_coe_finset] ... < ℵ₀ : cardinal.nat_lt_aleph_0 _ theorem dim_prod : module.rank K (V × V₁) = module.rank K V + module.rank K V₁ := begin let b := basis.of_vector_space K V, let c := basis.of_vector_space K V₁, rw [← cardinal.lift_inj, ← (basis.prod b c).mk_eq_dim, cardinal.lift_add, ← cardinal.mk_ulift, ← b.mk_eq_dim, ← c.mk_eq_dim, ← cardinal.mk_ulift, ← cardinal.mk_ulift, cardinal.add_def (ulift _)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm ⟩), end section fintype variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)] open linear_map lemma dim_pi [finite η] : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) := begin casesI nonempty_fintype η, let b := assume i, basis.of_vector_space K (φ i), let this : basis (Σ j, _) K (Π j, φ j) := pi.basis b, rw [← cardinal.lift_inj, ← this.mk_eq_dim], simp [← (b _).mk_range_eq_dim] end variable [fintype η] lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [module K V] : module.rank K (η → V) = fintype.card η * module.rank K V := by rw [dim_pi, cardinal.sum_const', cardinal.mk_fintype] lemma dim_fun_eq_lift_mul : module.rank K (η → V) = (fintype.card η : cardinal.{max u₁' v}) * cardinal.lift.{u₁'} (module.rank K V) := by rw [dim_pi, cardinal.sum_const, cardinal.mk_fintype, cardinal.lift_nat_cast] lemma dim_fun' : module.rank K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_self, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : module.rank K (fin n → K) = n := by simp [dim_fun'] end fintype theorem dim_quotient_add_dim (p : submodule K V) : module.rank K (V ⧸ p) + module.rank K p = module.rank K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₁) : module.rank K f.range + module.rank K f.ker = module.rank K V := begin haveI := λ (p : submodule K V), classical.dec_eq (V ⧸ p), rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_eq_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) : module.rank K V = module.rank K V₁ + module.rank K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] section variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V₃] [module K V₃] open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₂ →ₗ[K] V) (eb : V₃ →ₗ[K] V) (cd : V₁ →ₗ[K] V₂) (ce : V₁ →ₗ[K] V₃) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : module.rank K V + module.rank K V₁ = module.rank K V₂ + module.rank K V₃ := have hf : surjective (coprod db eb), by rwa [←range_eq_top, range_coprod, eq_top_iff], begin conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, refine linear_equiv.of_bijective _ _ _, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, pi.prod, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [← ker_eq_bot, ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [← range_eq_top, eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, set_like.mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range, pi.prod] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) + module.rank K (s ⊓ t : submodule K V) = module.rank K s + module.rank K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_rfl end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, obtain rfl : b₁ = b₂ := congr_arg subtype.val eq, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) ≤ module.rank K s + module.rank K t := by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ } end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < module.rank K s) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h end division_ring section rank section variables [ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables [add_comm_group V'] [module K V'] /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V') : cardinal := module.rank K f.range lemma rank_le_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ := dim_submodule_le _ @[simp] lemma rank_zero [nontrivial K] : rank (0 : V →ₗ[K] V') = 0 := by rw [rank, linear_map.range_zero, dim_bot] variables [add_comm_group V''] [module K V''] lemma rank_comp_le1 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'') : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact linear_map.map_le_range, end variables [add_comm_group V'₁] [module K V'₁] lemma rank_comp_le2 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'₁) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end end rank section division_ring variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables [add_comm_group V'] [module K V'] lemma rank_le_domain (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V := by { rw [← dim_range_add_dim_ker f], exact self_le_add_right _ _ } lemma rank_add_le (f g : V →ₗ[K] V') : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ module.rank K (f.range ⊔ g.range : submodule K V') : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V'), from mem_sup.2 ⟨_, ⟨x, rfl⟩, _, ⟨x, rfl⟩, rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V') : rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _)) /-- The `ι` indexed basis on `V`, where `ι` is an empty type and `V` is zero-dimensional. See also `finite_dimensional.fin_basis`. -/ def basis.of_dim_eq_zero {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) : basis ι K V := begin haveI : subsingleton V := dim_zero_iff.1 hV, exact basis.empty _ end @[simp] lemma basis.of_dim_eq_zero_apply {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) (i : ι) : basis.of_dim_eq_zero hV i = 0 := rfl lemma le_dim_iff_exists_linear_independent {c : cardinal} : c ≤ module.rank K V ↔ ∃ s : set V, #s = c ∧ linear_independent K (coe : s → V) := begin split, { intro h, let t := basis.of_vector_space K V, rw [← t.mk_eq_dim'', cardinal.le_mk_iff_exists_subset] at h, rcases h with ⟨s, hst, hsc⟩, exact ⟨s, hsc, (of_vector_space_index.linear_independent K V).mono hst⟩ }, { rintro ⟨s, rfl, si⟩, exact cardinal_le_dim_of_linear_independent si } end lemma le_dim_iff_exists_linear_independent_finset {n : ℕ} : ↑n ≤ module.rank K V ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (coe : (s : set V) → V) := begin simp only [le_dim_iff_exists_linear_independent, cardinal.mk_set_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end /-- A vector space has dimension at most `1` if and only if there is a single vector of which all vectors are multiples. -/ lemma dim_le_one_iff : module.rank K V ≤ 1 ↔ ∃ v₀ : V, ∀ v, ∃ r : K, r • v₀ = v := begin let b := basis.of_vector_space K V, split, { intro hd, rw [← b.mk_eq_dim'', cardinal.le_one_iff_subsingleton, subsingleton_coe] at hd, rcases eq_empty_or_nonempty (of_vector_space_index K V) with hb | ⟨⟨v₀, hv₀⟩⟩, { use 0, have h' : ∀ v : V, v = 0, { simpa [hb, submodule.eq_bot_iff] using b.span_eq.symm }, intro v, simp [h' v] }, { use v₀, have h' : (K ∙ v₀) = ⊤, { simpa [hd.eq_singleton_of_mem hv₀] using b.span_eq }, intro v, have hv : v ∈ (⊤ : submodule K V) := mem_top, rwa [←h', mem_span_singleton] at hv } }, { rintros ⟨v₀, hv₀⟩, have h : (K ∙ v₀) = ⊤, { ext, simp [mem_span_singleton, hv₀] }, rw [←dim_top, ←h], convert dim_span_le _, simp } end /-- A submodule has dimension at most `1` if and only if there is a single vector in the submodule such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀ ∈ s, s ≤ K ∙ v₀ := begin simp_rw [dim_le_one_iff, le_span_singleton_iff], split, { rintro ⟨⟨v₀, hv₀⟩, h⟩, use [v₀, hv₀], intros v hv, obtain ⟨r, hr⟩ := h ⟨v, hv⟩, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk] at hr, exact hr }, { rintro ⟨v₀, hv₀, h⟩, use ⟨v₀, hv₀⟩, rintro ⟨v, hv⟩, obtain ⟨r, hr⟩ := h v hv, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk], exact hr } end /-- A submodule has dimension at most `1` if and only if there is a single vector, not necessarily in the submodule, such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff' (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀, s ≤ K ∙ v₀ := begin rw dim_submodule_le_one_iff, split, { rintros ⟨v₀, hv₀, h⟩, exact ⟨v₀, h⟩ }, { rintros ⟨v₀, h⟩, by_cases hw : ∃ w : V, w ∈ s ∧ w ≠ 0, { rcases hw with ⟨w, hw, hw0⟩, use [w, hw], rcases mem_span_singleton.1 (h hw) with ⟨r', rfl⟩, have h0 : r' ≠ 0, { rintro rfl, simpa using hw0 }, rwa span_singleton_smul_eq (is_unit.mk0 _ h0) _ }, { push_neg at hw, rw ←submodule.eq_bot_iff at hw, simp [hw] } } end lemma submodule.rank_le_one_iff_is_principal (W : submodule K V) : module.rank K W ≤ 1 ↔ W.is_principal := begin simp only [dim_le_one_iff, submodule.is_principal_iff, le_antisymm_iff, le_span_singleton_iff, span_singleton_le_iff_mem], split, { rintro ⟨⟨m, hm⟩, hm'⟩, choose f hf using hm', exact ⟨m, ⟨λ v hv, ⟨f ⟨v, hv⟩, congr_arg coe (hf ⟨v, hv⟩)⟩, hm⟩⟩ }, { rintro ⟨a, ⟨h, ha⟩⟩, choose f hf using h, exact ⟨⟨a, ha⟩, λ v, ⟨f v.1 v.2, subtype.ext (hf v.1 v.2)⟩⟩ } end lemma module.rank_le_one_iff_top_is_principal : module.rank K V ≤ 1 ↔ (⊤ : submodule K V).is_principal := by rw [← submodule.rank_le_one_iff_is_principal, dim_top] lemma le_rank_iff_exists_linear_independent {c : cardinal} {f : V →ₗ[K] V'} : c ≤ rank f ↔ ∃ s : set V, cardinal.lift.{v'} (#s) = cardinal.lift.{v} c ∧ linear_independent K (λ x : s, f x) := begin rcases f.range_restrict.exists_right_inverse_of_surjective f.range_range_restrict with ⟨g, hg⟩, have fg : left_inverse f.range_restrict g, from linear_map.congr_fun hg, refine ⟨λ h, _, _⟩, { rcases le_dim_iff_exists_linear_independent.1 h with ⟨s, rfl, si⟩, refine ⟨g '' s, cardinal.mk_image_eq_lift _ _ fg.injective, _⟩, replace fg : ∀ x, f (g x) = x, by { intro x, convert congr_arg subtype.val (fg x) }, replace si : linear_independent K (λ x : s, f (g x)), by simpa only [fg] using si.map' _ (ker_subtype _), exact si.image_of_comp s g f }, { rintro ⟨s, hsc, si⟩, have : linear_independent K (λ x : s, f.range_restrict x), from linear_independent.of_comp (f.range.subtype) (by convert si), convert cardinal_le_dim_of_linear_independent this.image, rw [← cardinal.lift_inj, ← hsc, cardinal.mk_image_eq_of_inj_on_lift], exact inj_on_iff_injective.2 this.injective } end lemma le_rank_iff_exists_linear_independent_finset {n : ℕ} {f : V →ₗ[K] V'} : ↑n ≤ rank f ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (λ x : (s : set V), f x) := begin simp only [le_rank_iff_exists_linear_independent, cardinal.lift_nat_cast, cardinal.lift_eq_nat_iff, cardinal.mk_set_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end end division_ring end module
3160b1d241ab308aafcad204d3e5036152659f2f
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0501.lean
50599a0b3584a08936fc74a57f35069fa35f6475
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
127
lean
#check let y := 2 + 2 in y * y #reduce let y := 2 + 2 in y * y def t (x : ℕ) : ℕ := let y := x + x in y * y #reduce t 2
3339ba4f7b570dd5be50e14ed4f05e53442b2e06
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/converter/default.lean
8c8a0a1d5e5c1103096115bde09bbbedca2b32a4
[]
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
357
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Converter monad for building simplifiers. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.converter.conv import Mathlib.Lean3Lib.init.meta.converter.interactive namespace Mathlib
1ab5138ed5356cfed508c2a064fe16c6f1080ea0
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/analysis/normed_space/bounded_linear_maps.lean
d997add83b99b49818a26e1d51a0fefc198566a2
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
14,032
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Continuous linear functions -- functions between normed vector spaces which are bounded and linear. -/ import algebra.field import analysis.normed_space.operator_norm noncomputable theory open_locale classical filter open filter (tendsto) open metric 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] set_option class.instance_max_depth 70 /-- A function `f` satisfies `is_bounded_linear_map 𝕜 f` if it is linear and satisfies the inequality `∥ f x ∥ ≤ M * ∥ x ∥` for some positive constant `M`. -/ structure is_bounded_linear_map (𝕜 : Type*) [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E → F) extends is_linear_map 𝕜 f : Prop := (bound : ∃ M, 0 < M ∧ ∀ x : E, ∥ f x ∥ ≤ M * ∥ x ∥) lemma is_linear_map.with_bound {f : E → F} (hf : is_linear_map 𝕜 f) (M : ℝ) (h : ∀ x : E, ∥ f x ∥ ≤ M * ∥ x ∥) : is_bounded_linear_map 𝕜 f := ⟨ hf, classical.by_cases (assume : M ≤ 0, ⟨1, zero_lt_one, assume x, le_trans (h x) $ mul_le_mul_of_nonneg_right (le_trans this zero_le_one) (norm_nonneg x)⟩) (assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩ /-- A continuous linear map satisfies `is_bounded_linear_map` -/ lemma continuous_linear_map.is_bounded_linear_map (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 f := { bound := f.bound, ..f.to_linear_map } namespace is_bounded_linear_map /-- Construct a linear map from a function `f` satisfying `is_bounded_linear_map 𝕜 f`. -/ def to_linear_map (f : E → F) (h : is_bounded_linear_map 𝕜 f) : E →ₗ[𝕜] F := (is_linear_map.mk' _ h.to_is_linear_map) /-- Construct a continuous linear map from is_bounded_linear_map -/ def to_continuous_linear_map {f : E → F} (hf : is_bounded_linear_map 𝕜 f) : E →L[𝕜] F := { cont := let ⟨C, Cpos, hC⟩ := hf.bound in linear_map.continuous_of_bound _ C hC, ..to_linear_map f hf} lemma zero : is_bounded_linear_map 𝕜 (λ (x:E), (0:F)) := (0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl] lemma id : is_bounded_linear_map 𝕜 (λ (x:E), x) := linear_map.id.is_linear.with_bound 1 $ by simp [le_refl] lemma fst : is_bounded_linear_map 𝕜 (λ x : E × F, x.1) := begin refine (linear_map.fst 𝕜 E F).is_linear.with_bound 1 (λx, _), rw one_mul, exact le_max_left _ _ end lemma snd : is_bounded_linear_map 𝕜 (λ x : E × F, x.2) := begin refine (linear_map.snd 𝕜 E F).is_linear.with_bound 1 (λx, _), rw one_mul, exact le_max_right _ _ end variables { f g : E → F } lemma smul (c : 𝕜) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ e, c • f e) := let ⟨hlf, M, hMp, hM⟩ := hf in (c • hlf.mk' f).is_linear.with_bound (∥c∥ * M) $ assume x, calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x) ... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (hM _) (norm_nonneg _) ... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm lemma neg (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ e, -f e) := begin rw show (λ e, -f e) = (λ e, (-1 : 𝕜) • f e), { funext, simp }, exact smul (-1) hf end lemma add (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e + g e) := let ⟨hlf, Mf, hMfp, hMf⟩ := hf in let ⟨hlg, Mg, hMgp, hMg⟩ := hg in (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ assume x, calc ∥f x + g x∥ ≤ ∥f x∥ + ∥g x∥ : norm_triangle _ _ ... ≤ Mf * ∥x∥ + Mg * ∥x∥ : add_le_add (hMf x) (hMg x) ... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul lemma sub (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e - g e) := add hf (neg hg) lemma comp {g : F → G} (hg : is_bounded_linear_map 𝕜 g) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (g ∘ f) := let ⟨hlg, Mg, hMgp, hMg⟩ := hg in let ⟨hlf, Mf, hMfp, hMf⟩ := hf in ((hlg.mk' _).comp (hlf.mk' _)).is_linear.with_bound (Mg * Mf) $ assume x, calc ∥g (f x)∥ ≤ Mg * ∥f x∥ : hMg _ ... ≤ Mg * (Mf * ∥x∥) : mul_le_mul_of_nonneg_left (hMf _) (le_of_lt hMgp) ... = Mg * Mf * ∥x∥ : (mul_assoc _ _ _).symm lemma tendsto (x : E) (hf : is_bounded_linear_map 𝕜 f) : f →_{x} (f x) := let ⟨hf, M, hMp, hM⟩ := hf in tendsto_iff_norm_tendsto_zero.2 $ squeeze_zero (assume e, norm_nonneg _) (assume e, calc ∥f e - f x∥ = ∥hf.mk' f (e - x)∥ : by rw (hf.mk' _).map_sub e x; refl ... ≤ M * ∥e - x∥ : hM (e - x)) (suffices (λ (e : E), M * ∥e - x∥) →_{x} (M * 0), by simpa, tendsto_mul tendsto_const_nhds (lim_norm _)) lemma continuous (hf : is_bounded_linear_map 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λ _, hf.tendsto _ lemma lim_zero_bounded_linear_map (hf : is_bounded_linear_map 𝕜 f) : (f →_{0} 0) := (hf.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 hf.continuous 0 section open asymptotics filter theorem is_O_id {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := h.bound in ⟨M, hMp, mem_sets_of_superset univ_mem_sets (λ x _, hM x)⟩ theorem is_O_comp {E : Type*} {g : F → G} (hg : is_bounded_linear_map 𝕜 g) {f : E → F} (l : filter E) : is_O (λ x', g (f x')) f l := ((hg.is_O_id ⊤).comp _).mono (map_le_iff_le_comap.mp lattice.le_top) theorem is_O_sub {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := is_O_comp h l end end is_bounded_linear_map section set_option class.instance_max_depth 180 lemma is_bounded_linear_map_prod_iso : is_bounded_linear_map 𝕜 (λ(p : (E →L[𝕜] F) × (E →L[𝕜] G)), (continuous_linear_map.prod p.1 p.2 : (E →L[𝕜] (F × G)))) := begin refine is_linear_map.with_bound ⟨λu v, rfl, λc u, rfl⟩ 1 (λp, _), simp only [norm, one_mul], refine continuous_linear_map.op_norm_le_bound _ (le_trans (norm_nonneg _) (le_max_left _ _)) (λu, _), simp only [norm, continuous_linear_map.prod, max_le_iff], split, { calc ∥p.1 u∥ ≤ ∥p.1∥ * ∥u∥ : continuous_linear_map.le_op_norm _ _ ... ≤ max (∥p.1∥) (∥p.2∥) * ∥u∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) }, { calc ∥p.2 u∥ ≤ ∥p.2∥ * ∥u∥ : continuous_linear_map.le_op_norm _ _ ... ≤ max (∥p.1∥) (∥p.2∥) * ∥u∥ : mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg _) } end lemma continuous_linear_map.is_bounded_linear_map_comp_left (g : continuous_linear_map 𝕜 F G) : is_bounded_linear_map 𝕜 (λ(f : E →L[𝕜] F), continuous_linear_map.comp g f) := begin refine is_linear_map.with_bound ⟨λu v, _, λc u, _⟩ (∥g∥) (λu, continuous_linear_map.op_norm_comp_le _ _), { ext x, change g ((u+v) x) = g (u x) + g (v x), have : (u+v) x = u x + v x := rfl, rw [this, g.map_add] }, { ext x, change g ((c • u) x) = c • g (u x), have : (c • u) x = c • u x := rfl, rw [this, continuous_linear_map.map_smul] } end lemma continuous_linear_map.is_bounded_linear_map_comp_right (f : continuous_linear_map 𝕜 E F) : is_bounded_linear_map 𝕜 (λ(g : F →L[𝕜] G), continuous_linear_map.comp g f) := begin refine is_linear_map.with_bound ⟨λu v, rfl, λc u, rfl⟩ (∥f∥) (λg, _), rw mul_comm, exact continuous_linear_map.op_norm_comp_le _ _ end end section bilinear_map variable (𝕜) /-- A map `f : E × F → G` satisfies `is_bounded_bilinear_map 𝕜 f` if it is bilinear and continuous. -/ structure is_bounded_bilinear_map (f : E × F → G) : Prop := (add_left : ∀(x₁ x₂ : E) (y : F), f (x₁ + x₂, y) = f (x₁, y) + f (x₂, y)) (smul_left : ∀(c : 𝕜) (x : E) (y : F), f (c • x, y) = c • f (x,y)) (add_right : ∀(x : E) (y₁ y₂ : F), f (x, y₁ + y₂) = f (x, y₁) + f (x, y₂)) (smul_right : ∀(c : 𝕜) (x : E) (y : F), f (x, c • y) = c • f (x,y)) (bound : ∃C>0, ∀(x : E) (y : F), ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥) variable {𝕜} variable {f : E × F → G} lemma is_bounded_bilinear_map.map_sub_left (h : is_bounded_bilinear_map 𝕜 f) {x y : E} {z : F} : f (x - y, z) = f (x, z) - f(y, z) := calc f (x - y, z) = f (x + (-1 : 𝕜) • y, z) : by simp ... = f (x, z) + (-1 : 𝕜) • f (y, z) : by simp only [h.add_left, h.smul_left] ... = f (x, z) - f (y, z) : by simp lemma is_bounded_bilinear_map.map_sub_right (h : is_bounded_bilinear_map 𝕜 f) {x : E} {y z : F} : f (x, y - z) = f (x, y) - f (x, z) := calc f (x, y - z) = f (x, y + (-1 : 𝕜) • z) : by simp ... = f (x, y) + (-1 : 𝕜) • f (x, z) : by simp only [h.add_right, h.smul_right] ... = f (x, y) - f (x, z) : by simp lemma is_bounded_bilinear_map_smul : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × E), p.1 • p.2) := { add_left := add_smul, smul_left := λc x y, by simp [smul_smul], add_right := smul_add, smul_right := λc x y, by simp [smul_smul, mul_comm], bound := ⟨1, zero_lt_one, λx y, by simp [norm_smul]⟩ } lemma is_bounded_bilinear_map_mul : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_smul lemma is_bounded_bilinear_map_comp : is_bounded_bilinear_map 𝕜 (λ(p : (E →L[𝕜] F) × (F →L[𝕜] G)), p.2.comp p.1) := { add_left := λx₁ x₂ y, begin ext z, change y (x₁ z + x₂ z) = y (x₁ z) + y (x₂ z), rw y.map_add end, smul_left := λc x y, begin ext z, change y (c • (x z)) = c • y (x z), rw continuous_linear_map.map_smul end, add_right := λx y₁ y₂, rfl, smul_right := λc x y, rfl, bound := ⟨1, zero_lt_one, λx y, calc ∥continuous_linear_map.comp ((x, y).snd) ((x, y).fst)∥ ≤ ∥y∥ * ∥x∥ : continuous_linear_map.op_norm_comp_le _ _ ... = 1 * ∥x∥ * ∥ y∥ : by ring ⟩ } lemma is_bounded_bilinear_map_apply : is_bounded_bilinear_map 𝕜 (λp : (E →L[𝕜] F) × E, p.1 p.2) := { add_left := by simp, smul_left := by simp, add_right := by simp, smul_right := by simp, bound := ⟨1, zero_lt_one, by simp [continuous_linear_map.le_op_norm]⟩ } /-- Definition of the derivative of a bilinear map `f`, given at a point `p` by `q ↦ f(p.1, q.2) + f(q.1, p.2)` as in the standard formula for the derivative of a product. We define this function here a bounded linear map from `E × F` to `G`. The fact that this is indeed the derivative of `f` is proved in `is_bounded_bilinear_map.has_fderiv_at` in `deriv.lean`-/ def is_bounded_bilinear_map.linear_deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : (E × F) →ₗ[𝕜] G := { to_fun := λq, f (p.1, q.2) + f (q.1, p.2), add := λq₁ q₂, begin change f (p.1, q₁.2 + q₂.2) + f (q₁.1 + q₂.1, p.2) = f (p.1, q₁.2) + f (q₁.1, p.2) + (f (p.1, q₂.2) + f (q₂.1, p.2)), simp [h.add_left, h.add_right] end, smul := λc q, begin change f (p.1, c • q.2) + f (c • q.1, p.2) = c • (f (p.1, q.2) + f (q.1, p.2)), simp [h.smul_left, h.smul_right, smul_add] end } /-- The derivative of a bounded bilinear map at a point `p : E × F`, as a continuous linear map from `E × F` to `G`. -/ def is_bounded_bilinear_map.deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : (E × F) →L[𝕜] G := (h.linear_deriv p).with_bound $ begin rcases h.bound with ⟨C, Cpos, hC⟩, refine ⟨C * ∥p.1∥ + C * ∥p.2∥, λq, _⟩, calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ ∥f (p.1, q.2)∥ + ∥f (q.1, p.2)∥ : norm_triangle _ _ ... ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : add_le_add (hC _ _) (hC _ _) ... ≤ C * ∥p.1∥ * ∥q∥ + C * ∥q∥ * ∥p.2∥ : begin apply add_le_add, exact mul_le_mul_of_nonneg_left (le_max_right _ _) (mul_nonneg (le_of_lt Cpos) (norm_nonneg _)), apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), exact mul_le_mul_of_nonneg_left (le_max_left _ _) (le_of_lt Cpos), end ... = (C * ∥p.1∥ + C * ∥p.2∥) * ∥q∥ : by ring end @[simp] lemma is_bounded_bilinear_map_deriv_coe (h : is_bounded_bilinear_map 𝕜 f) (p q : E × F) : h.deriv p q = f (p.1, q.2) + f (q.1, p.2) := rfl set_option class.instance_max_depth 95 /-- Given a bounded bilinear map `f`, the map associating to a point `p` the derivative of `f` at `p` is itself a bounded linear map. -/ lemma is_bounded_bilinear_map.is_bounded_linear_map_deriv (h : is_bounded_bilinear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λp : E × F, h.deriv p) := begin rcases h.bound with ⟨C, Cpos, hC⟩, refine is_linear_map.with_bound ⟨λp₁ p₂, _, λc p, _⟩ (C + C) (λp, _), { ext q, simp [h.add_left, h.add_right] }, { ext q, simp [h.smul_left, h.smul_right, smul_add] }, { refine continuous_linear_map.op_norm_le_bound _ (mul_nonneg (add_nonneg (le_of_lt Cpos) (le_of_lt Cpos)) (norm_nonneg _)) (λq, _), calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ ∥f (p.1, q.2)∥ + ∥f (q.1, p.2)∥ : norm_triangle _ _ ... ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : add_le_add (hC _ _) (hC _ _) ... ≤ C * ∥p∥ * ∥q∥ + C * ∥q∥ * ∥p∥ : by apply_rules [add_le_add, mul_le_mul, norm_nonneg, le_of_lt Cpos, le_refl, le_max_left, le_max_right, mul_nonneg, norm_nonneg, norm_nonneg, norm_nonneg] ... = (C + C) * ∥p∥ * ∥q∥ : by ring }, end end bilinear_map
8ab9d2846962d1b8980c9937aaaddd3925240b77
5a8eb1c11f93715e070b588e85f2961065c3714d
/books/theorem-proving-in-lean/ch02-09.lean
598198b7ae0a59b84caf18e15ad171ad03585298
[ "MIT" ]
permissive
luksamuk/study
0e19bf99d33e0793127c3d3f8ad3936fbeb36505
6a9417e071a8624c4cd9db696c16a3abcc430219
refs/heads/master
1,677,960,533,266
1,676,234,529,000
1,676,234,529,000
151,009,060
4
1
MIT
1,676,234,531,000
1,538,343,224,000
C++
UTF-8
Lean
false
false
2,401
lean
namespace hidden universe u constant list : Type u → Type u namespace list constant cons : Π α : Type u, α → list α → list α constant nil : Π α : Type u, list α constant append : Π α : Type u, list α → list α → list α end list end hidden -- Constructing lists of elements of α open hidden.list variable α : Type variable a : α variables l1 l2 : hidden.list α #check cons α a (nil α) #check append α (cons α a (nil α)) l1 #check append α (append α (cons α a (nil α)) l1) l2 -- Inserting α every time is redundant, since one -- can infer α from the type of the second argument. -- Dependent type theory has the feature that often -- some information about terms can be inferred from -- the context. So we use the underscore _ to tell the -- system to infer the desired information. #check cons _ a (nil _) #check append _ (cons _ a (nil _)) l1 #check append _ (append _ (cons _ a (nil _)) l1) l2 -- Typing underscores is still tedious though, so we -- can specify that this argument should be left -- implicit by default. namespace hidden universe u namespace list constant cons' : Π {α : Type u}, α → list α → list α constant nil' : Π {α : Type u}, list α constant append' : Π {α : Type u}, list α → list α → list α end list end hidden open hidden.list variable α' : Type variable a' : α' variables l1' l2' : hidden.list α' #check cons' a' nil' #check append' (cons' a' nil') l1' #check append' (append' (cons' a' nil') l1') l2' -- This can also be used on function definitions: universe u def ident {α : Type u} (x : α) := x variables α'' β : Type u variables (a'' : α'') (b : β) #check ident #check ident a'' #check ident b -- Variables can also be specified as implicit -- when using the variables command section variable {α''' : Type u} variable x : α''' def ident' := x end #check ident' #check ident' a'' #check ident' b -- Types can also be specified for polymorphic -- expressions: #check list.nil #check id #check (list.nil : list ℕ) #check (id : ℕ → ℕ) -- Nmerals are overloaded in Lean, but when the -- type cannot be inferred, Lean assumes it is -- a ℕ. #check 2 #check (2 : ℕ) #check (2 : ℤ) -- To make the implicit arguments explicit, use @. #check @id #check @id α #check @id β #check @id α a #check @id β b
7e22466723a81d48978dfd2aad6139a9b6190849
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/init/simplifier.lean
aa2cdcebb718374dbdc20825ad128040abf96388
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
2,998
lean
/- Copyright (c) 2015 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam -/ prelude import init.logic namespace simplifier namespace empty end empty namespace prove attribute eq_self_iff_true [simp] end prove namespace unit_simp open eq.ops -- TODO(dhs): prove these lemmas elsewhere and only gather the -- [simp] attributes here variables {A B C : Prop} lemma and_imp [simp] : (A ∧ B → C) ↔ (A → B → C) := iff.intro (assume H a b, H (and.intro a b)) (assume H ab, H (and.left ab) (and.right ab)) lemma or_imp [simp] : (A ∨ B → C) ↔ ((A → C) ∧ (B → C)) := iff.intro (assume H, and.intro (assume a, H (or.inl a)) (assume b, H (or.inr b))) (assume H ab, and.rec_on H (assume Hac Hbc, or.rec_on ab Hac Hbc)) lemma imp_and [simp] : (A → B ∧ C) ↔ ((A → B) ∧ (A → C)) := iff.intro (assume H, and.intro (assume a, and.left (H a)) (assume a, and.right (H a))) (assume H a, and.rec_on H (assume Hab Hac, and.intro (Hab a) (Hac a))) -- TODO(dhs, leo): do we want to pre-process away the [iff]s? /- lemma iff_and_imp [simp] : ((A ↔ B) → C) ↔ (((A → B) ∧ (B → A)) → C) := iff.intro (assume H1 H2, and.rec_on H2 (assume ab ba, H1 (iff.intro ab ba))) (assume H1 H2, H1 (and.intro (iff.elim_left H2) (iff.elim_right H2))) -/ lemma a_of_a [simp] : (A → A) ↔ true := iff.intro (assume H, trivial) (assume t a, a) lemma not_true_of_false [simp] : ¬ true ↔ false := iff.intro (assume H, H trivial) (assume f, false.rec (¬ true) f) lemma imp_true [simp] : (A → true) ↔ true := iff.intro (assume H, trivial) (assume t a, trivial) lemma true_imp [simp] : (true → A) ↔ A := iff.intro (assume H, H trivial) (assume a t, a) -- lemma fold_not [simp] : (A → false) ↔ ¬ A := -- iff.intro id id lemma false_imp [simp] : (false → A) ↔ true := iff.intro (assume H, trivial) (assume t f, false.rec A f) lemma ite_and [simp] [A_dec : decidable A] : ite A B C ↔ ((A → B) ∧ (¬ A → C)) := iff.intro (assume H, and.intro (assume a, implies_of_if_pos H a) (assume a, implies_of_if_neg H a)) (assume H, and.rec_on H (assume Hab Hnac, decidable.rec_on A_dec (assume a, have rw : @decidable.inl A a = A_dec, from subsingleton.rec_on (subsingleton_decidable A) (assume H, H (@decidable.inl A a) A_dec), by rewrite [rw, if_pos a] ; exact Hab a) (assume na, have rw : @decidable.inr A na = A_dec, from subsingleton.rec_on (subsingleton_decidable A) (assume H, H (@decidable.inr A na) A_dec), by rewrite [rw, if_neg na] ; exact Hnac na))) end unit_simp end simplifier
747e529bc0c09fa43bf9abbb385a638e0eb81a17
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/convex/strict.lean
566223b0689d88bc8ec84c4d09dc63ab39b24633
[ "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
15,459
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import analysis.convex.basic import topology.algebra.order.basic /-! # Strictly convex sets This file defines strictly convex sets. A set is strictly convex if the open segment between any two distinct points lies in its interior. -/ open set open_locale convex pointwise variables {𝕜 𝕝 E F β : Type*} open function set open_locale convex section ordered_semiring variables [ordered_semiring 𝕜] [topological_space E] [topological_space F] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section has_smul variables (𝕜) [has_smul 𝕜 E] [has_smul 𝕜 F] (s : set E) /-- A set is strictly convex if the open segment between any two distinct points lies is in its interior. This basically means "convex and not flat on the boundary". -/ def strict_convex : Prop := s.pairwise $ λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ interior s variables {𝕜 s} {x y : E} {a b : 𝕜} lemma strict_convex_iff_open_segment_subset : strict_convex 𝕜 s ↔ s.pairwise (λ x y, open_segment 𝕜 x y ⊆ interior s) := forall₅_congr $ λ x hx y hy hxy, (open_segment_subset_iff 𝕜).symm lemma strict_convex.open_segment_subset (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : open_segment 𝕜 x y ⊆ interior s := strict_convex_iff_open_segment_subset.1 hs hx hy h lemma strict_convex_empty : strict_convex 𝕜 (∅ : set E) := pairwise_empty _ lemma strict_convex_univ : strict_convex 𝕜 (univ : set E) := begin intros x hx y hy hxy a b ha hb hab, rw interior_univ, exact mem_univ _, end protected lemma strict_convex.eq (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (h : a • x + b • y ∉ interior s) : x = y := hs.eq hx hy $ λ H, h $ H ha hb hab protected lemma strict_convex.inter {t : set E} (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s ∩ t) := begin intros x hx y hy hxy a b ha hb hab, rw interior_inter, exact ⟨hs hx.1 hy.1 hxy ha hb hab, ht hx.2 hy.2 hxy ha hb hab⟩, end lemma directed.strict_convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed (⊆) s) (hs : ∀ ⦃i : ι⦄, strict_convex 𝕜 (s i)) : strict_convex 𝕜 (⋃ i, s i) := begin rintro x hx y hy hxy a b ha hb hab, rw mem_Union at hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact interior_mono (subset_Union s k) (hs (hik hx) (hjk hy) hxy ha hb hab), end lemma directed_on.strict_convex_sUnion {S : set (set E)} (hdir : directed_on (⊆) S) (hS : ∀ s ∈ S, strict_convex 𝕜 s) : strict_convex 𝕜 (⋃₀ S) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).strict_convex_Union (λ s, hS _ s.2), end end has_smul section module variables [module 𝕜 E] [module 𝕜 F] {s : set E} protected lemma strict_convex.convex (hs : strict_convex 𝕜 s) : convex 𝕜 s := convex_iff_pairwise_pos.2 $ λ x hx y hy hxy a b ha hb hab, interior_subset $ hs hx hy hxy ha hb hab /-- An open convex set is strictly convex. -/ protected lemma convex.strict_convex_of_open (h : is_open s) (hs : convex 𝕜 s) : strict_convex 𝕜 s := λ x hx y hy _ a b ha hb hab, h.interior_eq.symm ▸ hs hx hy ha.le hb.le hab lemma is_open.strict_convex_iff (h : is_open s) : strict_convex 𝕜 s ↔ convex 𝕜 s := ⟨strict_convex.convex, convex.strict_convex_of_open h⟩ lemma strict_convex_singleton (c : E) : strict_convex 𝕜 ({c} : set E) := pairwise_singleton _ _ lemma set.subsingleton.strict_convex (hs : s.subsingleton) : strict_convex 𝕜 s := hs.pairwise _ lemma strict_convex.linear_image [semiring 𝕝] [module 𝕝 E] [module 𝕝 F] [linear_map.compatible_smul E F 𝕜 𝕝] (hs : strict_convex 𝕜 s) (f : E →ₗ[𝕝] F) (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := begin rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ hxy a b ha hb hab, refine hf.image_interior_subset _ ⟨a • x + b • y, hs hx hy (ne_of_apply_ne _ hxy) ha hb hab, _⟩, rw [map_add, f.map_smul_of_tower a, f.map_smul_of_tower b] end lemma strict_convex.is_linear_image (hs : strict_convex 𝕜 s) {f : E → F} (h : is_linear_map 𝕜 f) (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := hs.linear_image (h.mk' f) hf lemma strict_convex.linear_preimage {s : set F} (hs : strict_convex 𝕜 s) (f : E →ₗ[𝕜] F) (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (s.preimage f) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage hf _, rw [mem_preimage, f.map_add, f.map_smul, f.map_smul], exact hs hx hy (hfinj.ne hxy) ha hb hab, end lemma strict_convex.is_linear_preimage {s : set F} (hs : strict_convex 𝕜 s) {f : E → F} (h : is_linear_map 𝕜 f) (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (s.preimage f) := hs.linear_preimage (h.mk' f) hf hfinj section linear_ordered_cancel_add_comm_monoid variables [topological_space β] [linear_ordered_cancel_add_comm_monoid β] [order_topology β] [module 𝕜 β] [ordered_smul 𝕜 β] protected lemma set.ord_connected.strict_convex {s : set β} (hs : ord_connected s) : strict_convex 𝕜 s := begin refine strict_convex_iff_open_segment_subset.2 (λ x hx y hy hxy, _), cases hxy.lt_or_lt with hlt hlt; [skip, rw [open_segment_symm]]; exact (open_segment_subset_Ioo hlt).trans (is_open_Ioo.subset_interior_iff.2 $ Ioo_subset_Icc_self.trans $ hs.out ‹_› ‹_›) end lemma strict_convex_Iic (r : β) : strict_convex 𝕜 (Iic r) := ord_connected_Iic.strict_convex lemma strict_convex_Ici (r : β) : strict_convex 𝕜 (Ici r) := ord_connected_Ici.strict_convex lemma strict_convex_Iio (r : β) : strict_convex 𝕜 (Iio r) := ord_connected_Iio.strict_convex lemma strict_convex_Ioi (r : β) : strict_convex 𝕜 (Ioi r) := ord_connected_Ioi.strict_convex lemma strict_convex_Icc (r s : β) : strict_convex 𝕜 (Icc r s) := ord_connected_Icc.strict_convex lemma strict_convex_Ioo (r s : β) : strict_convex 𝕜 (Ioo r s) := ord_connected_Ioo.strict_convex lemma strict_convex_Ico (r s : β) : strict_convex 𝕜 (Ico r s) := ord_connected_Ico.strict_convex lemma strict_convex_Ioc (r s : β) : strict_convex 𝕜 (Ioc r s) := ord_connected_Ioc.strict_convex lemma strict_convex_interval (r s : β) : strict_convex 𝕜 (interval r s) := strict_convex_Icc _ _ lemma strict_convex_interval_oc (r s : β) : strict_convex 𝕜 (interval_oc r s) := strict_convex_Ioc _ _ end linear_ordered_cancel_add_comm_monoid end module end add_comm_monoid section add_cancel_comm_monoid variables [add_cancel_comm_monoid E] [has_continuous_add E] [module 𝕜 E] {s : set E} /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.preimage_add_right (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, z + x) ⁻¹' s) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage (continuous_add_left _) _, have h := hs hx hy ((add_right_injective _).ne hxy) ha hb hab, rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h, end /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.preimage_add_left (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, x + z) ⁻¹' s) := by simpa only [add_comm] using hs.preimage_add_right z end add_cancel_comm_monoid section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] section continuous_add variables [has_continuous_add E] {s t : set E} lemma strict_convex.add (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s + t) := begin rintro _ ⟨v, w, hv, hw, rfl⟩ _ ⟨x, y, hx, hy, rfl⟩ h a b ha hb hab, rw [smul_add, smul_add, add_add_add_comm], obtain rfl | hvx := eq_or_ne v x, { refine interior_mono (add_subset_add (singleton_subset_iff.2 hv) subset.rfl) _, rw [convex.combo_self hab, singleton_add], exact (is_open_map_add_left _).image_interior_subset _ (mem_image_of_mem _ $ ht hw hy (ne_of_apply_ne _ h) ha hb hab) }, exact subset_interior_add_left (add_mem_add (hs hv hx hvx ha hb hab) $ ht.convex hw hy ha.le hb.le hab) end lemma strict_convex.add_left (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, z + x) '' s) := by simpa only [singleton_add] using (strict_convex_singleton z).add hs lemma strict_convex.add_right (hs : strict_convex 𝕜 s) (z : E) : strict_convex 𝕜 ((λ x, x + z) '' s) := by simpa only [add_comm] using hs.add_left z /-- The translation of a strictly convex set is also strictly convex. -/ lemma strict_convex.vadd (hs : strict_convex 𝕜 s) (x : E) : strict_convex 𝕜 (x +ᵥ s) := hs.add_left x end continuous_add section continuous_smul variables [linear_ordered_field 𝕝] [module 𝕝 E] [has_continuous_const_smul 𝕝 E] [linear_map.compatible_smul E E 𝕜 𝕝] {s : set E} {x : E} lemma strict_convex.smul (hs : strict_convex 𝕜 s) (c : 𝕝) : strict_convex 𝕜 (c • s) := begin obtain rfl | hc := eq_or_ne c 0, { exact (subsingleton_zero_smul_set _).strict_convex }, { exact hs.linear_image (linear_map.lsmul _ _ c) (is_open_map_smul₀ hc) } end lemma strict_convex.affinity [has_continuous_add E] (hs : strict_convex 𝕜 s) (z : E) (c : 𝕝) : strict_convex 𝕜 (z +ᵥ c • s) := (hs.smul c).vadd z end continuous_smul end add_comm_group end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring 𝕜] [topological_space E] section add_comm_group variables [add_comm_group E] [module 𝕜 E] [no_zero_smul_divisors 𝕜 E] [has_continuous_const_smul 𝕜 E] {s : set E} lemma strict_convex.preimage_smul (hs : strict_convex 𝕜 s) (c : 𝕜) : strict_convex 𝕜 ((λ z, c • z) ⁻¹' s) := begin classical, obtain rfl | hc := eq_or_ne c 0, { simp_rw [zero_smul, preimage_const], split_ifs, { exact strict_convex_univ }, { exact strict_convex_empty } }, refine hs.linear_preimage (linear_map.lsmul _ _ c) _ (smul_right_injective E hc), unfold linear_map.lsmul linear_map.mk₂ linear_map.mk₂' linear_map.mk₂'ₛₗ, exact continuous_const_smul _, end end add_comm_group end ordered_comm_semiring section ordered_ring variables [ordered_ring 𝕜] [topological_space E] [topological_space F] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s t : set E} {x y : E} lemma strict_convex.eq_of_open_segment_subset_frontier [nontrivial 𝕜] [densely_ordered 𝕜] (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (h : open_segment 𝕜 x y ⊆ frontier s) : x = y := begin obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one, classical, by_contra hxy, exact (h ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, rfl⟩).2 (hs hx hy hxy ha₀ (sub_pos_of_lt ha₁) $ add_sub_cancel'_right _ _), end lemma strict_convex.add_smul_mem (hs : strict_convex 𝕜 s) (hx : x ∈ s) (hxy : x + y ∈ s) (hy : y ≠ 0) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : x + t • y ∈ interior s := begin have h : x + t • y = (1 - t) • x + t • (x + y), { rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] }, rw h, refine hs hx hxy (λ h, hy $ add_left_cancel _) (sub_pos_of_lt ht₁) ht₀ (sub_add_cancel _ _), exact x, rw [←h, add_zero], end lemma strict_convex.smul_mem_of_zero_mem (hs : strict_convex 𝕜 s) (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) (hx₀ : x ≠ 0) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : t • x ∈ interior s := by simpa using hs.add_smul_mem zero_mem (by simpa using hx) hx₀ ht₀ ht₁ lemma strict_convex.add_smul_sub_mem (h : strict_convex 𝕜 s) (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) {t : 𝕜} (ht₀ : 0 < t) (ht₁ : t < 1) : x + t • (y - x) ∈ interior s := begin apply h.open_segment_subset hx hy hxy, rw open_segment_eq_image', exact mem_image_of_mem _ ⟨ht₀, ht₁⟩, end /-- The preimage of a strictly convex set under an affine map is strictly convex. -/ lemma strict_convex.affine_preimage {s : set F} (hs : strict_convex 𝕜 s) {f : E →ᵃ[𝕜] F} (hf : continuous f) (hfinj : injective f) : strict_convex 𝕜 (f ⁻¹' s) := begin intros x hx y hy hxy a b ha hb hab, refine preimage_interior_subset_interior_preimage hf _, rw [mem_preimage, convex.combo_affine_apply hab], exact hs hx hy (hfinj.ne hxy) ha hb hab, end /-- The image of a strictly convex set under an affine map is strictly convex. -/ lemma strict_convex.affine_image (hs : strict_convex 𝕜 s) {f : E →ᵃ[𝕜] F} (hf : is_open_map f) : strict_convex 𝕜 (f '' s) := begin rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ hxy a b ha hb hab, exact hf.image_interior_subset _ ⟨a • x + b • y, ⟨hs hx hy (ne_of_apply_ne _ hxy) ha hb hab, convex.combo_affine_apply hab⟩⟩, end variables [topological_add_group E] lemma strict_convex.neg (hs : strict_convex 𝕜 s) : strict_convex 𝕜 (-s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg continuous_id.neg neg_injective lemma strict_convex.sub (hs : strict_convex 𝕜 s) (ht : strict_convex 𝕜 t) : strict_convex 𝕜 (s - t) := (sub_eq_add_neg s t).symm ▸ hs.add ht.neg end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] [topological_space E] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E} {x : E} /-- Alternative definition of set strict convexity, using division. -/ lemma strict_convex_iff_div : strict_convex 𝕜 s ↔ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → (a / (a + b)) • x + (b / (a + b)) • y ∈ interior s) := ⟨λ h x hx y hy hxy a b ha hb, begin apply h hx hy hxy (div_pos ha $ add_pos ha hb) (div_pos hb $ add_pos ha hb), rw ←add_div, exact div_self (add_pos ha hb).ne', end, λ h x hx y hy hxy a b ha hb hab, by convert h hx hy hxy ha hb; rw [hab, div_one] ⟩ lemma strict_convex.mem_smul_of_zero_mem (hs : strict_convex 𝕜 s) (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) (hx₀ : x ≠ 0) {t : 𝕜} (ht : 1 < t) : x ∈ t • interior s := begin rw mem_smul_set_iff_inv_smul_mem₀ (zero_lt_one.trans ht).ne', exact hs.smul_mem_of_zero_mem zero_mem hx hx₀ (inv_pos.2 $ zero_lt_one.trans ht) (inv_lt_one ht), end end add_comm_group end linear_ordered_field /-! #### Convex sets in an ordered space Relates `convex` and `set.ord_connected`. -/ section variables [linear_ordered_field 𝕜] [topological_space 𝕜] [order_topology 𝕜] {s : set 𝕜} /-- A set in a linear ordered field is strictly convex if and only if it is convex. -/ @[simp] lemma strict_convex_iff_convex : strict_convex 𝕜 s ↔ convex 𝕜 s := ⟨strict_convex.convex, λ hs, hs.ord_connected.strict_convex⟩ lemma strict_convex_iff_ord_connected : strict_convex 𝕜 s ↔ s.ord_connected := strict_convex_iff_convex.trans convex_iff_ord_connected alias strict_convex_iff_ord_connected ↔ strict_convex.ord_connected _ end
228e7ba597bed2bdeb69608aa49fc50f91a4e8d2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/defeq_match.lean
be7ef2271b788864af1fdcfa7ac0aead73bee4a8
[ "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
201
lean
constants (p : (nat → nat → nat) → Prop) (p_add : p nat.add) -- The failure case we want to avoid is unfolding `nat.add` and not `λ a b, nat.add a b` example : p (λ a b, nat.add a b) := p_add
462d3f8d92ab43d557410547661e74008572c579
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/topology/instances/real.lean
0d160a7537c2c8b0798c997d18723b6766a79879
[ "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
16,924
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring import ring_theory.subring import group_theory.archimedean import algebra.periodic /-! # Topological properties of ℝ -/ noncomputable theory open classical set filter topological_space metric open_locale classical topological_space filter uniformity interval universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = |x - y| := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl namespace int lemma uniform_embedding_coe_real : uniform_embedding (coe : ℤ → ℝ) := { comap_uniformity := begin refine le_antisymm (le_principal_iff.2 _) (@refl_le_uniformity ℤ $ uniform_space.comap coe (infer_instance : uniform_space ℝ)), refine (uniformity_basis_dist.comap _).mem_iff.2 ⟨1, zero_lt_one, _⟩, rintro ⟨a, b⟩ (h : |(a - b : ℝ)| < 1), norm_cast at h, erw [@int.lt_add_one_iff _ 0, abs_nonpos_iff, sub_eq_zero] at h, assumption end, inj := int.cast_injective } instance : metric_space ℤ := int.uniform_embedding_coe_real.comap_metric_space _ theorem dist_eq (x y : ℤ) : dist x y = |x - y| := rfl @[norm_cast, simp] theorem dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast theorem preimage_ball (x : ℤ) (r : ℝ) : coe ⁻¹' (ball (x : ℝ) r) = ball x r := rfl theorem preimage_closed_ball (x : ℤ) (r : ℝ) : coe ⁻¹' (closed_ball (x : ℝ) r) = closed_ball x r := rfl theorem ball_eq (x : ℤ) (r : ℝ) : ball x r = Ioo ⌊↑x - r⌋ ⌈↑x + r⌉ := by rw [← preimage_ball, real.ball_eq, preimage_Ioo] theorem closed_ball_eq (x : ℤ) (r : ℝ) : closed_ball x r = Icc ⌈↑x - r⌉ ⌊↑x + r⌋ := by rw [← preimage_closed_ball, real.closed_ball_eq, preimage_Icc] instance : proper_space ℤ := ⟨ begin intros x r, rw closed_ball_eq, exact (set.Icc_ℤ_finite _ _).is_compact, end ⟩ end int theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) instance : proper_space ℝ := { is_compact_closed_ball := λx r, by { rw real.closed_ball_eq, apply is_compact_Icc } } instance : second_countable_topology ℝ := second_countable_of_proper lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (is_open.mem_nhds hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ }, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩) /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, |y - x| < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ |x|) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | |r| / 2 < |x|} (half_pos r0) (λ x h, le_of_lt h)) (is_open.mem_nhds ((is_open_lt' (|r| / 2)).preimage continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (|x|) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, |(x : ℝ × ℝ).1| < r₁ ∧ |x.2| < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | |x| < |a₁| + 1}.prod {x | |x| < |a₂| + 1}) (λ x, id)) (is_open.mem_nhds (((is_open_gt' (|a₁| + 1)).preimage continuous_abs).prod ((is_open_gt' (|a₂| + 1)).preimage continuous_abs )) ⟨lt_add_one (|a₁|), lt_add_one (|a₂|)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, metric.cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply totally_bounded_Ioo lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw real.closed_ball_eq at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨bdd_below_Icc.mono hr, bdd_above_Icc.mono hr⟩ end, begin intro h, rcases bdd_below_bdd_above_iff_subset_Icc.1 h with ⟨m, M, I : s ⊆ Icc m M⟩, exact (bounded_Icc m M).subset I end⟩ lemma real.subset_Icc_Inf_Sup_of_bounded {s : set ℝ} (h : bounded s) : s ⊆ Icc (Inf s) (Sup s) := subset_Icc_cInf_cSup (real.bounded_iff_bdd_below_bdd_above.1 h).1 (real.bounded_iff_bdd_below_bdd_above.1 h).2 lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (is_compact_Icc.image_of_continuous_on h) lemma real.image_interval_eq_Icc {f : ℝ → ℝ} {a b : ℝ} (h : continuous_on f $ [a, b]) : f '' [a, b] = Icc (Inf (f '' [a, b])) (Sup (f '' [a, b])) := begin cases le_total a b with h2 h2, { simp_rw [interval_of_le h2] at h ⊢, exact real.image_Icc h2 h }, { simp_rw [interval_of_ge h2] at h ⊢, exact real.image_Icc h2 h }, end lemma real.image_interval {f : ℝ → ℝ} {a b : ℝ} (h : continuous_on f $ [a, b]) : f '' [a, b] = [Inf (f '' [a, b]), Sup (f '' [a, b])] := begin refine (real.image_interval_eq_Icc h).trans (interval_of_le _).symm, rw [real.image_interval_eq_Icc h], exact real.Inf_le_Sup _ bdd_below_Icc bdd_above_Icc end lemma real.interval_subset_image_interval {f : ℝ → ℝ} {a b x y : ℝ} (h : continuous_on f [a, b]) (hx : x ∈ [a, b]) (hy : y ∈ [a, b]) : [f x, f y] ⊆ f '' [a, b] := begin rw [real.image_interval h, interval_subset_interval_iff_mem, ← real.image_interval h], exact ⟨mem_image_of_mem f hx, mem_image_of_mem f hy⟩ end end section periodic namespace function lemma periodic.compact_of_continuous' [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : 0 < c) (hf : continuous f) : is_compact (range f) := begin convert is_compact_Icc.image hf, ext x, refine ⟨_, mem_range_of_mem_image f (Icc 0 c)⟩, rintros ⟨y, h1⟩, obtain ⟨z, hz, h2⟩ := hp.exists_mem_Ico hc y, exact ⟨z, mem_Icc_of_Ico hz, h2.symm.trans h1⟩, end /-- A continuous, periodic function has compact range. -/ lemma periodic.compact_of_continuous [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : is_compact (range f) := begin cases lt_or_gt_of_ne hc with hneg hpos, exacts [hp.neg.compact_of_continuous' (neg_pos.mpr hneg) hf, hp.compact_of_continuous' hpos hf], end /-- A continuous, periodic function is bounded. -/ lemma periodic.bounded_of_continuous [pseudo_metric_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : bounded (range f) := (hp.compact_of_continuous hc hf).bounded end function end periodic section subgroups /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, |x - g| < ε, by simpa only [real.mem_closure_iff, abs_sub_comm], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'), refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
620a575b2f186bca1f65ff85fa5b1b40533041bb
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Init/Classical.lean
4ffe96d6753007cd19b3c4186b9d1d464820e3f7
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,400
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 import Init.Core universes u v /- Classical reasoning support -/ namespace Classical axiom choice {α : Sort u} : Nonempty α → α noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop) (h : Exists (fun x => p x)) : {x // p x} := choice <| let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩ noncomputable def choose {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : α := (indefiniteDescription p h).val theorem chooseSpec {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : p (choose h) := (indefiniteDescription p h).property /- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/ theorem em (p : Prop) : p ∨ ¬p := let U (x : Prop) : Prop := x = True ∨ p; let V (x : Prop) : Prop := x = False ∨ p; have exU : Exists (fun x => U x) from ⟨True, Or.inl rfl⟩; have exV : Exists (fun x => V x) from ⟨False, Or.inl rfl⟩; let u : Prop := choose exU; let v : Prop := choose exV; have uDef : U u from chooseSpec exU; have vDef : V v from chooseSpec exV; have notUvOrP : u ≠ v ∨ p from match uDef, vDef with | Or.inr h, _ => Or.inr h | _, Or.inr h => Or.inr h | Or.inl hut, Or.inl hvf => have hne : u ≠ v from hvf.symm ▸ hut.symm ▸ trueNeFalse Or.inl hne have pImpliesUv : p → u = v from fun hp => have hpred : U = V from funext fun x => have hl : (x = True ∨ p) → (x = False ∨ p) from fun a => Or.inr hp; have hr : (x = False ∨ p) → (x = True ∨ p) from fun a => Or.inr hp; show (x = True ∨ p) = (x = False ∨ p) from propext (Iff.intro hl hr); have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV from hpred ▸ fun exU exV => rfl; show u = v from h₀ ..; match notUvOrP with | Or.inl hne => Or.inr (mt pImpliesUv hne) | Or.inr h => Or.inl h theorem existsTrueOfNonempty {α : Sort u} : Nonempty α → Exists (fun (x : α) => True) | ⟨x⟩ => ⟨x, trivial⟩ noncomputable def inhabitedOfNonempty {α : Sort u} (h : Nonempty α) : Inhabited α := ⟨choice h⟩ noncomputable def inhabitedOfExists {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : Inhabited α := inhabitedOfNonempty (Exists.elim h (fun w hw => ⟨w⟩)) /- all propositions are Decidable -/ noncomputable def propDecidable (a : Prop) : Decidable a := choice <| match em a with | Or.inl h => ⟨isTrue h⟩ | Or.inr h => ⟨isFalse h⟩ noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) := ⟨propDecidable a⟩ noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α := fun x y => propDecidable (x = y) noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) := match (propDecidable (Nonempty α)) with | (isTrue hp) => PSum.inl (@arbitrary _ (inhabitedOfNonempty hp)) | (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn) noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop) (h : Nonempty α) : {x : α // Exists (fun (y : α) => p y) → p x} := @dite _ (Exists (fun (x : α) => p x)) (propDecidable _) (fun (hp : Exists (fun (x : α) => p x)) => show {x : α // Exists (fun (y : α) => p y) → p x} from let xp := indefiniteDescription _ hp; ⟨xp.val, fun h' => xp.property⟩) (fun hp => ⟨choice h, fun h => absurd h hp⟩) /- the Hilbert epsilon Function -/ noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α := (strongIndefiniteDescription p h).val theorem epsilonSpecAux {α : Sort u} (h : Nonempty α) (p : α → Prop) : Exists (fun y => p y) → p (@epsilon α h p) := (strongIndefiniteDescription p h).property theorem epsilonSpec {α : Sort u} {p : α → Prop} (hex : Exists (fun y => p y)) : p (@epsilon α (nonemptyOfExists hex) p) := epsilonSpecAux (nonemptyOfExists hex) p hex theorem epsilonSingleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x := @epsilonSpec α (fun y => y = x) ⟨x, rfl⟩ /- the axiom of choice -/ theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, Exists (fun y => r x y)) : Exists (fun (f : ∀ x, β x) => ∀ x, r x (f x)) := ⟨_, fun x => chooseSpec (h x)⟩ theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} : (∀ x, Exists (fun y => p x y)) ↔ Exists (fun (f : ∀ x, b x) => ∀ x, p x (f x)) := ⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩ theorem propComplete (a : Prop) : a = True ∨ a = False := by cases em a with | inl _ => apply Or.inl; apply propext; apply Iff.intro; { intros; apply True.intro }; { intro; assumption } | inr hn => apply Or.inr; apply propext; apply Iff.intro; { intro h; exact hn h }; { intro h; apply False.elim h } -- this supercedes byCases in Decidable theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := Decidable.byCases (dec := propDecidable _) hpq hnpq -- this supercedes byContradiction in Decidable theorem byContradiction {p : Prop} (h : ¬p → False) : p := Decidable.byContradiction (dec := propDecidable _) h end Classical
6c4bd121209ed49caf4c954bd57444df57db6b49
90bd8c2a52dbaaba588bdab57b155a7ec1532de0
/src/mwe.lean
fec3d43aaeb9dca5a4039d86e06062a3152b27d7
[ "Apache-2.0" ]
permissive
shingtaklam1324/alg-top
fd434f1478925a232af45f18f370ee3a22811c54
4c88e28df6f0a329f26eab32bae023789193990e
refs/heads/master
1,689,447,024,947
1,630,073,400,000
1,630,073,400,000
381,528,689
2
0
null
null
null
null
UTF-8
Lean
false
false
979
lean
import data.real.pi open_locale real example : (⋃ (n : ℤ), set.Ioo (n * (2 * π) - (π / 2) : ℝ) (n * (2 * π) + (π / 2) : ℝ)) ∪ (⋃ (n : ℤ), set.Icc (n * (2 * π) + (π / 2) : ℝ) (n * (2 * π) + (3 * π/2) : ℝ)) = set.univ := begin rw set.eq_univ_iff_forall, intro x, end lemma cos_pos_iff (t : ℝ) : real.cos t > 0 ↔ t ∈ ⋃ (n : ℤ), set.Ioo (n * (2 * π) - (π / 2) : ℝ) (n * (2 * π) + (π / 2) : ℝ) := sorry -- begin -- split, -- { sorry }, -- { rintros ⟨V, ⟨n, rfl⟩, ht⟩, -- dsimp at ht, -- have h₁ : real.cos t = real.cos (t - n * (2 * π)), -- { rw real.cos_sub_int_mul_two_pi }, -- have h₂ : t - n * (2 * π) ∈ set.Ioo (-(π/2)) (π/2), -- { cases ht, split; linarith }, -- rw h₁, -- apply real.cos_pos_of_mem_Ioo h₂, } -- end -- #check div_div_div_div_eq -- #check pow_mul -- -- #check mul_assoc -- #check list.append_assoc -- #print notation + -- #print notation ++
754192fffe397465e3c2a78322731f5cbfb27ab3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/shapes/equalizers.lean
70bad5796f345f0892668a921f342ac55c069d93
[]
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
47,352
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.epi_mono import Mathlib.category_theory.limits.limits import Mathlib.PostPort universes v l u_1 u u₂ namespace Mathlib /-! # Equalizers and coequalizers This file defines (co)equalizers as special cases of (co)limits. An equalizer is the categorical generalization of the subobject {a ∈ A | f(a) = g(a)} known from abelian groups or modules. It is a limit cone over the diagram formed by `f` and `g`. A coequalizer is the dual concept. ## Main definitions * `walking_parallel_pair` is the indexing category used for (co)equalizer_diagrams * `parallel_pair` is a functor from `walking_parallel_pair` to our category `C`. * a `fork` is a cone over a parallel pair. * there is really only one interesting morphism in a fork: the arrow from the vertex of the fork to the domain of f and g. It is called `fork.ι`. * an `equalizer` is now just a `limit (parallel_pair f g)` Each of these has a dual. ## Main statements * `equalizer.ι_mono` states that every equalizer map is a monomorphism * `is_iso_limit_cone_parallel_pair_of_self` states that the identity on the domain of `f` is an equalizer of `f` and `f`. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1] -/ namespace category_theory.limits /-- The type of objects for the diagram indexing a (co)equalizer. -/ inductive walking_parallel_pair where | zero : walking_parallel_pair | one : walking_parallel_pair /-- The type family of morphisms for the diagram indexing a (co)equalizer. -/ inductive walking_parallel_pair_hom : walking_parallel_pair → walking_parallel_pair → Type v where | left : walking_parallel_pair_hom walking_parallel_pair.zero walking_parallel_pair.one | right : walking_parallel_pair_hom walking_parallel_pair.zero walking_parallel_pair.one | id : (X : walking_parallel_pair) → walking_parallel_pair_hom X X /-- Satisfying the inhabited linter -/ protected instance walking_parallel_pair_hom.inhabited : Inhabited (walking_parallel_pair_hom walking_parallel_pair.zero walking_parallel_pair.one) := { default := walking_parallel_pair_hom.left } /-- Composition of morphisms in the indexing diagram for (co)equalizers. -/ def walking_parallel_pair_hom.comp (X : walking_parallel_pair) (Y : walking_parallel_pair) (Z : walking_parallel_pair) (f : walking_parallel_pair_hom X Y) (g : walking_parallel_pair_hom Y Z) : walking_parallel_pair_hom X Z := sorry protected instance walking_parallel_pair_hom_category : small_category walking_parallel_pair := category.mk @[simp] theorem walking_parallel_pair_hom_id (X : walking_parallel_pair) : walking_parallel_pair_hom.id X = 𝟙 := rfl /-- `parallel_pair f g` is the diagram in `C` consisting of the two morphisms `f` and `g` with common domain and codomain. -/ def parallel_pair {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : walking_parallel_pair ⥤ C := functor.mk (fun (x : walking_parallel_pair) => sorry) fun (x y : walking_parallel_pair) (h : x ⟶ y) => sorry @[simp] theorem parallel_pair_obj_zero {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : functor.obj (parallel_pair f g) walking_parallel_pair.zero = X := rfl @[simp] theorem parallel_pair_obj_one {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : functor.obj (parallel_pair f g) walking_parallel_pair.one = Y := rfl @[simp] theorem parallel_pair_map_left {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : functor.map (parallel_pair f g) walking_parallel_pair_hom.left = f := rfl @[simp] theorem parallel_pair_map_right {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) : functor.map (parallel_pair f g) walking_parallel_pair_hom.right = g := rfl @[simp] theorem parallel_pair_functor_obj {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (j : walking_parallel_pair) : functor.obj (parallel_pair (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) j = functor.obj F j := sorry /-- Every functor indexing a (co)equalizer is naturally isomorphic (actually, equal) to a `parallel_pair` -/ def diagram_iso_parallel_pair {C : Type u} [category C] (F : walking_parallel_pair ⥤ C) : F ≅ parallel_pair (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right) := nat_iso.of_components (fun (j : walking_parallel_pair) => eq_to_iso sorry) sorry /-- A fork on `f` and `g` is just a `cone (parallel_pair f g)`. -/ def fork {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) := cone (parallel_pair f g) /-- A cofork on `f` and `g` is just a `cocone (parallel_pair f g)`. -/ def cofork {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) := cocone (parallel_pair f g) /-- A fork `t` on the parallel pair `f g : X ⟶ Y` consists of two morphisms `t.π.app zero : t.X ⟶ X` and `t.π.app one : t.X ⟶ Y`. Of these, only the first one is interesting, and we give it the shorter name `fork.ι t`. -/ def fork.ι {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : fork f g) : functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X t)) walking_parallel_pair.zero ⟶ functor.obj (parallel_pair f g) walking_parallel_pair.zero := nat_trans.app (cone.π t) walking_parallel_pair.zero /-- A cofork `t` on the parallel_pair `f g : X ⟶ Y` consists of two morphisms `t.ι.app zero : X ⟶ t.X` and `t.ι.app one : Y ⟶ t.X`. Of these, only the second one is interesting, and we give it the shorter name `cofork.π t`. -/ def cofork.π {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : cofork f g) : functor.obj (parallel_pair f g) walking_parallel_pair.one ⟶ functor.obj (functor.obj (functor.const walking_parallel_pair) (cocone.X t)) walking_parallel_pair.one := nat_trans.app (cocone.ι t) walking_parallel_pair.one @[simp] theorem fork.ι_eq_app_zero {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : fork f g) : fork.ι t = nat_trans.app (cone.π t) walking_parallel_pair.zero := rfl @[simp] theorem cofork.π_eq_app_one {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : cofork f g) : cofork.π t = nat_trans.app (cocone.ι t) walking_parallel_pair.one := rfl @[simp] theorem fork.app_zero_left {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (s : fork f g) : nat_trans.app (cone.π s) walking_parallel_pair.zero ≫ f = nat_trans.app (cone.π s) walking_parallel_pair.one := sorry @[simp] theorem fork.app_zero_right {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (s : fork f g) : nat_trans.app (cone.π s) walking_parallel_pair.zero ≫ g = nat_trans.app (cone.π s) walking_parallel_pair.one := sorry @[simp] theorem cofork.left_app_one_assoc {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (s : cofork f g) {X' : C} (f' : functor.obj (functor.obj (functor.const walking_parallel_pair) (cocone.X s)) walking_parallel_pair.one ⟶ X') : f ≫ nat_trans.app (cocone.ι s) walking_parallel_pair.one ≫ f' = nat_trans.app (cocone.ι s) walking_parallel_pair.zero ≫ f' := sorry @[simp] theorem cofork.right_app_one_assoc {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (s : cofork f g) {X' : C} (f' : functor.obj (functor.obj (functor.const walking_parallel_pair) (cocone.X s)) walking_parallel_pair.one ⟶ X') : g ≫ nat_trans.app (cocone.ι s) walking_parallel_pair.one ≫ f' = nat_trans.app (cocone.ι s) walking_parallel_pair.zero ≫ f' := sorry /-- A fork on `f g : X ⟶ Y` is determined by the morphism `ι : P ⟶ X` satisfying `ι ≫ f = ι ≫ g`. -/ @[simp] theorem fork.of_ι_X {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : cone.X (fork.of_ι ι w) = P := Eq.refl (cone.X (fork.of_ι ι w)) /-- A cofork on `f g : X ⟶ Y` is determined by the morphism `π : Y ⟶ P` satisfying `f ≫ π = g ≫ π`. -/ @[simp] theorem cofork.of_π_ι_app {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : ∀ (X_1 : walking_parallel_pair), nat_trans.app (cocone.ι (cofork.of_π π w)) X_1 = walking_parallel_pair.cases_on X_1 (f ≫ π) π := fun (X_1 : walking_parallel_pair) => Eq.refl (nat_trans.app (cocone.ι (cofork.of_π π w)) X_1) theorem fork.ι_of_ι {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : fork.ι (fork.of_ι ι w) = ι := rfl theorem cofork.π_of_π {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : cofork.π (cofork.of_π π w) = π := rfl theorem fork.condition {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : fork f g) : fork.ι t ≫ f = fork.ι t ≫ g := sorry theorem cofork.condition {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : cofork f g) : f ≫ cofork.π t = g ≫ cofork.π t := sorry /-- To check whether two maps are equalized by both maps of a fork, it suffices to check it for the first map -/ theorem fork.equalizer_ext {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (s : fork f g) {W : C} {k : W ⟶ cone.X s} {l : W ⟶ cone.X s} (h : k ≫ fork.ι s = l ≫ fork.ι s) (j : walking_parallel_pair) : k ≫ nat_trans.app (cone.π s) j = l ≫ nat_trans.app (cone.π s) j := sorry /-- To check whether two maps are coequalized by both maps of a cofork, it suffices to check it for the second map -/ theorem cofork.coequalizer_ext {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (s : cofork f g) {W : C} {k : cocone.X s ⟶ W} {l : cocone.X s ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) (j : walking_parallel_pair) : nat_trans.app (cocone.ι s) j ≫ k = nat_trans.app (cocone.ι s) j ≫ l := sorry theorem fork.is_limit.hom_ext {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {s : fork f g} (hs : is_limit s) {W : C} {k : W ⟶ cone.X s} {l : W ⟶ cone.X s} (h : k ≫ fork.ι s = l ≫ fork.ι s) : k = l := is_limit.hom_ext hs (fork.equalizer_ext s h) theorem cofork.is_colimit.hom_ext {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {s : cofork f g} (hs : is_colimit s) {W : C} {k : cocone.X s ⟶ W} {l : cocone.X s ⟶ W} (h : cofork.π s ≫ k = cofork.π s ≫ l) : k = l := is_colimit.hom_ext hs (cofork.coequalizer_ext s h) /-- If `s` is a limit fork over `f` and `g`, then a morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def fork.is_limit.lift' {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {s : fork f g} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : Subtype fun (l : W ⟶ cone.X s) => l ≫ fork.ι s = k := { val := is_limit.lift hs (fork.of_ι k h), property := sorry } /-- If `s` is a colimit cofork over `f` and `g`, then a morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cofork.is_colimit.desc' {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {s : cofork f g} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : Subtype fun (l : cocone.X s ⟶ W) => cofork.π s ≫ l = k := { val := is_colimit.desc hs (cofork.of_π k h), property := sorry } /-- This is a slightly more convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def fork.is_limit.mk {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : fork f g) (lift : (s : fork f g) → cone.X s ⟶ cone.X t) (fac : ∀ (s : fork f g), lift s ≫ fork.ι t = fork.ι s) (uniq : ∀ (s : fork f g) (m : cone.X s ⟶ cone.X t), (∀ (j : walking_parallel_pair), m ≫ nat_trans.app (cone.π t) j = nat_trans.app (cone.π s) j) → m = lift s) : is_limit t := is_limit.mk lift /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def fork.is_limit.mk' {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : fork f g) (create : (s : fork f g) → Subtype fun (l : functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X s)) walking_parallel_pair.zero ⟶ functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X t)) walking_parallel_pair.zero) => l ≫ fork.ι t = fork.ι s ∧ ∀ {m : functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X s)) walking_parallel_pair.zero ⟶ functor.obj (functor.obj (functor.const walking_parallel_pair) (cone.X t)) walking_parallel_pair.zero}, m ≫ fork.ι t = fork.ι s → m = l) : is_limit t := fork.is_limit.mk t (fun (s : fork f g) => subtype.val (create s)) sorry sorry /-- This is a slightly more convenient method to verify that a cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def cofork.is_colimit.mk {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : cofork f g) (desc : (s : cofork f g) → cocone.X t ⟶ cocone.X s) (fac : ∀ (s : cofork f g), cofork.π t ≫ desc s = cofork.π s) (uniq : ∀ (s : cofork f g) (m : cocone.X t ⟶ cocone.X s), (∀ (j : walking_parallel_pair), nat_trans.app (cocone.ι t) j ≫ m = nat_trans.app (cocone.ι s) j) → m = desc s) : is_colimit t := is_colimit.mk desc /-- This is another convenient method to verify that a fork is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def cofork.is_colimit.mk' {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (t : cofork f g) (create : (s : cofork f g) → Subtype fun (l : cocone.X t ⟶ cocone.X s) => cofork.π t ≫ l = cofork.π s ∧ ∀ {m : functor.obj (functor.obj (functor.const walking_parallel_pair) (cocone.X t)) walking_parallel_pair.one ⟶ functor.obj (functor.obj (functor.const walking_parallel_pair) (cocone.X s)) walking_parallel_pair.one}, cofork.π t ≫ m = cofork.π s → m = l) : is_colimit t := cofork.is_colimit.mk t (fun (s : cofork f g) => subtype.val (create s)) sorry sorry /-- Given a limit cone for the pair `f g : X ⟶ Y`, for any `Z`, morphisms from `Z` to its point are in bijection with morphisms `h : Z ⟶ X` such that `h ≫ f = h ≫ g`. Further, this bijection is natural in `Z`: see `fork.is_limit.hom_iso_natural`. This is a special case of `is_limit.hom_iso'`, often useful to construct adjunctions. -/ def fork.is_limit.hom_iso {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {t : fork f g} (ht : is_limit t) (Z : C) : (Z ⟶ cone.X t) ≃ Subtype fun (h : Z ⟶ X) => h ≫ f = h ≫ g := equiv.mk (fun (k : Z ⟶ cone.X t) => { val := k ≫ fork.ι t, property := sorry }) (fun (h : Subtype fun (h : Z ⟶ X) => h ≫ f = h ≫ g) => subtype.val (fork.is_limit.lift' ht ↑h sorry)) sorry sorry /-- The bijection of `fork.is_limit.hom_iso` is natural in `Z`. -/ theorem fork.is_limit.hom_iso_natural {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {t : fork f g} (ht : is_limit t) {Z : C} {Z' : C} (q : Z' ⟶ Z) (k : Z ⟶ cone.X t) : ↑(coe_fn (fork.is_limit.hom_iso ht Z') (q ≫ k)) = q ≫ ↑(coe_fn (fork.is_limit.hom_iso ht Z) k) := category.assoc q k (fork.ι t) /-- Given a colimit cocone for the pair `f g : X ⟶ Y`, for any `Z`, morphisms from the cocone point to `Z` are in bijection with morphisms `h : Y ⟶ Z` such that `f ≫ h = g ≫ h`. Further, this bijection is natural in `Z`: see `cofork.is_colimit.hom_iso_natural`. This is a special case of `is_colimit.hom_iso'`, often useful to construct adjunctions. -/ def cofork.is_colimit.hom_iso {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {t : cofork f g} (ht : is_colimit t) (Z : C) : (cocone.X t ⟶ Z) ≃ Subtype fun (h : Y ⟶ Z) => f ≫ h = g ≫ h := equiv.mk (fun (k : cocone.X t ⟶ Z) => { val := cofork.π t ≫ k, property := sorry }) (fun (h : Subtype fun (h : Y ⟶ Z) => f ≫ h = g ≫ h) => subtype.val (cofork.is_colimit.desc' ht ↑h sorry)) sorry sorry /-- The bijection of `cofork.is_colimit.hom_iso` is natural in `Z`. -/ theorem cofork.is_colimit.hom_iso_natural {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {t : cofork f g} {Z : C} {Z' : C} (q : Z ⟶ Z') (ht : is_colimit t) (k : cocone.X t ⟶ Z) : ↑(coe_fn (cofork.is_colimit.hom_iso ht Z') (k ≫ q)) = ↑(coe_fn (cofork.is_colimit.hom_iso ht Z) k) ≫ q := Eq.symm (category.assoc (cofork.π t) k q) /-- This is a helper construction that can be useful when verifying that a category has all equalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a fork on `F.map left` and `F.map right`, we get a cone on `F`. If you're thinking about using this, have a look at `has_equalizers_of_has_limit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cone.of_fork {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (t : fork (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) : cone F := cone.mk (cone.X t) (nat_trans.mk fun (X : walking_parallel_pair) => nat_trans.app (cone.π t) X ≫ eq_to_hom sorry) /-- This is a helper construction that can be useful when verifying that a category has all coequalizers. Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)`, and a cofork on `F.map left` and `F.map right`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_coequalizers_of_has_colimit_parallel_pair`, which you may find to be an easier way of achieving your goal. -/ def cocone.of_cofork {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (t : cofork (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) : cocone F := cocone.mk (cocone.X t) (nat_trans.mk fun (X : walking_parallel_pair) => eq_to_hom sorry ≫ nat_trans.app (cocone.ι t) X) @[simp] theorem cone.of_fork_π {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (t : fork (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) (j : walking_parallel_pair) : nat_trans.app (cone.π (cone.of_fork t)) j = nat_trans.app (cone.π t) j ≫ eq_to_hom (eq.mpr (id (Eq.trans ((fun (a a_1 : C) (e_1 : a = a_1) (ᾰ ᾰ_1 : C) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (functor.obj (parallel_pair (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) j) (functor.obj F j) (parallel_pair_functor_obj j) (functor.obj F j) (functor.obj F j) (Eq.refl (functor.obj F j))) (propext (eq_self_iff_true (functor.obj F j))))) trivial) := rfl @[simp] theorem cocone.of_cofork_ι {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (t : cofork (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) (j : walking_parallel_pair) : nat_trans.app (cocone.ι (cocone.of_cofork t)) j = eq_to_hom (eq.mpr (id (Eq.trans ((fun (a a_1 : C) (e_1 : a = a_1) (ᾰ ᾰ_1 : C) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (functor.obj F j) (functor.obj F j) (Eq.refl (functor.obj F j)) (functor.obj (parallel_pair (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) j) (functor.obj F j) (parallel_pair_functor_obj j)) (propext (eq_self_iff_true (functor.obj F j))))) trivial) ≫ nat_trans.app (cocone.ι t) j := rfl /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cone on `F`, we get a fork on `F.map left` and `F.map right`. -/ def fork.of_cone {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (t : cone F) : fork (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right) := cone.mk (cone.X t) (nat_trans.mk fun (X : walking_parallel_pair) => nat_trans.app (cone.π t) X ≫ eq_to_hom sorry) /-- Given `F : walking_parallel_pair ⥤ C`, which is really the same as `parallel_pair (F.map left) (F.map right)` and a cocone on `F`, we get a cofork on `F.map left` and `F.map right`. -/ def cofork.of_cocone {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (t : cocone F) : cofork (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right) := cocone.mk (cocone.X t) (nat_trans.mk fun (X : walking_parallel_pair) => eq_to_hom sorry ≫ nat_trans.app (cocone.ι t) X) @[simp] theorem fork.of_cone_π {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (t : cone F) (j : walking_parallel_pair) : nat_trans.app (cone.π (fork.of_cone t)) j = nat_trans.app (cone.π t) j ≫ eq_to_hom (eq.mpr (id (Eq.trans ((fun (a a_1 : C) (e_1 : a = a_1) (ᾰ ᾰ_1 : C) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (functor.obj F j) (functor.obj F j) (Eq.refl (functor.obj F j)) (functor.obj (parallel_pair (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) j) (functor.obj F j) (parallel_pair_functor_obj j)) (propext (eq_self_iff_true (functor.obj F j))))) trivial) := rfl @[simp] theorem cofork.of_cocone_ι {C : Type u} [category C] {F : walking_parallel_pair ⥤ C} (t : cocone F) (j : walking_parallel_pair) : nat_trans.app (cocone.ι (cofork.of_cocone t)) j = eq_to_hom (eq.mpr (id (Eq.trans ((fun (a a_1 : C) (e_1 : a = a_1) (ᾰ ᾰ_1 : C) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (functor.obj (parallel_pair (functor.map F walking_parallel_pair_hom.left) (functor.map F walking_parallel_pair_hom.right)) j) (functor.obj F j) (parallel_pair_functor_obj j) (functor.obj F j) (functor.obj F j) (Eq.refl (functor.obj F j))) (propext (eq_self_iff_true (functor.obj F j))))) trivial) ≫ nat_trans.app (cocone.ι t) j := rfl /-- Helper function for constructing morphisms between equalizer forks. -/ @[simp] theorem fork.mk_hom_hom {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {s : fork f g} {t : fork f g} (k : cone.X s ⟶ cone.X t) (w : k ≫ fork.ι t = fork.ι s) : cone_morphism.hom (fork.mk_hom k w) = k := Eq.refl (cone_morphism.hom (fork.mk_hom k w)) /-- To construct an isomorphism between forks, it suffices to give an isomorphism between the cone points and check that it commutes with the `ι` morphisms. -/ @[simp] theorem fork.ext_hom {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {s : fork f g} {t : fork f g} (i : cone.X s ≅ cone.X t) (w : iso.hom i ≫ fork.ι t = fork.ι s) : iso.hom (fork.ext i w) = fork.mk_hom (iso.hom i) w := Eq.refl (iso.hom (fork.ext i w)) /-- Helper function for constructing morphisms between coequalizer coforks. -/ @[simp] theorem cofork.mk_hom_hom {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {s : cofork f g} {t : cofork f g} (k : cocone.X s ⟶ cocone.X t) (w : cofork.π s ≫ k = cofork.π t) : cocone_morphism.hom (cofork.mk_hom k w) = k := Eq.refl (cocone_morphism.hom (cofork.mk_hom k w)) /-- To construct an isomorphism between coforks, it suffices to give an isomorphism between the cocone points and check that it commutes with the `π` morphisms. -/ def cofork.ext {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {s : cofork f g} {t : cofork f g} (i : cocone.X s ≅ cocone.X t) (w : cofork.π s ≫ iso.hom i = cofork.π t) : s ≅ t := iso.mk (cofork.mk_hom (iso.hom i) w) (cofork.mk_hom (iso.inv i) sorry) /-- `has_equalizer f g` represents a particular choice of limiting cone for the parallel pair of morphisms `f` and `g`. -/ def has_equalizer {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) := has_limit (parallel_pair f g) /-- If an equalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `equalizer f g`. -/ def equalizer {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] : C := limit (parallel_pair f g) /-- If an equalizer of `f` and `g` exists, we can access the inclusion `equalizer f g ⟶ X` by saying `equalizer.ι f g`. -/ def equalizer.ι {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] : equalizer f g ⟶ X := limit.π (parallel_pair f g) walking_parallel_pair.zero /-- An equalizer cone for a parallel pair `f` and `g`. -/ def equalizer.fork {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] : fork f g := limit.cone (parallel_pair f g) @[simp] theorem equalizer.fork_ι {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] : fork.ι (equalizer.fork f g) = equalizer.ι f g := rfl @[simp] theorem equalizer.fork_π_app_zero {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] : nat_trans.app (cone.π (equalizer.fork f g)) walking_parallel_pair.zero = equalizer.ι f g := rfl theorem equalizer.condition {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] : equalizer.ι f g ≫ f = equalizer.ι f g ≫ g := fork.condition (limit.cone (parallel_pair f g)) /-- The equalizer built from `equalizer.ι f g` is limiting. -/ def equalizer_is_equalizer {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_equalizer f g] : is_limit (fork.of_ι (equalizer.ι f g) (equalizer.condition f g)) := is_limit.of_iso_limit (limit.is_limit (parallel_pair f g)) (fork.ext (iso.refl (cone.X (limit.cone (parallel_pair f g)))) sorry) /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` factors through the equalizer of `f` and `g` via `equalizer.lift : W ⟶ equalizer f g`. -/ def equalizer.lift {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_equalizer f g] {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : W ⟶ equalizer f g := limit.lift (parallel_pair f g) (fork.of_ι k h) @[simp] theorem equalizer.lift_ι_assoc {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_equalizer f g] {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) {X' : C} (f' : X ⟶ X') : equalizer.lift k h ≫ equalizer.ι f g ≫ f' = k ≫ f' := sorry /-- A morphism `k : W ⟶ X` satisfying `k ≫ f = k ≫ g` induces a morphism `l : W ⟶ equalizer f g` satisfying `l ≫ equalizer.ι f g = k`. -/ def equalizer.lift' {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_equalizer f g] {W : C} (k : W ⟶ X) (h : k ≫ f = k ≫ g) : Subtype fun (l : W ⟶ equalizer f g) => l ≫ equalizer.ι f g = k := { val := equalizer.lift k h, property := equalizer.lift_ι k h } /-- Two maps into an equalizer are equal if they are are equal when composed with the equalizer map. -/ theorem equalizer.hom_ext {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_equalizer f g] {W : C} {k : W ⟶ equalizer f g} {l : W ⟶ equalizer f g} (h : k ≫ equalizer.ι f g = l ≫ equalizer.ι f g) : k = l := fork.is_limit.hom_ext (limit.is_limit (parallel_pair f g)) h /-- An equalizer morphism is a monomorphism -/ protected instance equalizer.ι_mono {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_equalizer f g] : mono (equalizer.ι f g) := mono.mk fun (Z : C) (h k : Z ⟶ equalizer f g) (w : h ≫ equalizer.ι f g = k ≫ equalizer.ι f g) => equalizer.hom_ext w /-- The equalizer morphism in any limit cone is a monomorphism. -/ theorem mono_of_is_limit_parallel_pair {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {c : cone (parallel_pair f g)} (i : is_limit c) : mono (fork.ι c) := sorry /-- The identity determines a cone on the equalizer diagram of `f` and `g` if `f = g`. -/ def id_fork {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (h : f = g) : fork f g := fork.of_ι 𝟙 sorry /-- The identity on `X` is an equalizer of `(f, g)`, if `f = g`. -/ def is_limit_id_fork {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (h : f = g) : is_limit (id_fork h) := fork.is_limit.mk (id_fork h) (fun (s : fork f g) => fork.ι s) sorry sorry /-- Every equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_eq {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (h₀ : f = g) {c : cone (parallel_pair f g)} (h : is_limit c) : is_iso (nat_trans.app (cone.π c) walking_parallel_pair.zero) := is_iso.of_iso (is_limit.cone_point_unique_up_to_iso h (is_limit_id_fork h₀)) /-- The equalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def equalizer.ι_of_eq {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_equalizer f g] (h : f = g) : is_iso (equalizer.ι f g) := is_iso_limit_cone_parallel_pair_of_eq h (limit.is_limit (parallel_pair f g)) /-- Every equalizer of `(f, f)` is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_self {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {c : cone (parallel_pair f f)} (h : is_limit c) : is_iso (nat_trans.app (cone.π c) walking_parallel_pair.zero) := is_iso_limit_cone_parallel_pair_of_eq sorry h /-- An equalizer that is an epimorphism is an isomorphism. -/ def is_iso_limit_cone_parallel_pair_of_epi {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {c : cone (parallel_pair f g)} (h : is_limit c) [epi (nat_trans.app (cone.π c) walking_parallel_pair.zero)] : is_iso (nat_trans.app (cone.π c) walking_parallel_pair.zero) := is_iso_limit_cone_parallel_pair_of_eq sorry h protected instance has_equalizer_of_self {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : has_equalizer f f := has_limit.mk (limit_cone.mk (id_fork rfl) (is_limit_id_fork rfl)) /-- The equalizer inclusion for `(f, f)` is an isomorphism. -/ protected instance equalizer.ι_of_self {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : is_iso (equalizer.ι f f) := equalizer.ι_of_eq sorry /-- The equalizer of a morphism with itself is isomorphic to the source. -/ def equalizer.iso_source_of_self {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : equalizer f f ≅ X := as_iso (equalizer.ι f f) @[simp] theorem equalizer.iso_source_of_self_hom {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : iso.hom (equalizer.iso_source_of_self f) = equalizer.ι f f := rfl @[simp] theorem equalizer.iso_source_of_self_inv {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : iso.inv (equalizer.iso_source_of_self f) = equalizer.lift 𝟙 (eq.mpr (id (Eq.trans ((fun (a a_1 : X ⟶ Y) (e_1 : a = a_1) (ᾰ ᾰ_1 : X ⟶ Y) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (𝟙 ≫ f) f (category.id_comp f) (𝟙 ≫ f) f (category.id_comp f)) (propext (eq_self_iff_true f)))) trivial) := rfl /-- `has_coequalizer f g` represents a particular choice of colimiting cocone for the parallel pair of morphisms `f` and `g`. -/ def has_coequalizer {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) := has_colimit (parallel_pair f g) /-- If a coequalizer of `f` and `g` exists, we can access an arbitrary choice of such by saying `coequalizer f g`. -/ def coequalizer {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] : C := colimit (parallel_pair f g) /-- If a coequalizer of `f` and `g` exists, we can access the corresponding projection by saying `coequalizer.π f g`. -/ def coequalizer.π {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] : Y ⟶ coequalizer f g := colimit.ι (parallel_pair f g) walking_parallel_pair.one /-- An arbitrary choice of coequalizer cocone for a parallel pair `f` and `g`. -/ def coequalizer.cofork {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] : cofork f g := colimit.cocone (parallel_pair f g) @[simp] theorem coequalizer.cofork_π {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] : cofork.π (coequalizer.cofork f g) = coequalizer.π f g := rfl @[simp] theorem coequalizer.cofork_ι_app_one {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] : nat_trans.app (cocone.ι (coequalizer.cofork f g)) walking_parallel_pair.one = coequalizer.π f g := rfl theorem coequalizer.condition_assoc {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] {X' : C} (f' : coequalizer f g ⟶ X') : f ≫ coequalizer.π f g ≫ f' = g ≫ coequalizer.π f g ≫ f' := sorry /-- The cofork built from `coequalizer.π f g` is colimiting. -/ def coequalizer_is_coequalizer {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) [has_coequalizer f g] : is_colimit (cofork.of_π (coequalizer.π f g) (coequalizer.condition f g)) := is_colimit.of_iso_colimit (colimit.is_colimit (parallel_pair f g)) (cofork.ext (iso.refl (cocone.X (colimit.cocone (parallel_pair f g)))) sorry) /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` factors through the coequalizer of `f` and `g` via `coequalizer.desc : coequalizer f g ⟶ W`. -/ def coequalizer.desc {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_coequalizer f g] {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : coequalizer f g ⟶ W := colimit.desc (parallel_pair f g) (cofork.of_π k h) @[simp] theorem coequalizer.π_desc_assoc {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_coequalizer f g] {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) {X' : C} (f' : W ⟶ X') : coequalizer.π f g ≫ coequalizer.desc k h ≫ f' = k ≫ f' := sorry /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = g ≫ k` induces a morphism `l : coequalizer f g ⟶ W` satisfying `coequalizer.π ≫ g = l`. -/ def coequalizer.desc' {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_coequalizer f g] {W : C} (k : Y ⟶ W) (h : f ≫ k = g ≫ k) : Subtype fun (l : coequalizer f g ⟶ W) => coequalizer.π f g ≫ l = k := { val := coequalizer.desc k h, property := coequalizer.π_desc k h } /-- Two maps from a coequalizer are equal if they are equal when composed with the coequalizer map -/ theorem coequalizer.hom_ext {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_coequalizer f g] {W : C} {k : coequalizer f g ⟶ W} {l : coequalizer f g ⟶ W} (h : coequalizer.π f g ≫ k = coequalizer.π f g ≫ l) : k = l := cofork.is_colimit.hom_ext (colimit.is_colimit (parallel_pair f g)) h /-- A coequalizer morphism is an epimorphism -/ protected instance coequalizer.π_epi {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_coequalizer f g] : epi (coequalizer.π f g) := epi.mk fun (Z : C) (h k : coequalizer f g ⟶ Z) (w : coequalizer.π f g ≫ h = coequalizer.π f g ≫ k) => coequalizer.hom_ext w /-- The coequalizer morphism in any colimit cocone is an epimorphism. -/ theorem epi_of_is_colimit_parallel_pair {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {c : cocone (parallel_pair f g)} (i : is_colimit c) : epi (nat_trans.app (cocone.ι c) walking_parallel_pair.one) := sorry /-- The identity determines a cocone on the coequalizer diagram of `f` and `g`, if `f = g`. -/ def id_cofork {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (h : f = g) : cofork f g := cofork.of_π 𝟙 sorry /-- The identity on `Y` is a coequalizer of `(f, g)`, where `f = g`. -/ def is_colimit_id_cofork {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (h : f = g) : is_colimit (id_cofork h) := cofork.is_colimit.mk (id_cofork h) (fun (s : cofork f g) => cofork.π s) sorry sorry /-- Every coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def is_iso_colimit_cocone_parallel_pair_of_eq {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} (h₀ : f = g) {c : cocone (parallel_pair f g)} (h : is_colimit c) : is_iso (nat_trans.app (cocone.ι c) walking_parallel_pair.one) := is_iso.of_iso (is_colimit.cocone_point_unique_up_to_iso (is_colimit_id_cofork h₀) h) /-- The coequalizer of `(f, g)`, where `f = g`, is an isomorphism. -/ def coequalizer.π_of_eq {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} [has_coequalizer f g] (h : f = g) : is_iso (coequalizer.π f g) := is_iso_colimit_cocone_parallel_pair_of_eq h (colimit.is_colimit (parallel_pair f g)) /-- Every coequalizer of `(f, f)` is an isomorphism. -/ def is_iso_colimit_cocone_parallel_pair_of_self {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {c : cocone (parallel_pair f f)} (h : is_colimit c) : is_iso (nat_trans.app (cocone.ι c) walking_parallel_pair.one) := is_iso_colimit_cocone_parallel_pair_of_eq sorry h /-- A coequalizer that is a monomorphism is an isomorphism. -/ def is_iso_limit_cocone_parallel_pair_of_epi {C : Type u} [category C] {X : C} {Y : C} {f : X ⟶ Y} {g : X ⟶ Y} {c : cocone (parallel_pair f g)} (h : is_colimit c) [mono (nat_trans.app (cocone.ι c) walking_parallel_pair.one)] : is_iso (nat_trans.app (cocone.ι c) walking_parallel_pair.one) := is_iso_colimit_cocone_parallel_pair_of_eq sorry h protected instance has_coequalizer_of_self {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : has_coequalizer f f := has_colimit.mk (colimit_cocone.mk (id_cofork rfl) (is_colimit_id_cofork rfl)) /-- The coequalizer projection for `(f, f)` is an isomorphism. -/ protected instance coequalizer.π_of_self {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : is_iso (coequalizer.π f f) := coequalizer.π_of_eq sorry /-- The coequalizer of a morphism with itself is isomorphic to the target. -/ def coequalizer.iso_target_of_self {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : coequalizer f f ≅ Y := iso.symm (as_iso (coequalizer.π f f)) @[simp] theorem coequalizer.iso_target_of_self_hom {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : iso.hom (coequalizer.iso_target_of_self f) = coequalizer.desc 𝟙 (eq.mpr (id (Eq.trans ((fun (a a_1 : X ⟶ Y) (e_1 : a = a_1) (ᾰ ᾰ_1 : X ⟶ Y) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (f ≫ 𝟙) f (category.comp_id f) (f ≫ 𝟙) f (category.comp_id f)) (propext (eq_self_iff_true f)))) trivial) := rfl @[simp] theorem coequalizer.iso_target_of_self_inv {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) : iso.inv (coequalizer.iso_target_of_self f) = coequalizer.π f f := rfl /-- The comparison morphism for the equalizer of `f,g`. This is an isomorphism iff `G` preserves the equalizer of `f,g`; see `category_theory/limits/preserves/shapes/equalizers.lean` -/ def equalizer_comparison {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) {D : Type u₂} [category D] (G : C ⥤ D) [has_equalizer f g] [has_equalizer (functor.map G f) (functor.map G g)] : functor.obj G (equalizer f g) ⟶ equalizer (functor.map G f) (functor.map G g) := equalizer.lift (functor.map G (equalizer.ι f g)) sorry @[simp] theorem equalizer_comparison_comp_π_assoc {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) {D : Type u₂} [category D] (G : C ⥤ D) [has_equalizer f g] [has_equalizer (functor.map G f) (functor.map G g)] {X' : D} (f' : functor.obj G X ⟶ X') : equalizer_comparison f g G ≫ equalizer.ι (functor.map G f) (functor.map G g) ≫ f' = functor.map G (equalizer.ι f g) ≫ f' := sorry @[simp] theorem map_lift_equalizer_comparison {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) {D : Type u₂} [category D] (G : C ⥤ D) [has_equalizer f g] [has_equalizer (functor.map G f) (functor.map G g)] {Z : C} {h : Z ⟶ X} (w : h ≫ f = h ≫ g) : functor.map G (equalizer.lift h w) ≫ equalizer_comparison f g G = equalizer.lift (functor.map G h) (eq.mpr (id ((fun (a a_1 : functor.obj G Z ⟶ functor.obj G Y) (e_1 : a = a_1) (ᾰ ᾰ_1 : functor.obj G Z ⟶ functor.obj G Y) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (functor.map G h ≫ functor.map G f) (functor.map G (h ≫ g)) (Eq.trans (Eq.symm (functor.map_comp G h f)) ((fun (c : C ⥤ D) {X Y : C} (ᾰ ᾰ_1 : X ⟶ Y) (e_4 : ᾰ = ᾰ_1) => congr_arg (functor.map c) e_4) G (h ≫ f) (h ≫ g) w)) (functor.map G h ≫ functor.map G g) (functor.map G (h ≫ g)) (Eq.symm (functor.map_comp G h g)))) (Eq.refl (functor.map G (h ≫ g)))) := sorry /-- The comparison morphism for the coequalizer of `f,g`. -/ def coequalizer_comparison {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) {D : Type u₂} [category D] (G : C ⥤ D) [has_coequalizer f g] [has_coequalizer (functor.map G f) (functor.map G g)] : coequalizer (functor.map G f) (functor.map G g) ⟶ functor.obj G (coequalizer f g) := coequalizer.desc (functor.map G (coequalizer.π f g)) sorry @[simp] theorem ι_comp_coequalizer_comparison {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) {D : Type u₂} [category D] (G : C ⥤ D) [has_coequalizer f g] [has_coequalizer (functor.map G f) (functor.map G g)] : coequalizer.π (functor.map G f) (functor.map G g) ≫ coequalizer_comparison f g G = functor.map G (coequalizer.π f g) := coequalizer.π_desc (functor.map G (coequalizer.π f g)) (coequalizer_comparison._proof_1 f g G) @[simp] theorem coequalizer_comparison_map_desc_assoc {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) (g : X ⟶ Y) {D : Type u₂} [category D] (G : C ⥤ D) [has_coequalizer f g] [has_coequalizer (functor.map G f) (functor.map G g)] {Z : C} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h) {X' : D} (f' : functor.obj G Z ⟶ X') : coequalizer_comparison f g G ≫ functor.map G (coequalizer.desc h w) ≫ f' = coequalizer.desc (functor.map G h) (eq.mpr (id ((fun (a a_1 : functor.obj G X ⟶ functor.obj G Z) (e_1 : a = a_1) (ᾰ ᾰ_1 : functor.obj G X ⟶ functor.obj G Z) (e_2 : ᾰ = ᾰ_1) => congr (congr_arg Eq e_1) e_2) (functor.map G f ≫ functor.map G h) (functor.map G (g ≫ h)) (Eq.trans (Eq.symm (functor.map_comp G f h)) ((fun (c : C ⥤ D) {X Y : C} (ᾰ ᾰ_1 : X ⟶ Y) (e_4 : ᾰ = ᾰ_1) => congr_arg (functor.map c) e_4) G (f ≫ h) (g ≫ h) w)) (functor.map G g ≫ functor.map G h) (functor.map G (g ≫ h)) (Eq.symm (functor.map_comp G g h)))) (Eq.refl (functor.map G (g ≫ h)))) ≫ f' := sorry /-- `has_equalizers` represents a choice of equalizer for every pair of morphisms -/ def has_equalizers (C : Type u) [category C] := has_limits_of_shape walking_parallel_pair C /-- `has_coequalizers` represents a choice of coequalizer for every pair of morphisms -/ def has_coequalizers (C : Type u) [category C] := has_colimits_of_shape walking_parallel_pair C /-- If `C` has all limits of diagrams `parallel_pair f g`, then it has all equalizers -/ theorem has_equalizers_of_has_limit_parallel_pair (C : Type u) [category C] [∀ {X Y : C} {f g : X ⟶ Y}, has_limit (parallel_pair f g)] : has_equalizers C := has_limits_of_shape.mk fun (F : walking_parallel_pair ⥤ C) => has_limit_of_iso (iso.symm (diagram_iso_parallel_pair F)) /-- If `C` has all colimits of diagrams `parallel_pair f g`, then it has all coequalizers -/ theorem has_coequalizers_of_has_colimit_parallel_pair (C : Type u) [category C] [∀ {X Y : C} {f g : X ⟶ Y}, has_colimit (parallel_pair f g)] : has_coequalizers C := has_colimits_of_shape.mk fun (F : walking_parallel_pair ⥤ C) => has_colimit_of_iso (diagram_iso_parallel_pair F) -- In this section we show that a split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. Here we build the cone, and show in `split_mono_equalizes` that it is a limit cone. -/ @[simp] theorem cone_of_split_mono_X {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) [split_mono f] : cone.X (cone_of_split_mono f) = X := Eq.refl (cone.X (cone_of_split_mono f)) /-- A split mono `f` equalizes `(retraction f ≫ f)` and `(𝟙 Y)`. -/ def split_mono_equalizes {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) [split_mono f] : is_limit (cone_of_split_mono f) := fork.is_limit.mk' (cone_of_split_mono f) fun (s : fork 𝟙 (retraction f ≫ f)) => { val := fork.ι s ≫ retraction f, property := sorry } -- In this section we show that a split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. Here we build the cocone, and show in `split_epi_coequalizes` that it is a colimit cocone. -/ def cocone_of_split_epi {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) [split_epi f] : cocone (parallel_pair 𝟙 (f ≫ section_ f)) := cofork.of_π f sorry /-- A split epi `f` coequalizes `(f ≫ section_ f)` and `(𝟙 X)`. -/ def split_epi_coequalizes {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) [split_epi f] : is_colimit (cocone_of_split_epi f) := cofork.is_colimit.mk' (cocone_of_split_epi f) fun (s : cofork 𝟙 (f ≫ section_ f)) => { val := section_ f ≫ cofork.π s, property := sorry }
9e814b30a409a02fa9088425c7557918ca33e177
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/group_theory/subgroup.lean
f6dc640fb03c3a58f2b0fae1f879be352fc57a37
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
17,073
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, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro -/ import group_theory.submonoid open set function variables {α : Type*} {β : Type*} {a a₁ a₂ b c: α} section group variables [group α] [add_group β] @[to_additive injective_add] lemma injective_mul {a : α} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ class is_subgroup (s : set α) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) /-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/ class is_add_subgroup (s : set β) extends is_add_submonoid s : Prop := (neg_mem {a} : a ∈ s → -a ∈ s) attribute [to_additive is_add_subgroup] is_subgroup attribute [to_additive is_add_subgroup.to_is_add_submonoid] is_subgroup.to_is_submonoid attribute [to_additive is_add_subgroup.neg_mem] is_subgroup.inv_mem attribute [to_additive is_add_subgroup.mk] is_subgroup.mk instance additive.is_add_subgroup (s : set α) [is_subgroup s] : @is_add_subgroup (additive α) _ s := ⟨@is_subgroup.inv_mem _ _ _ _⟩ theorem additive.is_add_subgroup_iff {s : set α} : @is_add_subgroup (additive α) _ s ↔ is_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk α _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by resetI; apply_instance⟩ instance multiplicative.is_subgroup (s : set β) [is_add_subgroup s] : @is_subgroup (multiplicative β) _ s := ⟨@is_add_subgroup.neg_mem _ _ _ _⟩ theorem multiplicative.is_subgroup_iff {s : set β} : @is_subgroup (multiplicative β) _ s ↔ is_add_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk β _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by resetI; apply_instance⟩ instance subtype.group {s : set α} [is_subgroup s] : group s := by subtype_instance instance subtype.add_group {s : set β} [is_add_subgroup s] : add_group s := by subtype_instance attribute [to_additive subtype.add_group] subtype.group theorem is_subgroup.of_div (s : set α) (one_mem : (1:α) ∈ s) (div_mem : ∀{a b:α}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s): is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } theorem is_add_subgroup.of_sub (s : set β) (zero_mem : (0:β) ∈ s) (sub_mem : ∀{a b:β}, a ∈ s → b ∈ s → a - b ∈ s): is_add_subgroup s := multiplicative.is_subgroup_iff.1 $ @is_subgroup.of_div (multiplicative β) _ _ zero_mem @sub_mem def gpowers (x : α) : set α := {y | ∃i:ℤ, x^i = y} def gmultiples (x : β) : set β := {y | ∃i:ℤ, gsmul i x = y} attribute [to_additive gmultiples] gpowers instance gpowers.is_subgroup (x : α) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } instance gmultiples.is_add_subgroup (x : β) : is_add_subgroup (gmultiples x) := multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _ attribute [to_additive gmultiples.is_add_subgroup] gpowers.is_subgroup lemma is_subgroup.gpow_mem {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma is_add_subgroup.gsmul_mem {a : β} {s : set β} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s := @is_subgroup.gpow_mem (multiplicative β) _ _ _ _ lemma mem_gpowers {a : α} : a ∈ gpowers a := ⟨1, by simp⟩ lemma mem_gmultiples {a : β} : a ∈ gmultiples a := ⟨1, by simp⟩ attribute [to_additive mem_gmultiples] mem_gpowers end group namespace is_subgroup open is_submonoid variables [group α] (s : set α) [is_subgroup s] @[to_additive is_add_subgroup.neg_mem_iff] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := ⟨λ h, by simpa using inv_mem h, inv_mem⟩ @[to_additive is_add_subgroup.add_mem_cancel_left] lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := ⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩ @[to_additive is_add_subgroup.add_mem_cancel_right] lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := ⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩ end is_subgroup namespace group open is_submonoid is_subgroup variables [group α] {s : set α} inductive in_closure (s : set α) : α → Prop | basic {a : α} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : α} : in_closure a → in_closure a⁻¹ | mul {a b : α} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def closure (s : set α) : set α := {a | in_closure s a } lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := in_closure.basic instance closure.is_subgroup (s : set α) : is_subgroup (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } theorem subset_closure {s : set α} : s ⊆ closure s := λ a, mem_closure theorem closure_subset {s t : set α} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] theorem gpowers_eq_closure {a : α} : gpowers a = closure {a} := subset.antisymm (assume x h, match x, h with _, ⟨i, rfl⟩ := gpow_mem (mem_closure $ by simp) end) (closure_subset $ by simp [mem_gpowers]) end group namespace add_group open is_add_submonoid is_add_subgroup variables [add_group α] {s : set α} /-- `add_group.closure s` is the additive subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def closure (s : set α) : set α := @group.closure (multiplicative α) _ s attribute [to_additive add_group.closure] group.closure lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := group.mem_closure attribute [to_additive add_group.mem_closure] group.mem_closure instance closure.is_add_subgroup (s : set α) : is_add_subgroup (closure s) := multiplicative.is_subgroup_iff.1 $ group.closure.is_subgroup _ attribute [to_additive add_group.closure.is_add_subgroup] group.closure.is_subgroup attribute [to_additive add_group.subset_closure] group.subset_closure theorem closure_subset {s t : set α} [is_add_subgroup t] : s ⊆ t → closure s ⊆ t := group.closure_subset attribute [to_additive add_group.closure_subset] group.closure_subset theorem gmultiples_eq_closure {a : α} : gmultiples a = closure {a} := group.gpowers_eq_closure attribute [to_additive add_group.gmultiples_eq_closure] group.gpowers_eq_closure end add_group class normal_subgroup [group α] (s : set α) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g * n * g⁻¹ ∈ s) class normal_add_subgroup [add_group α] (s : set α) extends is_add_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g + n - g ∈ s) attribute [to_additive normal_add_subgroup] normal_subgroup attribute [to_additive normal_add_subgroup.to_is_add_subgroup] normal_subgroup.to_is_subgroup attribute [to_additive normal_add_subgroup.normal] normal_subgroup.normal attribute [to_additive normal_add_subgroup.mk] normal_subgroup.mk @[to_additive normal_add_subgroup_of_add_comm_group] lemma normal_subgroup_of_comm_group [comm_group α] (s : set α) [hs : is_subgroup s] : normal_subgroup s := { normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul], ..hs } instance additive.normal_add_subgroup [group α] (s : set α) [normal_subgroup s] : @normal_add_subgroup (additive α) _ s := ⟨@normal_subgroup.normal _ _ _ _⟩ theorem additive.normal_add_subgroup_iff [group α] {s : set α} : @normal_add_subgroup (additive α) _ s ↔ normal_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_subgroup.mk α _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂, λ h, by resetI; apply_instance⟩ instance multiplicative.normal_subgroup [add_group α] (s : set α) [normal_add_subgroup s] : @normal_subgroup (multiplicative α) _ s := ⟨@normal_add_subgroup.normal _ _ _ _⟩ theorem multiplicative.normal_subgroup_iff [add_group α] {s : set α} : @normal_subgroup (multiplicative α) _ s ↔ normal_add_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_add_subgroup.mk α _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂, λ h, by resetI; apply_instance⟩ namespace is_subgroup variable [group α] -- Normal subgroup properties lemma mem_norm_comm {s : set α} [normal_subgroup s] {a b : α} (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h lemma mem_norm_comm_iff {s : set α} [normal_subgroup s] {a b : α} : a * b ∈ s ↔ b * a ∈ s := ⟨mem_norm_comm, mem_norm_comm⟩ /-- The trivial subgroup -/ def trivial (α : Type*) [group α] : set α := {1} @[simp] lemma mem_trivial [group α] {g : α} : g ∈ trivial α ↔ g = 1 := mem_singleton_iff instance trivial_normal : normal_subgroup (trivial α) := by refine {..}; simp [trivial] {contextual := tt} lemma trivial_eq_closure : trivial α = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) instance univ_subgroup : normal_subgroup (@univ α) := by refine {..}; simp def center (α : Type*) [group α] : set α := {z | ∀ g, g * z = z * g} lemma mem_center {a : α} : a ∈ center α ↔ ∀g, g * a = a * g := iff.rfl instance center_normal : normal_subgroup (center α) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } end is_subgroup namespace is_add_subgroup variable [add_group α] attribute [to_additive is_add_subgroup.mem_norm_comm] is_subgroup.mem_norm_comm attribute [to_additive is_add_subgroup.mem_norm_comm_iff] is_subgroup.mem_norm_comm_iff /-- The trivial subgroup -/ def trivial (α : Type*) [add_group α] : set α := {0} attribute [to_additive is_add_subgroup.trivial] is_subgroup.trivial attribute [to_additive is_add_subgroup.mem_trivial] is_subgroup.mem_trivial instance trivial_normal : normal_add_subgroup (trivial α) := multiplicative.normal_subgroup_iff.1 is_subgroup.trivial_normal attribute [to_additive is_add_subgroup.trivial_normal] is_subgroup.trivial_normal attribute [to_additive is_add_subgroup.trivial_eq_closure] is_subgroup.trivial_eq_closure instance univ_add_subgroup : normal_add_subgroup (@univ α) := multiplicative.normal_subgroup_iff.1 is_subgroup.univ_subgroup attribute [to_additive is_add_subgroup.univ_add_subgroup] is_subgroup.univ_subgroup def center (α : Type*) [add_group α] : set α := {z | ∀ g, g + z = z + g} attribute [to_additive is_add_subgroup.center] is_subgroup.center attribute [to_additive is_add_subgroup.mem_center] is_subgroup.mem_center instance center_normal : normal_add_subgroup (center α) := multiplicative.normal_subgroup_iff.1 is_subgroup.center_normal end is_add_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup variables [group α] [group β] @[to_additive is_add_group_hom.ker] def ker (f : α → β) [is_group_hom f] : set α := preimage f (trivial β) attribute [to_additive is_add_group_hom.ker.equations._eqn_1] ker.equations._eqn_1 @[to_additive is_add_group_hom.mem_ker] lemma mem_ker (f : α → β) [is_group_hom f] {x : α} : x ∈ ker f ↔ f x = 1 := mem_trivial @[to_additive is_add_group_hom.zero_ker_neg] lemma one_ker_inv (f : α → β) [is_group_hom f] {a b : α} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [mul f, inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end @[to_additive is_add_group_hom.neg_ker_zero] lemma inv_ker_one (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←inv f, ←mul f] at this @[to_additive is_add_group_hom.zero_iff_ker_neg] lemma one_iff_ker_inv (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ @[to_additive is_add_group_hom.neg_iff_ker] lemma inv_iff_ker (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ instance image_subgroup (f : α → β) [is_group_hom f] (s : set α) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, mul f]⟩, one_mem := ⟨1, one_mem s, one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw inv f; simp *⟩ } attribute [to_additive is_add_group_hom.image_add_subgroup._match_1] is_group_hom.image_subgroup._match_1 attribute [to_additive is_add_group_hom.image_add_subgroup._match_2] is_group_hom.image_subgroup._match_2 attribute [to_additive is_add_group_hom.image_add_subgroup._match_3] is_group_hom.image_subgroup._match_3 attribute [to_additive is_add_group_hom.image_add_subgroup] is_group_hom.image_subgroup attribute [to_additive is_add_group_hom.image_add_subgroup._match_1.equations._eqn_1] is_group_hom.image_subgroup._match_1.equations._eqn_1 attribute [to_additive is_add_group_hom.image_add_subgroup._match_2.equations._eqn_1] is_group_hom.image_subgroup._match_2.equations._eqn_1 attribute [to_additive is_add_group_hom.image_add_subgroup._match_3.equations._eqn_1] is_group_hom.image_subgroup._match_3.equations._eqn_1 attribute [to_additive is_add_group_hom.image_add_subgroup.equations._eqn_1] is_group_hom.image_subgroup.equations._eqn_1 instance range_subgroup (f : α → β) [is_group_hom f] : is_subgroup (set.range f) := @set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ attribute [to_additive is_add_group_hom.range_add_subgroup] is_group_hom.range_subgroup attribute [to_additive is_add_group_hom.range_add_subgroup.equations._eqn_1] is_group_hom.range_subgroup.equations._eqn_1 local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal instance preimage (f : α → β) [is_group_hom f] (s : set β) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [mul f, one f, inv f, @inv_mem β _ s] {contextual:=tt} attribute [to_additive is_add_group_hom.preimage] is_group_hom.preimage attribute [to_additive is_add_group_hom.preimage.equations._eqn_1] is_group_hom.preimage.equations._eqn_1 instance preimage_normal (f : α → β) [is_group_hom f] (s : set β) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [mul f, inv f] {contextual:=tt}⟩ attribute [to_additive is_add_group_hom.preimage_normal] is_group_hom.preimage_normal attribute [to_additive is_add_group_hom.preimage_normal.equations._eqn_1] is_group_hom.preimage_normal.equations._eqn_1 instance normal_subgroup_ker (f : α → β) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial β) attribute [to_additive is_add_group_hom.normal_subgroup_ker] is_group_hom.normal_subgroup_ker attribute [to_additive is_add_group_hom.normal_subgroup_ker.equations._eqn_1] is_group_hom.normal_subgroup_ker.equations._eqn_1 lemma inj_of_trivial_ker (f : α → β) [is_group_hom f] (h : ker f = trivial α) : function.injective f := begin intros a₁ a₂ hfa, simp [ext_iff, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end lemma trivial_ker_of_inj (f : α → β) [is_group_hom f] (h : function.injective f) : ker f = trivial α := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.one f] {contextual := tt}) lemma inj_iff_trivial_ker (f : α → β) [is_group_hom f] : function.injective f ↔ ker f = trivial α := ⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩ end is_group_hom
f36b624510dab2e054981f885c559d5107e4deee
cf39355caa609c0f33405126beee2739aa3cb77e
/leanpkg/leanpkg/lean_version.lean
1fde253823352416f800ac246994ddbba8620fe4
[ "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
726
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ namespace leanpkg def lean_version_string_core := let (major, minor, patch) := lean.version in sformat!("{major}.{minor}.{patch}") def lean_version_string := if lean.is_release then "leanprover-community/lean:" ++ lean_version_string_core else if lean.special_version_desc ≠ "" then lean.special_version_desc else "master" def ui_lean_version_string := if lean.is_release then lean_version_string_core else if lean.special_version_desc ≠ "" then lean.special_version_desc else "master (" ++ lean_version_string_core ++ ")" end leanpkg
8ee4c8abf85dee2dd9cfb121b7a7cb82bf43d91e
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/analysis/convex/caratheodory.lean
e982764c4400e71d4c7b88c1c96203798570e6d3
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,886
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import analysis.convex.basic /-! # Carathéodory's convexity theorem This file is devoted to proving Carathéodory's convexity theorem: The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`. ## Main results: * `convex_hull_eq_union`: Carathéodory's convexity theorem ## Implementation details This theorem was formalized as part of the Sphere Eversion project. ## Tags convex hull, caratheodory -/ universes u open set finset finite_dimensional open_locale big_operators variables {E : Type u} [add_comm_group E] [module ℝ E] [finite_dimensional ℝ E] namespace caratheodory /-- If `x` is in the convex hull of some finset `t` with strictly more than `finrank + 1` elements, then it is in the union of the convex hulls of the finsets `t.erase y` for `y ∈ t`. -/ lemma mem_convex_hull_erase [decidable_eq E] {t : finset E} (h : finrank ℝ E + 1 < t.card) {x : E} (m : x ∈ convex_hull (↑t : set E)) : ∃ (y : (↑t : set E)), x ∈ convex_hull (↑(t.erase y) : set E) := begin simp only [finset.convex_hull_eq, mem_set_of_eq] at m ⊢, obtain ⟨f, fpos, fsum, rfl⟩ := m, obtain ⟨g, gcombo, gsum, gpos⟩ := exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card h, clear h, let s := t.filter (λ z : E, 0 < g z), obtain ⟨i₀, mem, w⟩ : ∃ i₀ ∈ s, ∀ i ∈ s, f i₀ / g i₀ ≤ f i / g i, { apply s.exists_min_image (λ z, f z / g z), obtain ⟨x, hx, hgx⟩ : ∃ x ∈ t, 0 < g x := gpos, exact ⟨x, mem_filter.mpr ⟨hx, hgx⟩⟩, }, have hg : 0 < g i₀ := by { rw mem_filter at mem, exact mem.2 }, have hi₀ : i₀ ∈ t := filter_subset _ _ mem, let k : E → ℝ := λ z, f z - (f i₀ / g i₀) * g z, have hk : k i₀ = 0 := by field_simp [k, ne_of_gt hg], have ksum : ∑ e in t.erase i₀, k e = 1, { calc ∑ e in t.erase i₀, k e = ∑ e in t, k e : by conv_rhs { rw [← insert_erase hi₀, sum_insert (not_mem_erase i₀ t), hk, zero_add], } ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) : rfl ... = 1 : by rw [sum_sub_distrib, fsum, ← mul_sum, gsum, mul_zero, sub_zero] }, refine ⟨⟨i₀, hi₀⟩, k, _, ksum, _⟩, { simp only [and_imp, sub_nonneg, mem_erase, ne.def, subtype.coe_mk], intros e hei₀ het, by_cases hes : e ∈ s, { have hge : 0 < g e := by { rw mem_filter at hes, exact hes.2 }, rw ← le_div_iff hge, exact w _ hes, }, { calc _ ≤ 0 : mul_nonpos_of_nonneg_of_nonpos _ _ -- prove two goals below ... ≤ f e : fpos e het, { apply div_nonneg (fpos i₀ (mem_of_subset (filter_subset _ t) mem)) (le_of_lt hg) }, { simpa only [mem_filter, het, true_and, not_lt] using hes }, } }, { simp only [subtype.coe_mk, center_mass_eq_of_sum_1 _ id ksum, id], calc ∑ e in t.erase i₀, k e • e = ∑ e in t, k e • e : sum_erase _ (by rw [hk, zero_smul]) ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) • e : rfl ... = t.center_mass f id : _, simp only [sub_smul, mul_smul, sum_sub_distrib, ← smul_sum, gcombo, smul_zero, sub_zero, center_mass, fsum, inv_one, one_smul, id.def], }, end /-- The convex hull of a finset `t` with `finrank ℝ E + 1 < t.card` is equal to the union of the convex hulls of the finsets `t.erase x` for `x ∈ t`. -/ lemma step [decidable_eq E] (t : finset E) (h : finrank ℝ E + 1 < t.card) : convex_hull (↑t : set E) = ⋃ (x : (↑t : set E)), convex_hull ↑(t.erase x) := begin apply set.subset.antisymm, { intros x m', obtain ⟨y, m⟩ := mem_convex_hull_erase h m', exact mem_Union.2 ⟨y, m⟩, }, { refine Union_subset _, intro x, apply convex_hull_mono, apply erase_subset, } end /-- The convex hull of a finset `t` with `finrank ℝ E + 1 < t.card` is contained in the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ finrank ℝ E + 1`. -/ lemma shrink' (t : finset E) (k : ℕ) (h : t.card = finrank ℝ E + 1 + k) : convex_hull (↑t : set E) ⊆ ⋃ (t' : finset E) (w : t' ⊆ t) (b : t'.card ≤ finrank ℝ E + 1), convex_hull ↑t' := begin induction k with k ih generalizing t, { apply subset_subset_Union t, apply subset_subset_Union (set.subset.refl _), exact subset_subset_Union (le_of_eq h) (subset.refl _), }, { classical, rw step _ (by { rw h, simp, } : finrank ℝ E + 1 < t.card), apply Union_subset, intro i, transitivity, { apply ih, rw [card_erase_of_mem, h, nat.add_succ, nat.pred_succ], exact i.2, }, { apply Union_subset_Union, intro t', apply Union_subset_Union_const, exact λ h, set.subset.trans h (erase_subset _ _), } } end /-- The convex hull of any finset `t` is contained in the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ finrank ℝ E + 1`. -/ lemma shrink (t : finset E) : convex_hull (↑t : set E) ⊆ ⋃ (t' : finset E) (w : t' ⊆ t) (b : t'.card ≤ finrank ℝ E + 1), convex_hull ↑t' := begin by_cases h : t.card ≤ finrank ℝ E + 1, { apply subset_subset_Union t, apply subset_subset_Union (set.subset.refl _), exact subset_subset_Union h (set.subset.refl _), }, push_neg at h, obtain ⟨k, w⟩ := le_iff_exists_add.mp (le_of_lt h), clear h, exact shrink' _ _ w, end end caratheodory /-- One inclusion of **Carathéodory's convexity theorem**. The convex hull of a set `s` in ℝᵈ is contained in the union of the convex hulls of the (d+1)-tuples in `s`. -/ lemma convex_hull_subset_union (s : set E) : convex_hull s ⊆ ⋃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1), convex_hull ↑t := begin -- First we replace `convex_hull s` with the union of the convex hulls of finite subsets, rw convex_hull_eq_union_convex_hull_finite_subsets, -- and prove the inclusion for each of those. apply Union_subset, intro r, apply Union_subset, intro h, -- Second, for each convex hull of a finite subset, we shrink it. refine subset.trans (caratheodory.shrink _) _, -- After that it's just shuffling unions around. refine Union_subset_Union (λ t, _), exact Union_subset_Union2 (λ htr, ⟨subset.trans htr h, subset.refl _⟩) end /-- **Carathéodory's convexity theorem**. The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`. -/ theorem convex_hull_eq_union (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1), convex_hull ↑t := begin apply set.subset.antisymm, { apply convex_hull_subset_union, }, iterate 3 { convert Union_subset _, intro, }, exact convex_hull_mono ‹_›, end /-- A more explicit formulation of **Carathéodory's convexity theorem**, writing an element of a convex hull as the center of mass of an explicit `finset` with cardinality at most `dim + 1`. -/ theorem eq_center_mass_card_le_dim_succ_of_mem_convex_hull {s : set E} {x : E} (h : x ∈ convex_hull s) : ∃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1) (f : E → ℝ), (∀ y ∈ t, 0 ≤ f y) ∧ t.sum f = 1 ∧ t.center_mass f id = x := begin rw convex_hull_eq_union at h, simp only [exists_prop, mem_Union] at h, obtain ⟨t, w, b, m⟩ := h, refine ⟨t, w, b, _⟩, rw finset.convex_hull_eq at m, simpa only [exists_prop] using m, end /-- A variation on **Carathéodory's convexity theorem**, writing an element of a convex hull as a center of mass of an explicit `finset` with cardinality at most `dim + 1`, where all coefficients in the center of mass formula are strictly positive. (This is proved using `eq_center_mass_card_le_dim_succ_of_mem_convex_hull`, and discarding any elements of the set with coefficient zero.) -/ theorem eq_pos_center_mass_card_le_dim_succ_of_mem_convex_hull {s : set E} {x : E} (h : x ∈ convex_hull s) : ∃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1) (f : E → ℝ), (∀ y ∈ t, 0 < f y) ∧ t.sum f = 1 ∧ t.center_mass f id = x := begin obtain ⟨t, w, b, f, ⟨pos, sum, center⟩⟩ := eq_center_mass_card_le_dim_succ_of_mem_convex_hull h, let t' := t.filter (λ z, 0 < f z), have t'sum : t'.sum f = 1, { rw ← sum, exact sum_filter_of_ne (λ x hxt hfx, (pos x hxt).lt_of_ne hfx.symm) }, refine ⟨t', _, _, f, ⟨_, t'sum, _⟩⟩, { exact subset.trans (filter_subset _ t) w, }, { exact (card_filter_le _ _).trans b, }, { exact λ y H, (mem_filter.mp H).right, }, { rw ← center, simp only [center_mass, t'sum, sum, inv_one, one_smul, id.def], refine sum_filter_of_ne (λ x hxt hfx, (pos x hxt).lt_of_ne $ λ hf₀, _), rw [← hf₀, zero_smul] at hfx, exact hfx rfl }, end
5c5cd0e6e27c4e8abdb8c35d279f0691f2b5d807
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/meta/simp_tactic.lean
34760f44310b9c1171334a9aeaaf96933e1d7807
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
18,593
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.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences init.meta.quote import init.data.option.instances open tactic meta constant simp_lemmas : Type meta constant simp_lemmas.mk : simp_lemmas meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas meta constant simp_lemmas.mk_default_core : transparency → tactic simp_lemmas meta constant simp_lemmas.add_core : transparency → simp_lemmas → expr → tactic simp_lemmas meta constant simp_lemmas.add_simp_core : transparency → simp_lemmas → name → tactic simp_lemmas meta constant simp_lemmas.add_congr_core : transparency → simp_lemmas → name → tactic simp_lemmas meta def simp_lemmas.mk_default : tactic simp_lemmas := simp_lemmas.mk_default_core reducible meta def simp_lemmas.add : simp_lemmas → expr → tactic simp_lemmas := simp_lemmas.add_core reducible meta def simp_lemmas.add_simp : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_simp_core reducible meta def simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_congr_core reducible meta def simp_lemmas.append : simp_lemmas → list expr → tactic simp_lemmas | sls [] := return sls | sls (l::ls) := do new_sls ← simp_lemmas.add sls l, simp_lemmas.append new_sls ls /- (simp_lemmas.rewrite_core m s prove R e) apply a simplification lemma from 's' - 'prove' is used to discharge proof obligations. - 'R' is the equivalence relation being used (e.g., 'eq', 'iff') - 'e' is the expression to be "simplified" Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite_core : transparency → simp_lemmas → tactic unit → name → expr → tactic (expr × expr) meta def simp_lemmas.rewrite : simp_lemmas → tactic unit → name → expr → tactic (expr × expr) := simp_lemmas.rewrite_core reducible /- (simp_lemmas.drewrite s e) tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite_core : transparency → simp_lemmas → expr → tactic expr meta def simp_lemmas.drewrite : simp_lemmas → expr → tactic expr := simp_lemmas.drewrite_core reducible /- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. -/ meta constant simp_lemmas.dsimplify_core (max_steps : nat) (visit_instances : bool) : simp_lemmas → expr → tactic expr meta constant is_valid_simp_lemma_cnst : transparency → name → tactic bool meta constant is_valid_simp_lemma : transparency → expr → tactic bool def default_max_steps := 10000000 meta def simp_lemmas.dsimplify : simp_lemmas → expr → tactic expr := simp_lemmas.dsimplify_core default_max_steps ff meta constant simp_lemmas.pp : simp_lemmas → tactic format namespace tactic /- (get_eqn_lemmas_for deps d) returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta constant get_eqn_lemmas_for : bool → name → tactic (list name) meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (max_steps : nat) /- If visit_instances = ff, then instance implicit arguments are not visited, but tactic will canonize them. -/ (visit_instances : bool) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) : expr → tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () default_max_steps ff (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta constant dunfold_expr_core : transparency → expr → tactic expr /- Remark: we use transparency.instances by default to make sure that we can unfold projections of type classes. Example: dunfold_expr (@has_add.add nat nat.has_add a b) -/ meta def dunfold_expr : expr → tactic expr := dunfold_expr_core transparency.instances meta constant unfold_projection_core : transparency → expr → tactic expr meta def unfold_projection : expr → tactic expr := unfold_projection_core transparency.instances meta def dunfold_occs_core (m : transparency) (max_steps : nat) (occs : occurrences) (cs : list name) (e : expr) : tactic expr := let unfold (c : nat) (e : expr) : tactic (nat × expr × bool) := do guard (cs.any e.is_app_of), new_e ← dunfold_expr_core m e, if occs.contains c then return (c+1, new_e, tt) else return (c+1, e, tt) in do (c, new_e) ← dsimplify_core 1 max_steps tt unfold (λ c e, failed) e, return new_e meta def dunfold_core (m : transparency) (max_steps : nat) (cs : list name) (e : expr) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (cs.any e.is_app_of), new_e ← dunfold_expr_core m e, return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () max_steps tt (λ c e, failed) unfold e, return new_e meta def dunfold : list name → tactic unit := λ cs, target >>= dunfold_core transparency.instances default_max_steps cs >>= change meta def dunfold_occs_of (occs : list nat) (c : name) : tactic unit := target >>= dunfold_occs_core transparency.instances default_max_steps (occurrences.pos occs) [c] >>= change meta def dunfold_core_at (occs : occurrences) (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← dunfold_occs_core transparency.instances default_max_steps occs cs d, change $ expr.pi n bi new_d b, intron num_reverted meta def dunfold_at (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← dunfold_core transparency.instances default_max_steps cs d, change $ expr.pi n bi new_d b, intron num_reverted structure delta_config := (max_steps := default_max_steps) (visit_instances := tt) private meta def is_delta_target (e : expr) (cs : list name) : bool := cs.any (λ c, if e.is_app_of c then tt /- Exact match -/ else let f := e.get_app_fn in /- f is an auxiliary constant generated when compiling c -/ f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c)) /- Delta reduce the given constant names -/ meta def delta_core (cfg : delta_config) (cs : list name) (e : expr) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (is_delta_target e cs), (expr.const f_name f_lvls) ← return e.get_app_fn, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, new_e ← head_beta (expr.mk_app new_f e.get_app_args), return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () cfg.max_steps cfg.visit_instances (λ c e, failed) unfold e, return new_e meta def delta (cs : list name) : tactic unit := target >>= delta_core {} cs >>= change meta def delta_at (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← delta_core {} cs d, change $ expr.pi n bi new_d b, intron num_reverted structure simp_config := (max_steps : nat := default_max_steps) (contextual : bool := ff) (lift_eq : bool := tt) (canonize_instances : bool := tt) (canonize_proofs : bool := ff) (use_axioms : bool := tt) (zeta : bool := tt) (beta : bool := tt) (eta : bool := tt) (proj : bool := tt) -- reduce projections meta constant simplify_core (c : simp_config) (s : simp_lemmas) (r : name) : expr → tactic (expr × expr) meta constant ext_simplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (c : simp_config) /- Congruence and simplification lemmas. Remark: the simplification lemmas at not applied automatically like in the simplify_core tactic. the caller must use them at pre/post. -/ (s : simp_lemmas) /- Tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user state. -/ (prove : α → tactic α) /- (pre a S r s p e) is invoked before visiting the children of subterm 'e', 'r' is the simplification relation being used, 's' is the updated set of lemmas if 'contextual' is tt, 'p' is the "parent" expression (if there is one). if it succeeds the result is (new_a, new_e, new_pr, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression s.t. 'e r new_e' - 'new_pr' is a proof for 'e r new_e', If it is none, the proof is assumed to be by reflexivity - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- (post a r s p e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a r s p e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- simplification relation -/ (r : name) : expr → tactic (α × expr × expr) meta def simplify (S : simp_lemmas) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := do e_type ← infer_type e >>= whnf, simplify_core cfg S `eq e meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do assert `htarget new_target, swap, ht ← get_local `htarget, mk_eq_mpr pr ht >>= exact meta def simplify_goal (S : simp_lemmas) (cfg : simp_config := {}) : tactic unit := do t ← target, (new_t, pr) ← simplify S t cfg, replace_target new_t pr meta def simp (cfg : simp_config := {}) : tactic unit := do S ← simp_lemmas.mk_default, simplify_goal S cfg >> try triv >> try (reflexivity reducible) meta def simp_using (hs : list expr) (cfg : simp_config := {}) : tactic unit := do S ← simp_lemmas.mk_default, S ← S.append hs, simplify_goal S cfg >> try triv meta def dsimp_core (s : simp_lemmas) : tactic unit := target >>= s.dsimplify >>= change meta def dsimp : tactic unit := simp_lemmas.mk_default >>= dsimp_core meta def dsimp_at_core (s : simp_lemmas) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, h_simp ← s.dsimplify d, change $ expr.pi n bi h_simp b, intron num_reverted meta def dsimp_at (h : expr) : tactic unit := do s ← simp_lemmas.mk_default, dsimp_at_core s h private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end private meta def collect_simps : list expr → tactic (list expr) | [] := return [] | (h :: hs) := do result ← collect_simps hs, htype ← infer_type h >>= whnf, if is_equation htype then return (h :: result) else do pr ← is_prop htype, return $ if pr then (h :: result) else result meta def collect_ctx_simps : tactic (list expr) := local_context >>= collect_simps /-- Simplify target using all hypotheses in the local context. -/ meta def simp_using_hs (cfg : simp_config := {}) : tactic unit := do es ← collect_ctx_simps, simp_using es cfg meta def simph (cfg : simp_config := {}) := simp_using_hs cfg meta def intro1_aux : bool → list name → tactic expr | ff _ := intro1 | tt (n::ns) := intro n | _ _ := failed meta def simp_intro_aux (cfg : simp_config) (updt : bool) : simp_lemmas → bool → list name → tactic simp_lemmas | S tt [] := try (simplify_goal S cfg) >> return S | S use_ns ns := do t ← target, if t.is_napp_of `not 1 then intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail else if t.is_arrow then do { d ← return t.binding_domain, (new_d, h_d_eq_new_d) ← simplify S d cfg, h_d ← intro1_aux use_ns ns, h_new_d ← mk_eq_mp h_d_eq_new_d h_d, assertv_core h_d.local_pp_name new_d h_new_d, h_new ← intro1, new_S ← if updt && is_equation new_d then S.add h_new else return S, clear h_d, simp_intro_aux new_S use_ns ns } <|> -- failed to simplify... we just introduce and continue (intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail) else if t.is_pi || t.is_let then intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail else do new_t ← whnf t reducible, if new_t.is_pi then change new_t >> simp_intro_aux S use_ns ns else try (simplify_goal S cfg) >> mcond (expr.is_pi <$> target) (simp_intro_aux S use_ns ns) (if use_ns ∧ ¬ns.empty then failed else return S) meta def simp_intros_using (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ simp_intro_aux cfg ff s ff [] meta def simph_intros_using (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ do s ← collect_ctx_simps >>= s.append, simp_intro_aux cfg tt s ff [] meta def simp_intro_lst_using (ns : list name) (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ simp_intro_aux cfg ff s tt ns meta def simph_intro_lst_using (ns : list name) (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ do s ← collect_ctx_simps >>= s.append, simp_intro_aux cfg tt s tt ns meta def simp_at (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic unit := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, S ← simp_lemmas.mk_default, S ← S.append extra_lemmas, (new_htype, heq) ← simplify S htype cfg, assert (expr.local_pp_name h) new_htype, mk_eq_mp heq h >>= exact, try $ clear h meta def simp_at_using_hs (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic unit := do hs ← collect_ctx_simps, simp_at h (list.filter (≠ h) hs ++ extra_lemmas) cfg meta def simph_at (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic unit := simp_at_using_hs h extra_lemmas cfg meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← S.add_simp n, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) : command := do let t := ```(caching_user_attribute simp_lemmas), v ← to_expr ``({name := %%(quote attr_name), descr := "simplifier attribute", mk_cache := λ ns, do {tactic.to_simp_lemmas simp_lemmas.mk ns}, dependencies := [`reducibility] } : caching_user_attribute simp_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute simp_lemmas) cnst, caching_user_attribute.get_cache attr meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R meta def join_user_simp_lemmas : list name → tactic simp_lemmas | [] := simp_lemmas.mk_default | attr_names := join_user_simp_lemmas_core simp_lemmas.mk attr_names /- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral, and pr is a proof that the input argument is equal to n. -/ meta constant norm_num : expr → tactic (expr × expr) meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) (λ _ _ _ _ _, failed) `eq e meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg, replace_target new_target pr meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) `eq e meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg, replace_target new_target pr end tactic export tactic (mk_simp_attr)
d0fd5c9044e839de45f7445c80a64337dc9603bc
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed_space/basic.lean
462b1fb9034ba55fd4d1976d131c98aea6c68f37
[ "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
24,861
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import analysis.normed.field.basic import analysis.normed.group.infinite_sum import data.real.sqrt import data.matrix.basic import topology.sequences /-! # Normed spaces In this file we define (semi)normed spaces and algebras. We also prove some theorems about these definitions. -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric function set open_locale topological_space big_operators nnreal ennreal uniformity pointwise section seminormed_add_comm_group section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. Note that since this requires `seminormed_add_comm_group` and not `normed_add_comm_group`, this typeclass can be used for "semi normed spaces" too, just as `module` can be used for "semi modules". -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [seminormed_add_comm_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) end prio variables [normed_field α] [seminormed_add_comm_group β] @[priority 100] -- see Note [lower instance priority] instance normed_space.has_bounded_smul [normed_space α β] : has_bounded_smul α β := { dist_smul_pair' := λ x y₁ y₂, by simpa [dist_eq_norm, smul_sub] using normed_space.norm_smul_le x (y₁ - y₂), dist_pair_smul' := λ x₁ x₂ y, by simpa [dist_eq_norm, sub_smul] using normed_space.norm_smul_le (x₁ - x₂) y } instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin by_cases h : s = 0, { simp [h] }, { refine le_antisymm (normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul₀ h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _) ... = ∥s • x∥ : by rw [norm_inv, ← mul_assoc, mul_inv_cancel (mt norm_eq_zero.1 h), one_mul] } end lemma norm_zsmul (α) [normed_field α] [normed_space α β] (n : ℤ) (x : β) : ∥n • x∥ = ∥(n : α)∥ * ∥x∥ := by rw [← norm_smul, ← int.smul_one_eq_coe, smul_assoc, one_smul] @[simp] lemma abs_norm_eq_norm (z : β) : |∥z∥| = ∥z∥ := (abs_eq (norm_nonneg z)).mpr (or.inl rfl) lemma inv_norm_smul_mem_closed_unit_ball [normed_space ℝ β] (x : β) : ∥x∥⁻¹ • x ∈ closed_ball (0 : β) 1 := by simp only [mem_closed_ball_zero_iff, norm_smul, norm_inv, norm_norm, ← div_eq_inv_mul, div_self_le_one] lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥₊ = ∥s∥₊ * ∥x∥₊ := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = ∥s∥₊ * nndist x y := nnreal.eq $ dist_smul s x y lemma lipschitz_with_smul [normed_space α β] (s : α) : lipschitz_with ∥s∥₊ ((•) s : β → β) := lipschitz_with_iff_dist_le_mul.2 $ λ x y, by rw [dist_smul, coe_nnnorm] lemma norm_smul_of_nonneg [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} [seminormed_add_comm_group E] [normed_space α E] variables {F : Type*} [seminormed_add_comm_group F] [normed_space α F] theorem eventually_nhds_norm_smul_sub_lt (c : α) (x : E) {ε : ℝ} (h : 0 < ε) : ∀ᶠ y in 𝓝 x, ∥c • (y - x)∥ < ε := have tendsto (λ y, ∥c • (y - x)∥) (𝓝 x) (𝓝 0), from ((continuous_id.sub continuous_const).const_smul _).norm.tendsto' _ _ (by simp), this.eventually (gt_mem_nhds h) lemma filter.tendsto.zero_smul_is_bounded_under_le {f : ι → α} {g : ι → E} {l : filter ι} (hf : tendsto f l (𝓝 0)) (hg : is_bounded_under (≤) l (norm ∘ g)) : tendsto (λ x, f x • g x) l (𝓝 0) := hf.op_zero_is_bounded_under_le hg (•) (λ x y, (norm_smul x y).le) lemma filter.is_bounded_under.smul_tendsto_zero {f : ι → α} {g : ι → E} {l : filter ι} (hf : is_bounded_under (≤) l (norm ∘ f)) (hg : tendsto g l (𝓝 0)) : tendsto (λ x, f x • g x) l (𝓝 0) := hg.op_zero_is_bounded_under_le hf (flip (•)) (λ x y, ((norm_smul y x).trans (mul_comm _ _)).le) theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : closure (ball x r) = closed_ball x r := begin refine subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_ne_one ℝ _ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, replace hr : 0 < r, from ((norm_nonneg _).trans hy).lt_of_ne hr.symm, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : interior (closed_ball x r) = ball x r := begin cases hr.lt_or_lt with hr hr, { rw [closed_ball_eq_empty.2 hr, ball_eq_empty.2 hr.le, interior_empty] }, refine subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases (mem_closed_ball.1 $ interior_subset hy).lt_or_eq with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] instance {E : Type*} [normed_add_comm_group E] [normed_space ℚ E] (e : E) : discrete_topology $ add_subgroup.zmultiples e := begin rcases eq_or_ne e 0 with rfl | he, { rw [add_subgroup.zmultiples_zero_eq_bot], apply_instance, }, { rw [discrete_topology_iff_open_singleton_zero, is_open_induced_iff], refine ⟨metric.ball 0 (∥e∥), metric.is_open_ball, _⟩, ext ⟨x, hx⟩, obtain ⟨k, rfl⟩ := add_subgroup.mem_zmultiples_iff.mp hx, rw [mem_preimage, mem_ball_zero_iff, add_subgroup.coe_mk, mem_singleton_iff, subtype.ext_iff, add_subgroup.coe_mk, add_subgroup.coe_zero, norm_zsmul ℚ k e, int.norm_cast_rat, int.norm_eq_abs, ← int.cast_abs, mul_lt_iff_lt_one_left (norm_pos_iff.mpr he), ← @int.cast_one ℝ _, int.cast_lt, int.abs_lt_one_iff, smul_eq_zero, or_iff_left he], }, end /-- A (semi) normed real vector space is homeomorphic to the unit ball in the same space. This homeomorphism sends `x : E` to `(1 + ∥x∥²)^(- ½) • x`. In many cases the actual implementation is not important, so we don't mark the projection lemmas `homeomorph_unit_ball_apply_coe` and `homeomorph_unit_ball_symm_apply` as `@[simp]`. See also `cont_diff_homeomorph_unit_ball` and `cont_diff_on_homeomorph_unit_ball_symm` for smoothness properties that hold when `E` is an inner-product space. -/ @[simps { attrs := [] }] def homeomorph_unit_ball [normed_space ℝ E] : E ≃ₜ ball (0 : E) 1 := { to_fun := λ x, ⟨(1 + ∥x∥^2).sqrt⁻¹ • x, begin have : 0 < 1 + ∥x∥ ^ 2, by positivity, rw [mem_ball_zero_iff, norm_smul, real.norm_eq_abs, abs_inv, ← div_eq_inv_mul, div_lt_one (abs_pos.mpr $ real.sqrt_ne_zero'.mpr this), ← abs_norm_eq_norm x, ← sq_lt_sq, abs_norm_eq_norm, real.sq_sqrt this.le], exact lt_one_add _, end⟩, inv_fun := λ y, (1 - ∥(y : E)∥^2).sqrt⁻¹ • (y : E), left_inv := λ x, begin have : 0 < 1 + ∥x∥ ^ 2, by positivity, field_simp [norm_smul, smul_smul, this.ne', real.sq_sqrt this.le, ← real.sqrt_div this.le], end, right_inv := λ y, begin have : 0 < 1 - ∥(y : E)∥ ^ 2 := by nlinarith [norm_nonneg (y : E), (mem_ball_zero_iff.1 y.2 : ∥(y : E)∥ < 1)], field_simp [norm_smul, smul_smul, this.ne', real.sq_sqrt this.le, ← real.sqrt_div this.le], end, continuous_to_fun := begin suffices : continuous (λ x, (1 + ∥x∥^2).sqrt⁻¹), from (this.smul continuous_id).subtype_mk _, refine continuous.inv₀ _ (λ x, real.sqrt_ne_zero'.mpr (by positivity)), continuity, end, continuous_inv_fun := begin suffices : ∀ (y : ball (0 : E) 1), (1 - ∥(y : E)∥ ^ 2).sqrt ≠ 0, { continuity, }, intros y, rw real.sqrt_ne_zero', nlinarith [norm_nonneg (y : E), (mem_ball_zero_iff.1 y.2 : ∥(y : E)∥ < 1)], end } @[simp] lemma coe_homeomorph_unit_ball_apply_zero [normed_space ℝ E] : (homeomorph_unit_ball (0 : E) : E) = 0 := by simp [homeomorph_unit_ball] open normed_field instance : normed_space α (ulift E) := { norm_smul_le := λ s x, (normed_space.norm_smul_le s x.down : _), ..ulift.normed_add_comm_group, ..ulift.module' } /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance prod.normed_space : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], ..prod.normed_add_comm_group, ..prod.module } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, seminormed_add_comm_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), ∥a • f b∥₊)) : ℝ) = ∥a∥₊ * ↑(finset.sup finset.univ (λ (b : ι), ∥f b∥₊)), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 R : Type*} [has_smul 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [seminormed_add_comm_group E] [normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } /-- If there is a scalar `c` with `∥c∥>1`, then any element with nonzero norm can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell_semi_normed {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : ∥x∥ ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos ((ne.symm hx).le_iff_lt.1 (norm_nonneg x)) εpos, rcases exists_mem_Ico_zpow xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_zpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ < ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_zpow], exact (div_lt_iff εpos).1 (hn.2) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_zpow, zpow_add₀ (ne_of_gt cpos), zpow_one, mul_inv_rev, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (zpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv, norm_zpow, zpow_add₀ (ne_of_gt cpos), zpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end end seminormed_add_comm_group section normed_add_comm_group variables [normed_field α] variables {E : Type*} [normed_add_comm_group E] [normed_space α E] variables {F : Type*} [normed_add_comm_group F] [normed_space α F] open normed_field /-- While this may appear identical to `normed_space.to_module`, it contains an implicit argument involving `normed_add_comm_group.to_seminormed_add_comm_group` that typeclass inference has trouble inferring. Specifically, the following instance cannot be found without this `normed_space.to_module'`: ```lean example (𝕜 ι : Type*) (E : ι → Type*) [normed_field 𝕜] [Π i, normed_add_comm_group (E i)] [Π i, normed_space 𝕜 (E i)] : Π i, module 𝕜 (E i) := by apply_instance ``` [This Zulip thread](https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Typeclass.20resolution.20under.20binders/near/245151099) gives some more context. -/ @[priority 100] instance normed_space.to_module' : module α F := normed_space.to_module section surj variables (E) [normed_space ℝ E] [nontrivial E] lemma exists_norm_eq {c : ℝ} (hc : 0 ≤ c) : ∃ x : E, ∥x∥ = c := begin rcases exists_ne (0 : E) with ⟨x, hx⟩, rw ← norm_ne_zero_iff at hx, use c • ∥x∥⁻¹ • x, simp [norm_smul, real.norm_of_nonneg hc, hx] end @[simp] lemma range_norm : range (norm : E → ℝ) = Ici 0 := subset.antisymm (range_subset_iff.2 norm_nonneg) (λ _, exists_norm_eq E) lemma nnnorm_surjective : surjective (nnnorm : E → ℝ≥0) := λ c, (exists_norm_eq E c.coe_nonneg).imp $ λ x h, nnreal.eq h @[simp] lemma range_nnnorm : range (nnnorm : E → ℝ≥0) = univ := (nnnorm_surjective E).range_eq end surj theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases eq_or_ne r 0 with rfl|hr, { rw [closed_ball_zero, ball_zero, interior_singleton] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] variables {α} /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := rescale_to_shell_semi_normed hc εpos (ne_of_lt (norm_pos_iff.2 hx)).symm end normed_add_comm_group section nontrivially_normed_space variables (𝕜 E : Type*) [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [nontrivial E] include 𝕜 /-- If `E` is a nontrivial normed space over a nontrivially normed field `𝕜`, then `E` is unbounded: for any `c : ℝ`, there exists a vector `x : E` with norm strictly greater than `c`. -/ lemma normed_space.exists_lt_norm (c : ℝ) : ∃ x : E, c < ∥x∥ := begin rcases exists_ne (0 : E) with ⟨x, hx⟩, rcases normed_field.exists_lt_norm 𝕜 (c / ∥x∥) with ⟨r, hr⟩, use r • x, rwa [norm_smul, ← div_lt_iff], rwa norm_pos_iff end protected lemma normed_space.unbounded_univ : ¬bounded (univ : set E) := λ h, let ⟨R, hR⟩ := bounded_iff_forall_norm_le.1 h, ⟨x, hx⟩ := normed_space.exists_lt_norm 𝕜 E R in hx.not_le (hR x trivial) /-- A normed vector space over a nontrivially normed field is a noncompact space. This cannot be an instance because in order to apply it, Lean would have to search for `normed_space 𝕜 E` with unknown `𝕜`. We register this as an instance in two cases: `𝕜 = E` and `𝕜 = ℝ`. -/ protected lemma normed_space.noncompact_space : noncompact_space E := ⟨λ h, normed_space.unbounded_univ 𝕜 _ h.bounded⟩ @[priority 100] instance nontrivially_normed_field.noncompact_space : noncompact_space 𝕜 := normed_space.noncompact_space 𝕜 𝕜 omit 𝕜 @[priority 100] instance real_normed_space.noncompact_space [normed_space ℝ E] : noncompact_space E := normed_space.noncompact_space ℝ E end nontrivially_normed_space section normed_algebra /-- A normed algebra `𝕜'` over `𝕜` is normed module that is also an algebra. See the implementation notes for `algebra` for a discussion about non-unital algebras. Following the strategy there, a non-unital *normed* algebra can be written as: ```lean variables [normed_field 𝕜] [non_unital_semi_normed_ring 𝕜'] variables [normed_module 𝕜 𝕜'] [smul_comm_class 𝕜 𝕜' 𝕜'] [is_scalar_tower 𝕜 𝕜' 𝕜'] ``` -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_smul_le : ∀ (r : 𝕜) (x : 𝕜'), ∥r • x∥ ≤ ∥r∥ * ∥x∥) variables {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[priority 100] instance normed_algebra.to_normed_space : normed_space 𝕜 𝕜' := { norm_smul_le := normed_algebra.norm_smul_le } /-- While this may appear identical to `normed_algebra.to_normed_space`, it contains an implicit argument involving `normed_ring.to_semi_normed_ring` that typeclass inference has trouble inferring. Specifically, the following instance cannot be found without this `normed_space.to_module'`: ```lean example (𝕜 ι : Type*) (E : ι → Type*) [normed_field 𝕜] [Π i, normed_ring (E i)] [Π i, normed_algebra 𝕜 (E i)] : Π i, module 𝕜 (E i) := by apply_instance ``` See `normed_space.to_module'` for a similar situation. -/ @[priority 100] instance normed_algebra.to_normed_space' {𝕜'} [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := by apply_instance lemma norm_algebra_map (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ * ∥(1 : 𝕜')∥ := begin rw algebra.algebra_map_eq_smul_one, exact norm_smul _ _, end lemma nnnorm_algebra_map (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥₊ = ∥x∥₊ * ∥(1 : 𝕜')∥₊ := subtype.ext $ norm_algebra_map 𝕜' x @[simp] lemma norm_algebra_map' [norm_one_class 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := by rw [norm_algebra_map, norm_one, mul_one] @[simp] lemma nnnorm_algebra_map' [norm_one_class 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥₊ = ∥x∥₊ := subtype.ext $ norm_algebra_map' _ _ variables (𝕜 𝕜') /-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/ lemma algebra_map_isometry [norm_one_class 𝕜'] : isometry (algebra_map 𝕜 𝕜') := begin refine isometry.of_dist_eq (λx y, _), rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map'], end /-- The inclusion of the base field in a normed algebra as a continuous linear map. -/ @[simps] def algebra_map_clm : 𝕜 →L[𝕜] 𝕜' := { to_fun := algebra_map 𝕜 𝕜', map_add' := (algebra_map 𝕜 𝕜').map_add, map_smul' := λ r x, by rw [algebra.id.smul_eq_mul, map_mul, ring_hom.id_apply, algebra.smul_def], cont := have lipschitz_with ∥(1 : 𝕜')∥₊ (algebra_map 𝕜 𝕜') := λ x y, begin rw [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm_sub, ←map_sub, ←ennreal.coe_mul, ennreal.coe_le_coe, mul_comm], exact (nnnorm_algebra_map _ _).le, end, this.continuous } lemma algebra_map_clm_coe : (algebra_map_clm 𝕜 𝕜' : 𝕜 → 𝕜') = (algebra_map 𝕜 𝕜' : 𝕜 → 𝕜') := rfl lemma algebra_map_clm_to_linear_map : (algebra_map_clm 𝕜 𝕜').to_linear_map = algebra.linear_map 𝕜 𝕜' := rfl instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { .. normed_field.to_normed_space, .. algebra.id 𝕜} /-- Any normed characteristic-zero division ring that is a normed_algebra over the reals is also a normed algebra over the rationals. Phrased another way, if `𝕜` is a normed algebra over the reals, then `algebra_rat` respects that norm. -/ instance normed_algebra_rat {𝕜} [normed_division_ring 𝕜] [char_zero 𝕜] [normed_algebra ℝ 𝕜] : normed_algebra ℚ 𝕜 := { norm_smul_le := λ q x, by rw [←smul_one_smul ℝ q x, rat.smul_one_eq_coe, norm_smul, rat.norm_cast_real], } instance punit.normed_algebra : normed_algebra 𝕜 punit := { norm_smul_le := λ q x, by simp only [punit.norm_eq_zero, mul_zero] } instance : normed_algebra 𝕜 (ulift 𝕜') := { ..ulift.normed_space } /-- The product of two normed algebras is a normed algebra, with the sup norm. -/ instance prod.normed_algebra {E F : Type*} [semi_normed_ring E] [semi_normed_ring F] [normed_algebra 𝕜 E] [normed_algebra 𝕜 F] : normed_algebra 𝕜 (E × F) := { ..prod.normed_space } /-- The product of finitely many normed algebras is a normed algebra, with the sup norm. -/ instance pi.normed_algebra {E : ι → Type*} [fintype ι] [Π i, semi_normed_ring (E i)] [Π i, normed_algebra 𝕜 (E i)] : normed_algebra 𝕜 (Π i, E i) := { .. pi.normed_space, .. pi.algebra _ E } end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [seminormed_add_comm_group E] [normed_space 𝕜' E] instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : seminormed_add_comm_group E] : seminormed_add_comm_group (restrict_scalars 𝕜 𝕜' E) := I instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_add_comm_group E] : normed_add_comm_group (restrict_scalars 𝕜 𝕜' E) := I /-- If `E` is a normed space over `𝕜'` and `𝕜` is a normed algebra over `𝕜'`, then `restrict_scalars.module` is additionally a `normed_space`. -/ instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := { norm_smul_le := λ c x, (normed_space.norm_smul_le (algebra_map 𝕜 𝕜' c) (_ : E)).trans_eq $ by rw norm_algebra_map', ..restrict_scalars.module 𝕜 𝕜' E } /-- The action of the original normed_field on `restrict_scalars 𝕜 𝕜' E`. This is not an instance as it would be contrary to the purpose of `restrict_scalars`. -/ -- If you think you need this, consider instead reproducing `restrict_scalars.lsmul` -- appropriately modified here. def module.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [seminormed_add_comm_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` and/or `restrict_scalars 𝕜 𝕜' E` instead. This definition allows the `restrict_scalars.normed_space` instance to be put directly on `E` rather on `restrict_scalars 𝕜 𝕜' E`. This would be a very bad instance; both because `𝕜'` cannot be inferred, and because it is likely to create instance diamonds. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := restrict_scalars.normed_space _ 𝕜' _ end restrict_scalars
d8fb8eccbf618287d1fd03adfa8b49a1ea594bb2
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Util/Constructions.lean
3b384fb98b3763021c23eb47831edc651a70e58a
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,997
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Environment import Lean.MonadEnv namespace Lean @[extern "lean_mk_cases_on"] constant mkCasesOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_rec_on"] constant mkRecOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_no_confusion"] constant mkNoConfusionImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_below"] constant mkBelowImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_ibelow"] constant mkIBelowImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_brec_on"] constant mkBRecOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_binduction_on"] constant mkBInductionOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment variable {m} [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] @[inline] private def adaptFn (f : Environment → Name → Except KernelException Environment) (declName : Name) : m Unit := do match f (← getEnv) declName with | Except.ok env => modifyEnv fun _ => env | Except.error ex => throwKernelException ex def mkCasesOn (declName : Name) : m Unit := adaptFn mkCasesOnImp declName def mkRecOn (declName : Name) : m Unit := adaptFn mkRecOnImp declName def mkNoConfusion (declName : Name) : m Unit := adaptFn mkNoConfusionImp declName def mkBelow (declName : Name) : m Unit := adaptFn mkBelowImp declName def mkIBelow (declName : Name) : m Unit := adaptFn mkIBelowImp declName def mkBRecOn (declName : Name) : m Unit := adaptFn mkBRecOnImp declName def mkBInductionOn (declName : Name) : m Unit := adaptFn mkBInductionOnImp declName end Lean
c359d26ef5c6dfcdaf7f0dc970e6d09c1d161bb2
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/Script/IntegerType.lean
f51f8784b123792a6a640d7e81882dd6a0cdd724
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,043
lean
import Lean.Parser import Papyrus.Script.SyntaxUtil import Papyrus.IR.Types namespace Papyrus.Script -- # Matcher partial def isDecimalTail (str : String) (i : String.Pos) : Bool := if str.atEnd i then true else if (str.get i).isDigit then isDecimalTail str (str.next i) else false def isDecimal (str : String) (i : String.Pos) : Bool := if str.atEnd i then false else if (str.get i).isDigit then isDecimalTail str (str.next i) else false partial def decodeDecimalTail? (str : String) (i : String.Pos) (val : Nat) : Option Nat := if str.atEnd i then some val else let c := str.get i if c.isDigit then decodeDecimalTail? str (str.next i) (10*val + c.toNat - '0'.toNat) else none def decodeDecimal? (str : String) (i : String.Pos) : Option Nat := if str.atEnd i then none else let c := str.get i if c.isDigit then decodeDecimalTail? str (str.next i) (c.toNat - '0'.toNat) else none def isIntTypeLit (str : String) : Bool := let i : String.Pos := 0 if str.atEnd i then false else if str.get i == 'i' then isDecimal str (str.next i) else false -- # Parser open Lean section open Parser def intTypeLitFn : ParserFn := fun c s => let errorMsg := "'intTypeLit'" let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn [errorMsg] c s if s.hasError then s else match s.stxStack.back with | Syntax.ident info rawVal _ _ => let atom := rawVal.toString if isIntTypeLit atom then let s := s.popSyntax s.pushSyntax <| Syntax.mkLit `Papyrus.Script.intTypeLit atom info else s.mkErrorAt errorMsg startPos initStackSz | _ => s.mkErrorAt errorMsg startPos initStackSz @[inline] def intTypeLitNoAntiquot : Parser := { fn := intTypeLitFn info := { firstTokens := FirstTokens.tokens [ "intTypeLit", "ident" ] } } def intTypeLit : Parser := withAntiquot (mkAntiquot "intTypeLit" `Papyrus.Script.intTypeLit) intTypeLitNoAntiquot end -- # Pretty Printer section open PrettyPrinter Formatter Parenthesizer @[combinatorFormatter Papyrus.Script.intTypeLitNoAntiquot] def intTypeLitNoAntiquot.formatter := identNoAntiquot.formatter @[combinatorParenthesizer Papyrus.Script.intTypeLitNoAntiquot] def intTypeLitNoAntiquot.parenthesizer := identNoAntiquot.parenthesizer end attribute [runParserAttributeHooks] intTypeLit -- # Macro def decodeIntTypeLit? (stx : Lean.Syntax) : Option Nat := OptionM.run do decodeDecimal? (← stx.isLit? ``intTypeLit) 1 def expandIntTypeLitAsNatLit (stx : Syntax) : MacroM Syntax := match stx.isLit? ``intTypeLit with | some str => mkNumLitFrom stx (str.drop 1) | none => Macro.throwErrorAt stx "ill-formed integer type literal" def expandIntTypeLitAsType (stx : Syntax) : MacroM Syntax := do mkCAppFrom stx ``integerType #[← expandIntTypeLitAsNatLit stx] def expandIntTypeLitAsRef (stx : Syntax) : MacroM Syntax := do mkCAppFrom stx ``IntegerTypeRef.get #[← expandIntTypeLitAsNatLit stx] scoped macro:max (priority := high) x:intTypeLit : term => expandIntTypeLitAsType x
392796485650a8b5fb8a6848bc3558007550e6fd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/integral/riesz_markov_kakutani.lean
6b25ad04cfa052df9d21d092426d9f0735fc6674
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,125
lean
/- Copyright (c) 2022 Jesse Reimann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Reimann, Kalle Kytölä -/ import topology.continuous_function.bounded import topology.sets.compacts /-! # Riesz–Markov–Kakutani representation theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file will prove different versions of the Riesz-Markov-Kakutani representation theorem. The theorem is first proven for compact spaces, from which the statements about linear functionals on bounded continuous functions or compactly supported functions on locally compact spaces follow. To make use of the existing API, the measure is constructed from a content `λ` on the compact subsets of the space X, rather than the usual construction of open sets in the literature. ## References * [Walter Rudin, Real and Complex Analysis.][Rud87] -/ noncomputable theory open_locale bounded_continuous_function nnreal ennreal open set function topological_space variables {X : Type*} [topological_space X] variables (Λ : (X →ᵇ ℝ≥0) →ₗ[ℝ≥0] ℝ≥0) /-! ### Construction of the content: -/ /-- Given a positive linear functional Λ on X, for `K ⊆ X` compact define `λ(K) = inf {Λf | 1≤f on K}`. When X is a compact Hausdorff space, this will be shown to be a content, and will be shown to agree with the Riesz measure on the compact subsets `K ⊆ X`. -/ def riesz_content_aux : (compacts X) → ℝ≥0 := λ K, Inf (Λ '' {f : X →ᵇ ℝ≥0 | ∀ x ∈ K, (1 : ℝ≥0) ≤ f x}) section riesz_monotone /-- For any compact subset `K ⊆ X`, there exist some bounded continuous nonnegative functions f on X such that `f ≥ 1` on K. -/ lemma riesz_content_aux_image_nonempty (K : compacts X) : (Λ '' {f : X →ᵇ ℝ≥0 | ∀ x ∈ K, (1 : ℝ≥0) ≤ f x}).nonempty := begin rw nonempty_image_iff, use (1 : X →ᵇ ℝ≥0), intros x x_in_K, simp only [bounded_continuous_function.coe_one, pi.one_apply], end /-- Riesz content λ (associated with a positive linear functional Λ) is monotone: if `K₁ ⊆ K₂` are compact subsets in X, then `λ(K₁) ≤ λ(K₂)`. -/ lemma riesz_content_aux_mono {K₁ K₂ : compacts X} (h : K₁ ≤ K₂) : riesz_content_aux Λ K₁ ≤ riesz_content_aux Λ K₂ := cInf_le_cInf (order_bot.bdd_below _) (riesz_content_aux_image_nonempty Λ K₂) (image_subset Λ (set_of_subset_set_of.mpr (λ f f_hyp x x_in_K₁, f_hyp x (h x_in_K₁)))) end riesz_monotone section riesz_subadditive /-- Any bounded continuous nonnegative f such that `f ≥ 1` on K gives an upper bound on the content of K; namely `λ(K) ≤ Λ f`. -/ lemma riesz_content_aux_le {K : compacts X} {f : X →ᵇ ℝ≥0} (h : ∀ x ∈ K, (1 : ℝ≥0) ≤ f x) : riesz_content_aux Λ K ≤ Λ f := cInf_le (order_bot.bdd_below _) ⟨f, ⟨h, rfl⟩⟩ /-- The Riesz content can be approximated arbitrarily well by evaluating the positive linear functional on test functions: for any `ε > 0`, there exists a bounded continuous nonnegative function f on X such that `f ≥ 1` on K and such that `λ(K) ≤ Λ f < λ(K) + ε`. -/ lemma exists_lt_riesz_content_aux_add_pos (K : compacts X) {ε : ℝ≥0} (εpos : 0 < ε) : ∃ (f : X →ᵇ ℝ≥0), (∀ x ∈ K, (1 : ℝ≥0) ≤ f x) ∧ Λ f < riesz_content_aux Λ K + ε := begin --choose a test function `f` s.t. `Λf = α < λ(K) + ε` obtain ⟨α, ⟨⟨f, f_hyp⟩, α_hyp⟩⟩ := exists_lt_of_cInf_lt (riesz_content_aux_image_nonempty Λ K) (lt_add_of_pos_right (riesz_content_aux Λ K) εpos), refine ⟨f, f_hyp.left, _ ⟩, rw f_hyp.right, exact α_hyp, end /-- The Riesz content λ associated to a given positive linear functional Λ is finitely subadditive: `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)` for any compact subsets `K₁, K₂ ⊆ X`. -/ lemma riesz_content_aux_sup_le (K1 K2 : compacts X) : riesz_content_aux Λ (K1 ⊔ K2) ≤ riesz_content_aux Λ (K1) + riesz_content_aux Λ (K2) := begin apply nnreal.le_of_forall_pos_le_add, intros ε εpos, --get test functions s.t. `λ(Ki) ≤ Λfi ≤ λ(Ki) + ε/2, i=1,2` obtain ⟨f1, f_test_function_K1⟩ := exists_lt_riesz_content_aux_add_pos Λ K1 (half_pos εpos), obtain ⟨f2, f_test_function_K2⟩ := exists_lt_riesz_content_aux_add_pos Λ K2 (half_pos εpos), --let `f := f1 + f2` test function for the content of `K` have f_test_function_union : (∀ x ∈ (K1 ⊔ K2), (1 : ℝ≥0) ≤ (f1 + f2) x), { rintros x (x_in_K1 | x_in_K2), { exact le_add_right (f_test_function_K1.left x x_in_K1) }, { exact le_add_left (f_test_function_K2.left x x_in_K2) }}, --use that `Λf` is an upper bound for `λ(K1⊔K2)` apply (riesz_content_aux_le Λ f_test_function_union).trans (le_of_lt _), rw map_add, --use that `Λfi` are lower bounds for `λ(Ki) + ε/2` apply lt_of_lt_of_le (add_lt_add f_test_function_K1.right f_test_function_K2.right) (le_of_eq _), rw [add_assoc, add_comm (ε/2), add_assoc, add_halves ε, add_assoc], end end riesz_subadditive
ec194282732d5e6930a853fbf7cb48e07a0539e3
6950a6e5cebf75da9b91f42789baf52514655111
/hol/datastructures_hol.lean
74f98d8dfb91bd29840b27fcd9ba9eafa57117a7
[]
no_license
phlippe/Lean_hammer
a6d0a1af09fbce0c58b801032099b9b91d49ecf0
2116279b9c6b334f5b661e4abf4561368cca2391
refs/heads/master
1,587,486,769,513
1,561,466,931,000
1,561,466,931,000
169,705,506
0
1
null
1,550,228,564,000
1,549,614,939,000
Lean
UTF-8
Lean
false
false
13,167
lean
meta mutual inductive holtype, holterm with holtype : Type | o : holtype -- Boolean (predefined TFF $o) | i : holtype -- Individual (predefined TFF $i, default type) | int : holtype -- Individual (predefined TFF $int, integer) | rat : holtype -- Individual (predefined TFF $rat, rational numbers) | real : holtype -- Individual (predefined TFF $real, real numbers) | type : holtype -- Type (predefined TFF $tType) | ltype : name → holtype -- Self-specified type | functor : list holtype → holtype → holtype -- binder !> in HOL (example: !>[A: $tType, B: $tType] : ((map@A@B) > A > B)) where map : $tType > $tType > $tType | dep_binder : list (name × holtype) → holtype → holtype -- We only encode !>[A: $tType, B: $tType] by the first list. Afterwards, it can be any holtype -- Should for example encode "map@A@B" as stated above | partial_app : holterm → holtype -- Problem: dependencies to each other... with holterm : Type | const : name → holterm -- Constant with given label | lconst : name → holtype → holterm -- Second term should rather by holtype | prf : holterm | var : nat → holterm -- Variables just specified by counter: X1,X2,X3,... | app : holterm → holterm → holterm -- @(t,s) is the same as t s => apply t on input s -- Encode λ-expressions explicitly | lambda : name → holtype → holterm → holterm -- Pi expression should not be necessary/implemented in TH1? -- | pi : nat → holtype → holterm → holterm -- Boolean constant | top : holterm | bottom : holterm meta inductive holform | P : holterm → holform -- Provability of a term (used in e.g. hammer_f if expression does not fit to any other option) | T : holterm → holtype → holform -- Encoding of term constraints | eq : holterm → holterm → holform -- Equality. t == s | bottom : holform -- Constant False | top : holform -- Constant True | neg : holform → holform -- Negation function. ¬A | imp : holform → holform → holform -- Imply: A → B | iff : holform → holform → holform -- Two-sided imply/iff: A ↔ B | conj : holform → holform → holform -- Conjunction: A ∧ B | disj : holform → holform → holform -- Disjunction: A ∨ B | all : name → holtype → holform → holform -- For all: ∀ (a : α) t -- a is the name of the parameter/variable, α the type, t the formula | exist : name → holtype → holform → holform -- Exists: ∃ (a : α) t -- Similar as above meta structure introduced_constant := -- Structure representing a new constant introduced for translation (n : name) (e : expr) -- name and type meta structure axioma := -- Note: axiom is reserved word in Lean, thus the additional a (n : name) (f : holform) -- Every axiom is specified by a name and its formula meta structure type_def := (def_name : name) (type_name : name) (t : holtype) meta inductive role -- Role of a formula. Can be either axiom, definition or conjecture | axioma : role | r_definition : role -- Keyword "definition" already used in Lean | conjecture : role meta def role.to_format : role → format | role.axioma := to_fmt "axiom" | role.r_definition := to_fmt "definition" | role.conjecture := to_fmt "conjecture" meta structure hammer_state := -- Structure representing the state of the hammer (list of axioms with corresponding list of newly introduced constants for translation) (axiomas : list axioma) (type_definitions : list type_def) (introduced_constants : list introduced_constant) meta def hammer_tactic := state_t hammer_state tactic meta def holterm.abstract_locals_core : holterm → ℕ → list name → holterm | e@(holterm.lconst n n1) d ln := list.foldl (λ e' n', if n = n' then holterm.var $ d + ln.reverse.find_index (= n) else e') e ln | (holterm.app t1 t2) d ln := holterm.app (t1.abstract_locals_core d ln) (t2.abstract_locals_core d ln) -- | e@(holterm.lambda n t1 ) | e d ln := e meta def holterm.abstract_locals : holterm → list name → holterm := λ f l, f.abstract_locals_core 0 l meta def holform.abstract_locals_core : holform → nat → list name → holform | e@(holform.P t) d ln := holform.P $ t.abstract_locals_core d ln | e@(holform.T t u) d ln := e | e@(holform.eq t u) d ln := holform.eq (t.abstract_locals_core d ln) (u.abstract_locals_core d ln) | e@(holform.neg f) d ln := holform.neg (f.abstract_locals_core d ln) | e@(holform.imp f1 f2) d ln := holform.imp (f1.abstract_locals_core d ln) (f2.abstract_locals_core d ln) | e@(holform.iff f1 f2) d ln := holform.iff (f1.abstract_locals_core d ln) (f2.abstract_locals_core d ln) | e@(holform.conj f1 f2) d ln := holform.conj (f1.abstract_locals_core d ln) (f2.abstract_locals_core d ln) | e@(holform.disj f1 f2) d ln := holform.disj (f1.abstract_locals_core d ln) (f2.abstract_locals_core d ln) | e@(holform.all n n1 f) d ln := holform.all n n1 (f.abstract_locals_core (d+1) ln) | e@(holform.exist n n1 f) d ln := holform.exist n n1 (f.abstract_locals_core (d+1) ln) | e d ln := e meta def holform.abstract_locals : holform → list name → holform := λ f l, f.abstract_locals_core 0 l meta mutual def holtype_list_to_repr, holtype_cross_list_to_repr, holtype.repr, holterm.repr with holtype_list_to_repr : list holtype → string | (x :: xs) := x.repr ++ " " ++ (holtype_list_to_repr xs) | [] := "" with holtype_cross_list_to_repr : list (name × holtype) → string | ((n,x) :: xs) := name.to_string n ++ ":" ++ x.repr ++ " " ++ (holtype_cross_list_to_repr xs) | [] := "" with holtype.repr : holtype → string | e@(holtype.o) := "(holtype.o)" | e@(holtype.i) := "(holtype.i)" | e@(holtype.int) := "(holtype.int)" | e@(holtype.rat) := "(holtype.rat)" | e@(holtype.real) := "(holtype.real)" | e@(holtype.type) := "(holtype.type)" | e@(holtype.ltype n) := "(holtype.ltype " ++ name.to_string n ++ ")" | e@(holtype.functor ts t) := "(holtype.functor [" ++ holtype_list_to_repr ts ++ "] " ++ t.repr ++ ")" | e@(holtype.dep_binder ts t) := "(holtype.dep_binder [" ++ holtype_cross_list_to_repr ts ++ "] " ++ t.repr ++ ")" | e@(holtype.partial_app t) := "(holtype.partial_app " ++ t.repr ++ ")" with holterm.repr : holterm → string | e@(holterm.const n) := "(holterm.constant " ++ name.to_string n ++ ")" | e@(holterm.lconst n t) := "(holterm.local_const " ++ name.to_string n ++ holtype.repr t ++ ")" | e@(holterm.prf) := "(holterm.prf)" | e@(holterm.var n) := "(holterm.var " ++ repr n ++ ")" | e@(holterm.app t1 t2) := "(holterm.app " ++ holterm.repr t1 ++ " " ++ holterm.repr t2 ++ ")" -- Encode λ-expressions explicitly | e@(holterm.lambda n ty t) := "(holterm.lambda " ++ name.to_string n ++ " " ++ holtype.repr ty ++ " " ++ holterm.repr t ++ ")" -- | e@(holterm.pi n ty t) := "(holterm.pi " ++ repr n ++ " " ++ holtype.repr ty ++ " " ++ holterm.repr t ++ ")" -- Boolean constant | e@(holterm.top) := "(holterm.top)" | e@(holterm.bottom) := "(holterm.bottom)" meta def holform.repr : holform → string | e@(holform.P t) := "(holform.P " ++ t.repr ++ ")" | e@(holform.T n t) := "(holform.T " ++ holterm.repr n ++ holtype.repr t ++ ")" | e@(holform.eq t1 t2) := "(holform.eq " ++ t1.repr ++ t2.repr ++ ")" -- Boolean constant | e@(holform.bottom) := "(holform.bottom)" | e@(holform.top) := "(holform.top)" | e@(holform.neg f) := "(holform.neg " ++ f.repr ++ ")" | e@(holform.imp f1 f2) := "(holform.imp " ++ f1.repr ++ " " ++ f2.repr ++ ")" | e@(holform.iff f1 f2) := "(holform.iff " ++ f1.repr ++ " " ++ f2.repr ++ ")" | e@(holform.conj f1 f2) := "(holform.conj " ++ f1.repr ++ " " ++ f2.repr ++ ")" | e@(holform.disj f1 f2) := "(holform.disj " ++ f1.repr ++ " " ++ f2.repr ++ ")" | e@(holform.all n t f) := "(holform.all " ++ name.to_string n ++ " " ++ t.repr ++ " " ++ f.repr ++ ")" | e@(holform.exist n t f) := "(holform.exist " ++ name.to_string n ++ " " ++ t.repr ++ " " ++ f.repr ++ ")" meta mutual def holtype_list_to_format, holtype_cross_list_to_format, holtype.to_format_aux, holterm.to_format_aux with holtype_list_to_format : list holtype → ℕ → ℕ → string → format | (x :: xs) depth n c := if n > 0 then " " ++ c ++ " " ++ x.to_format_aux depth ++ (holtype_list_to_format xs depth (n+1) c) else x.to_format_aux depth ++ (holtype_list_to_format xs depth (n+1) c) | [] depth n c := "" with holtype_cross_list_to_format : list (name × holtype) → ℕ → ℕ → string → format | ((na,x) :: xs) depth n c := if n > 0 then " " ++ c ++ " " ++ to_fmt na ++ ": " ++ x.to_format_aux depth ++ (holtype_cross_list_to_format xs depth (n+1) c) else to_fmt na ++ ": " ++ x.to_format_aux depth ++ (holtype_cross_list_to_format xs depth (n+1) c) | [] depth n c := "" with holtype.to_format_aux : holtype → ℕ → format | e@(holtype.o) _ := "$o" | e@(holtype.i) _ := "$i" | e@(holtype.int) _ := "$int" | e@(holtype.rat) _ := "$rat" | e@(holtype.real) _ := "$real" | e@(holtype.type) _ := "$tType" | e@(holtype.ltype n) _ := to_fmt n | e@(holtype.functor ts t) depth := (holtype_list_to_format ts depth 0 ">") ++ " > " ++ t.to_format_aux depth | e@(holtype.dep_binder ts t) depth := "!>[" ++ holtype_cross_list_to_format ts depth 0 "," ++ "] : (" ++ t.to_format_aux depth ++ ")" | e@(holtype.partial_app t) depth := "(" ++ t.to_format_aux depth ++ ")" with holterm.to_format_aux : holterm → ℕ → format | e@(holterm.const n) _ := to_fmt n | e@(holterm.lconst n _) _ := to_fmt n | e@(holterm.prf) _ := "prf" | e@(holterm.var n) depth := "V" ++ to_fmt (depth - n) | e@(holterm.app t1 t2) depth := "(" ++ t1.to_format_aux depth ++ "@" ++ t2.to_format_aux depth ++ ")" | e@(holterm.lambda n ty t) depth := "( ^[" ++ to_fmt n ++ ":" ++ ty.to_format_aux depth ++ "] : " ++ t.to_format_aux (depth + 1) ++ " )" -- Boolean constant | e@(holterm.top) _ := "$true" | e@(holterm.bottom) _ := "$false" meta def holform.to_format_aux : holform → ℕ → format | e@(holform.P t) depth := "p(" ++ t.to_format_aux depth ++ ")" | e@(holform.T n t) depth := "t(" ++ n.to_format_aux depth ++ t.to_format_aux depth ++ ")" | e@(holform.eq t1 t2) depth := "(" ++ t1.to_format_aux depth ++ "=" ++ t2.to_format_aux depth ++ ")" -- Boolean constant | e@(holform.bottom) _ := to_fmt "$false" | e@(holform.top) _ := to_fmt "$true" | e@(holform.neg f) depth := "~(" ++ f.to_format_aux depth ++ ")" | e@(holform.imp f1 f2) depth := "(" ++ f1.to_format_aux depth ++ " => " ++ f2.to_format_aux depth ++ ")" | e@(holform.iff f1 f2) depth := "(" ++ f1.to_format_aux depth ++ " <=> " ++ f2.to_format_aux depth ++ ")" | e@(holform.conj f1 f2) depth := "(" ++ f1.to_format_aux depth ++ " & " ++ f2.to_format_aux depth ++ ")" | e@(holform.disj f1 f2) depth := "(" ++ f1.to_format_aux depth ++ " | " ++ f2.to_format_aux depth ++ ")" | e@(holform.all n t f) depth := "! [" ++ to_fmt n ++ ":" ++ t.to_format_aux depth ++ "] : " ++ f.to_format_aux (depth + 1) | e@(holform.exist n t f) depth := "? [" ++ to_fmt n ++ ":" ++ t.to_format_aux depth ++ "] : " ++ f.to_format_aux (depth + 1) meta def holtype.to_format (t : holtype) : format := t.to_format_aux 0 meta def holterm.to_format (t : holterm) : format := t.to_format_aux 0 meta def holform.to_format (f : holform) : format := f.to_format_aux 0 meta def holterm.to_name : holterm → name | e := e.to_format.to_string meta def holtype.to_name : holtype → name | e := e.repr -- Convert formula with name and role to output string meta def axiom_to_thf (id : string) (r : role) (f : holform) : format := to_fmt "thf(" ++ to_fmt id ++ "," ++ r.to_format ++ ",(" ++ f.to_format ++ "))." -- Convert formula with name and role to output string meta def typedef_to_thf (id : string) (type_name : name) (t : holtype) : format := to_fmt "thf(" ++ to_fmt id ++ ",type,(" ++ to_fmt type_name ++ " : " ++ t.to_format ++ "))." -- Combine list of axioma, type definitions and conjecture into single string meta def export_formula : list type_def → list axioma → holform → format | (⟨def_n, type_n, t⟩::tds) axiomas conjectures := typedef_to_thf ("'" ++ to_string def_n ++ "'") type_n t ++ "\n\n" ++ export_formula tds axiomas conjectures | [] (⟨n, f⟩::as) conjecture := axiom_to_thf ("'" ++ to_string n ++ "'") role.axioma f ++ "\n\n" ++ export_formula [] as conjecture | [] [] conjecture := axiom_to_thf "'problem_conjecture'" role.conjecture conjecture --------------------- -- DEBUG FUNCTIONS -- --------------------- meta def example_formula : holform := holform.all `test (holtype.ltype `myType) $ holform.eq (holterm.app (holterm.app (holterm.const `h1) (holterm.const `h2)) (holterm.const `test)) (holterm.var 1) meta def example_type : holtype := holtype.dep_binder [(`A, holtype.o), (`B, holtype.i)] $ holtype.functor [holtype.partial_app (holterm.app (holterm.const `map) (holterm.const `A)), holtype.ltype `B] holtype.type meta def example_axiom : axioma := ⟨`test_axiom, example_formula⟩ meta def example_type_def : type_def := ⟨`test_type_def, `myType, example_type⟩ run_cmd do tactic.trace example_formula.to_format run_cmd do tactic.trace example_type.to_format run_cmd do tactic.trace $ export_formula [example_type_def] [example_axiom] example_formula
7f50e9c2e69bdc124a4f29a5db6c2d13c1ad7327
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/data/nat/digits.lean
4082758e5f8e22f90307dffe3308b0bb5c6e70e3
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
15,902
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.int.modeq import tactic.interval_cases import tactic.linarith /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. -/ /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_0 : ℕ → list ℕ | 0 := [] | (n+1) := [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_1 (n : ℕ) : list ℕ := list.repeat 1 n /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux (b : ℕ) (h : 2 ≤ b) : ℕ → list ℕ | 0 := [] | (n+1) := have (n+1)/b < n+1 := nat.div_lt_self (nat.succ_pos _) h, (n+1) % b :: digits_aux ((n+1)/b) @[simp] lemma digits_aux_zero (b : ℕ) (h : 2 ≤ b) : digits_aux b h 0 = [] := rfl lemma digits_aux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digits_aux b h n = n % b :: digits_aux b h (n/b) := begin cases n, { cases w, }, { rw [digits_aux], } end /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `of_digits b L = L.foldr (λ x y, x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = list.repeat 1 n`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `nat.to_digits` in core, which is used for printing numerals. In particular, `nat.to_digits b 0 = [0]`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → list ℕ | 0 := digits_aux_0 | 1 := digits_aux_1 | (b+2) := digits_aux (b+2) (by norm_num) @[simp] lemma digits_zero (b : ℕ) : digits b 0 = [] := begin cases b, { refl, }, { cases b; refl, }, end @[simp] lemma digits_zero_zero : digits 0 0 = [] := rfl @[simp] lemma digits_zero_succ (n : ℕ) : digits 0 (n.succ) = [n+1] := rfl @[simp] lemma digits_one (n : ℕ) : digits 1 n = list.repeat 1 n := rfl @[simp] lemma digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl @[simp] lemma digits_add_two_add_one (b n : ℕ) : digits (b+2) (n+1) = (((n+1) % (b+2)) :: digits (b+2) ((n+1) / (b+2))) := rfl @[simp] lemma digits_of_lt (b x : ℕ) (w₁ : 0 < x) (w₂ : x < b) : digits b x = [x] := begin cases b, { cases w₂ }, { cases b, { interval_cases x, }, { cases x, { cases w₁, }, { dsimp [digits], rw digits_aux, rw nat.div_eq_of_lt w₂, dsimp only [digits_aux_zero], rw nat.mod_eq_of_lt w₂, } } } end /-- The digits in the base b+2 expansion of n are all less than b+2 -/ lemma digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b+2) m → d < b+2 := begin apply nat.strong_induction_on m, intros n IH d hd, unfold digits at hd IH, cases n with n, { cases hd }, -- base b+2 expansion of 0 has no digits rw digits_aux_def (b+2) (by linarith) n.succ (nat.zero_lt_succ n) at hd, cases hd, { rw hd, exact n.succ.mod_lt (by linarith) }, { exact IH _ (nat.div_lt_self (nat.succ_pos _) (by linarith)) hd } end /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ lemma digits_lt_base {b m d : ℕ} (hb : 2 ≤ b) (hd : d ∈ digits b m) : d < b := begin rcases b with _ | _ | b; try {linarith}, exact digits_lt_base' hd, end lemma digits_add (b : ℕ) (h : 2 ≤ b) (x y : ℕ) (w : x < b) (w' : 0 < x ∨ 0 < y) : digits b (x + b * y) = x :: digits b y := begin cases b, { cases h, }, { cases b, { norm_num at h, }, { cases y, { norm_num at w', simp [w, w'], }, dsimp [digits], rw digits_aux_def, { congr, { simp [nat.add_mod, nat.mod_eq_of_lt w], }, { simp [mul_comm (b+2), nat.add_mul_div_right, nat.div_eq_of_lt w], } }, { apply nat.succ_pos, }, }, }, end. /-- `of_digits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. def of_digits {α : Type*} [semiring α] (b : α) : list ℕ → α | [] := 0 | (h :: t) := h + b * of_digits t lemma of_digits_eq_foldr {α : Type*} [semiring α] (b : α) (L : list ℕ) : of_digits b L = L.foldr (λ x y, x + b * y) 0 := begin induction L with d L ih, { refl, }, { dsimp [of_digits], rw ih, }, end @[simp] lemma of_digits_one_cons {α : Type*} [semiring α] (h : ℕ) (L : list ℕ) : of_digits (1 : α) (h :: L) = h + of_digits 1 L := by simp [of_digits] lemma of_digits_append {b : ℕ} {l1 l2 : list ℕ} : of_digits b (l1 ++ l2) = of_digits b l1 + b^(l1.length) * of_digits b l2 := begin induction l1 with hd tl IH, { simp [of_digits] }, { rw [of_digits, list.cons_append, of_digits, IH, list.length_cons, nat.pow_succ], ring } end /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ lemma of_digits_lt_base_pow_length' {b : ℕ} {l : list ℕ} (hl : ∀ x ∈ l, x < b+2) : of_digits (b+2) l < (b+2)^(l.length) := begin induction l with hd tl IH, { simp [of_digits], }, { rw [of_digits, list.length_cons, nat.pow_succ, mul_comm], have : (of_digits (b + 2) tl + 1) * (b+2) ≤ (b + 2) ^ tl.length * (b+2) := mul_le_mul (IH (λ x hx, hl _ (list.mem_cons_of_mem _ hx))) (by refl) dec_trivial (nat.zero_le _), suffices : ↑hd < b + 2, { linarith }, norm_cast, exact hl hd (list.mem_cons_self _ _) } end /-- an n-digit number in base b is less than b^n if b ≥ 2 -/ lemma of_digits_lt_base_pow_length {b : ℕ} {l : list ℕ} (hb : 2 ≤ b) (hl : ∀ x ∈ l, x < b) : of_digits b l < b^l.length := begin rcases b with _ | _ | b; try { linarith }, exact of_digits_lt_base_pow_length' hl, end @[norm_cast] lemma coe_of_digits (α : Type*) [semiring α] (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : α) = of_digits (b : α) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end @[norm_cast] lemma coe_int_of_digits (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : ℤ) = of_digits (b : ℤ) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end lemma digits_zero_of_eq_zero {b : ℕ} (h : 1 ≤ b) {L : list ℕ} (w : of_digits b L = 0) : ∀ l ∈ L, l = 0 := begin induction L with d L ih, { intros l m, cases m, }, { intros l m, dsimp [of_digits] at w, rcases m with rfl, { convert nat.eq_zero_of_add_eq_zero_right w, simp, }, { exact ih ((nat.mul_right_inj h).mp (nat.eq_zero_of_add_eq_zero_left w)) _ m, }, } end lemma digits_of_digits (b : ℕ) (h : 2 ≤ b) (L : list ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ (h : L ≠ []), L.last h ≠ 0) : digits b (of_digits b L) = L := begin induction L with d L ih, { dsimp [of_digits], simp }, { dsimp [of_digits], replace w₂ := w₂ (by simp), rw digits_add b h, { rw ih, { simp, }, { intros l m, apply w₁, exact list.mem_cons_of_mem _ m, }, { intro h, { rw [list.last_cons _ h] at w₂, convert w₂, }}}, { convert w₁ d (list.mem_cons_self _ _), simp, }, { by_cases h' : L = [], { rcases h' with rfl, simp at w₂, left, apply nat.pos_of_ne_zero, convert w₂, simp, }, { right, apply nat.pos_of_ne_zero, contrapose! w₂, apply digits_zero_of_eq_zero _ w₂, { rw list.last_cons _ h', exact list.last_mem h', }, { exact le_of_lt h, }, }, }, }, end lemma of_digits_digits (b n : ℕ) : of_digits b (digits b n) = n := begin cases b with b, { cases n with n, { refl, }, { change of_digits 0 [n+1] = n+1, dsimp [of_digits], simp, } }, { cases b with b, { induction n with n ih, { refl, }, { simp only [ih, add_comm 1, of_digits_one_cons, nat.cast_id, digits_one_succ], } }, { apply nat.strong_induction_on n _, clear n, intros n h, cases n, { refl, }, { simp only [nat.succ_eq_add_one, digits_add_two_add_one], dsimp [of_digits], rw h _ (nat.div_lt_self' n b), rw [nat.cast_id, nat.mod_add_div], }, }, }, end lemma of_digits_one (L : list ℕ) : of_digits 1 L = L.sum := begin induction L with d L ih, { refl, }, { simp [of_digits, list.sum_cons, ih], } end /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ lemma lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := begin convert of_digits_lt_base_pow_length' (λ _, digits_lt_base'), rw of_digits_digits (b+2) m, end /-- Any number m is less than b^(number of digits in the base b representation of m) -/ lemma lt_base_pow_length_digits {b m : ℕ} (hb : 2 ≤ b) : m < b^(digits b m).length := begin rcases b with _ | _ | b; try { linarith }, exact lt_base_pow_length_digits', end lemma of_digits_digits_append_digits {b m n : ℕ} : of_digits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m:= by rw [of_digits_append, of_digits_digits, of_digits_digits] -- This is really a theorem about polynomials. lemma dvd_of_digits_sub_of_digits {α : Type*} [comm_ring α] {a b k : α} (h : k ∣ a - b) (L : list ℕ) : k ∣ of_digits a L - of_digits b L := begin induction L with d L ih, { change k ∣ 0 - 0, simp, }, { simp only [of_digits, add_sub_add_left_eq_sub], exact dvd_mul_sub_mul h ih, } end lemma of_digits_modeq' (b b' : ℕ) (k : ℕ) (h : b ≡ b' [MOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [MOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [nat.modeq] at *, conv_lhs { rw [nat.add_mod, nat.mul_mod, h, ih], }, conv_rhs { rw [nat.add_mod, nat.mul_mod], }, } end lemma of_digits_modeq (b k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [MOD k] := of_digits_modeq' b (b % k) k (nat.modeq.symm (nat.modeq.mod_modeq b k)) L lemma of_digits_mod (b k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_modeq b k L lemma of_digits_zmodeq' (b b' : ℤ) (k : ℕ) (h : b ≡ b' [ZMOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [ZMOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [int.modeq] at *, conv_lhs { rw [int.add_mod, int.mul_mod, h, ih], }, conv_rhs { rw [int.add_mod, int.mul_mod], }, } end lemma of_digits_zmodeq (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [ZMOD k] := of_digits_zmodeq' b (b % k) k (int.modeq.symm (int.modeq.mod_modeq b ↑k)) L lemma of_digits_zmod (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_zmodeq b k L lemma modeq_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : n ≡ (digits b' n).sum [MOD b] := begin rw ←of_digits_one, conv { congr, skip, rw ←(of_digits_digits b' n) }, convert of_digits_modeq _ _ _, exact h.symm, end lemma modeq_three_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 3] := modeq_digits_sum 3 10 (by norm_num) n lemma modeq_nine_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 9] := modeq_digits_sum 9 10 (by norm_num) n lemma dvd_iff_dvd_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ (digits b' n).sum := begin rw ←of_digits_one, conv_lhs { rw ←(of_digits_digits b' n) }, rw [nat.dvd_iff_mod_eq_zero, nat.dvd_iff_mod_eq_zero, of_digits_mod, h], end lemma three_dvd_iff (n : ℕ) : 3 ∣ n ↔ 3 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 3 10 (by norm_num) n lemma nine_dvd_iff (n : ℕ) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by norm_num) n lemma zmodeq_of_digits_digits (b b' : ℕ) (c : ℤ) (h : b' ≡ c [ZMOD b]) (n : ℕ) : n ≡ of_digits c (digits b' n) [ZMOD b] := begin conv { congr, skip, rw ←(of_digits_digits b' n) }, rw coe_int_of_digits, apply of_digits_zmodeq' _ _ _ h, end lemma of_digits_neg_one : Π (L : list ℕ), of_digits (-1 : ℤ) L = (L.map (λ n : ℕ, (n : ℤ))).alternating_sum | [] := rfl | [n] := by simp [of_digits, list.alternating_sum] | (a :: b :: t) := begin simp only [of_digits, list.alternating_sum, list.map_cons, of_digits_neg_one t], push_cast, ring, end lemma modeq_eleven_digits_sum (n : ℕ) : n ≡ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum [ZMOD 11] := begin have t := zmodeq_of_digits_digits 11 10 (-1 : ℤ) dec_trivial n, rw of_digits_neg_one at t, exact t, end lemma dvd_iff_dvd_of_digits (b b' : ℕ) (c : ℤ) (h : (b : ℤ) ∣ (b' : ℤ) - c) (n : ℕ) : b ∣ n ↔ (b : ℤ) ∣ of_digits c (digits b' n) := begin rw ←int.coe_nat_dvd, exact dvd_iff_dvd_of_dvd_sub (int.modeq.modeq_iff_dvd.1 (zmodeq_of_digits_digits b b' c (int.modeq.modeq_iff_dvd.2 h).symm _).symm), end lemma eleven_dvd_iff (n : ℕ) : 11 ∣ n ↔ (11 : ℤ) ∣ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum := begin have t := dvd_iff_dvd_of_digits 11 10 (-1 : ℤ) (by norm_num) n, rw of_digits_neg_one at t, exact t, end lemma digits_len_le_digits_len_succ (b n : ℕ) : (digits b n).length ≤ (digits b (n + 1)).length := begin cases b, { -- base 0 cases n; simp }, { cases b, { -- base 1 simp }, { -- base >= 2 apply nat.strong_induction_on n, clear n, intros n IH, cases n, { simp }, { rw [digits_add_two_add_one, digits_add_two_add_one], by_cases hdvd : (b.succ.succ) ∣ (n.succ+1), { rw [nat.succ_div_of_dvd hdvd, list.length_cons, list.length_cons, nat.succ_le_succ_iff], apply IH, exact nat.div_lt_self (by linarith) (by linarith) }, { rw nat.succ_div_of_not_dvd hdvd, refl } } } } end lemma le_digits_len_le (b n m : ℕ) (h : n ≤ m) : (digits b n).length ≤ (digits b m).length := monotone_of_monotone_nat (digits_len_le_digits_len_succ b) h -- future refactor to proof using lists (see lt_base_pow_length_digits) lemma base_pow_length_digits_le' (b m : ℕ) : m ≠ 0 → (b + 2) ^ ((digits (b + 2) m).length) ≤ (b + 2) * m := begin apply nat.strong_induction_on m, clear m, intros n IH npos, cases n, { contradiction }, { unfold digits at IH ⊢, rw [digits_aux_def (b+2) (by simp) n.succ nat.succ_pos', list.length_cons], specialize IH ((n.succ) / (b+2)) (nat.div_lt_self' n b), rw [nat.pow_add, nat.pow_one, nat.mul_comm], cases nat.lt_or_ge n.succ (b+2), { rw [nat.div_eq_of_lt h, digits_aux_zero, list.length, nat.pow_zero], apply nat.mul_le_mul_left, exact nat.succ_pos n }, { have geb : (n.succ / (b + 2)) ≥ 1 := nat.div_pos h (by linarith), specialize IH (by linarith [geb]), replace IH := nat.mul_le_mul_left (b + 2) IH, have IH' : (b + 2) * ((b + 2) * (n.succ / (b + 2))) ≤ (b + 2) * n.succ, { apply nat.mul_le_mul_left, rw nat.mul_comm, exact nat.div_mul_le_self n.succ (b + 2) }, exact le_trans IH IH' } } end lemma base_pow_length_digits_le (b m : ℕ) (hb : 2 ≤ b): m ≠ 0 → b ^ ((digits b m).length) ≤ b * m := begin rcases b with _ | _ | b; try { linarith }, exact base_pow_length_digits_le' b m, end
81b682f0779875d1a4bebd73cbfc948fcea98236
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/field_theory/perfect_closure.lean
3921be78a35e2ee46ef7f2b283256e5f150c83a4
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
16,665
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau The perfect closure of a field. -/ import algebra.char_p universes u v /-- A perfect field is a field of characteristic p that has p-th root. -/ class perfect_field (α : Type u) [field α] (p : ℕ) [char_p α p] : Type u := (pth_root : α → α) (frobenius_pth_root : ∀ x, frobenius α p (pth_root x) = x) theorem frobenius_pth_root (α : Type u) [field α] (p : ℕ) [char_p α p] [perfect_field α p] (x : α) : frobenius α p (perfect_field.pth_root p x) = x := perfect_field.frobenius_pth_root p x theorem pth_root_frobenius (α : Type u) [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] (x : α) : perfect_field.pth_root p (frobenius α p x) = x := frobenius_inj α p _ _ (by rw frobenius_pth_root) instance pth_root.is_ring_hom (α : Type u) [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] : is_ring_hom (@perfect_field.pth_root α _ p _ _) := { map_one := frobenius_inj α p _ _ (by rw [frobenius_pth_root, frobenius_one]), map_mul := λ x y, frobenius_inj α p _ _ (by simp only [frobenius_pth_root, frobenius_mul]), map_add := λ x y, frobenius_inj α p _ _ (by simp only [frobenius_pth_root, frobenius_add]) } theorem is_ring_hom.pth_root {α : Type u} [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] {β : Type v} [field β] [char_p β p] [perfect_field β p] (f : α → β) [is_ring_hom f] {x : α} : f (perfect_field.pth_root p x) = perfect_field.pth_root p (f x) := frobenius_inj β p _ _ (by rw [← is_monoid_hom.map_frobenius f, frobenius_pth_root, frobenius_pth_root]) inductive perfect_closure.r (α : Type u) [monoid α] (p : ℕ) : (ℕ × α) → (ℕ × α) → Prop | intro : ∀ n x, perfect_closure.r (n, x) (n+1, frobenius α p x) run_cmd tactic.mk_iff_of_inductive_prop `perfect_closure.r `perfect_closure.r_iff /-- The perfect closure is the smallest extension that makes frobenius surjective. -/ def perfect_closure (α : Type u) [monoid α] (p : ℕ) : Type u := quot (perfect_closure.r α p) namespace perfect_closure variables (α : Type u) private lemma mul_aux_left [comm_monoid α] (p : ℕ) (x1 x2 y : ℕ × α) (H : r α p x1 x2) : quot.mk (r α p) (x1.1 + y.1, ((frobenius α p)^[y.1] x1.2) * ((frobenius α p)^[x1.1] y.2)) = quot.mk (r α p) (x2.1 + y.1, ((frobenius α p)^[y.1] x2.2) * ((frobenius α p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro _ n x := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ', nat.iterate_succ', ← frobenius_mul, nat.succ_add]; apply r.intro end private lemma mul_aux_right [comm_monoid α] (p : ℕ) (x y1 y2 : ℕ × α) (H : r α p y1 y2) : quot.mk (r α p) (x.1 + y1.1, ((frobenius α p)^[y1.1] x.2) * ((frobenius α p)^[x.1] y1.2)) = quot.mk (r α p) (x.1 + y2.1, ((frobenius α p)^[y2.1] x.2) * ((frobenius α p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro _ n y := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ', nat.iterate_succ', ← frobenius_mul]; apply r.intro end instance [comm_monoid α] (p : ℕ) : has_mul (perfect_closure α p) := ⟨quot.lift (λ x:ℕ×α, quot.lift (λ y:ℕ×α, quot.mk (r α p) (x.1 + y.1, ((frobenius α p)^[y.1] x.2) * ((frobenius α p)^[x.1] y.2))) (mul_aux_right α p x)) (λ x1 x2 (H : r α p x1 x2), funext $ λ e, quot.induction_on e $ λ y, mul_aux_left α p x1 x2 y H)⟩ instance [comm_monoid α] (p : ℕ) : comm_monoid (perfect_closure α p) := { mul_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, mul_assoc, nat.iterate₂ (frobenius_mul _ _), (nat.iterate_add _ _ _ _).symm, add_comm, add_left_comm], one := quot.mk _ (0, 1), one_mul := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate_zero, one_mul, zero_add]), mul_one := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate_zero, mul_one, add_zero]), mul_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm, mul_comm])), .. (infer_instance : has_mul (perfect_closure α p)) } instance [comm_monoid α] (p) : inhabited (perfect_closure α p) := ⟨1⟩ private lemma add_aux_left [comm_ring α] (p : ℕ) (hp : nat.prime p) [char_p α p] (x1 x2 y : ℕ × α) (H : r α p x1 x2) : quot.mk (r α p) (x1.1 + y.1, ((frobenius α p)^[y.1] x1.2) + ((frobenius α p)^[x1.1] y.2)) = quot.mk (r α p) (x2.1 + y.1, ((frobenius α p)^[y.1] x2.2) + ((frobenius α p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro _ n x := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ', nat.iterate_succ', ← frobenius_add, nat.succ_add]; apply r.intro end private lemma add_aux_right [comm_ring α] (p : ℕ) (hp : nat.prime p) [char_p α p] (x y1 y2 : ℕ × α) (H : r α p y1 y2) : quot.mk (r α p) (x.1 + y1.1, ((frobenius α p)^[y1.1] x.2) + ((frobenius α p)^[x.1] y1.2)) = quot.mk (r α p) (x.1 + y2.1, ((frobenius α p)^[y2.1] x.2) + ((frobenius α p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro _ n y := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ', nat.iterate_succ', ← frobenius_add]; apply r.intro end instance [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : has_add (perfect_closure α p) := ⟨quot.lift (λ x:ℕ×α, quot.lift (λ y:ℕ×α, quot.mk (r α p) (x.1 + y.1, ((frobenius α p)^[y.1] x.2) + ((frobenius α p)^[x.1] y.2))) (add_aux_right α p hp x)) (λ x1 x2 (H : r α p x1 x2), funext $ λ e, quot.induction_on e $ λ y, add_aux_left α p hp x1 x2 y H)⟩ instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : has_neg (perfect_closure α p) := ⟨quot.lift (λ x:ℕ×α, quot.mk (r α p) (x.1, -x.2)) (λ x y (H : r α p x y), match x, y, H with | _, _, r.intro _ n x := quot.sound $ by rw ← frobenius_neg; apply r.intro end)⟩ theorem mk_zero [comm_ring α] (p : ℕ) [nat.prime p] (n : ℕ) : quot.mk (r α p) (n, 0) = quot.mk (r α p) (0, 0) := by induction n with n ih; [refl, rw ← ih]; symmetry; apply quot.sound; have := r.intro p n (0:α); rwa [frobenius_zero α p] at this theorem r.sound [monoid α] (p m n : ℕ) (x y : α) (H : frobenius α p^[m] x = y) : quot.mk (r α p) (n, x) = quot.mk (r α p) (m + n, y) := by subst H; induction m with m ih; [simp only [zero_add, nat.iterate_zero], rw [ih, nat.succ_add, nat.iterate_succ']]; apply quot.sound; apply r.intro instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : comm_ring (perfect_closure α p) := { add_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, nat.iterate₂ (frobenius_add α p), (nat.iterate_add _ _ _ _).symm, add_comm, add_left_comm], zero := quot.mk _ (0, 0), zero_add := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, zero_add]), add_zero := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, add_zero]), add_left_neg := λ e, quot.induction_on e (λ ⟨n, x⟩, show quot.mk _ _ = _, by simp only [nat.iterate₁ (frobenius_neg α p), add_left_neg, mk_zero]; refl), add_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm])), left_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm, add_left_comm]; apply r.sound; simp only [nat.iterate₂ (frobenius_mul α p), nat.iterate₂ (frobenius_add α p), (nat.iterate_add _ _ _ _).symm, mul_add, add_comm, add_left_comm], right_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm _ s, add_left_comm _ s]; apply r.sound; simp only [nat.iterate₂ (frobenius_mul α p), nat.iterate₂ (frobenius_add α p), (nat.iterate_add _ _ _ _).symm, add_mul, add_comm, add_left_comm], .. (infer_instance : has_add (perfect_closure α p)), .. (infer_instance : has_neg (perfect_closure α p)), .. (infer_instance : comm_monoid (perfect_closure α p)) } instance [field α] (p : ℕ) [nat.prime p] [char_p α p] : has_inv (perfect_closure α p) := ⟨quot.lift (λ x:ℕ×α, quot.mk (r α p) (x.1, x.2⁻¹)) (λ x y (H : r α p x y), match x, y, H with | _, _, r.intro _ n x := quot.sound $ by simp only [frobenius]; rw ← inv_pow'; apply r.intro end)⟩ theorem eq_iff' [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x y : ℕ × α) : quot.mk (r α p) x = quot.mk (r α p) y ↔ ∃ z, (frobenius α p^[y.1 + z] x.2) = (frobenius α p^[x.1 + z] y.2) := begin split, { intro H, replace H := quot.exact _ H, induction H, case eqv_gen.rel : x y H { cases H with n x, exact ⟨0, rfl⟩ }, case eqv_gen.refl : H { exact ⟨0, rfl⟩ }, case eqv_gen.symm : x y H ih { cases ih with w ih, exact ⟨w, ih.symm⟩ }, case eqv_gen.trans : x y z H1 H2 ih1 ih2 { cases ih1 with z1 ih1, cases ih2 with z2 ih2, existsi z2+(y.1+z1), rw [← add_assoc, nat.iterate_add, ih1], rw [← nat.iterate_add, add_comm, nat.iterate_add, ih2], rw [← nat.iterate_add], simp only [add_comm, add_left_comm] } }, intro H, cases x with m x, cases y with n y, cases H with z H, dsimp only at H, rw [r.sound α p (n+z) m x _ rfl, r.sound α p (m+z) n y _ rfl, H], rw [add_assoc, add_comm, add_comm z] end theorem eq_iff [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] (x y : ℕ × α) : quot.mk (r α p) x = quot.mk (r α p) y ↔ (frobenius α p^[y.1] x.2) = (frobenius α p^[x.1] y.2) := (eq_iff' α p x y).trans ⟨λ ⟨z, H⟩, nat.iterate_inj (frobenius_inj α p) z _ _ $ by simpa only [add_comm, nat.iterate_add] using H, λ H, ⟨0, H⟩⟩ instance [field α] (p : ℕ) [nat.prime p] [char_p α p] : field (perfect_closure α p) := { zero_ne_one := λ H, zero_ne_one ((eq_iff _ _ _ _).1 H), mul_inv_cancel := λ e, quot.induction_on e $ λ ⟨m, x⟩ H, have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2 (by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, (nat.iterate₂ (frobenius_mul α p)).symm] at this ⊢; rw [mul_inv_cancel this, nat.iterate₀ (frobenius_one _ _)]), inv_zero := congr_arg (quot.mk (r α p)) (by rw [inv_zero]), .. (infer_instance : has_inv (perfect_closure α p)), .. (infer_instance : comm_ring (perfect_closure α p)) } theorem frobenius_mk [comm_monoid α] (p : ℕ) (x : ℕ × α) : frobenius (perfect_closure α p) p (quot.mk (r α p) x) = quot.mk _ (x.1, x.2^p) := begin unfold frobenius, cases x with n x, dsimp only, suffices : ∀ p':ℕ, (quot.mk (r α p) (n, x) ^ p' : perfect_closure α p) = quot.mk (r α p) (n, x ^ p'), { apply this }, intro p, induction p with p ih, case nat.zero { apply r.sound, rw [nat.iterate₀ (frobenius_one _ _), pow_zero] }, case nat.succ { rw [pow_succ, ih], symmetry, apply r.sound, simp only [pow_succ, nat.iterate₂ (frobenius_mul _ _)] } end def frobenius_equiv [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : perfect_closure α p ≃ perfect_closure α p := { to_fun := frobenius (perfect_closure α p) p, inv_fun := λ e, quot.lift_on e (λ x, quot.mk (r α p) (x.1 + 1, x.2)) (λ x y H, match x, y, H with | _, _, r.intro _ n x := quot.sound (r.intro _ _ _) end), left_inv := λ e, quot.induction_on e (λ ⟨m, x⟩, by rw frobenius_mk; symmetry; apply quot.sound; apply r.intro), right_inv := λ e, quot.induction_on e (λ ⟨m, x⟩, by rw frobenius_mk; symmetry; apply quot.sound; apply r.intro) } theorem frobenius_equiv_apply [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] {x : perfect_closure α p} : frobenius_equiv α p x = frobenius _ p x := rfl theorem nat_cast [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (n x : ℕ) : (x : perfect_closure α p) = quot.mk (r α p) (n, x) := begin induction n with n ih, { induction x with x ih, {refl}, rw [nat.cast_succ, nat.cast_succ, ih], refl }, rw ih, apply quot.sound, conv {congr, skip, skip, rw ← frobenius_nat_cast α p x}, apply r.intro end theorem int_cast [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℤ) : (x : perfect_closure α p) = quot.mk (r α p) (0, x) := by induction x; simp only [int.cast_of_nat, int.cast_neg_succ_of_nat, nat_cast α p 0]; refl theorem nat_cast_eq_iff [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x y : ℕ) : (x : perfect_closure α p) = y ↔ (x : α) = y := begin split; intro H, { rw [nat_cast α p 0, nat_cast α p 0, eq_iff'] at H, cases H with z H, simpa only [zero_add, nat.iterate₀ (frobenius_nat_cast α p _)] using H }, rw [nat_cast α p 0, nat_cast α p 0, H] end instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : char_p (perfect_closure α p) p := begin constructor, intro x, rw ← char_p.cast_eq_zero_iff α, rw [← nat.cast_zero, nat_cast_eq_iff, nat.cast_zero] end instance [field α] (p : ℕ) [nat.prime p] [char_p α p] : perfect_field (perfect_closure α p) p := { pth_root := (frobenius_equiv α p).symm, frobenius_pth_root := (frobenius_equiv α p).apply_symm_apply } def of [monoid α] (p : ℕ) (x : α) : perfect_closure α p := quot.mk _ (0, x) instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : is_ring_hom (of α p) := { map_one := rfl, map_mul := λ x y, rfl, map_add := λ x y, rfl } theorem eq_pth_root [field α] (p : ℕ) [nat.prime p] [char_p α p] (m : ℕ) (x : α) : quot.mk (r α p) (m, x) = (perfect_field.pth_root p^[m] (of α p x) : perfect_closure α p) := begin unfold of, induction m with m ih, {refl}, rw [nat.iterate_succ', ← ih]; refl end def UMP [field α] (p : ℕ) [nat.prime p] [char_p α p] (β : Type v) [field β] [char_p β p] [perfect_field β p] : { f : α → β // is_ring_hom f } ≃ { f : perfect_closure α p → β // is_ring_hom f } := { to_fun := λ f, ⟨λ e, quot.lift_on e (λ x, perfect_field.pth_root p^[x.1] (f.1 x.2)) (λ x y H, match x, y, H with | _, _, r.intro _ n x := by letI := f.2; simp only [is_monoid_hom.map_frobenius f.1, nat.iterate_succ, pth_root_frobenius] end), show f.1 1 = 1, from f.2.1, λ j k, quot.induction_on j $ λ ⟨m, x⟩, quot.induction_on k $ λ ⟨n, y⟩, show (perfect_field.pth_root p^[_] _) = (perfect_field.pth_root p^[_] _) * (perfect_field.pth_root p^[_] _), by letI := f.2; simp only [is_ring_hom.map_mul f.1, (nat.iterate₁ (λ x, (is_monoid_hom.map_frobenius f.1 p x).symm)).symm, @nat.iterate₂ β _ (*) (λ x y, is_ring_hom.map_mul (perfect_field.pth_root p))]; rw [nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p), add_comm, nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p)], λ j k, quot.induction_on j $ λ ⟨m, x⟩, quot.induction_on k $ λ ⟨n, y⟩, show (perfect_field.pth_root p^[_] _) = (perfect_field.pth_root p^[_] _) + (perfect_field.pth_root p^[_] _), by letI := f.2; simp only [is_ring_hom.map_add f.1, (nat.iterate₁ (λ x, (is_monoid_hom.map_frobenius f.1 p x).symm)).symm, @nat.iterate₂ β _ (+) (λ x y, is_ring_hom.map_add (perfect_field.pth_root p))]; rw [nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p), add_comm m, nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p)]⟩, inv_fun := λ f, ⟨f.1 ∘ of α p, @@is_ring_hom.comp _ _ _ _ _ _ f.2⟩, left_inv := λ ⟨f, hf⟩, subtype.eq rfl, right_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ i, quot.induction_on i $ λ ⟨m, x⟩, show perfect_field.pth_root p^[m] (f _) = f _, by resetI; rw [eq_pth_root, @nat.iterate₁ _ _ _ _ f (λ x:perfect_closure α p, (is_ring_hom.pth_root p f).symm)] } end perfect_closure
17566cc4d4aaef66808fe3baf217af131b1ef130
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/continuous_function/zero_at_infty.lean
252957f0c600094eef93c0715accb491f1a00d64
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
22,502
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import topology.continuous_function.bounded import topology.continuous_function.cocompact_map /-! # Continuous functions vanishing at infinity The type of continuous functions vanishing at infinity. When the domain is compact `C(α, β) ≃ C₀(α, β)` via the identity map. When the codomain is a metric space, every continuous map which vanishes at infinity is a bounded continuous function. When the domain is a locally compact space, this type has nice properties. ## TODO * Create more intances of algebraic structures (e.g., `non_unital_semiring`) once the necessary type classes (e.g., `topological_ring`) are sufficiently generalized. * Relate the unitization of `C₀(α, β)` to the Alexandroff compactification. -/ universes u v w variables {F : Type*} {α : Type u} {β : Type v} {γ : Type w} [topological_space α] open_locale bounded_continuous_function topological_space open filter metric /-- `C₀(α, β)` is the type of continuous functions `α → β` which vanish at infinity from a topological space to a metric space with a zero element. When possible, instead of parametrizing results over `(f : C₀(α, β))`, you should parametrize over `(F : Type*) [zero_at_infty_continuous_map_class F α β] (f : F)`. When you extend this structure, make sure to extend `zero_at_infty_continuous_map_class`. -/ structure zero_at_infty_continuous_map (α : Type u) (β : Type v) [topological_space α] [has_zero β] [topological_space β] extends continuous_map α β : Type (max u v) := (zero_at_infty' : tendsto to_fun (cocompact α) (𝓝 0)) localized "notation [priority 2000] `C₀(` α `, ` β `)` := zero_at_infty_continuous_map α β" in zero_at_infty localized "notation α ` →C₀ ` β := zero_at_infty_continuous_map α β" in zero_at_infty /-- `zero_at_infty_continuous_map_class F α β` states that `F` is a type of continuous maps which vanish at infinity. You should also extend this typeclass when you extend `zero_at_infty_continuous_map`. -/ class zero_at_infty_continuous_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [has_zero β] [topological_space β] extends continuous_map_class F α β := (zero_at_infty (f : F) : tendsto f (cocompact α) (𝓝 0)) export zero_at_infty_continuous_map_class (zero_at_infty) namespace zero_at_infty_continuous_map section basics variables [topological_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β] instance : zero_at_infty_continuous_map_class C₀(α, β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_continuous := λ f, f.continuous_to_fun, zero_at_infty := λ f, f.zero_at_infty' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun C₀(α, β) (λ _, α → β) := fun_like.has_coe_to_fun instance : has_coe_t F C₀(α, β) := ⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f, zero_at_infty' := zero_at_infty f }⟩ @[simp] lemma coe_to_continuous_fun (f : C₀(α, β)) : (f.to_continuous_map : α → β) = f := rfl @[ext] lemma ext {f g : C₀(α, β)} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h /-- Copy of a `zero_at_infinity_continuous_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : C₀(α, β)) (f' : α → β) (h : f' = f) : C₀(α, β) := { to_fun := f', continuous_to_fun := by { rw h, exact f.continuous_to_fun }, zero_at_infty' := by { simp_rw h, exact f.zero_at_infty' } } lemma eq_of_empty [is_empty α] (f g : C₀(α, β)) : f = g := ext $ is_empty.elim ‹_› /-- A continuous function on a compact space is automatically a continuous function vanishing at infinity. -/ @[simps] def continuous_map.lift_zero_at_infty [compact_space α] : C(α, β) ≃ C₀(α, β) := { to_fun := λ f, { to_fun := f, continuous_to_fun := f.continuous, zero_at_infty' := by simp }, inv_fun := λ f, f, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- A continuous function on a compact space is automatically a continuous function vanishing at infinity. This is not an instance to avoid type class loops. -/ @[simps] def zero_at_infty_continuous_map_class.of_compact {G : Type*} [continuous_map_class G α β] [compact_space α] : zero_at_infty_continuous_map_class G α β := { coe := λ g, g, coe_injective' := λ f g h, fun_like.coe_fn_eq.mp h, map_continuous := map_continuous, zero_at_infty := by simp } end basics /-! ### Algebraic structure Whenever `β` has suitable algebraic structure and a compatible topological structure, then `C₀(α, β)` inherits a corresponding algebraic structure. The primary exception to this is that `C₀(α, β)` will not have a multiplicative identity. -/ section algebraic_structure variables [topological_space β] (x : α) instance [has_zero β] : has_zero C₀(α, β) := ⟨⟨0, tendsto_const_nhds⟩⟩ instance [has_zero β] : inhabited C₀(α, β) := ⟨0⟩ @[simp] lemma coe_zero [has_zero β] : ⇑(0 : C₀(α, β)) = 0 := rfl lemma zero_apply [has_zero β] : (0 : C₀(α, β)) x = 0 := rfl instance [mul_zero_class β] [has_continuous_mul β] : has_mul C₀(α, β) := ⟨λ f g, ⟨f * g, by simpa only [mul_zero] using (zero_at_infty f).mul (zero_at_infty g)⟩⟩ @[simp] lemma coe_mul [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) : ⇑(f * g) = f * g := rfl lemma mul_apply [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) : (f * g) x = f x * g x := rfl instance [mul_zero_class β] [has_continuous_mul β] : mul_zero_class C₀(α, β) := fun_like.coe_injective.mul_zero_class _ coe_zero coe_mul instance [semigroup_with_zero β] [has_continuous_mul β] : semigroup_with_zero C₀(α, β) := fun_like.coe_injective.semigroup_with_zero _ coe_zero coe_mul instance [add_zero_class β] [has_continuous_add β] : has_add C₀(α, β) := ⟨λ f g, ⟨f + g, by simpa only [add_zero] using (zero_at_infty f).add (zero_at_infty g)⟩⟩ @[simp] lemma coe_add [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) : ⇑(f + g) = f + g := rfl lemma add_apply [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) : (f + g) x = f x + g x := rfl instance [add_zero_class β] [has_continuous_add β] : add_zero_class C₀(α, β) := fun_like.coe_injective.add_zero_class _ coe_zero coe_add section add_monoid variables [add_monoid β] [has_continuous_add β] (f g : C₀(α, β)) @[simp] lemma coe_nsmul_rec : ∀ n, ⇑(nsmul_rec n f) = n • f | 0 := by rw [nsmul_rec, zero_smul, coe_zero] | (n + 1) := by rw [nsmul_rec, succ_nsmul, coe_add, coe_nsmul_rec] instance has_nat_scalar : has_scalar ℕ C₀(α, β) := ⟨λ n f, ⟨n • f, by simpa [coe_nsmul_rec] using zero_at_infty (nsmul_rec n f)⟩⟩ instance : add_monoid C₀(α, β) := fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, rfl) end add_monoid instance [add_comm_monoid β] [has_continuous_add β] : add_comm_monoid C₀(α, β) := fun_like.coe_injective.add_comm_monoid _ coe_zero coe_add (λ _ _, rfl) section add_group variables [add_group β] [topological_add_group β] (f g : C₀(α, β)) instance : has_neg C₀(α, β) := ⟨λ f, ⟨-f, by simpa only [neg_zero] using (zero_at_infty f).neg⟩⟩ @[simp] lemma coe_neg : ⇑(-f) = -f := rfl lemma neg_apply : (-f) x = -f x := rfl instance : has_sub C₀(α, β) := ⟨λ f g, ⟨f - g, by simpa only [sub_zero] using (zero_at_infty f).sub (zero_at_infty g)⟩⟩ @[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl lemma sub_apply : (f - g) x = f x - g x := rfl @[simp] lemma coe_zsmul_rec : ∀ z, ⇑(zsmul_rec z f) = z • f | (int.of_nat n) := by rw [zsmul_rec, int.of_nat_eq_coe, coe_nsmul_rec, coe_nat_zsmul] | -[1+ n] := by rw [zsmul_rec, zsmul_neg_succ_of_nat, coe_neg, coe_nsmul_rec] instance has_int_scalar : has_scalar ℤ C₀(α, β) := ⟨λ n f, ⟨n • f, by simpa using zero_at_infty (zsmul_rec n f)⟩⟩ instance : add_group C₀(α, β) := fun_like.coe_injective.add_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) end add_group instance [add_comm_group β] [topological_add_group β] : add_comm_group C₀(α, β) := fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] : has_scalar R C₀(α, β) := ⟨λ r f, ⟨r • f, by simpa [smul_zero] using (zero_at_infty f).const_smul r⟩⟩ @[simp] lemma coe_smul [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) : ⇑(r • f) = r • f := rfl lemma smul_apply [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) (x : α) : (r • f) x = r • f x := rfl instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [smul_with_zero Rᵐᵒᵖ β] [has_continuous_const_smul R β] [is_central_scalar R β] : is_central_scalar R C₀(α, β) := ⟨λ r f, ext $ λ x, op_smul_eq_smul _ _⟩ instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [has_continuous_const_smul R β] : smul_with_zero R C₀(α, β) := function.injective.smul_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul instance [has_zero β] {R : Type*} [monoid_with_zero R] [mul_action_with_zero R β] [has_continuous_const_smul R β] : mul_action_with_zero R C₀(α, β) := function.injective.mul_action_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul instance [add_comm_monoid β] [has_continuous_add β] {R : Type*} [semiring R] [module R β] [has_continuous_const_smul R β] : module R C₀(α, β) := function.injective.module R ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul instance [non_unital_non_assoc_semiring β] [topological_semiring β] : non_unital_non_assoc_semiring C₀(α, β) := fun_like.coe_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_semiring β] [topological_semiring β] : non_unital_semiring C₀(α, β) := fun_like.coe_injective.non_unital_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_comm_semiring β] [topological_semiring β] : non_unital_comm_semiring C₀(α, β) := fun_like.coe_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_non_assoc_ring β] [topological_ring β] : non_unital_non_assoc_ring C₀(α, β) := fun_like.coe_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_ring β] [topological_ring β] : non_unital_ring C₀(α, β) := fun_like.coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_comm_ring β] [topological_ring β] : non_unital_comm_ring C₀(α, β) := fun_like.coe_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β] [module R β] [has_continuous_const_smul R β] [is_scalar_tower R β β] : is_scalar_tower R C₀(α, β) C₀(α, β) := { smul_assoc := λ r f g, begin ext, simp only [smul_eq_mul, coe_mul, coe_smul, pi.mul_apply, pi.smul_apply], rw [←smul_eq_mul, ←smul_eq_mul, smul_assoc], end } instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β] [module R β] [has_continuous_const_smul R β] [smul_comm_class R β β] : smul_comm_class R C₀(α, β) C₀(α, β) := { smul_comm := λ r f g, begin ext, simp only [smul_eq_mul, coe_smul, coe_mul, pi.smul_apply, pi.mul_apply], rw [←smul_eq_mul, ←smul_eq_mul, smul_comm], end } end algebraic_structure /-! ### Metric structure When `β` is a metric space, then every element of `C₀(α, β)` is bounded, and so there is a natural inclusion map `zero_at_infty_continuous_map.to_bcf : C₀(α, β) → (α →ᵇ β)`. Via this map `C₀(α, β)` inherits a metric as the pullback of the metric on `α →ᵇ β`. Moreover, this map has closed range in `α →ᵇ β` and consequently `C₀(α, β)` is a complete space whenever `β` is complete. -/ section metric open metric set variables [metric_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β] protected lemma bounded (f : F) : ∃ C, ∀ x y : α, dist ((f : α → β) x) (f y) ≤ C := begin obtain ⟨K : set α, hK₁, hK₂⟩ := mem_cocompact.mp (tendsto_def.mp (zero_at_infty (f : F)) _ (closed_ball_mem_nhds (0 : β) zero_lt_one)), obtain ⟨C, hC⟩ := (hK₁.image (map_continuous f)).bounded.subset_ball (0 : β), refine ⟨max C 1 + max C 1, (λ x y, _)⟩, have : ∀ x, f x ∈ closed_ball (0 : β) (max C 1), { intro x, by_cases hx : x ∈ K, { exact (mem_closed_ball.mp $ hC ⟨x, hx, rfl⟩).trans (le_max_left _ _) }, { exact (mem_closed_ball.mp $ mem_preimage.mp (hK₂ hx)).trans (le_max_right _ _) } }, exact (dist_triangle (f x) 0 (f y)).trans (add_le_add (mem_closed_ball.mp $ this x) (mem_closed_ball'.mp $ this y)), end lemma bounded_range (f : C₀(α, β)) : bounded (range f) := bounded_range_iff.2 f.bounded lemma bounded_image (f : C₀(α, β)) (s : set α) : bounded (f '' s) := f.bounded_range.mono $ image_subset_range _ _ @[priority 100] instance : bounded_continuous_map_class F α β := { map_bounded := λ f, zero_at_infty_continuous_map.bounded f } /-- Construct a bounded continuous function from a continuous function vanishing at infinity. -/ @[simps] def to_bcf (f : C₀(α, β)) : α →ᵇ β := ⟨f, map_bounded f⟩ section variables (α) (β) lemma to_bcf_injective : function.injective (to_bcf : C₀(α, β) → α →ᵇ β) := λ f g h, by { ext, simpa only using fun_like.congr_fun h x, } end variables {C : ℝ} {f g : C₀(α, β)} /-- The type of continuous functions vanishing at infinity, with the uniform distance induced by the inclusion `zero_at_infinity_continuous_map.to_bcf`, is a metric space. -/ noncomputable instance : metric_space C₀(α, β) := metric_space.induced _ (to_bcf_injective α β) (by apply_instance) @[simp] lemma dist_to_bcf_eq_dist {f g : C₀(α, β)} : dist f.to_bcf g.to_bcf = dist f g := rfl open bounded_continuous_function /-- Convergence in the metric on `C₀(α, β)` is uniform convergence. -/ lemma tendsto_iff_tendsto_uniformly {ι : Type*} {F : ι → C₀(α, β)} {f : C₀(α, β)} {l : filter ι} : tendsto F l (𝓝 f) ↔ tendsto_uniformly (λ i, F i) f l := by simpa only [metric.tendsto_nhds] using @bounded_continuous_function.tendsto_iff_tendsto_uniformly _ _ _ _ _ (λ i, (F i).to_bcf) f.to_bcf l lemma isometry_to_bcf : isometry (to_bcf : C₀(α, β) → α →ᵇ β) := by tauto lemma closed_range_to_bcf : is_closed (range (to_bcf : C₀(α, β) → α →ᵇ β)) := begin refine is_closed_iff_cluster_pt.mpr (λ f hf, _), rw cluster_pt_principal_iff at hf, have : tendsto f (cocompact α) (𝓝 0), { refine metric.tendsto_nhds.mpr (λ ε hε, _), obtain ⟨_, hg, g, rfl⟩ := hf (ball f (ε / 2)) (ball_mem_nhds f $ half_pos hε), refine (metric.tendsto_nhds.mp (zero_at_infty g) (ε / 2) (half_pos hε)).mp (eventually_of_forall $ λ x hx, _), calc dist (f x) 0 ≤ dist (g.to_bcf x) (f x) + dist (g x) 0 : dist_triangle_left _ _ _ ... < dist g.to_bcf f + ε / 2 : add_lt_add_of_le_of_lt (dist_coe_le_dist x) hx ... < ε : by simpa [add_halves ε] using add_lt_add_right hg (ε / 2) }, exact ⟨⟨f.to_continuous_map, this⟩, by {ext, refl}⟩, end /-- Continuous functions vanishing at infinity taking values in a complete space form a complete space. -/ instance [complete_space β] : complete_space C₀(α, β) := (complete_space_iff_is_complete_range isometry_to_bcf.uniform_inducing).mpr closed_range_to_bcf.is_complete end metric section norm /-! ### Normed space The norm structure on `C₀(α, β)` is the one induced by the inclusion `to_bcf : C₀(α, β) → (α →ᵇ b)`, viewed as an additive monoid homomorphism. Then `C₀(α, β)` is naturally a normed space over a normed field `𝕜` whenever `β` is as well. -/ section normed_space variables [normed_group β] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] /-- The natural inclusion `to_bcf : C₀(α, β) → (α →ᵇ β)` realized as an additive monoid homomorphism. -/ def to_bcf_add_monoid_hom : C₀(α, β) →+ (α →ᵇ β) := { to_fun := to_bcf, map_zero' := rfl, map_add' := λ x y, rfl } @[simp] lemma coe_to_bcf_add_monoid_hom (f : C₀(α, β)) : (f.to_bcf_add_monoid_hom : α → β) = f := rfl noncomputable instance : normed_group C₀(α, β) := normed_group.induced to_bcf_add_monoid_hom (to_bcf_injective α β) @[simp] lemma norm_to_bcf_eq_norm {f : C₀(α, β)} : ∥f.to_bcf∥ = ∥f∥ := rfl instance : normed_space 𝕜 C₀(α, β) := { norm_smul_le := λ k f, (norm_smul k f.to_bcf).le } end normed_space section normed_ring variables [non_unital_normed_ring β] noncomputable instance : non_unital_normed_ring C₀(α, β) := { norm_mul := λ f g, norm_mul_le f.to_bcf g.to_bcf, ..zero_at_infty_continuous_map.non_unital_ring, ..zero_at_infty_continuous_map.normed_group } end normed_ring end norm section star /-! ### Star structure It is possible to equip `C₀(α, β)` with a pointwise `star` operation whenever there is a continuous `star : β → β` for which `star (0 : β) = 0`. We don't have quite this weak a typeclass, but `star_add_monoid` is close enough. The `star_add_monoid` and `normed_star_group` classes on `C₀(α, β)` are inherited from their counterparts on `α →ᵇ β`. Ultimately, when `β` is a C⋆-ring, then so is `C₀(α, β)`. -/ variables [topological_space β] [add_monoid β] [star_add_monoid β] [has_continuous_star β] instance : has_star C₀(α, β) := { star := λ f, { to_fun := λ x, star (f x), continuous_to_fun := (map_continuous f).star, zero_at_infty' := by simpa only [star_zero] using (continuous_star.tendsto (0 : β)).comp (zero_at_infty f) } } @[simp] lemma coe_star (f : C₀(α, β)) : ⇑(star f) = star f := rfl lemma star_apply (f : C₀(α, β)) (x : α) : (star f) x = star (f x) := rfl instance [has_continuous_add β] : star_add_monoid C₀(α, β) := { star_involutive := λ f, ext $ λ x, star_star (f x), star_add := λ f g, ext $ λ x, star_add (f x) (g x) } end star section normed_star variables [normed_group β] [star_add_monoid β] [normed_star_group β] instance : normed_star_group C₀(α, β) := { norm_star := λ f, (norm_star f.to_bcf : _) } end normed_star section star_module variables {𝕜 : Type*} [has_zero 𝕜] [has_star 𝕜] [add_monoid β] [star_add_monoid β] [topological_space β] [has_continuous_star β] [smul_with_zero 𝕜 β] [has_continuous_const_smul 𝕜 β] [star_module 𝕜 β] instance : star_module 𝕜 C₀(α, β) := { star_smul := λ k f, ext $ λ x, star_smul k (f x) } end star_module section star_ring variables [non_unital_semiring β] [star_ring β] [topological_space β] [has_continuous_star β] [topological_semiring β] instance : star_ring C₀(α, β) := { star_mul := λ f g, ext $ λ x, star_mul (f x) (g x), ..zero_at_infty_continuous_map.star_add_monoid } end star_ring section cstar_ring instance [non_unital_normed_ring β] [star_ring β] [cstar_ring β] : cstar_ring C₀(α, β) := { norm_star_mul_self := λ f, @cstar_ring.norm_star_mul_self _ _ _ _ f.to_bcf } end cstar_ring /-! ### C₀ as a functor For each `β` with sufficient structure, there is a contravariant functor `C₀(-, β)` from the category of topological spaces with morphisms given by `cocompact_map`s. -/ variables {δ : Type*} [topological_space β] [topological_space γ] [topological_space δ] local notation α ` →co ` β := cocompact_map α β section variables [has_zero δ] /-- Composition of a continuous function vanishing at infinity with a cocompact map yields another continuous function vanishing at infinity. -/ def comp (f : C₀(γ, δ)) (g : β →co γ) : C₀(β, δ) := { to_continuous_map := (f : C(γ, δ)).comp g, zero_at_infty' := (zero_at_infty f).comp (cocompact_tendsto g) } @[simp] lemma coe_comp_to_continuous_fun (f : C₀(γ, δ)) (g : β →co γ) : ((f.comp g).to_continuous_map : β → δ) = f ∘ g := rfl @[simp] lemma comp_id (f : C₀(γ, δ)) : f.comp (cocompact_map.id γ) = f := ext (λ x, rfl) @[simp] lemma comp_assoc (f : C₀(γ, δ)) (g : β →co γ) (h : α →co β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma zero_comp (g : β →co γ) : (0 : C₀(γ, δ)).comp g = 0 := rfl end /-- Composition as an additive monoid homomorphism. -/ def comp_add_monoid_hom [add_monoid δ] [has_continuous_add δ] (g : β →co γ) : C₀(γ, δ) →+ C₀(β, δ) := { to_fun := λ f, f.comp g, map_zero' := zero_comp g, map_add' := λ f₁ f₂, rfl } /-- Composition as a semigroup homomorphism. -/ def comp_mul_hom [mul_zero_class δ] [has_continuous_mul δ] (g : β →co γ) : C₀(γ, δ) →ₙ* C₀(β, δ) := { to_fun := λ f, f.comp g, map_mul' := λ f₁ f₂, rfl } /-- Composition as a linear map. -/ def comp_linear_map [add_comm_monoid δ] [has_continuous_add δ] {R : Type*} [semiring R] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) : C₀(γ, δ) →ₗ[R] C₀(β, δ) := { to_fun := λ f, f.comp g, map_add' := λ f₁ f₂, rfl, map_smul' := λ r f, rfl } /-- Composition as a non-unital algebra homomorphism. -/ def comp_non_unital_alg_hom {R : Type*} [semiring R] [non_unital_non_assoc_semiring δ] [topological_semiring δ] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) : C₀(γ, δ) →ₙₐ[R] C₀(β, δ) := { to_fun := λ f, f.comp g, map_smul' := λ r f, rfl, map_zero' := rfl, map_add' := λ f₁ f₂, rfl, map_mul' := λ f₁ f₂, rfl } end zero_at_infty_continuous_map
42820983f1657bb71a200b4c602a294a7ae50c78
618003631150032a5676f229d13a079ac875ff77
/src/dynamics/fixed_points.lean
58f676c38a977175d2b26ec9f5a450a8d7c5e229
[ "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
4,941
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.set.function import logic.function.iterate /-! # Fixed points of a self-map In this file we define * the predicate `is_fixed_pt f x := f x = x`; * the set `fixed_points f` of fixed points of a self-map `f`. We also prove some simple lemmas about `is_fixed_pt` and `∘`, `iterate`, and `semiconj`. ## Tags fixed point -/ universes u v variables {α : Type u} {β : Type v} {f fa g : α → α} {x y : α} {fb : β → β} {m n k : ℕ} namespace function /-- A point `x` is a fixed point of `f : α → α` if `f x = x`. -/ def is_fixed_pt (f : α → α) (x : α) := f x = x /-- Every point is a fixed point of `id`. -/ lemma is_fixed_pt_id (x : α) : is_fixed_pt id x := (rfl : _) namespace is_fixed_pt instance [h : decidable_eq α] {f : α → α} {x : α} : decidable (is_fixed_pt f x) := h (f x) x /-- If `x` is a fixed point of `f`, then `f x = x`. This is useful, e.g., for `rw` or `simp`.-/ protected lemma eq (hf : is_fixed_pt f x) : f x = x := hf /-- If `x` is a fixed point of `f` and `g`, then it is a fixed point of `f ∘ g`. -/ protected lemma comp (hf : is_fixed_pt f x) (hg : is_fixed_pt g x) : is_fixed_pt (f ∘ g) x := calc f (g x) = f x : congr_arg f hg ... = x : hf /-- If `x` is a fixed point of `f`, then it is a fixed point of `f^[n]`. -/ protected lemma iterate (hf : is_fixed_pt f x) (n : ℕ) : is_fixed_pt (f^[n]) x := iterate_fixed hf n /-- If `x` is a fixed point of `f ∘ g` and `g`, then it is a fixed point of `f`. -/ lemma left_of_comp (hfg : is_fixed_pt (f ∘ g) x) (hg : is_fixed_pt g x) : is_fixed_pt f x := calc f x = f (g x) : congr_arg f hg.symm ... = x : hfg /-- If `x` is a fixed point of `f` and `g` is a left inverse of `f`, then `x` is a fixed point of `g`. -/ lemma to_left_inverse (hf : is_fixed_pt f x) (h : left_inverse g f) : is_fixed_pt g x := calc g x = g (f x) : congr_arg g hf.symm ... = x : h x /-- If `g` (semi)conjugates `fa` to `fb`, then it sends fixed points of `fa` to fixed points of `fb`. -/ protected lemma map {x : α} (hx : is_fixed_pt fa x) {g : α → β} (h : semiconj g fa fb) : is_fixed_pt fb (g x) := calc fb (g x) = g (fa x) : (h.eq x).symm ... = g x : congr_arg g hx end is_fixed_pt /-- The set of fixed points of a map `f : α → α`. -/ def fixed_points (f : α → α) : set α := {x : α | is_fixed_pt f x} @[simp] lemma mem_fixed_points : x ∈ fixed_points f ↔ is_fixed_pt f x := iff.rfl /-- If `g` semiconjugates `fa` to `fb`, then it sends fixed points of `fa` to fixed points of `fb`. -/ lemma semiconj.maps_to_fixed_pts {g : α → β} (h : semiconj g fa fb) : set.maps_to g (fixed_points fa) (fixed_points fb) := λ x hx, hx.map h /-- Any two maps `f : α → β` and `g : β → α` are inverse of each other on the sets of fixed points of `f ∘ g` and `g ∘ f`, respectively. -/ lemma inv_on_fixed_pts_comp (f : α → β) (g : β → α) : set.inv_on f g (fixed_points $ f ∘ g) (fixed_points $ g ∘ f) := ⟨λ x, id, λ x, id⟩ /-- Any map `f` sends fixed points of `g ∘ f` to fixed points of `f ∘ g`. -/ lemma maps_to_fixed_pts_comp (f : α → β) (g : β → α) : set.maps_to f (fixed_points $ g ∘ f) (fixed_points $ f ∘ g) := λ x hx, hx.map $ λ x, rfl /-- Given two maps `f : α → β` and `g : β → α`, `g` is a bijective map between the fixed points of `f ∘ g` and the fixed points of `g ∘ f`. The inverse map is `f`, see `inv_on_fixed_pts_comp`. -/ lemma bij_on_fixed_pts_comp (f : α → β) (g : β → α) : set.bij_on g (fixed_points $ f ∘ g) (fixed_points $ g ∘ f) := (inv_on_fixed_pts_comp f g).bij_on (maps_to_fixed_pts_comp g f) (maps_to_fixed_pts_comp f g) /-- If self-maps `f` and `g` commute, then they are inverse of each other on the set of fixed points of `f ∘ g`. This is a particular case of `function.inv_on_fixed_pts_comp`. -/ lemma commute.inv_on_fixed_pts_comp (h : commute f g) : set.inv_on f g (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using inv_on_fixed_pts_comp f g /-- If self-maps `f` and `g` commute, then `f` is bijective on the set of fixed points of `f ∘ g`. This is a particular case of `function.bij_on_fixed_pts_comp`. -/ lemma commute.left_bij_on_fixed_pts_comp (h : commute f g) : set.bij_on f (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using bij_on_fixed_pts_comp g f /-- If self-maps `f` and `g` commute, then `g` is bijective on the set of fixed points of `f ∘ g`. This is a particular case of `function.bij_on_fixed_pts_comp`. -/ lemma commute.right_bij_on_fixed_pts_comp (h : commute f g) : set.bij_on g (fixed_points $ f ∘ g) (fixed_points $ f ∘ g) := by simpa only [h.comp_eq] using bij_on_fixed_pts_comp f g end function
b48694ba4fe104f1c00afe155bdbdaa4f234e86c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/module/prod.lean
3f5d9ca458169fd4ce19af392c35f99069e7b4c4
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,871
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import algebra.module.basic import group_theory.group_action.prod /-! # Prod instances for module and multiplicative actions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines instances for binary product of modules -/ variables {R : Type*} {S : Type*} {M : Type*} {N : Type*} namespace prod instance smul_with_zero [has_zero R] [has_zero M] [has_zero N] [smul_with_zero R M] [smul_with_zero R N] : smul_with_zero R (M × N) := { smul_zero := λ r, prod.ext (smul_zero _) (smul_zero _), zero_smul := λ ⟨m, n⟩, prod.ext (zero_smul _ _) (zero_smul _ _), ..prod.has_smul } instance mul_action_with_zero [monoid_with_zero R] [has_zero M] [has_zero N] [mul_action_with_zero R M] [mul_action_with_zero R N] : mul_action_with_zero R (M × N) := { smul_zero := λ r, prod.ext (smul_zero _) (smul_zero _), zero_smul := λ ⟨m, n⟩, prod.ext (zero_smul _ _) (zero_smul _ _), ..prod.mul_action } instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] : module R (M × N) := { add_smul := λ a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, zero_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, .. prod.distrib_mul_action } instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] [no_zero_smul_divisors R M] [no_zero_smul_divisors R N] : no_zero_smul_divisors R (M × N) := ⟨λ c ⟨x, y⟩ h, or_iff_not_imp_left.mpr (λ hc, mk.inj_iff.mpr ⟨(smul_eq_zero.mp (congr_arg fst h)).resolve_left hc, (smul_eq_zero.mp (congr_arg snd h)).resolve_left hc⟩)⟩ end prod
ea5cd618d251e2d83a9ee4911bb205fa6fbdb747
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/ring_theory/algebra_operations.lean
969f68f4b7db54b3a8a2750b601f06a26b16e988
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
11,538
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.algebra /-! # Multiplication and division of submodules of an algebra. An interface for multiplication and division of sub-R-modules of an R-algebra A is developed. ## Main definitions Let `R` be a commutative ring (or semiring) and aet `A` be an `R`-algebra. * `1 : submodule R A` : the R-submodule R of the R-algebra A * `has_mul (submodule R A)` : multiplication of two sub-R-modules M and N of A is defined to be the smallest submodule containing all the products `m * n`. * `has_div (submodule R A)` : `I / J` is defined to be the submodule consisting of all `a : A` such that `a • J ⊆ I` It is proved that `submodule R A` is a semiring, and also an algebra over `set A`. ## Tags multiplication of submodules, division of subodules, submodule semiring -/ universes u v open algebra set namespace submodule variables {R : Type u} [comm_semiring R] section ring variables {A : Type v} [semiring A] [algebra R A] variables (S T : set A) {M N P Q : submodule R A} {m n : A} /-- `1 : submodule R A` is the submodule R of A. -/ instance : has_one (submodule R A) := ⟨submodule.map (of_id R A).to_linear_map (⊤ : submodule R R)⟩ theorem one_eq_map_top : (1 : submodule R A) = submodule.map (of_id R A).to_linear_map (⊤ : submodule R R) := rfl theorem one_eq_span : (1 : submodule R A) = span R {1} := begin apply submodule.ext, intro a, erw [mem_map, mem_span_singleton], apply exists_congr, intro r, simpa [smul_def], end theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P := by simpa only [one_eq_span, span_le, set.singleton_subset_iff] /-- Multiplication of sub-R-modules of an R-algebra A. The submodule `M * N` is the smallest R-submodule of `A` containing the elements `m * n` for `m ∈ M` and `n ∈ N`. -/ instance : has_mul (submodule R A) := ⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩ theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N := (le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩ theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P := ⟨λ H m hm n hn, H $ mul_mem_mul hm hn, λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩ @[elab_as_eliminator] protected theorem mul_induction_on {C : A → Prop} {r : A} (hr : r ∈ M * N) (hm : ∀ (m ∈ M) (n ∈ N), C (m * n)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := (@mul_le _ _ _ _ _ _ _ ⟨C, h0, ha, hs⟩).2 hm hr variables R theorem span_mul_span : span R S * span R T = span R (S * T) := begin apply le_antisymm, { rw mul_le, intros a ha b hb, apply span_induction ha, work_on_goal 0 { intros, apply span_induction hb, work_on_goal 0 { intros, exact subset_span ⟨_, _, ‹_›, ‹_›, rfl⟩ } }, all_goals { intros, simp only [mul_zero, zero_mul, zero_mem, left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc], try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' }, { rw span_le, rintros _ ⟨a, b, ha, hb, rfl⟩, exact mul_mem_mul (subset_span ha) (subset_span hb) } end variables {R} variables (M N P Q) protected theorem mul_assoc : (M * N) * P = M * (N * P) := le_antisymm (mul_le.2 $ λ mn hmn p hp, suffices M * N ≤ (M * (N * P)).comap ((algebra.lmul R A).flip p), from this hmn, mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from (mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp)) (mul_le.2 $ λ m hm np hnp, suffices N * P ≤ (M * N * P).comap (algebra.lmul R A m), from this hnp, mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp) @[simp] theorem mul_bot : M * ⊥ = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero] @[simp] theorem bot_mul : ⊥ * M = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul] @[simp] protected theorem one_mul : (1 : submodule R A) * M = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] } @[simp] protected theorem mul_one : M * 1 = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] } variables {M N P Q} @[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q := mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn) theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P := mul_le_mul h (le_refl P) theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P := mul_le_mul (le_refl M) h variables (M N P) theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P := le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩) (sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right)) theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P := le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩) (sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right)) lemma mul_subset_mul : (↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) := by { rintros _ ⟨i, j, hi, hj, rfl⟩, exact mul_mem_mul hi hj } lemma map_mul {A'} [semiring A'] [algebra R A'] (f : A →ₐ[R] A') : map f.to_linear_map (M * N) = map f.to_linear_map M * map f.to_linear_map N := calc map f.to_linear_map (M * N) = ⨆ (i : M), (N.map (lmul R A i)).map f.to_linear_map : map_supr _ _ ... = map f.to_linear_map M * map f.to_linear_map N : begin apply congr_arg Sup, ext S, split; rintros ⟨y, hy⟩, { use [f y, mem_map.mpr ⟨y.1, y.2, rfl⟩], refine trans _ hy, ext, simp }, { obtain ⟨y', hy', fy_eq⟩ := mem_map.mp y.2, use [y', hy'], refine trans _ hy, rw f.to_linear_map_apply at fy_eq, ext, simp [fy_eq] } end variables {M N P} /-- Sub-R-modules of an R-algebra form a semiring. -/ instance : semiring (submodule R A) := { one_mul := submodule.one_mul, mul_one := submodule.mul_one, mul_assoc := submodule.mul_assoc, zero_mul := bot_mul, mul_zero := mul_bot, left_distrib := mul_sup, right_distrib := sup_mul, ..submodule.add_comm_monoid_submodule, ..submodule.has_one, ..submodule.has_mul } variables (M) lemma pow_subset_pow {n : ℕ} : (↑M : set A)^n ⊆ ↑(M^n : submodule R A) := begin induction n with n ih, { erw [pow_zero, pow_zero, set.singleton_subset_iff], rw [mem_coe, ← one_le], exact le_refl _ }, { rw [pow_succ, pow_succ], refine set.subset.trans (set.mul_subset_mul (subset.refl _) ih) _, apply mul_subset_mul } end /-- `span` is a semiring homomorphism (recall multiplication is pointwise multiplication of subsets on either side). -/ def span.ring_hom : set_semiring A →+* submodule R A := { to_fun := submodule.span R, map_zero' := span_empty, map_one' := le_antisymm (span_le.2 $ singleton_subset_iff.2 ⟨1, ⟨⟩, (algebra_map R A).map_one⟩) (map_le_iff_le_comap.2 $ λ r _, mem_span_singleton.2 ⟨r, (algebra_map_eq_smul_one r).symm⟩), map_add' := span_union, map_mul' := λ s t, by erw [span_mul_span, ← image_mul_prod] } end ring section comm_ring variables {A : Type v} [comm_semiring A] [algebra R A] variables {M N : submodule R A} {m n : A} theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N := mul_comm m n ▸ mul_mem_mul hm hn variables (M N) protected theorem mul_comm : M * N = N * M := le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm) (mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn) /-- Sub-R-modules of an R-algebra A form a semiring. -/ instance : comm_semiring (submodule R A) := { mul_comm := submodule.mul_comm, .. submodule.semiring } variables (R A) /-- R-submodules of the R-algebra A are a module over `set A`. -/ instance semimodule_set : semimodule (set_semiring A) (submodule R A) := { smul := λ s P, span R s * P, smul_add := λ _ _ _, mul_add _ _ _, add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] }, mul_smul := λ s t P, show _ = _ * (_ * _), by { rw [← mul_assoc, span_mul_span, ← image_mul_prod] }, one_smul := λ P, show span R {(1 : A)} * P = _, by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] }, zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul], smul_zero := λ _, mul_bot _ } variables {R A} lemma smul_def {s : set_semiring A} {P : submodule R A} : s • P = span R s * P := rfl lemma smul_le_smul {s t : set_semiring A} {M N : submodule R A} (h₁ : s.down ≤ t.down) (h₂ : M ≤ N) : s • M ≤ t • N := mul_le_mul (span_mono h₁) h₂ lemma smul_singleton (a : A) (M : submodule R A) : ({a} : set A).up • M = M.map (lmul_left _ _ a) := begin conv_lhs {rw ← span_eq M}, change span _ _ * span _ _ = _, rw [span_mul_span], apply le_antisymm, { rw span_le, rintros _ ⟨b, m, hb, hm, rfl⟩, rw [mem_coe, mem_map, set.mem_singleton_iff.mp hb], exact ⟨m, hm, rfl⟩ }, { rintros _ ⟨m, hm, rfl⟩, exact subset_span ⟨a, m, set.mem_singleton a, hm, rfl⟩ } end section quotient /-- The elements of `I / J` are the `x` such that `x • J ⊆ I`. In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`), which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs. This is the general form of the ideal quotient, traditionally written $I : J$. -/ instance : has_div (submodule R A) := ⟨ λ I J, { carrier := { x | ∀ y ∈ J, x * y ∈ I }, zero_mem' := λ y hy, by { rw zero_mul, apply submodule.zero_mem }, add_mem' := λ a b ha hb y hy, by { rw add_mul, exact submodule.add_mem _ (ha _ hy) (hb _ hy) }, smul_mem' := λ r x hx y hy, by { rw algebra.smul_mul_assoc, exact submodule.smul_mem _ _ (hx _ hy) } } ⟩ lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := iff.refl _ lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I := ⟨ λ h y ⟨y', hy', xy'_eq_y⟩, by { rw ← xy'_eq_y, apply h, assumption }, λ h y hy, h (set.smul_mem_smul_set hy) ⟩ lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _ lemma le_div_iff_mul_le {I J K : submodule R A} : I ≤ J / K ↔ I * K ≤ J := by rw [le_div_iff, mul_le] @[simp] lemma map_div {B : Type*} [comm_ring B] [algebra R B] (I J : submodule R A) (h : A ≃ₐ[R] B) : (I / J).map h.to_linear_map = I.map h.to_linear_map / J.map h.to_linear_map := begin ext x, simp only [mem_map, mem_div_iff_forall_mul_mem], split, { rintro ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, exact ⟨x * y, hx _ hy, h.map_mul x y⟩ }, { rintro hx, refine ⟨h.symm x, λ z hz, _, h.apply_symm_apply x⟩, obtain ⟨xz, xz_mem, hxz⟩ := hx (h z) ⟨z, hz, rfl⟩, convert xz_mem, apply h.injective, erw [h.map_mul, h.apply_symm_apply, hxz] } end end quotient end comm_ring end submodule
abd04dfe04db18f4382dd34c21a8281eee5e522b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/Simp/Rewrite.lean
c52516accc12f1a6b1928b45c0dca87de2ea562a
[ "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
11,477
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.ACLt import Lean.Meta.Match.MatchEqsExt import Lean.Meta.AppBuilder import Lean.Meta.SynthInstance import Lean.Meta.Tactic.Simp.Types import Lean.Meta.Tactic.LinearArith.Simp namespace Lean.Meta.Simp def mkEqTrans (r₁ r₂ : Result) : MetaM Result := do match r₁.proof? with | none => return r₂ | some p₁ => match r₂.proof? with | none => return { r₂ with proof? := r₁.proof? } | some p₂ => return { r₂ with proof? := (← Meta.mkEqTrans p₁ p₂) } def synthesizeArgs (thmId : Origin) (xs : Array Expr) (bis : Array BinderInfo) (discharge? : Expr → SimpM (Option Expr)) : SimpM Bool := do for x in xs, bi in bis do let type ← inferType x -- Note that the binderInfo may be misleading here: -- `simp [foo _]` uses `abstractMVars` to turn the elaborated term with -- mvars into the lambda expression `fun α x inst => foo x`, and all -- its bound variables have default binderInfo! if bi.isInstImplicit then unless (← synthesizeInstance x type) do return false else if (← instantiateMVars x).isMVar then -- A hypothesis can be both a type class instance as well as a proposition, -- in that case we try both TC synthesis and the discharger -- (because we don't know whether the argument was originally explicit or instance-implicit). if (← isClass? type).isSome then if (← synthesizeInstance x type) then continue if (← isProp type) then match (← discharge? type) with | some proof => unless (← isDefEq x proof) do trace[Meta.Tactic.simp.discharge] "{← ppOrigin thmId}, failed to assign proof{indentExpr type}" return false | none => trace[Meta.Tactic.simp.discharge] "{← ppOrigin thmId}, failed to discharge hypotheses{indentExpr type}" return false return true where synthesizeInstance (x type : Expr) : SimpM Bool := do match (← trySynthInstance type) with | LOption.some val => if (← withReducibleAndInstances <| isDefEq x val) then return true else trace[Meta.Tactic.simp.discharge] "{← ppOrigin thmId}, failed to assign instance{indentExpr type}\nsythesized value{indentExpr val}\nis not definitionally equal to{indentExpr x}" return false | _ => trace[Meta.Tactic.simp.discharge] "{← ppOrigin thmId}, failed to synthesize instance{indentExpr type}" return false private def tryTheoremCore (lhs : Expr) (xs : Array Expr) (bis : Array BinderInfo) (val : Expr) (type : Expr) (e : Expr) (thm : SimpTheorem) (numExtraArgs : Nat) (discharge? : Expr → SimpM (Option Expr)) : SimpM (Option Result) := do let rec go (e : Expr) : SimpM (Option Result) := do if (← isDefEq lhs e) then unless (← synthesizeArgs thm.origin xs bis discharge?) do return none let proof? ← if thm.rfl then pure none else let proof ← instantiateMVars (mkAppN val xs) if (← hasAssignableMVar proof) then trace[Meta.Tactic.simp.rewrite] "{← ppSimpTheorem thm}, has unassigned metavariables after unification" return none pure <| some proof let rhs := (← instantiateMVars type).appArg! if e == rhs then return none if thm.perm then /- We use `.reduceSimpleOnly` because this is how we indexed the discrimination tree. See issue #1815 -/ if !(← Expr.acLt rhs e .reduceSimpleOnly) then trace[Meta.Tactic.simp.rewrite] "{← ppSimpTheorem thm}, perm rejected {e} ==> {rhs}" return none trace[Meta.Tactic.simp.rewrite] "{← ppSimpTheorem thm}, {e} ==> {rhs}" recordSimpTheorem thm.origin return some { expr := rhs, proof? } else unless lhs.isMVar do -- We do not report unification failures when `lhs` is a metavariable -- Example: `x = ()` -- TODO: reconsider if we want thms such as `(x : Unit) → x = ()` trace[Meta.Tactic.simp.unify] "{← ppSimpTheorem thm}, failed to unify{indentExpr lhs}\nwith{indentExpr e}" return none /- Check whether we need something more sophisticated here. This simple approach was good enough for Mathlib 3 -/ let mut extraArgs := #[] let mut e := e for _ in [:numExtraArgs] do extraArgs := extraArgs.push e.appArg! e := e.appFn! extraArgs := extraArgs.reverse match (← go e) with | none => return none | some { expr := eNew, proof? := none, .. } => if (← hasAssignableMVar eNew) then trace[Meta.Tactic.simp.rewrite] "{← ppSimpTheorem thm}, resulting expression has unassigned metavariables" return none return some { expr := mkAppN eNew extraArgs } | some { expr := eNew, proof? := some proof, .. } => let mut proof := proof for extraArg in extraArgs do proof ← mkCongrFun proof extraArg if (← hasAssignableMVar eNew) then trace[Meta.Tactic.simp.rewrite] "{← ppSimpTheorem thm}, resulting expression has unassigned metavariables" return none return some { expr := mkAppN eNew extraArgs, proof? := some proof } def tryTheoremWithExtraArgs? (e : Expr) (thm : SimpTheorem) (numExtraArgs : Nat) (discharge? : Expr → SimpM (Option Expr)) : SimpM (Option Result) := withNewMCtxDepth do let val ← thm.getValue let type ← inferType val let (xs, bis, type) ← forallMetaTelescopeReducing type let type ← whnf (← instantiateMVars type) let lhs := type.appFn!.appArg! tryTheoremCore lhs xs bis val type e thm numExtraArgs discharge? def tryTheorem? (e : Expr) (thm : SimpTheorem) (discharge? : Expr → SimpM (Option Expr)) : SimpM (Option Result) := do withNewMCtxDepth do let val ← thm.getValue let type ← inferType val let (xs, bis, type) ← forallMetaTelescopeReducing type let type ← whnf (← instantiateMVars type) let lhs := type.appFn!.appArg! match (← tryTheoremCore lhs xs bis val type e thm 0 discharge?) with | some result => return some result | none => let lhsNumArgs := lhs.getAppNumArgs let eNumArgs := e.getAppNumArgs if eNumArgs > lhsNumArgs then tryTheoremCore lhs xs bis val type e thm (eNumArgs - lhsNumArgs) discharge? else return none /-- Remark: the parameter tag is used for creating trace messages. It is irrelevant otherwise. -/ def rewrite? (e : Expr) (s : SimpTheoremTree) (erased : PHashSet Origin) (discharge? : Expr → SimpM (Option Expr)) (tag : String) (rflOnly : Bool) : SimpM (Option Result) := do let candidates ← s.getMatchWithExtra e if candidates.isEmpty then trace[Debug.Meta.Tactic.simp] "no theorems found for {tag}-rewriting {e}" return none else let candidates := candidates.insertionSort fun e₁ e₂ => e₁.1.priority > e₂.1.priority for (thm, numExtraArgs) in candidates do unless inErasedSet thm || (rflOnly && !thm.rfl) do if let some result ← tryTheoremWithExtraArgs? e thm numExtraArgs discharge? then trace[Debug.Meta.Tactic.simp] "rewrite result {e} => {result.expr}" return some result return none where inErasedSet (thm : SimpTheorem) : Bool := erased.contains thm.origin @[inline] def andThen (s : Step) (f? : Expr → SimpM (Option Step)) : SimpM Step := do match s with | Step.done _ => return s | Step.visit r => if let some s' ← f? r.expr then return s'.updateResult (← mkEqTrans r s'.result) else return s def rewriteCtorEq? (e : Expr) : MetaM (Option Result) := withReducibleAndInstances do match e.eq? with | none => return none | some (_, lhs, rhs) => let lhs ← whnf lhs let rhs ← whnf rhs let env ← getEnv match lhs.constructorApp? env, rhs.constructorApp? env with | some (c₁, _), some (c₂, _) => if c₁.name != c₂.name then withLocalDeclD `h e fun h => return some { expr := mkConst ``False, proof? := (← mkEqFalse' (← mkLambdaFVars #[h] (← mkNoConfusion (mkConst ``False) h))) } else return none | _, _ => return none @[inline] def tryRewriteCtorEq? (e : Expr) : SimpM (Option Step) := do match (← rewriteCtorEq? e) with | some r => return Step.done r | none => return none def rewriteUsingDecide? (e : Expr) : MetaM (Option Result) := withReducibleAndInstances do if e.hasFVar || e.hasMVar || e.consumeMData.isConstOf ``True || e.consumeMData.isConstOf ``False then return none else try let d ← mkDecide e let r ← withDefault <| whnf d if r.isConstOf ``true then return some { expr := mkConst ``True, proof? := mkAppN (mkConst ``eq_true_of_decide) #[e, d.appArg!, (← mkEqRefl (mkConst ``true))] } else if r.isConstOf ``false then return some { expr := mkConst ``False, proof? := mkAppN (mkConst ``eq_false_of_decide) #[e, d.appArg!, (← mkEqRefl (mkConst ``false))] } else return none catch _ => return none @[inline] def tryRewriteUsingDecide? (e : Expr) : SimpM (Option Step) := do if (← read).config.decide then match (← rewriteUsingDecide? e) with | some r => return Step.done r | none => return none else return none def simpArith? (e : Expr) : SimpM (Option Step) := do if !(← read).config.arith then return none let some (e', h) ← Linear.simp? e (← read).parent? | return none return Step.visit { expr := e', proof? := h } def simpMatchCore? (app : MatcherApp) (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM (Option Step) := do for matchEq in (← Match.getEquationsFor app.matcherName).eqnNames do -- Try lemma match (← withReducible <| Simp.tryTheorem? e { origin := .decl matchEq, proof := mkConst matchEq, rfl := (← isRflTheorem matchEq) } discharge?) with | none => pure () | some r => return some (Simp.Step.done r) return none def simpMatch? (discharge? : Expr → SimpM (Option Expr)) (e : Expr) : SimpM (Option Step) := do if (← read).config.iota then let some app ← matchMatcherApp? e | return none simpMatchCore? app e discharge? else return none def rewritePre (e : Expr) (discharge? : Expr → SimpM (Option Expr)) (rflOnly := false) : SimpM Step := do for thms in (← read).simpTheorems do if let some r ← rewrite? e thms.pre thms.erased discharge? (tag := "pre") (rflOnly := rflOnly) then return Step.visit r return Step.visit { expr := e } def rewritePost (e : Expr) (discharge? : Expr → SimpM (Option Expr)) (rflOnly := false) : SimpM Step := do for thms in (← read).simpTheorems do if let some r ← rewrite? e thms.post thms.erased discharge? (tag := "post") (rflOnly := rflOnly) then return Step.visit r return Step.visit { expr := e } def preDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let s ← rewritePre e discharge? andThen s tryRewriteUsingDecide? def postDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let s ← rewritePost e discharge? let s ← andThen s (simpMatch? discharge?) let s ← andThen s simpArith? let s ← andThen s tryRewriteUsingDecide? andThen s tryRewriteCtorEq? end Lean.Meta.Simp
67f05d33bc77c4be500fec344446ee084d97db7a
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/init/logic.hlean
bfeb4bf3cd973449e78c85966cf97c42090499e4
[ "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
14,902
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Floris van Doorn -/ prelude import init.reserved_notation open unit /- not -/ definition not [reducible] (a : Type) := a → empty prefix ¬ := not definition absurd {a b : Type} (H₁ : a) (H₂ : ¬a) : b := empty.rec (λ e, b) (H₂ H₁) definition mt {a b : Type} (H₁ : a → b) (H₂ : ¬b) : ¬a := assume Ha : a, absurd (H₁ Ha) H₂ protected definition not_empty : ¬ empty := assume H : empty, H definition not_not_intro {a : Type} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna definition not.elim {a : Type} (H₁ : ¬a) (H₂ : a) : empty := H₁ H₂ definition not.intro {a : Type} (H : a → empty) : ¬a := H definition not_not_of_not_implies {a b : Type} (H : ¬(a → b)) : ¬¬a := assume Hna : ¬a, absurd (assume Ha : a, absurd Ha Hna) H definition not_of_not_implies {a b : Type} (H : ¬(a → b)) : ¬b := assume Hb : b, absurd (assume Ha : a, Hb) H /- eq -/ infix = := eq definition rfl {A : Type} {a : A} := eq.refl a namespace eq variables {A : Type} {a b c : A} definition subst [unfold 5] {P : A → Type} (H₁ : a = b) (H₂ : P a) : P b := eq.rec H₂ H₁ definition trans [unfold 5] (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ definition symm [unfold 4] (H : a = b) : b = a := subst H (refl a) theorem mp {a b : Type} : (a = b) → a → b := eq.rec_on theorem mpr {a b : Type} : (a = b) → b → a := assume H₁ H₂, eq.rec_on (eq.symm H₁) H₂ namespace ops postfix ⁻¹ := symm --input with \sy or \-1 or \inv infixl ⬝ := trans infixr ▸ := subst end ops end eq -- Auxiliary definition used by automation. It has the same type of eq.rec in the standard library definition eq.nrec.{l₁ l₂} {A : Type.{l₂}} {a : A} {C : A → Type.{l₁}} (H₁ : C a) (b : A) (H₂ : a = b) : C b := eq.rec H₁ H₂ definition congr {A B : Type} {f₁ f₂ : A → B} {a₁ a₂ : A} (H₁ : f₁ = f₂) (H₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst H₁ (eq.subst H₂ rfl) theorem congr_fun {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a := eq.subst H (eq.refl (f a)) theorem congr_arg {A B : Type} (a a' : A) (f : A → B) (Ha : a = a') : f a = f a' := eq.subst Ha rfl theorem congr_arg2 {A B C : Type} (a a' : A) (b b' : B) (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := eq.subst Ha (eq.subst Hb rfl) section variables {A : Type} {a b c: A} open eq.ops definition trans_rel_left (R : A → A → Type) (H₁ : R a b) (H₂ : b = c) : R a c := H₂ ▸ H₁ definition trans_rel_right (R : A → A → Type) (H₁ : a = b) (H₂ : R b c) : R a c := H₁⁻¹ ▸ H₂ end attribute eq.subst [subst] attribute eq.refl [refl] attribute eq.trans [trans] attribute eq.symm [symm] namespace lift definition down_up.{l₁ l₂} {A : Type.{l₁}} (a : A) : down (up.{l₁ l₂} a) = a := rfl definition up_down.{l₁ l₂} {A : Type.{l₁}} (a : lift.{l₁ l₂} A) : up (down a) = a := lift.rec_on a (λ d, rfl) end lift /- ne -/ definition ne {A : Type} (a b : A) := ¬(a = b) infix ≠ := ne namespace ne open eq.ops variable {A : Type} variables {a b : A} definition intro : (a = b → empty) → a ≠ b := assume H, H definition elim : a ≠ b → a = b → empty := assume H₁ H₂, H₁ H₂ definition irrefl : a ≠ a → empty := assume H, H rfl definition symm : a ≠ b → b ≠ a := assume (H : a ≠ b) (H₁ : b = a), H H₁⁻¹ end ne section open eq.ops variables {A : Type} {a b c : A} definition empty.of_ne : a ≠ a → empty := assume H, H rfl definition ne.of_eq_of_ne : a = b → b ≠ c → a ≠ c := assume H₁ H₂, H₁⁻¹ ▸ H₂ definition ne.of_ne_of_eq : a ≠ b → b = c → a ≠ c := assume H₁ H₂, H₂ ▸ H₁ end /- iff -/ definition iff (a b : Type) := prod (a → b) (b → a) infix <-> := iff infix ↔ := iff variables {a b c : Type} namespace iff definition def : (a ↔ b) = (prod (a → b) (b → a)) := rfl definition intro (H₁ : a → b) (H₂ : b → a) : a ↔ b := prod.mk H₁ H₂ definition elim (H₁ : (a → b) → (b → a) → c) (H₂ : a ↔ b) : c := prod.rec H₁ H₂ definition elim_left (H : a ↔ b) : a → b := elim (assume H₁ H₂, H₁) H definition mp := @elim_left definition elim_right (H : a ↔ b) : b → a := elim (assume H₁ H₂, H₂) H definition mpr := @elim_right definition flip_sign (H₁ : a ↔ b) : ¬a ↔ ¬b := intro (assume Hna, mt (elim_right H₁) Hna) (assume Hnb, mt (elim_left H₁) Hnb) definition refl (a : Type) : a ↔ a := intro (assume H, H) (assume H, H) definition rfl {a : Type} : a ↔ a := refl a definition iff_of_eq (a b : Type) (p : a = b) : a ↔ b := eq.rec rfl p definition trans (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c := intro (assume Ha, elim_left H₂ (elim_left H₁ Ha)) (assume Hc, elim_right H₁ (elim_right H₂ Hc)) definition symm (H : a ↔ b) : b ↔ a := intro (assume Hb, elim_right H Hb) (assume Ha, elim_left H Ha) definition unit_elim (H : a ↔ unit) : a := mp (symm H) unit.star definition empty_elim (H : a ↔ empty) : ¬a := assume Ha : a, mp H Ha open eq.ops definition of_eq {a b : Type} (H : a = b) : a ↔ b := iff.intro (λ Ha, H ▸ Ha) (λ Hb, H⁻¹ ▸ Hb) definition pi_iff_pi {A : Type} {P Q : A → Type} (H : Πa, (P a ↔ Q a)) : (Πa, P a) ↔ Πa, Q a := iff.intro (λp a, iff.elim_left (H a) (p a)) (λq a, iff.elim_right (H a) (q a)) theorem imp_iff {P : Type} (Q : Type) (p : P) : (P → Q) ↔ Q := iff.intro (λf, f p) (λq p, q) end iff theorem not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (Hna : ¬ a) (Hb : b), Hna (iff.elim_right H₁ Hb)) (assume (Hnb : ¬ b) (Ha : a), Hnb (iff.elim_left H₁ Ha)) theorem of_iff_unit (H : a ↔ unit) : a := iff.mp (iff.symm H) star theorem not_of_iff_empty : (a ↔ empty) → ¬a := iff.mp theorem iff_unit_intro (H : a) : a ↔ unit := iff.intro (λ Hl, star) (λ Hr, H) theorem iff_empty_intro (H : ¬a) : a ↔ empty := iff.intro H (empty.rec _) theorem not_non_contradictory_iff_absurd (a : Type) : ¬¬¬a ↔ ¬a := iff.intro (λ (Hl : ¬¬¬a) (Ha : a), Hl (λf, f Ha)) absurd attribute iff.refl [refl] attribute iff.trans [trans] attribute iff.symm [symm] /- inhabited -/ inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A namespace inhabited protected definition destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B := inhabited.rec H2 H1 definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) := inhabited.destruct H (λb, mk (λa, b)) definition inhabited_Pi [instance] (A : Type) {B : A → Type} [H : Πx, inhabited (B x)] : inhabited (Πx, B x) := mk (λa, inhabited.destruct (H a) (λb, b)) definition default (A : Type) [H : inhabited A] : A := inhabited.destruct H (take a, a) end inhabited /- decidable -/ inductive decidable.{l} [class] (p : Type.{l}) : Type.{l} := | inl : p → decidable p | inr : ¬p → decidable p namespace decidable variables {p q : Type} definition pos_witness [C : decidable p] (H : p) : p := decidable.rec_on C (λ Hp, Hp) (λ Hnp, absurd H Hnp) definition neg_witness [C : decidable p] (H : ¬ p) : ¬ p := decidable.rec_on C (λ Hp, absurd Hp H) (λ Hnp, Hnp) definition by_cases {q : Type} [C : decidable p] (Hpq : p → q) (Hnpq : ¬p → q) : q := decidable.rec_on C (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp) definition em (p : Type) [H : decidable p] : sum p ¬p := by_cases (λ Hp, sum.inl Hp) (λ Hnp, sum.inr Hnp) definition by_contradiction [Hp : decidable p] (H : ¬p → empty) : p := by_cases (assume H₁ : p, H₁) (assume H₁ : ¬p, empty.rec (λ e, p) (H H₁)) definition decidable_iff_equiv (Hp : decidable p) (H : p ↔ q) : decidable q := decidable.rec_on Hp (assume Hp : p, inl (iff.elim_left H Hp)) (assume Hnp : ¬p, inr (iff.elim_left (iff.flip_sign H) Hnp)) definition decidable_eq_equiv.{l} {p q : Type.{l}} (Hp : decidable p) (H : p = q) : decidable q := decidable_iff_equiv Hp (iff.of_eq H) end decidable section variables {p q : Type} open decidable (rec_on inl inr) definition decidable_unit [instance] : decidable unit := inl unit.star definition decidable_empty [instance] : decidable empty := inr not_empty definition decidable_prod [instance] [Hp : decidable p] [Hq : decidable q] : decidable (prod p q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (prod.mk Hp Hq)) (assume Hnq : ¬q, inr (λ H : prod p q, prod.rec_on H (λ Hp Hq, absurd Hq Hnq)))) (assume Hnp : ¬p, inr (λ H : prod p q, prod.rec_on H (λ Hp Hq, absurd Hp Hnp))) definition decidable_sum [instance] [Hp : decidable p] [Hq : decidable q] : decidable (sum p q) := rec_on Hp (assume Hp : p, inl (sum.inl Hp)) (assume Hnp : ¬p, rec_on Hq (assume Hq : q, inl (sum.inr Hq)) (assume Hnq : ¬q, inr (λ H : sum p q, sum.rec_on H (λ Hp, absurd Hp Hnp) (λ Hq, absurd Hq Hnq)))) definition decidable_not [instance] [Hp : decidable p] : decidable (¬p) := rec_on Hp (assume Hp, inr (not_not_intro Hp)) (assume Hnp, inl Hnp) definition decidable_implies [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p → q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (assume H, Hq)) (assume Hnq : ¬q, inr (assume H : p → q, absurd (H Hp) Hnq))) (assume Hnp : ¬p, inl (assume Hp, absurd Hp Hnp)) definition decidable_if [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ↔ q) := show decidable (prod (p → q) (q → p)), from _ end definition decidable_pred [reducible] {A : Type} (R : A → Type) := Π (a : A), decidable (R a) definition decidable_rel [reducible] {A : Type} (R : A → A → Type) := Π (a b : A), decidable (R a b) definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A) definition decidable_ne [instance] {A : Type} [H : decidable_eq A] : decidable_rel (@ne A) := show Π x y : A, decidable (x = y → empty), from _ definition ite (c : Type) [H : decidable c] {A : Type} (t e : A) : A := decidable.rec_on H (λ Hc, t) (λ Hnc, e) definition if_pos {c : Type} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (if c then t else e) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H definition if_neg {c : Type} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (if c then t else e) = e := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H definition if_t_t (c : Type) [H : decidable c] {A : Type} (t : A) : (if c then t else t) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t)) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t)) H definition if_unit {A : Type} (t e : A) : (if unit then t else e) = t := if_pos unit.star definition if_empty {A : Type} (t e : A) : (if empty then t else e) = e := if_neg not_empty section open eq.ops definition if_cond_congr {c₁ c₂ : Type} [H₁ : decidable c₁] [H₂ : decidable c₂] (Heq : c₁ ↔ c₂) {A : Type} (t e : A) : (if c₁ then t else e) = (if c₂ then t else e) := decidable.rec_on H₁ (λ Hc₁ : c₁, decidable.rec_on H₂ (λ Hc₂ : c₂, if_pos Hc₁ ⬝ (if_pos Hc₂)⁻¹) (λ Hnc₂ : ¬c₂, absurd (iff.elim_left Heq Hc₁) Hnc₂)) (λ Hnc₁ : ¬c₁, decidable.rec_on H₂ (λ Hc₂ : c₂, absurd (iff.elim_right Heq Hc₂) Hnc₁) (λ Hnc₂ : ¬c₂, if_neg Hnc₁ ⬝ (if_neg Hnc₂)⁻¹)) definition if_congr_aux {c₁ c₂ : Type} [H₁ : decidable c₁] [H₂ : decidable c₂] {A : Type} {t₁ t₂ e₁ e₂ : A} (Hc : c₁ ↔ c₂) (Ht : t₁ = t₂) (He : e₁ = e₂) : (if c₁ then t₁ else e₁) = (if c₂ then t₂ else e₂) := Ht ▸ He ▸ (if_cond_congr Hc t₁ e₁) definition if_congr {c₁ c₂ : Type} [H₁ : decidable c₁] {A : Type} {t₁ t₂ e₁ e₂ : A} (Hc : c₁ ↔ c₂) (Ht : t₁ = t₂) (He : e₁ = e₂) : (if c₁ then t₁ else e₁) = (@ite c₂ (decidable.decidable_iff_equiv H₁ Hc) A t₂ e₂) := have H2 [visible] : decidable c₂, from (decidable.decidable_iff_equiv H₁ Hc), if_congr_aux Hc Ht He theorem implies_of_if_pos {c t e : Type} [H : decidable c] (h : if c then t else e) : c → t := assume Hc, eq.rec_on (if_pos Hc) h theorem implies_of_if_neg {c t e : Type} [H : decidable c] (h : if c then t else e) : ¬c → e := assume Hnc, eq.rec_on (if_neg Hnc) h -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches definition dite (c : Type) [H : decidable c] {A : Type} (t : c → A) (e : ¬ c → A) : A := decidable.rec_on H (λ Hc, t Hc) (λ Hnc, e Hnc) definition dif_pos {c : Type} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = t (decidable.pos_witness Hc) := decidable.rec (λ Hc : c, eq.refl (@dite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H definition dif_neg {c : Type} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = e (decidable.neg_witness Hnc) := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@dite c (decidable.inr Hnc) A t e)) H -- Remark: dite and ite are "definitionally equal" when we ignore the proofs. definition dite_ite_eq (c : Type) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e := rfl end open eq.ops unit definition is_unit (c : Type) [H : decidable c] : Type₀ := if c then unit else empty definition is_empty (c : Type) [H : decidable c] : Type₀ := if c then empty else unit theorem of_is_unit {c : Type} [H₁ : decidable c] (H₂ : is_unit c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, empty.rec _ (if_neg Hnc ▸ H₂)) notation `dec_trivial` := of_is_unit star theorem not_of_not_is_unit {c : Type} [H₁ : decidable c] (H₂ : ¬ is_unit c) : ¬ c := decidable.rec_on H₁ (λ Hc, absurd star (if_pos Hc ▸ H₂)) (λ Hnc, Hnc) theorem not_of_is_empty {c : Type} [H₁ : decidable c] (H₂ : is_empty c) : ¬ c := decidable.rec_on H₁ (λ Hc, empty.rec _ (if_pos Hc ▸ H₂)) (λ Hnc, Hnc) theorem of_not_is_empty {c : Type} [H₁ : decidable c] (H₂ : ¬ is_empty c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, absurd star (if_neg Hnc ▸ H₂))
e63b553818fafd18aaa09b31ff60a51f73b9fb4f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/field_theory/fixed.lean
afb8a7d4b910250b551bee57084e0e51eaf30eba
[ "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
12,503
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.group_ring_action import deprecated.subfield import field_theory.normal import field_theory.separable import field_theory.tower import ring_theory.polynomial /-! # Fixed field under a group action. This is the basis of the Fundamental Theorem of Galois Theory. Given a (finite) group `G` that acts on a field `F`, we define `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`. This subfield is then normal and separable, and in addition (TODO) if `G` acts faithfully on `F` then `finrank (fixed_points G F) F = fintype.card G`. ## Main Definitions - `fixed_points G F`, the subfield consisting of elements of `F` fixed_points by every element of `G`, where `G` is a group that acts on `F`. -/ noncomputable theory open_locale classical big_operators open mul_action finset finite_dimensional universes u v w variables (G : Type u) [group G] (F : Type v) [field F] [mul_semiring_action G F] (g : G) instance fixed_by.is_subfield : is_subfield (fixed_by G F g) := { zero_mem := smul_zero g, add_mem := λ x y hx hy, (smul_add g x y).trans $ congr_arg2 _ hx hy, neg_mem := λ x hx, (smul_neg g x).trans $ congr_arg _ hx, one_mem := smul_one g, mul_mem := λ x y hx hy, (smul_mul' g x y).trans $ congr_arg2 _ hx hy, inv_mem := λ x hx, (smul_inv' F g x).trans $ congr_arg _ hx } namespace fixed_points instance : is_subfield (fixed_points G F) := by convert @is_subfield.Inter F _ G (fixed_by G F) _; rw fixed_eq_Inter_fixed_by instance : is_invariant_subring G (fixed_points G F) := { smul_mem := λ g x hx g', by rw [hx, hx] } @[simp] theorem smul (g : G) (x : fixed_points G F) : g • x = x := subtype.eq $ x.2 g -- Why is this so slow? @[simp] theorem smul_polynomial (g : G) (p : polynomial (fixed_points G F)) : g • p = p := polynomial.induction_on p (λ x, by rw [polynomial.smul_C, smul]) (λ p q ihp ihq, by rw [smul_add, ihp, ihq]) (λ n x ih, by rw [smul_mul', polynomial.smul_C, smul, smul_pow, polynomial.smul_X]) instance : algebra (fixed_points G F) F := algebra.of_is_subring _ theorem coe_algebra_map : algebra_map (fixed_points G F) F = is_subring.subtype (fixed_points G F) := rfl lemma linear_independent_smul_of_linear_independent {s : finset F} : linear_independent (fixed_points G F) (λ i : (↑s : set F), (i : F)) → linear_independent F (λ i : (↑s : set F), mul_action.to_fun G F i) := begin refine finset.induction_on s (λ _, linear_independent_empty_type $ λ ⟨x⟩, x.2) (λ a s has ih hs, _), rw coe_insert at hs ⊢, rw linear_independent_insert (mt mem_coe.1 has) at hs, rw linear_independent_insert' (mt mem_coe.1 has), refine ⟨ih hs.1, λ ha, _⟩, rw finsupp.mem_span_image_iff_total at ha, rcases ha with ⟨l, hl, hla⟩, rw [finsupp.total_apply_of_mem_supported F hl] at hla, suffices : ∀ i ∈ s, l i ∈ fixed_points G F, { replace hla := (sum_apply _ _ (λ i, l i • to_fun G F i)).symm.trans (congr_fun hla 1), simp_rw [pi.smul_apply, to_fun_apply, one_smul] at hla, refine hs.2 (hla ▸ submodule.sum_mem _ (λ c hcs, _)), change (⟨l c, this c hcs⟩ : fixed_points G F) • c ∈ _, exact submodule.smul_mem _ _ (submodule.subset_span $ mem_coe.2 hcs) }, intros i his g, refine eq_of_sub_eq_zero (linear_independent_iff'.1 (ih hs.1) s.attach (λ i, g • l i - l i) _ ⟨i, his⟩ (mem_attach _ _) : _), refine (@sum_attach _ _ s _ (λ i, (g • l i - l i) • (to_fun G F) i)).trans _, ext g', dsimp only, conv_lhs { rw sum_apply, congr, skip, funext, rw [pi.smul_apply, sub_smul, smul_eq_mul] }, rw [sum_sub_distrib, pi.zero_apply, sub_eq_zero], conv_lhs { congr, skip, funext, rw [to_fun_apply, ← mul_inv_cancel_left g g', mul_smul, ← smul_mul', ← to_fun_apply _ x] }, show ∑ x in s, g • (λ y, l y • to_fun G F y) x (g⁻¹ * g') = ∑ x in s, (λ y, l y • to_fun G F y) x g', rw [← smul_sum, ← sum_apply _ _ (λ y, l y • to_fun G F y), ← sum_apply _ _ (λ y, l y • to_fun G F y)], dsimp only, rw [hla, to_fun_apply, to_fun_apply, smul_smul, mul_inv_cancel_left] end variables [fintype G] (x : F) /-- `minpoly G F x` is the minimal polynomial of `(x : F)` over `fixed_points G F`. -/ def minpoly : polynomial (fixed_points G F) := (prod_X_sub_smul G F x).to_subring _ $ λ c hc g, let ⟨n, hc0, hn⟩ := polynomial.mem_frange_iff.1 hc in hn.symm ▸ prod_X_sub_smul.coeff G F x g n namespace minpoly theorem monic : (minpoly G F x).monic := by { simp only [minpoly, polynomial.monic_to_subring], exact prod_X_sub_smul.monic G F x } theorem eval₂ : polynomial.eval₂ (is_subring.subtype $ fixed_points G F) x (minpoly G F x) = 0 := begin rw [← prod_X_sub_smul.eval G F x, polynomial.eval₂_eq_eval_map], simp [minpoly], end theorem ne_one : minpoly G F x ≠ (1 : polynomial (fixed_points G F)) := λ H, have _ := eval₂ G F x, (one_ne_zero : (1 : F) ≠ 0) $ by rwa [H, polynomial.eval₂_one] at this theorem of_eval₂ (f : polynomial (fixed_points G F)) (hf : polynomial.eval₂ (is_subring.subtype $ fixed_points G F) x f = 0) : minpoly G F x ∣ f := begin rw [← polynomial.map_dvd_map' (is_subring.subtype $ fixed_points G F), minpoly, polynomial.map_to_subring, prod_X_sub_smul], refine fintype.prod_dvd_of_coprime (polynomial.pairwise_coprime_X_sub $ mul_action.injective_of_quotient_stabilizer G x) (λ y, quotient_group.induction_on y $ λ g, _), rw [polynomial.dvd_iff_is_root, polynomial.is_root.def, mul_action.of_quotient_stabilizer_mk, polynomial.eval_smul', ← is_invariant_subring.coe_subtype_hom' G (fixed_points G F), ← mul_semiring_action_hom.coe_polynomial, ← mul_semiring_action_hom.map_smul, smul_polynomial, mul_semiring_action_hom.coe_polynomial, is_invariant_subring.coe_subtype_hom', polynomial.eval_map, hf, smul_zero] end /- Why is this so slow? -/ theorem irreducible_aux (f g : polynomial (fixed_points G F)) (hf : f.monic) (hg : g.monic) (hfg : f * g = minpoly G F x) : f = 1 ∨ g = 1 := begin have hf2 : f ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_right _ _ }, have hg2 : g ∣ minpoly G F x, { rw ← hfg, exact dvd_mul_left _ _ }, have := eval₂ G F x, rw [← hfg, polynomial.eval₂_mul, mul_eq_zero] at this, cases this, { right, have hf3 : f = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hf (monic G F x) (associated_of_dvd_dvd hf2 $ @of_eval₂ G _ F _ _ _ x f this) }, rwa [← mul_one (minpoly G F x), hf3, mul_right_inj' (monic G F x).ne_zero] at hfg }, { left, have hg3 : g = minpoly G F x, { exact polynomial.eq_of_monic_of_associated hg (monic G F x) (associated_of_dvd_dvd hg2 $ @of_eval₂ G _ F _ _ _ x g this) }, rwa [← one_mul (minpoly G F x), hg3, mul_left_inj' (monic G F x).ne_zero] at hfg } end theorem irreducible : irreducible (minpoly G F x) := (polynomial.irreducible_of_monic (monic G F x) (ne_one G F x)).2 (irreducible_aux G F x) end minpoly theorem is_integral : is_integral (fixed_points G F) x := ⟨minpoly G F x, minpoly.monic G F x, minpoly.eval₂ G F x⟩ theorem minpoly_eq_minpoly : minpoly G F x = _root_.minpoly (fixed_points G F) x := minpoly.unique' (minpoly.irreducible G F x) (minpoly.eval₂ G F x) (minpoly.monic G F x) instance normal : normal (fixed_points G F) F := ⟨λ x, is_integral G F x, λ x, (polynomial.splits_id_iff_splits _).1 $ by { rw [← minpoly_eq_minpoly, minpoly, coe_algebra_map, polynomial.map_to_subring, prod_X_sub_smul], exact polynomial.splits_prod _ (λ _ _, polynomial.splits_X_sub_C _) }⟩ instance separable : is_separable (fixed_points G F) F := ⟨λ x, is_integral G F x, λ x, by { rw [← minpoly_eq_minpoly, ← polynomial.separable_map (is_subring.subtype (fixed_points G F)), minpoly, polynomial.map_to_subring], exact polynomial.separable_prod_X_sub_C_iff.2 (injective_of_quotient_stabilizer G x) }⟩ lemma dim_le_card : module.rank (fixed_points G F) F ≤ fintype.card G := begin refine dim_le (λ s hs, cardinal.nat_cast_le.1 _), rw [← @dim_fun' F G, ← cardinal.lift_nat_cast.{v (max u v)}, cardinal.finset_card, ← cardinal.lift_id (module.rank F (G → F))], exact linear_independent_le_dim'.{_ _ _ (max u v)} (linear_independent_smul_of_linear_independent G F hs) end instance : finite_dimensional (fixed_points G F) F := is_noetherian.iff_dim_lt_omega.2 $ lt_of_le_of_lt (dim_le_card G F) (cardinal.nat_lt_omega _) lemma finrank_le_card : finrank (fixed_points G F) F ≤ fintype.card G := by exact_mod_cast trans_rel_right (≤) (finrank_eq_dim _ _) (dim_le_card G F) end fixed_points lemma linear_independent_to_linear_map (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [integral_domain A] [algebra R A] [integral_domain B] [algebra R B] : linear_independent B (alg_hom.to_linear_map : (A →ₐ[R] B) → (A →ₗ[R] B)) := have linear_independent B (linear_map.lto_fun R A B ∘ alg_hom.to_linear_map), from ((linear_independent_monoid_hom A B).comp (coe : (A →ₐ[R] B) → (A →* B)) (λ f g hfg, alg_hom.ext $ monoid_hom.ext_iff.1 hfg) : _), this.of_comp _ lemma cardinal_mk_alg_hom (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : cardinal.mk (V →ₐ[K] W) ≤ finrank W (V →ₗ[K] W) := cardinal_mk_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V W noncomputable instance alg_hom.fintype (K : Type u) (V : Type v) (W : Type w) [field K] [field V] [algebra K V] [finite_dimensional K V] [field W] [algebra K W] [finite_dimensional K W] : fintype (V →ₐ[K] W) := classical.choice $ cardinal.lt_omega_iff_fintype.1 $ lt_of_le_of_lt (cardinal_mk_alg_hom K V W) (cardinal.nat_lt_omega _) noncomputable instance alg_equiv.fintype (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype (V ≃ₐ[K] V) := fintype.of_equiv (V →ₐ[K] V) (alg_equiv_equiv_alg_hom K V).symm lemma finrank_alg_hom (K : Type u) (V : Type v) [field K] [field V] [algebra K V] [finite_dimensional K V] : fintype.card (V →ₐ[K] V) ≤ finrank V (V →ₗ[K] V) := fintype_card_le_finrank_of_linear_independent $ linear_independent_to_linear_map K V V namespace fixed_points /-- Embedding produced from a faithful action. -/ @[simps apply {fully_applied := ff}] def to_alg_hom (G : Type u) (F : Type v) [group G] [field F] [faithful_mul_semiring_action G F] : G ↪ (F →ₐ[fixed_points G F] F) := { to_fun := λ g, { commutes' := λ x, x.2 g, .. mul_semiring_action.to_semiring_hom G F g }, inj' := λ g₁ g₂ hg, to_semiring_hom_injective G F $ ring_hom.ext $ λ x, alg_hom.ext_iff.1 hg x, } lemma to_alg_hom_apply_apply {G : Type u} {F : Type v} [group G] [field F] [faithful_mul_semiring_action G F] (g : G) (x : F) : to_alg_hom G F g x = g • x := rfl theorem finrank_eq_card (G : Type u) (F : Type v) [group G] [field F] [fintype G] [faithful_mul_semiring_action G F] : finrank (fixed_points G F) F = fintype.card G := le_antisymm (fixed_points.finrank_le_card G F) $ calc fintype.card G ≤ fintype.card (F →ₐ[fixed_points G F] F) : fintype.card_le_of_injective _ (to_alg_hom G F).2 ... ≤ finrank F (F →ₗ[fixed_points G F] F) : finrank_alg_hom (fixed_points G F) F ... = finrank (fixed_points G F) F : finrank_linear_map' _ _ _ theorem to_alg_hom_bijective (G : Type u) (F : Type v) [group G] [field F] [fintype G] [faithful_mul_semiring_action G F] : function.bijective (to_alg_hom G F) := begin rw fintype.bijective_iff_injective_and_card, split, { exact (to_alg_hom G F).injective }, { apply le_antisymm, { exact fintype.card_le_of_injective _ (to_alg_hom G F).injective }, { rw ← finrank_eq_card G F, exact has_le.le.trans_eq (finrank_alg_hom _ F) (finrank_linear_map' _ _ _) } }, end /-- Bijection between G and algebra homomorphisms that fix the fixed points -/ def to_alg_hom_equiv (G : Type u) (F : Type v) [group G] [field F] [fintype G] [faithful_mul_semiring_action G F] : G ≃ (F →ₐ[fixed_points G F] F) := function.embedding.equiv_of_surjective (to_alg_hom G F) (to_alg_hom_bijective G F).2 end fixed_points
eaf5b0705f200b14f44c6f9190bddbecd07df3e1
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/analytic/radius_liminf.lean
bd745bebaee509c268e2af0c344bbb4dff70c19b
[ "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
2,501
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.analytic.basic import analysis.special_functions.pow /-! # Representation of `formal_multilinear_series.radius` as a `liminf` In this file we prove that the radius of convergence of a `formal_multilinear_series` is equal to $\liminf_{n\to\infty} \frac{1}{\sqrt[n]{‖p n‖}}$. This lemma can't go to `basic.lean` because this would create a circular dependency once we redefine `exp` using `formal_multilinear_series`. -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] open_locale topology classical big_operators nnreal ennreal open filter asymptotics namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) /-- The radius of a formal multilinear series is equal to $\liminf_{n\to\infty} \frac{1}{\sqrt[n]{‖p n‖}}$. The actual statement uses `ℝ≥0` and some coercions. -/ lemma radius_eq_liminf : p.radius = liminf (λ n, 1/((‖p n‖₊) ^ (1 / (n : ℝ)) : ℝ≥0)) at_top := begin have : ∀ (r : ℝ≥0) {n : ℕ}, 0 < n → ((r : ℝ≥0∞) ≤ 1 / ↑(‖p n‖₊ ^ (1 / (n : ℝ))) ↔ ‖p n‖₊ * r ^ n ≤ 1), { intros r n hn, have : 0 < (n : ℝ) := nat.cast_pos.2 hn, conv_lhs {rw [one_div, ennreal.le_inv_iff_mul_le, ← ennreal.coe_mul, ennreal.coe_le_one_iff, one_div, ← nnreal.rpow_one r, ← mul_inv_cancel this.ne', nnreal.rpow_mul, ← nnreal.mul_rpow, ← nnreal.one_rpow (n⁻¹), nnreal.rpow_le_rpow_iff (inv_pos.2 this), mul_comm, nnreal.rpow_nat_cast] } }, apply le_antisymm; refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), { rcases ((tfae_exists_lt_is_o_pow (λ n, ‖p n‖ * r ^ n) 1).out 1 7).1 (p.is_o_of_lt_radius hr) with ⟨a, ha, H⟩, refine le_Liminf_of_le (by apply_auto_param) (eventually_map.2 $ _), refine H.mp ((eventually_gt_at_top 0).mono $ λ n hn₀ hn, (this _ hn₀).2 (nnreal.coe_le_coe.1 _)), push_cast, exact (le_abs_self _).trans (hn.trans (pow_le_one _ ha.1.le ha.2.le)) }, { refine p.le_radius_of_is_O (is_O.of_bound 1 _), refine (eventually_lt_of_lt_liminf hr).mp ((eventually_gt_at_top 0).mono (λ n hn₀ hn, _)), simpa using nnreal.coe_le_coe.2 ((this _ hn₀).1 hn.le) } end end formal_multilinear_series
a0bafa2b0463d1a8c5cd2880a9644907fe573347
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/multiset/basic.lean
24efa4ecbdd36590062010ee7e31f84f594eecf8
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
86,927
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.list.perm import algebra.group_power /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `multiset.cons`. -/ open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `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.is_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 /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof [has_sizeof α] (s : multiset α) : ℕ := quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩ /- 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 (p.cons a)) infixr ` ::ₘ `:67 := multiset.cons 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, singleton_perm_singleton.1 $ (perm_append_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 @[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` fails 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, h.rec_heq (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 $ e.mem_iff) 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 forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} : (∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x := quotient.induction_on' s $ λ L, list.forall_mem_cons 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_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ 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 section to_list /-- Produces a list of the elements in the multiset using choice. -/ @[reducible] noncomputable def to_list {α : Type*} (s : multiset α) := classical.some (quotient.exists_rep s) @[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] := (multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero)) lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s := classical.some_spec (quotient.exists_rep _) lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s := by rw [←multiset.mem_coe, multiset.coe_to_list] end to_list /- 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₂, subperm.subset 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, (nil_sublist l).subperm 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], ⟨(sublist_cons _ _).subperm, λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ 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 $ ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) 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_eq @[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 -/ instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩ instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩ @[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 $ p₁.append 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_append_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_append_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_add_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_nsmul, *, nat.succ_mul]; cc @[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⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_add_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_add_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)), 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) ▸ s, sublist.subperm⟩ /- 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 (p.erase a)) @[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, priority 990] 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, priority 980] 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, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_cons_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 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, (erase_sublist a l).subperm @[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, (h.erase _).subperm 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)⟩ @[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 card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) 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 (p.map f)) theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} : (∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) := quotient.induction_on' s $ λ L, list.forall_mem_map_iff @[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 lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by { induction k, simp, simpa } @[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) := { map_add := map_add _, map_zero := map_zero _ } @[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 _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_injective 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 _ _ _ 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, (h.map f).subperm @[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, p.foldl_eq H 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, p.foldr_eq H 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` -/ @[to_additive] def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 @[to_additive] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive] 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] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ attribute [norm_cast] coe_prod coe_sum @[simp, to_additive] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a ::ₘ s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive] theorem prod_singleton [comm_monoid α] (a : α) : prod (a ::ₘ 0) = a := by simp @[simp, to_additive] 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 α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (n •ℕ m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_smul n] @[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] prod_repeat lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := by simp lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := by simp attribute [to_additive] prod_map_one @[simp, to_additive] 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] 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]) theorem prod_ne_zero {R : Type*} [integral_domain R] {m : multiset R} : (∀ x ∈ m, (x : _) ≠ 0) → m.prod ≠ 0 := multiset.induction_on m (λ _, one_ne_zero) $ λ hd tl ih H, by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) } lemma prod_eq_zero {α : Type*} [comm_semiring α] {s : multiset α} (h : (0 : α) ∈ s) : multiset.prod s = 0 := begin rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩, simp [hs', multiset.prod_cons] end @[to_additive] lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) : (s.map f).prod = f s.prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod] @[to_additive] theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (s.map f).prod (s.map g).prod := quotient.induction_on s $ λ l, by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod] lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a theorem prod_eq_zero_iff [comm_cancel_monoid_with_zero α] [nontrivial α] {s : multiset α} : s.prod = 0 ↔ (0 : α) ∈ s := multiset.induction_on s (by simp) $ assume a s, by simp [mul_eq_zero, @eq_comm _ 0 a] {contextual := tt} @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod := quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl @[to_additive] lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod := quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} : (∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) := begin apply quotient.induction_on m, simp only [quot_mk_to_coe, coe_prod, mem_coe], intros l hl₁ hl₂ x hx, apply all_one_of_le_one_le_of_prod_eq_one hl₁ hl₂ _ hx, end lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} : m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) := quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left ih _) lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum := multiset.induction_on s (λ _, dvd_zero _) (λ x s ih h, by rw sum_cons; exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy))))) /- 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, 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 [add_comm, add_left_comm] {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] 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; cc @[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; cc @[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 (pp.subset 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 $ pp.pmap f @[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 sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := by { induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl } 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 $ p₁.diff 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₂, symmetry, 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 $ p₁.bag_inter 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₂, (bag_inter_sublist_left _ _).subperm 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 } 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, add_assoc] 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 $ h.filter p) @[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, (filter_sublist _).subperm @[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, (filter_sublist_filter h).subperm 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 $ h.filter_map f) @[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, (h.filter_map _).subperm /-! ### 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_eq 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 α → ℕ) := { map_add := countp_add, map_zero := countp_zero _ } 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, priority 990] 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_nsmul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp, priority 980] 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 theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [ne.def, count_eq_zero] @[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] theorem count_repeat (a b : α) (n : ℕ) : count a (repeat b n) = if (a = b) then n else 0 := begin split_ifs with h₁, { rw [h₁, count_repeat_self] }, { rw [count_eq_zero], apply mt eq_of_mem_repeat h₁ }, end @[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, priority 980] 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_sum {m : multiset β} {f : β → multiset α} {a : α} : count a (map f m).sum = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) ( by simp) lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum 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_of_pos {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 @[simp] theorem count_filter_of_neg {p} [decidable_pred p] {a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 := multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t)) 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 @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp 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 only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.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) 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 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 map_injective {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₂ 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, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a ::ₘ 0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] 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 := by rw [disjoint_comm, disjoint_add_left]; tauto @[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 := by rw [disjoint_comm, disjoint_cons_left]; tauto 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⟩, ((quotient.exact eq).pairwise_iff hr).2 h) (assume h, ⟨l, rfl, h⟩) end multiset namespace multiset section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ 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 variable (α) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } end multiset @[to_additive] theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) : f s.prod = (s.map f).prod := (s.prod_hom f).symm
f4fef0aeea8f11ef5e3ed37d1993a7fa5f9b689c
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_547.lean
64c63fc8ce5cfcda17d9e3f2c8b24f709f6c3a30
[]
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
348
lean
import tactic variables (R : Type*) [comm_ring R] variables a b c d : R example : (c * b) * a = b * (a * c) := by ring example : (a + b) * (a + b) = a * a + 2 * (a * b) + b * b := by ring example : (a + b) * (a - b) = a^2 - b^2 := by ring example (hyp : c = d * a + b) (hyp' : b = a * d) : c = 2 * a * d := begin rw [hyp, hyp'], ring end
dfc3efc20be17b6466f55a8131752302afc389e6
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/tactic28.lean
5c70900a561ea5aeb8100bd1e03470f22a2c8a69
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
814
lean
import logic data.num open tactic inhabited namespace foo inductive sum (A : Type) (B : Type) : Type := inl : A → sum A B, inr : B → sum A B theorem inl_inhabited {A : Type} (B : Type) (H : inhabited A) : inhabited (sum A B) := inhabited.destruct H (λ a, inhabited.mk (sum.inl B a)) theorem inr_inhabited (A : Type) {B : Type} (H : inhabited B) : inhabited (sum A B) := inhabited.destruct H (λ b, inhabited.mk (sum.inr A b)) infixl `..`:10 := append definition my_tac := repeat (trace "iteration"; state; ( apply @inl_inhabited; trace "used inl" .. apply @inr_inhabited; trace "used inr" .. apply @num.is_inhabited; trace "used num")) ; now tactic_hint my_tac theorem T : inhabited (sum false num) end foo
f5820c6c9cd2439b6dd9bb9d1ec0c671f38eaf5a
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/tests/lean/holeErrors.lean
d6be4d745252d26ce02c843d58526be8b3e2d30b
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
150
lean
def f1 := id def f2 : _ := id def f3 := let x := id; x def f4 (x) := x def f5 (x : _) := x def f6 := fun x => x def f7 := let rec x := id; 10
38ff58519429de01b1197d8f14dfd00b5a5d1c3f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/combinatorics/configuration.lean
045dc0b38b4bb567d77b7ea66312f8cd8450151c
[ "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
23,710
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.big_operators.order import combinatorics.hall.basic import data.fintype.big_operators import set_theory.cardinal.finite /-! # Configurations of Points and lines This file introduces abstract configurations of points and lines, and proves some basic properties. ## Main definitions * `configuration.nondegenerate`: Excludes certain degenerate configurations, and imposes uniqueness of intersection points. * `configuration.has_points`: A nondegenerate configuration in which every pair of lines has an intersection point. * `configuration.has_lines`: A nondegenerate configuration in which every pair of points has a line through them. * `configuration.line_count`: The number of lines through a given point. * `configuration.point_count`: The number of lines through a given line. ## Main statements * `configuration.has_lines.card_le`: `has_lines` implies `|P| ≤ |L|`. * `configuration.has_points.card_le`: `has_points` implies `|L| ≤ |P|`. * `configuration.has_lines.has_points`: `has_lines` and `|P| = |L|` implies `has_points`. * `configuration.has_points.has_lines`: `has_points` and `|P| = |L|` implies `has_lines`. Together, these four statements say that any two of the following properties imply the third: (a) `has_lines`, (b) `has_points`, (c) `|P| = |L|`. -/ open_locale big_operators namespace configuration universe u variables (P L : Type u) [has_mem P L] /-- A type synonym. -/ def dual := P instance [this : inhabited P] : inhabited (dual P) := this instance [finite P] : finite (dual P) := ‹finite P› instance [this : fintype P] : fintype (dual P) := this instance : has_mem (dual L) (dual P) := ⟨function.swap (has_mem.mem : P → L → Prop)⟩ /-- A configuration is nondegenerate if: 1) there does not exist a line that passes through all of the points, 2) there does not exist a point that is on all of the lines, 3) there is at most one line through any two points, 4) any two lines have at most one intersection point. Conditions 3 and 4 are equivalent. -/ class nondegenerate : Prop := (exists_point : ∀ l : L, ∃ p, p ∉ l) (exists_line : ∀ p, ∃ l : L, p ∉ l) (eq_or_eq : ∀ {p₁ p₂ : P} {l₁ l₂ : L}, p₁ ∈ l₁ → p₂ ∈ l₁ → p₁ ∈ l₂ → p₂ ∈ l₂ → p₁ = p₂ ∨ l₁ = l₂) /-- A nondegenerate configuration in which every pair of lines has an intersection point. -/ class has_points extends nondegenerate P L : Type u := (mk_point : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), P) (mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂) /-- A nondegenerate configuration in which every pair of points has a line through them. -/ class has_lines extends nondegenerate P L : Type u := (mk_line : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), L) (mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h) open nondegenerate has_points has_lines instance [nondegenerate P L] : nondegenerate (dual L) (dual P) := { exists_point := @exists_line P L _ _, exists_line := @exists_point P L _ _, eq_or_eq := λ l₁ l₂ p₁ p₂ h₁ h₂ h₃ h₄, (@eq_or_eq P L _ _ p₁ p₂ l₁ l₂ h₁ h₃ h₂ h₄).symm } instance [has_points P L] : has_lines (dual L) (dual P) := { mk_line := @mk_point P L _ _, mk_line_ax := λ _ _, mk_point_ax } instance [has_lines P L] : has_points (dual L) (dual P) := { mk_point := @mk_line P L _ _, mk_point_ax := λ _ _, mk_line_ax } lemma has_points.exists_unique_point [has_points P L] (l₁ l₂ : L) (hl : l₁ ≠ l₂) : ∃! p, p ∈ l₁ ∧ p ∈ l₂ := ⟨mk_point hl, mk_point_ax hl, λ p hp, (eq_or_eq hp.1 (mk_point_ax hl).1 hp.2 (mk_point_ax hl).2).resolve_right hl⟩ lemma has_lines.exists_unique_line [has_lines P L] (p₁ p₂ : P) (hp : p₁ ≠ p₂) : ∃! l : L, p₁ ∈ l ∧ p₂ ∈ l := has_points.exists_unique_point (dual L) (dual P) p₁ p₂ hp variables {P L} /-- If a nondegenerate configuration has at least as many points as lines, then there exists an injective function `f` from lines to points, such that `f l` does not lie on `l`. -/ lemma nondegenerate.exists_injective_of_card_le [nondegenerate P L] [fintype P] [fintype L] (h : fintype.card L ≤ fintype.card P) : ∃ f : L → P, function.injective f ∧ ∀ l, (f l) ∉ l := begin classical, let t : L → finset P := λ l, (set.to_finset {p | p ∉ l}), suffices : ∀ s : finset L, s.card ≤ (s.bUnion t).card, -- Hall's marriage theorem { obtain ⟨f, hf1, hf2⟩ := (finset.all_card_le_bUnion_card_iff_exists_injective t).mp this, exact ⟨f, hf1, λ l, set.mem_to_finset.mp (hf2 l)⟩ }, intro s, by_cases hs₀ : s.card = 0, -- If `s = ∅`, then `s.card = 0 ≤ (s.bUnion t).card` { simp_rw [hs₀, zero_le] }, by_cases hs₁ : s.card = 1, -- If `s = {l}`, then pick a point `p ∉ l` { obtain ⟨l, rfl⟩ := finset.card_eq_one.mp hs₁, obtain ⟨p, hl⟩ := exists_point l, rw [finset.card_singleton, finset.singleton_bUnion, nat.one_le_iff_ne_zero], exact finset.card_ne_zero_of_mem (set.mem_to_finset.mpr hl) }, suffices : (s.bUnion t)ᶜ.card ≤ sᶜ.card, -- Rephrase in terms of complements (uses `h`) { rw [finset.card_compl, finset.card_compl, tsub_le_iff_left] at this, replace := h.trans this, rwa [←add_tsub_assoc_of_le s.card_le_univ, le_tsub_iff_left (le_add_left s.card_le_univ), add_le_add_iff_right] at this }, have hs₂ : (s.bUnion t)ᶜ.card ≤ 1, -- At most one line through two points of `s` { refine finset.card_le_one_iff.mpr (λ p₁ p₂ hp₁ hp₂, _), simp_rw [finset.mem_compl, finset.mem_bUnion, exists_prop, not_exists, not_and, set.mem_to_finset, set.mem_set_of_eq, not_not] at hp₁ hp₂, obtain ⟨l₁, l₂, hl₁, hl₂, hl₃⟩ := finset.one_lt_card_iff.mp (nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨hs₀, hs₁⟩), exact (eq_or_eq (hp₁ l₁ hl₁) (hp₂ l₁ hl₁) (hp₁ l₂ hl₂) (hp₂ l₂ hl₂)).resolve_right hl₃ }, by_cases hs₃ : sᶜ.card = 0, { rw [hs₃, le_zero_iff], rw [finset.card_compl, tsub_eq_zero_iff_le, has_le.le.le_iff_eq (finset.card_le_univ _), eq_comm, finset.card_eq_iff_eq_univ] at hs₃ ⊢, rw hs₃, rw finset.eq_univ_iff_forall at hs₃ ⊢, exact λ p, exists.elim (exists_line p) -- If `s = univ`, then show `s.bUnion t = univ` (λ l hl, finset.mem_bUnion.mpr ⟨l, finset.mem_univ l, set.mem_to_finset.mpr hl⟩) }, { exact hs₂.trans (nat.one_le_iff_ne_zero.mpr hs₃) }, -- If `s < univ`, then consequence of `hs₂` end variables {P} (L) /-- Number of points on a given line. -/ noncomputable def line_count (p : P) : ℕ := nat.card {l : L // p ∈ l} variables (P) {L} /-- Number of lines through a given point. -/ noncomputable def point_count (l : L) : ℕ := nat.card {p : P // p ∈ l} variables (P L) lemma sum_line_count_eq_sum_point_count [fintype P] [fintype L] : ∑ p : P, line_count L p = ∑ l : L, point_count P l := begin classical, simp only [line_count, point_count, nat.card_eq_fintype_card, ←fintype.card_sigma], apply fintype.card_congr, calc (Σ p, {l : L // p ∈ l}) ≃ {x : P × L // x.1 ∈ x.2} : (equiv.subtype_prod_equiv_sigma_subtype (∈)).symm ... ≃ {x : L × P // x.2 ∈ x.1} : (equiv.prod_comm P L).subtype_equiv (λ x, iff.rfl) ... ≃ (Σ l, {p // p ∈ l}) : equiv.subtype_prod_equiv_sigma_subtype (λ (l : L) (p : P), p ∈ l), end variables {P L} lemma has_lines.point_count_le_line_count [has_lines P L] {p : P} {l : L} (h : p ∉ l) [finite {l : L // p ∈ l}] : point_count P l ≤ line_count L p := begin by_cases hf : infinite {p : P // p ∈ l}, { exactI (le_of_eq nat.card_eq_zero_of_infinite).trans (zero_le (line_count L p)) }, haveI := fintype_of_not_infinite hf, casesI nonempty_fintype {l : L // p ∈ l}, rw [line_count, point_count, nat.card_eq_fintype_card, nat.card_eq_fintype_card], have : ∀ p' : {p // p ∈ l}, p ≠ p' := λ p' hp', h ((congr_arg (∈ l) hp').mpr p'.2), exact fintype.card_le_of_injective (λ p', ⟨mk_line (this p'), (mk_line_ax (this p')).1⟩) (λ p₁ p₂ hp, subtype.ext ((eq_or_eq p₁.2 p₂.2 (mk_line_ax (this p₁)).2 ((congr_arg _ (subtype.ext_iff.mp hp)).mpr (mk_line_ax (this p₂)).2)).resolve_right (λ h', (congr_arg _ h').mp h (mk_line_ax (this p₁)).1))), end lemma has_points.line_count_le_point_count [has_points P L] {p : P} {l : L} (h : p ∉ l) [hf : finite {p : P // p ∈ l}] : line_count L p ≤ point_count P l := @has_lines.point_count_le_line_count (dual L) (dual P) _ _ l p h hf variables (P L) /-- If a nondegenerate configuration has a unique line through any two points, then `|P| ≤ |L|`. -/ lemma has_lines.card_le [has_lines P L] [fintype P] [fintype L] : fintype.card P ≤ fintype.card L := begin classical, by_contradiction hc₂, obtain ⟨f, hf₁, hf₂⟩ := nondegenerate.exists_injective_of_card_le (le_of_not_le hc₂), have := calc ∑ p, line_count L p = ∑ l, point_count P l : sum_line_count_eq_sum_point_count P L ... ≤ ∑ l, line_count L (f l) : finset.sum_le_sum (λ l hl, has_lines.point_count_le_line_count (hf₂ l)) ... = ∑ p in finset.univ.image f, line_count L p : finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_image_of_mem f hl) (λ l hl, rfl) (λ l₁ l₂ hl₁ hl₂ hl₃, hf₁ hl₃) (λ p, by simp_rw [finset.mem_image, eq_comm, imp_self]) ... < ∑ p, line_count L p : _, { exact lt_irrefl _ this }, { obtain ⟨p, hp⟩ := not_forall.mp (mt (fintype.card_le_of_surjective f) hc₂), refine finset.sum_lt_sum_of_subset ((finset.univ.image f).subset_univ) (finset.mem_univ p) _ _ (λ p hp₁ hp₂, zero_le (line_count L p)), { simpa only [finset.mem_image, exists_prop, finset.mem_univ, true_and] }, { rw [line_count, nat.card_eq_fintype_card, fintype.card_pos_iff], obtain ⟨l, hl⟩ := @exists_line P L _ _ p, exact let this := not_exists.mp hp l in ⟨⟨mk_line this, (mk_line_ax this).2⟩⟩ } }, end /-- If a nondegenerate configuration has a unique point on any two lines, then `|L| ≤ |P|`. -/ lemma has_points.card_le [has_points P L] [fintype P] [fintype L] : fintype.card L ≤ fintype.card P := @has_lines.card_le (dual L) (dual P) _ _ _ _ variables {P L} lemma has_lines.exists_bijective_of_card_eq [has_lines P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : ∃ f : L → P, function.bijective f ∧ ∀ l, point_count P l = line_count L (f l) := begin classical, obtain ⟨f, hf1, hf2⟩ := nondegenerate.exists_injective_of_card_le (ge_of_eq h), have hf3 := (fintype.bijective_iff_injective_and_card f).mpr ⟨hf1, h.symm⟩, refine ⟨f, hf3, λ l, (finset.sum_eq_sum_iff_of_le (by exact λ l hl, has_lines.point_count_le_line_count (hf2 l))).mp ((sum_line_count_eq_sum_point_count P L).symm.trans ((finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, refl (line_count L (f l))) (λ l₁ l₂ hl₁ hl₂ hl, hf1 hl) (λ p hp, _)).symm)) l (finset.mem_univ l)⟩, obtain ⟨l, rfl⟩ := hf3.2 p, exact ⟨l, finset.mem_univ l, rfl⟩, end lemma has_lines.line_count_eq_point_count [has_lines P L] [fintype P] [fintype L] (hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : line_count L p = point_count P l := begin classical, obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq hPL, let s : finset (P × L) := set.to_finset {i | i.1 ∈ i.2}, have step1 : ∑ i : P × L, line_count L i.1 = ∑ i : P × L, point_count P i.2, { rw [←finset.univ_product_univ, finset.sum_product_right, finset.sum_product], simp_rw [finset.sum_const, finset.card_univ, hPL, sum_line_count_eq_sum_point_count] }, have step2 : ∑ i in s, line_count L i.1 = ∑ i in s, point_count P i.2, { rw [s.sum_finset_product finset.univ (λ p, set.to_finset {l | p ∈ l})], rw [s.sum_finset_product_right finset.univ (λ l, set.to_finset {p | p ∈ l})], refine (finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, _) (λ _ _ _ _ h, hf1.1 h) (λ p hp, _)).symm, { simp_rw [finset.sum_const, set.to_finset_card, ←nat.card_eq_fintype_card], change (point_count P l) • (point_count P l) = (line_count L (f l)) • (line_count L (f l)), rw hf2 }, { obtain ⟨l, hl⟩ := hf1.2 p, exact ⟨l, finset.mem_univ l, hl.symm⟩ }, all_goals { simp_rw [finset.mem_univ, true_and, set.mem_to_finset], exact λ p, iff.rfl } }, have step3 : ∑ i in sᶜ, line_count L i.1 = ∑ i in sᶜ, point_count P i.2, { rwa [←s.sum_add_sum_compl, ←s.sum_add_sum_compl, step2, add_left_cancel_iff] at step1 }, rw ← set.to_finset_compl at step3, exact ((finset.sum_eq_sum_iff_of_le (by exact λ i hi, has_lines.point_count_le_line_count (set.mem_to_finset.mp hi))).mp step3.symm (p, l) (set.mem_to_finset.mpr hpl)).symm, end lemma has_points.line_count_eq_point_count [has_points P L] [fintype P] [fintype L] (hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : line_count L p = point_count P l := (@has_lines.line_count_eq_point_count (dual L) (dual P) _ _ _ _ hPL.symm l p hpl).symm /-- If a nondegenerate configuration has a unique line through any two points, and if `|P| = |L|`, then there is a unique point on any two lines. -/ noncomputable def has_lines.has_points [has_lines P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : has_points P L := let this : ∀ l₁ l₂ : L, l₁ ≠ l₂ → ∃ p : P, p ∈ l₁ ∧ p ∈ l₂ := λ l₁ l₂ hl, begin classical, obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq h, haveI : nontrivial L := ⟨⟨l₁, l₂, hl⟩⟩, haveI := fintype.one_lt_card_iff_nontrivial.mp ((congr_arg _ h).mpr fintype.one_lt_card), have h₁ : ∀ p : P, 0 < line_count L p := λ p, exists.elim (exists_ne p) (λ q hq, (congr_arg _ nat.card_eq_fintype_card).mpr (fintype.card_pos_iff.mpr ⟨⟨mk_line hq, (mk_line_ax hq).2⟩⟩)), have h₂ : ∀ l : L, 0 < point_count P l := λ l, (congr_arg _ (hf2 l)).mpr (h₁ (f l)), obtain ⟨p, hl₁⟩ := fintype.card_pos_iff.mp ((congr_arg _ nat.card_eq_fintype_card).mp (h₂ l₁)), by_cases hl₂ : p ∈ l₂, exact ⟨p, hl₁, hl₂⟩, have key' : fintype.card {q : P // q ∈ l₂} = fintype.card {l : L // p ∈ l}, { exact ((has_lines.line_count_eq_point_count h hl₂).trans nat.card_eq_fintype_card).symm.trans nat.card_eq_fintype_card, }, have : ∀ q : {q // q ∈ l₂}, p ≠ q := λ q hq, hl₂ ((congr_arg (∈ l₂) hq).mpr q.2), let f : {q : P // q ∈ l₂} → {l : L // p ∈ l} := λ q, ⟨mk_line (this q), (mk_line_ax (this q)).1⟩, have hf : function.injective f := λ q₁ q₂ hq, subtype.ext ((eq_or_eq q₁.2 q₂.2 (mk_line_ax (this q₁)).2 ((congr_arg _ (subtype.ext_iff.mp hq)).mpr (mk_line_ax (this q₂)).2)).resolve_right (λ h, (congr_arg _ h).mp hl₂ (mk_line_ax (this q₁)).1)), have key' := ((fintype.bijective_iff_injective_and_card f).mpr ⟨hf, key'⟩).2, obtain ⟨q, hq⟩ := key' ⟨l₁, hl₁⟩, exact ⟨q, (congr_arg _ (subtype.ext_iff.mp hq)).mp (mk_line_ax (this q)).2, q.2⟩, end in { mk_point := λ l₁ l₂ hl, classical.some (this l₁ l₂ hl), mk_point_ax := λ l₁ l₂ hl, classical.some_spec (this l₁ l₂ hl) } /-- If a nondegenerate configuration has a unique point on any two lines, and if `|P| = |L|`, then there is a unique line through any two points. -/ noncomputable def has_points.has_lines [has_points P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : has_lines P L := let this := @has_lines.has_points (dual L) (dual P) _ _ _ _ h.symm in { mk_line := λ _ _, this.mk_point, mk_line_ax := λ _ _, this.mk_point_ax } variables (P L) /-- A projective plane is a nondegenerate configuration in which every pair of lines has an intersection point, every pair of points has a line through them, and which has three points in general position. -/ class projective_plane extends nondegenerate P L : Type u := (mk_point : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), P) (mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂) (mk_line : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), L) (mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h) (exists_config : ∃ (p₁ p₂ p₃ : P) (l₁ l₂ l₃ : L), p₁ ∉ l₂ ∧ p₁ ∉ l₃ ∧ p₂ ∉ l₁ ∧ p₂ ∈ l₂ ∧ p₂ ∈ l₃ ∧ p₃ ∉ l₁ ∧ p₃ ∈ l₂ ∧ p₃ ∉ l₃) namespace projective_plane @[priority 100] -- see Note [lower instance priority] instance has_points [h : projective_plane P L] : has_points P L := { .. h } @[priority 100] -- see Note [lower instance priority] instance has_lines [h : projective_plane P L] : has_lines P L := { .. h } variables [projective_plane P L] instance : projective_plane (dual L) (dual P) := { mk_line := @mk_point P L _ _, mk_line_ax := λ _ _, mk_point_ax, mk_point := @mk_line P L _ _, mk_point_ax := λ _ _, mk_line_ax, exists_config := by { obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _, exact ⟨l₁, l₂, l₃, p₁, p₂, p₃, h₂₁, h₃₁, h₁₂, h₂₂, h₃₂, h₁₃, h₂₃, h₃₃⟩ }, .. dual.nondegenerate P L } /-- The order of a projective plane is one less than the number of lines through an arbitrary point. Equivalently, it is one less than the number of points on an arbitrary line. -/ noncomputable def order : ℕ := line_count L (classical.some (@exists_config P L _ _)) - 1 lemma card_points_eq_card_lines [fintype P] [fintype L] : fintype.card P = fintype.card L := le_antisymm (has_lines.card_le P L) (has_points.card_le P L) variables {P} (L) lemma line_count_eq_line_count [finite P] [finite L] (p q : P) : line_count L p = line_count L q := begin casesI nonempty_fintype P, casesI nonempty_fintype L, obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := exists_config, have h := card_points_eq_card_lines P L, let n := line_count L p₂, have hp₂ : line_count L p₂ = n := rfl, have hl₁ : point_count P l₁ = n := (has_lines.line_count_eq_point_count h h₂₁).symm.trans hp₂, have hp₃ : line_count L p₃ = n := (has_lines.line_count_eq_point_count h h₃₁).trans hl₁, have hl₃ : point_count P l₃ = n := (has_lines.line_count_eq_point_count h h₃₃).symm.trans hp₃, have hp₁ : line_count L p₁ = n := (has_lines.line_count_eq_point_count h h₁₃).trans hl₃, have hl₂ : point_count P l₂ = n := (has_lines.line_count_eq_point_count h h₁₂).symm.trans hp₁, suffices : ∀ p : P, line_count L p = n, { exact (this p).trans (this q).symm }, refine λ p, or_not.elim (λ h₂, _) (λ h₂, (has_lines.line_count_eq_point_count h h₂).trans hl₂), refine or_not.elim (λ h₃, _) (λ h₃, (has_lines.line_count_eq_point_count h h₃).trans hl₃), rwa (eq_or_eq h₂ h₂₂ h₃ h₂₃).resolve_right (λ h, h₃₃ ((congr_arg (has_mem.mem p₃) h).mp h₃₂)), end variables (P) {L} lemma point_count_eq_point_count [finite P] [finite L] (l m : L) : point_count P l = point_count P m := line_count_eq_line_count (dual P) l m variables {P L} lemma line_count_eq_point_count [finite P] [finite L] (p : P) (l : L) : line_count L p = point_count P l := exists.elim (exists_point l) $ λ q hq, (line_count_eq_line_count L p q).trans $ by { casesI nonempty_fintype P, casesI nonempty_fintype L, exact has_lines.line_count_eq_point_count (card_points_eq_card_lines P L) hq } variables (P L) lemma dual.order [finite P] [finite L] : order (dual L) (dual P) = order P L := congr_arg (λ n, n - 1) (line_count_eq_point_count _ _) variables {P} (L) lemma line_count_eq [finite P] [finite L] (p : P) : line_count L p = order P L + 1 := begin classical, obtain ⟨q, -, -, l, -, -, -, -, h, -⟩ := classical.some_spec (@exists_config P L _ _), casesI nonempty_fintype {l : L // q ∈ l}, rw [order, line_count_eq_line_count L p q, line_count_eq_line_count L (classical.some _) q, line_count, nat.card_eq_fintype_card, nat.sub_add_cancel], exact fintype.card_pos_iff.mpr ⟨⟨l, h⟩⟩, end variables (P) {L} lemma point_count_eq [finite P] [finite L] (l : L) : point_count P l = order P L + 1 := (line_count_eq (dual P) l).trans (congr_arg (λ n, n + 1) (dual.order P L)) variables (P L) lemma one_lt_order [finite P] [finite L] : 1 < order P L := begin obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, -, -, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _, classical, casesI nonempty_fintype {p : P // p ∈ l₂}, rw [←add_lt_add_iff_right, ←point_count_eq _ l₂, point_count, nat.card_eq_fintype_card], simp_rw [fintype.two_lt_card_iff, ne, subtype.ext_iff], have h := mk_point_ax (λ h, h₂₁ ((congr_arg _ h).mpr h₂₂)), exact ⟨⟨mk_point _, h.2⟩, ⟨p₂, h₂₂⟩, ⟨p₃, h₃₂⟩, ne_of_mem_of_not_mem h.1 h₂₁, ne_of_mem_of_not_mem h.1 h₃₁, ne_of_mem_of_not_mem h₂₃ h₃₃⟩, end variables {P} (L) lemma two_lt_line_count [finite P] [finite L] (p : P) : 2 < line_count L p := by simpa only [line_count_eq L p, nat.succ_lt_succ_iff] using one_lt_order P L variables (P) {L} lemma two_lt_point_count [finite P] [finite L] (l : L) : 2 < point_count P l := by simpa only [point_count_eq P l, nat.succ_lt_succ_iff] using one_lt_order P L variables (P) (L) lemma card_points [fintype P] [finite L] : fintype.card P = order P L ^ 2 + order P L + 1 := begin casesI nonempty_fintype L, obtain ⟨p, -⟩ := @exists_config P L _ _, let ϕ : {q // q ≠ p} ≃ Σ (l : {l : L // p ∈ l}), {q // q ∈ l.1 ∧ q ≠ p} := { to_fun := λ q, ⟨⟨mk_line q.2, (mk_line_ax q.2).2⟩, q, (mk_line_ax q.2).1, q.2⟩, inv_fun := λ lq, ⟨lq.2, lq.2.2.2⟩, left_inv := λ q, subtype.ext rfl, right_inv := λ lq, sigma.subtype_ext (subtype.ext ((eq_or_eq (mk_line_ax lq.2.2.2).1 (mk_line_ax lq.2.2.2).2 lq.2.2.1 lq.1.2).resolve_left lq.2.2.2)) rfl }, classical, have h1 : fintype.card {q // q ≠ p} + 1 = fintype.card P, { apply (eq_tsub_iff_add_eq_of_le (nat.succ_le_of_lt (fintype.card_pos_iff.mpr ⟨p⟩))).mp, convert (fintype.card_subtype_compl _).trans (congr_arg _ (fintype.card_subtype_eq p)) }, have h2 : ∀ l : {l : L // p ∈ l}, fintype.card {q // q ∈ l.1 ∧ q ≠ p} = order P L, { intro l, rw [←fintype.card_congr (equiv.subtype_subtype_equiv_subtype_inter _ _), fintype.card_subtype_compl (λ (x : subtype (∈ l.val)), x.val = p), ←nat.card_eq_fintype_card], refine tsub_eq_of_eq_add ((point_count_eq P l.1).trans _), rw ← fintype.card_subtype_eq (⟨p, l.2⟩ : {q : P // q ∈ l.1}), simp_rw subtype.ext_iff_val }, simp_rw [←h1, fintype.card_congr ϕ, fintype.card_sigma, h2, finset.sum_const, finset.card_univ], rw [←nat.card_eq_fintype_card, ←line_count, line_count_eq, smul_eq_mul, nat.succ_mul, sq], end lemma card_lines [finite P] [fintype L] : fintype.card L = order P L ^ 2 + order P L + 1 := (card_points (dual L) (dual P)).trans (congr_arg (λ n, n ^ 2 + n + 1) (dual.order P L)) end projective_plane end configuration
a79179bf6947b8413c609f4fbc9f7ac8ca98760a
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/types/pointed.hlean
08ad9c7c38090289c413ee714f9695bc7b746f9f
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
47,601
hlean
/- Copyright (c) 2014-2016 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 Early library ported from Coq HoTT, but greatly extended since. The basic definitions are in init.pointed See also .pointed2 -/ import .nat.basic ..arity ..prop_trunc open is_trunc eq prod sigma nat equiv option is_equiv bool unit sigma.ops sum algebra function namespace pointed variables {A B : Type} definition pointed_loop [instance] [constructor] (a : A) : pointed (a = a) := pointed.mk idp definition pointed_fun_closed [constructor] (f : A → B) [H : pointed A] : pointed B := pointed.mk (f pt) definition loop [reducible] [constructor] (A : Type*) : Type* := pointed.mk' (point A = point A) definition loopn [reducible] : ℕ → Type* → Type* | loopn 0 X := X | loopn (n+1) X := loop (loopn n X) notation `Ω` := loop notation `Ω[`:95 n:0 `]`:0 := loopn n namespace ops -- this is in a separate namespace because it caused type class inference to loop in some places definition is_trunc_pointed_MK [instance] [priority 1100] (n : ℕ₋₂) {A : Type} (a : A) [H : is_trunc n A] : is_trunc n (pointed.MK A a) := H end ops definition is_trunc_loop [instance] [priority 1100] (A : Type*) (n : ℕ₋₂) [H : is_trunc (n.+1) A] : is_trunc n (Ω A) := !is_trunc_eq definition loopn_zero_eq [unfold_full] (A : Type*) : Ω[0] A = A := rfl definition loopn_succ_eq [unfold_full] (k : ℕ) (A : Type*) : Ω[succ k] A = Ω (Ω[k] A) := rfl definition rfln [constructor] [reducible] {n : ℕ} {A : Type*} : Ω[n] A := pt definition refln [constructor] [reducible] (n : ℕ) (A : Type*) : Ω[n] A := pt definition refln_eq_refl [unfold_full] (A : Type*) (n : ℕ) : rfln = rfl :> Ω[succ n] A := rfl definition loopn_space [unfold 3] (A : Type) [H : pointed A] (n : ℕ) : Type := Ω[n] (pointed.mk' A) definition loop_mul {k : ℕ} {A : Type*} (mul : A → A → A) : Ω[k] A → Ω[k] A → Ω[k] A := begin cases k with k, exact mul, exact concat end definition pType_eq {A B : Type*} (f : A ≃ B) (p : f pt = pt) : A = B := begin cases A with A a, cases B with B b, esimp at *, fapply apdt011 @pType.mk, { apply ua f}, { rewrite [cast_ua, p]}, end definition pType_eq_elim {A B : Type*} (p : A = B :> Type*) : Σ(p : carrier A = carrier B :> Type), Point A =[p] Point B := by induction p; exact ⟨idp, idpo⟩ protected definition pType.sigma_char.{u} : pType.{u} ≃ Σ(X : Type.{u}), X := begin fapply equiv.MK, { intro x, induction x with X x, exact ⟨X, x⟩}, { intro x, induction x with X x, exact pointed.MK X x}, { intro x, induction x with X x, reflexivity}, { intro x, induction x with X x, reflexivity}, end definition pType.eta_expand [constructor] (A : Type*) : Type* := pointed.MK A pt definition add_point [constructor] (A : Type) : Type* := pointed.Mk (none : option A) postfix `₊`:(max+1) := add_point -- the inclusion A → A₊ is called "some", the extra point "pt" or "none" ("@none A") end pointed namespace pointed /- truncated pointed types -/ definition ptrunctype_eq {n : ℕ₋₂} {A B : n-Type*} (p : A = B :> Type) (q : Point A =[p] Point B) : A = B := begin induction A with A HA a, induction B with B HB b, esimp at *, induction q, esimp, refine ap010 (ptrunctype.mk A) _ a, exact !is_prop.elim end definition ptrunctype_eq_of_pType_eq {n : ℕ₋₂} {A B : n-Type*} (p : A = B :> Type*) : A = B := begin cases pType_eq_elim p with q r, exact ptrunctype_eq q r end definition is_trunc_ptrunctype [instance] {n : ℕ₋₂} (A : n-Type*) : is_trunc n A := trunctype.struct A end pointed open pointed namespace pointed variables {A B C D : Type*} {f g h : A →* B} {P : A → Type} {p₀ : P pt} {k k' l m : ppi P p₀} /- categorical properties of pointed maps -/ definition pid [constructor] [refl] (A : Type*) : A →* A := pmap.mk id idp definition pcompose [constructor] [trans] {A B C : Type*} (g : B →* C) (f : A →* B) : A →* C := pmap.mk (λa, g (f a)) (ap g (respect_pt f) ⬝ respect_pt g) infixr ` ∘* `:60 := pcompose definition pmap_of_map [constructor] {A B : Type} (f : A → B) (a : A) : pointed.MK A a →* pointed.MK B (f a) := pmap.mk f idp definition respect_pt_pcompose {A B C : Type*} (g : B →* C) (f : A →* B) : respect_pt (g ∘* f) = ap g (respect_pt f) ⬝ respect_pt g := idp definition passoc [constructor] (h : C →* D) (g : B →* C) (f : A →* B) : (h ∘* g) ∘* f ~* h ∘* (g ∘* f) := phomotopy.mk (λa, idp) abstract !idp_con ⬝ whisker_right _ (!ap_con ⬝ whisker_right _ !ap_compose'⁻¹) ⬝ !con.assoc end definition pid_pcompose [constructor] (f : A →* B) : pid B ∘* f ~* f := begin fapply phomotopy.mk, { intro a, reflexivity}, { reflexivity} end definition pcompose_pid [constructor] (f : A →* B) : f ∘* pid A ~* f := begin fapply phomotopy.mk, { intro a, reflexivity}, { reflexivity} end /- equivalences and equalities -/ protected definition ppi.sigma_char [constructor] {A : Type*} (B : A → Type) (b₀ : B pt) : ppi B b₀ ≃ Σ(k : Πa, B a), k pt = b₀ := begin fapply equiv.MK: intro x, { constructor, exact respect_pt x }, { induction x, constructor, assumption }, { induction x, reflexivity }, { induction x, reflexivity } end definition pmap.sigma_char [constructor] {A B : Type*} : (A →* B) ≃ Σ(f : A → B), f pt = pt := !ppi.sigma_char definition pmap.eta_expand [constructor] {A B : Type*} (f : A →* B) : A →* B := pmap.mk f (respect_pt f) definition pmap_equiv_right (A : Type*) (B : Type) : (Σ(b : B), A →* (pointed.Mk b)) ≃ (A → B) := begin fapply equiv.MK, { intro u a, exact pmap.to_fun u.2 a}, { intro f, refine ⟨f pt, _⟩, fapply pmap.mk, intro a, esimp, exact f a, reflexivity}, { intro f, reflexivity}, { intro u, cases u with b f, cases f with f p, esimp at *, induction p, reflexivity} end /- some specific pointed maps -/ -- The constant pointed map between any two types definition pconst [constructor] (A B : Type*) : A →* B := !ppi_const -- the pointed type of pointed maps -- TODO: remove definition ppmap [constructor] (A B : Type*) : Type* := @pppi A (λa, B) definition pcast [constructor] {A B : Type*} (p : A = B) : A →* B := pmap.mk (cast (ap pType.carrier p)) (by induction p; reflexivity) definition pinverse [constructor] {X : Type*} : Ω X →* Ω X := pmap.mk eq.inverse idp /- we generalize the definition of ap1 to arbitrary paths, so that we can prove properties about it using path induction (see for example ap1_gen_con and ap1_gen_con_natural) -/ definition ap1_gen [reducible] [unfold 6 9 10] {A B : Type} (f : A → B) {a a' : A} {b b' : B} (q : f a = b) (q' : f a' = b') (p : a = a') : b = b' := q⁻¹ ⬝ ap f p ⬝ q' definition ap1_gen_idp [unfold 6] {A B : Type} (f : A → B) {a : A} {b : B} (q : f a = b) : ap1_gen f q q idp = idp := con.left_inv q definition ap1_gen_idp_left [unfold 6] {A B : Type} (f : A → B) {a a' : A} (p : a = a') : ap1_gen f idp idp p = ap f p := proof idp_con (ap f p) qed definition ap1_gen_idp_left_con {A B : Type} (f : A → B) {a : A} (p : a = a) (q : ap f p = idp) : ap1_gen_idp_left f p ⬝ q = proof ap (concat idp) q qed := proof idp_con_idp q qed definition ap1 [constructor] (f : A →* B) : Ω A →* Ω B := pmap.mk (λp, ap1_gen f (respect_pt f) (respect_pt f) p) (ap1_gen_idp f (respect_pt f)) definition apn (n : ℕ) (f : A →* B) : Ω[n] A →* Ω[n] B := begin induction n with n IH, { exact f}, { esimp [loopn], exact ap1 IH} end notation `Ω→`:(max+5) := ap1 notation `Ω→[`:95 n:0 `]`:0 := apn n definition ptransport [constructor] {A : Type} (B : A → Type*) {a a' : A} (p : a = a') : B a →* B a' := pmap.mk (transport B p) (apdt (λa, Point (B a)) p) definition pmap_of_eq_pt [constructor] {A : Type} {a a' : A} (p : a = a') : pointed.MK A a →* pointed.MK A a' := pmap.mk id p definition pbool_pmap [constructor] {A : Type*} (a : A) : pbool →* A := pmap.mk (bool.rec pt a) idp /- properties of pointed maps -/ definition apn_zero [unfold_full] (f : A →* B) : Ω→[0] f = f := idp definition apn_succ [unfold_full] (n : ℕ) (f : A →* B) : Ω→[n + 1] f = Ω→ (Ω→[n] f) := idp definition ap1_gen_con {A B : Type} (f : A → B) {a₁ a₂ a₃ : A} {b₁ b₂ b₃ : B} (q₁ : f a₁ = b₁) (q₂ : f a₂ = b₂) (q₃ : f a₃ = b₃) (p₁ : a₁ = a₂) (p₂ : a₂ = a₃) : ap1_gen f q₁ q₃ (p₁ ⬝ p₂) = ap1_gen f q₁ q₂ p₁ ⬝ ap1_gen f q₂ q₃ p₂ := begin induction p₂, induction q₃, induction q₂, reflexivity end definition ap1_gen_inv {A B : Type} (f : A → B) {a₁ a₂ : A} {b₁ b₂ : B} (q₁ : f a₁ = b₁) (q₂ : f a₂ = b₂) (p₁ : a₁ = a₂) : ap1_gen f q₂ q₁ p₁⁻¹ = (ap1_gen f q₁ q₂ p₁)⁻¹ := begin induction p₁, induction q₁, induction q₂, reflexivity end definition ap1_con {A B : Type*} (f : A →* B) (p q : Ω A) : ap1 f (p ⬝ q) = ap1 f p ⬝ ap1 f q := ap1_gen_con f (respect_pt f) (respect_pt f) (respect_pt f) p q theorem ap1_inv (f : A →* B) (p : Ω A) : ap1 f p⁻¹ = (ap1 f p)⁻¹ := ap1_gen_inv f (respect_pt f) (respect_pt f) p -- the following two facts are used for the suspension axiom to define spectrum cohomology definition ap1_gen_con_natural {A B : Type} (f : A → B) {a₁ a₂ a₃ : A} {p₁ p₁' : a₁ = a₂} {p₂ p₂' : a₂ = a₃} {b₁ b₂ b₃ : B} (q₁ : f a₁ = b₁) (q₂ : f a₂ = b₂) (q₃ : f a₃ = b₃) (r₁ : p₁ = p₁') (r₂ : p₂ = p₂') : square (ap1_gen_con f q₁ q₂ q₃ p₁ p₂) (ap1_gen_con f q₁ q₂ q₃ p₁' p₂') (ap (ap1_gen f q₁ q₃) (r₁ ◾ r₂)) (ap (ap1_gen f q₁ q₂) r₁ ◾ ap (ap1_gen f q₂ q₃) r₂) := begin induction r₁, induction r₂, exact vrfl end definition ap1_gen_con_idp {A B : Type} (f : A → B) {a : A} {b : B} (q : f a = b) : ap1_gen_con f q q q idp idp ⬝ con.left_inv q ◾ con.left_inv q = con.left_inv q := by induction q; reflexivity definition apn_con (n : ℕ) (f : A →* B) (p q : Ω[n+1] A) : apn (n+1) f (p ⬝ q) = apn (n+1) f p ⬝ apn (n+1) f q := ap1_con (apn n f) p q definition apn_inv (n : ℕ) (f : A →* B) (p : Ω[n+1] A) : apn (n+1) f p⁻¹ = (apn (n+1) f p)⁻¹ := ap1_inv (apn n f) p definition is_equiv_ap1 (f : A →* B) [is_equiv f] : is_equiv (ap1 f) := begin induction B with B b, induction f with f pf, esimp at *, cases pf, esimp, apply is_equiv.homotopy_closed (ap f), intro p, exact !idp_con⁻¹ end definition is_equiv_apn (n : ℕ) (f : A →* B) [H : is_equiv f] : is_equiv (apn n f) := begin induction n with n IH, { exact H}, { exact is_equiv_ap1 (apn n f)} end definition pinverse_con [constructor] {X : Type*} (p q : Ω X) : pinverse (p ⬝ q) = pinverse q ⬝ pinverse p := !con_inv definition pinverse_inv [constructor] {X : Type*} (p : Ω X) : pinverse p⁻¹ = (pinverse p)⁻¹ := idp definition ap1_pcompose_pinverse [constructor] {X Y : Type*} (f : X →* Y) : Ω→ f ∘* pinverse ~* pinverse ∘* Ω→ f := phomotopy.mk (ap1_gen_inv f (respect_pt f) (respect_pt f)) abstract begin induction Y with Y y₀, induction f with f f₀, esimp at * ⊢, induction f₀, reflexivity end end definition is_equiv_pcast [instance] {A B : Type*} (p : A = B) : is_equiv (pcast p) := !is_equiv_cast /- categorical properties of pointed homotopies -/ variable (k) protected definition phomotopy.refl [constructor] : k ~* k := phomotopy.mk homotopy.rfl !idp_con variable {k} protected definition phomotopy.rfl [reducible] [constructor] [refl] : k ~* k := phomotopy.refl k protected definition phomotopy.symm [constructor] [symm] (p : k ~* l) : l ~* k := phomotopy.mk p⁻¹ʰᵗʸ (inv_con_eq_of_eq_con (to_homotopy_pt p)⁻¹) protected definition phomotopy.trans [constructor] [trans] (p : k ~* l) (q : l ~* m) : k ~* m := phomotopy.mk (λa, p a ⬝ q a) (!con.assoc ⬝ whisker_left (p pt) (to_homotopy_pt q) ⬝ to_homotopy_pt p) infix ` ⬝* `:75 := phomotopy.trans postfix `⁻¹*`:(max+1) := phomotopy.symm /- equalities and equivalences relating pointed homotopies -/ definition phomotopy.rec' [recursor] (B : k ~* l → Type) (H : Π(h : k ~ l) (p : h pt ⬝ respect_pt l = respect_pt k), B (phomotopy.mk h p)) (h : k ~* l) : B h := begin induction h with h p, refine transport (λp, B (ppi.mk h p)) _ (H h (con_eq_of_eq_con_inv p)), apply to_left_inv !eq_con_inv_equiv_con_eq p end definition phomotopy.eta_expand [constructor] (p : k ~* l) : k ~* l := phomotopy.mk p (to_homotopy_pt p) definition is_trunc_ppi [instance] (n : ℕ₋₂) {A : Type*} (B : A → Type) (b₀ : B pt) [Πa, is_trunc n (B a)] : is_trunc n (ppi B b₀) := is_trunc_equiv_closed_rev _ !ppi.sigma_char definition is_trunc_pmap [instance] (n : ℕ₋₂) (A B : Type*) [is_trunc n B] : is_trunc n (A →* B) := !is_trunc_ppi definition is_trunc_ppmap [instance] (n : ℕ₋₂) {A B : Type*} [is_trunc n B] : is_trunc n (ppmap A B) := !is_trunc_pmap definition phomotopy_of_eq [constructor] (p : k = l) : k ~* l := phomotopy.mk (ap010 ppi.to_fun p) begin induction p, refine !idp_con end definition phomotopy_of_eq_idp (k : ppi P p₀) : phomotopy_of_eq idp = phomotopy.refl k := idp definition pconcat_eq [constructor] (p : k ~* l) (q : l = m) : k ~* m := p ⬝* phomotopy_of_eq q definition eq_pconcat [constructor] (p : k = l) (q : l ~* m) : k ~* m := phomotopy_of_eq p ⬝* q infix ` ⬝*p `:75 := pconcat_eq infix ` ⬝p* `:75 := eq_pconcat definition pr1_phomotopy_eq {p q : k ~* l} (r : p = q) (a : A) : p a = q a := ap010 to_homotopy r a definition pwhisker_left [constructor] (h : B →* C) (p : f ~* g) : h ∘* f ~* h ∘* g := phomotopy.mk (λa, ap h (p a)) abstract !con.assoc⁻¹ ⬝ whisker_right _ (!ap_con⁻¹ ⬝ ap02 _ (to_homotopy_pt p)) end definition pwhisker_right [constructor] (h : C →* A) (p : f ~* g) : f ∘* h ~* g ∘* h := phomotopy.mk (λa, p (h a)) abstract !con.assoc⁻¹ ⬝ whisker_right _ (!ap_con_eq_con_ap)⁻¹ ⬝ !con.assoc ⬝ whisker_left _ (to_homotopy_pt p) end definition pconcat2 [constructor] {A B C : Type*} {h i : B →* C} {f g : A →* B} (q : h ~* i) (p : f ~* g) : h ∘* f ~* i ∘* g := pwhisker_left _ p ⬝* pwhisker_right _ q variables (k l) definition phomotopy.sigma_char [constructor] : (k ~* l) ≃ Σ(p : k ~ l), p pt ⬝ respect_pt l = respect_pt k := begin fapply equiv.MK : intros h, { exact ⟨h , to_homotopy_pt h⟩ }, { cases h with h p, exact phomotopy.mk h p }, { cases h with h p, exact ap (dpair h) (to_right_inv !eq_con_inv_equiv_con_eq p) }, { induction h using phomotopy.rec' with h p, exact ap (phomotopy.mk h) (to_right_inv !eq_con_inv_equiv_con_eq p) } end definition ppi_eq_equiv_internal : (k = l) ≃ (k ~* l) := calc (k = l) ≃ ppi.sigma_char P p₀ k = ppi.sigma_char P p₀ l : eq_equiv_fn_eq (ppi.sigma_char P p₀) k l ... ≃ Σ(p : k = l), pathover (λh, h pt = p₀) (respect_pt k) p (respect_pt l) : sigma_eq_equiv _ _ ... ≃ Σ(p : k = l), respect_pt k = ap (λh, h pt) p ⬝ respect_pt l : sigma_equiv_sigma_right (λp, eq_pathover_equiv_Fl p (respect_pt k) (respect_pt l)) ... ≃ Σ(p : k = l), respect_pt k = apd10 p pt ⬝ respect_pt l : sigma_equiv_sigma_right (λp, equiv_eq_closed_right _ (whisker_right _ (ap_eq_apd10 p _))) ... ≃ Σ(p : k ~ l), respect_pt k = p pt ⬝ respect_pt l : sigma_equiv_sigma_left' eq_equiv_homotopy ... ≃ Σ(p : k ~ l), p pt ⬝ respect_pt l = respect_pt k : sigma_equiv_sigma_right (λp, eq_equiv_eq_symm _ _) ... ≃ (k ~* l) : phomotopy.sigma_char k l definition ppi_eq_equiv_internal_idp : ppi_eq_equiv_internal k k idp = phomotopy.refl k := begin apply ap (phomotopy.mk (homotopy.refl _)), induction k with k k₀, esimp at * ⊢, induction k₀, reflexivity end definition ppi_eq_equiv [constructor] : (k = l) ≃ (k ~* l) := begin refine equiv_change_fun (ppi_eq_equiv_internal k l) _, { apply phomotopy_of_eq }, { intro p, induction p, exact ppi_eq_equiv_internal_idp k } end variables {k l} definition pmap_eq_equiv [constructor] (f g : A →* B) : (f = g) ≃ (f ~* g) := ppi_eq_equiv f g definition eq_of_phomotopy (p : k ~* l) : k = l := to_inv (ppi_eq_equiv k l) p definition eq_of_phomotopy_refl (k : ppi P p₀) : eq_of_phomotopy (phomotopy.refl k) = idpath k := begin apply to_inv_eq_of_eq, reflexivity end definition phomotopy_of_homotopy (h : k ~ l) [Πa, is_set (P a)] : k ~* l := begin fapply phomotopy.mk, { exact h }, { apply is_set.elim } end definition ppi_eq_of_homotopy [Πa, is_set (P a)] (p : k ~ l) : k = l := eq_of_phomotopy (phomotopy_of_homotopy p) definition pmap_eq_of_homotopy [is_set B] (p : f ~ g) : f = g := ppi_eq_of_homotopy p definition phomotopy_of_eq_of_phomotopy (p : k ~* l) : phomotopy_of_eq (eq_of_phomotopy p) = p := to_right_inv (ppi_eq_equiv k l) p definition phomotopy_rec_eq [recursor] {Q : (k ~* k') → Type} (p : k ~* k') (H : Π(q : k = k'), Q (phomotopy_of_eq q)) : Q p := phomotopy_of_eq_of_phomotopy p ▸ H (eq_of_phomotopy p) definition phomotopy_rec_idp [recursor] {Q : Π {k' : ppi P p₀}, (k ~* k') → Type} {k' : ppi P p₀} (H : k ~* k') (q : Q (phomotopy.refl k)) : Q H := begin induction H using phomotopy_rec_eq with t, induction t, exact phomotopy_of_eq_idp k ▸ q, end definition phomotopy_rec_idp' (Q : Π ⦃k' : ppi P p₀⦄, (k ~* k') → (k = k') → Type) (q : Q phomotopy.rfl idp) ⦃k' : ppi P p₀⦄ (H : k ~* k') : Q H (eq_of_phomotopy H) := begin induction H using phomotopy_rec_idp, exact transport (Q phomotopy.rfl) !eq_of_phomotopy_refl⁻¹ q end attribute phomotopy.rec' [recursor] definition phomotopy_rec_eq_phomotopy_of_eq {Q : (k ~* l) → Type} (p : k = l) (H : Π(q : k = l), Q (phomotopy_of_eq q)) : phomotopy_rec_eq (phomotopy_of_eq p) H = H p := begin unfold phomotopy_rec_eq, refine ap (λp, p ▸ _) !adj ⬝ _, refine !tr_compose⁻¹ ⬝ _, apply apdt end definition phomotopy_rec_idp_refl {Q : Π{l}, (k ~* l) → Type} (H : Q (phomotopy.refl k)) : phomotopy_rec_idp phomotopy.rfl H = H := !phomotopy_rec_eq_phomotopy_of_eq definition phomotopy_rec_idp'_refl (Q : Π ⦃k' : ppi P p₀⦄, (k ~* k') → (k = k') → Type) (q : Q phomotopy.rfl idp) : phomotopy_rec_idp' Q q phomotopy.rfl = transport (Q phomotopy.rfl) !eq_of_phomotopy_refl⁻¹ q := !phomotopy_rec_idp_refl /- maps out of or into contractible types -/ definition phomotopy_of_is_contr_cod [constructor] (k l : ppi P p₀) [Πa, is_contr (P a)] : k ~* l := phomotopy.mk (λa, !eq_of_is_contr) !eq_of_is_contr definition phomotopy_of_is_contr_cod_pmap [constructor] (f g : A →* B) [is_contr B] : f ~* g := phomotopy_of_is_contr_cod f g definition phomotopy_of_is_contr_dom [constructor] (k l : ppi P p₀) [is_contr A] : k ~* l := begin fapply phomotopy.mk, { intro a, exact eq_of_pathover_idp (change_path !is_prop.elim (apd k !is_prop.elim ⬝op respect_pt k ⬝ (respect_pt l)⁻¹ ⬝o apd l !is_prop.elim)) }, rewrite [▸*, +is_prop_elim_self, +apd_idp, cono_idpo], refine ap (λx, eq_of_pathover_idp (change_path x _)) !is_prop_elim_self ◾ idp ⬝ _, xrewrite [change_path_idp, idpo_concato_eq, inv_con_cancel_right], end /- adjunction between (-)₊ : Type → Type* and pType.carrier : Type* → Type -/ definition pmap_equiv_left (A : Type) (B : Type*) : A₊ →* B ≃ (A → B) := begin fapply equiv.MK, { intro f a, cases f with f p, exact f (some a) }, { intro f, fconstructor, intro a, cases a, exact pt, exact f a, reflexivity }, { intro f, reflexivity }, { intro f, cases f with f p, esimp, fapply eq_of_phomotopy, fapply phomotopy.mk, { intro a, cases a; all_goals (esimp at *), exact p⁻¹ }, { esimp, exact !con.left_inv }}, end -- pmap_pbool_pequiv is the pointed equivalence definition pmap_pbool_equiv [constructor] (B : Type*) : (pbool →* B) ≃ B := begin fapply equiv.MK, { intro f, cases f with f p, exact f tt }, { intro b, fconstructor, intro u, cases u, exact pt, exact b, reflexivity }, { intro b, reflexivity }, { intro f, cases f with f p, esimp, fapply eq_of_phomotopy, fapply phomotopy.mk, { intro a, cases a; all_goals (esimp at *), exact p⁻¹ }, { esimp, exact !con.left_inv }}, end /- Pointed maps respecting pointed homotopies. In general we need function extensionality for pap, but for particular F we can do it without function extensionality. This might be preferred, because such pointed homotopies compute. On the other hand, when using function extensionality, it's easier to prove that if p is reflexivity, then the resulting pointed homotopy is reflexivity -/ definition pap (F : (A →* B) → (C →* D)) {f g : A →* B} (p : f ~* g) : F f ~* F g := begin induction p using phomotopy_rec_idp, reflexivity end definition pap_refl (F : (A →* B) → (C →* D)) (f : A →* B) : pap F (phomotopy.refl f) = phomotopy.refl (F f) := !phomotopy_rec_idp_refl definition ap1_phomotopy {f g : A →* B} (p : f ~* g) : Ω→ f ~* Ω→ g := pap Ω→ p definition ap1_phomotopy_refl {X Y : Type*} (f : X →* Y) : ap1_phomotopy (phomotopy.refl f) = phomotopy.refl (Ω→ f) := !pap_refl --a proof not using function extensionality: definition ap1_phomotopy_explicit {f g : A →* B} (p : f ~* g) : Ω→ f ~* Ω→ g := begin induction p with p q, induction f with f pf, induction g with g pg, induction B with B b, esimp at * ⊢, induction q, induction pg, fapply phomotopy.mk, { intro l, refine _ ⬝ !idp_con⁻¹ᵖ, refine !con.assoc ⬝ _, apply inv_con_eq_of_eq_con, apply ap_con_eq_con_ap}, { induction A with A a, unfold [ap_con_eq_con_ap], generalize p a, generalize g a, intro b q, induction q, reflexivity} end definition apn_phomotopy {f g : A →* B} (n : ℕ) (p : f ~* g) : apn n f ~* apn n g := begin induction n with n IH, { exact p}, { exact ap1_phomotopy IH} end -- the following two definitiongs are mostly the same, maybe we should remove one definition ap_eq_of_phomotopy {A B : Type*} {f g : A →* B} (p : f ~* g) (a : A) : ap (λf : A →* B, f a) (eq_of_phomotopy p) = p a := ap010 to_homotopy (phomotopy_of_eq_of_phomotopy p) a definition to_fun_eq_of_phomotopy {A B : Type*} {f g : A →* B} (p : f ~* g) (a : A) : ap010 pmap.to_fun (eq_of_phomotopy p) a = p a := begin induction p using phomotopy_rec_idp, exact ap (λx, ap010 pmap.to_fun x a) !eq_of_phomotopy_refl end definition ap1_eq_of_phomotopy {A B : Type*} {f g : A →* B} (p : f ~* g) : ap Ω→ (eq_of_phomotopy p) = eq_of_phomotopy (ap1_phomotopy p) := begin induction p using phomotopy_rec_idp, refine ap02 _ !eq_of_phomotopy_refl ⬝ !eq_of_phomotopy_refl⁻¹ ⬝ ap eq_of_phomotopy _, exact !ap1_phomotopy_refl⁻¹ end /- pointed homotopies between the given pointed maps -/ definition ap1_pid [constructor] {A : Type*} : ap1 (pid A) ~* pid (Ω A) := begin fapply phomotopy.mk, { intro p, esimp, refine !idp_con ⬝ !ap_id}, { reflexivity} end definition ap1_pinverse [constructor] {A : Type*} : ap1 (@pinverse A) ~* @pinverse (Ω A) := begin fapply phomotopy.mk, { intro p, refine !idp_con ⬝ _, exact !inv_eq_inv2⁻¹ }, { reflexivity} end definition ap1_gen_compose {A B C : Type} (g : B → C) (f : A → B) {a₁ a₂ : A} {b₁ b₂ : B} {c₁ c₂ : C} (q₁ : f a₁ = b₁) (q₂ : f a₂ = b₂) (r₁ : g b₁ = c₁) (r₂ : g b₂ = c₂) (p : a₁ = a₂) : ap1_gen (g ∘ f) (ap g q₁ ⬝ r₁) (ap g q₂ ⬝ r₂) p = ap1_gen g r₁ r₂ (ap1_gen f q₁ q₂ p) := begin induction p, induction q₁, induction q₂, induction r₁, induction r₂, reflexivity end definition ap1_gen_compose_idp {A B C : Type} (g : B → C) (f : A → B) {a : A} {b : B} {c : C} (q : f a = b) (r : g b = c) : ap1_gen_compose g f q q r r idp ⬝ (ap (ap1_gen g r r) (ap1_gen_idp f q) ⬝ ap1_gen_idp g r) = ap1_gen_idp (g ∘ f) (ap g q ⬝ r) := begin induction q, induction r, reflexivity end definition ap1_pcompose [constructor] {A B C : Type*} (g : B →* C) (f : A →* B) : ap1 (g ∘* f) ~* ap1 g ∘* ap1 f := phomotopy.mk (ap1_gen_compose g f (respect_pt f) (respect_pt f) (respect_pt g) (respect_pt g)) (ap1_gen_compose_idp g f (respect_pt f) (respect_pt g)) definition ap1_pconst [constructor] (A B : Type*) : Ω→(pconst A B) ~* pconst (Ω A) (Ω B) := phomotopy.mk (λp, ap1_gen_idp_left (const A pt) p ⬝ ap_constant p pt) rfl definition ap1_gen_con_left {A B : Type} {a a' : A} {b₀ b₁ b₂ : B} {f : A → b₀ = b₁} {f' : A → b₁ = b₂} {q₀ q₁ : b₀ = b₁} {q₀' q₁' : b₁ = b₂} (r₀ : f a = q₀) (r₁ : f a' = q₁) (r₀' : f' a = q₀') (r₁' : f' a' = q₁') (p : a = a') : ap1_gen (λa, f a ⬝ f' a) (r₀ ◾ r₀') (r₁ ◾ r₁') p = whisker_right q₀' (ap1_gen f r₀ r₁ p) ⬝ whisker_left q₁ (ap1_gen f' r₀' r₁' p) := begin induction r₀, induction r₁, induction r₀', induction r₁', induction p, reflexivity end definition ap1_gen_con_left_idp {A B : Type} {a : A} {b₀ b₁ b₂ : B} {f : A → b₀ = b₁} {f' : A → b₁ = b₂} {q₀ : b₀ = b₁} {q₁ : b₁ = b₂} (r₀ : f a = q₀) (r₁ : f' a = q₁) : ap1_gen_con_left r₀ r₀ r₁ r₁ idp = !con.left_inv ⬝ (ap (whisker_right q₁) !con.left_inv ◾ ap (whisker_left _) !con.left_inv)⁻¹ := begin induction r₀, induction r₁, reflexivity end definition ptransport_change_eq [constructor] {A : Type} (B : A → Type*) {a a' : A} {p q : a = a'} (r : p = q) : ptransport B p ~* ptransport B q := phomotopy.mk (λb, ap (λp, transport B p b) r) begin induction r, apply idp_con end definition pnatural_square {A B : Type} (X : B → Type*) {f g : A → B} (h : Πa, X (f a) →* X (g a)) {a a' : A} (p : a = a') : h a' ∘* ptransport X (ap f p) ~* ptransport X (ap g p) ∘* h a := by induction p; exact !pcompose_pid ⬝* !pid_pcompose⁻¹* definition apn_pid [constructor] {A : Type*} (n : ℕ) : apn n (pid A) ~* pid (Ω[n] A) := begin induction n with n IH, { reflexivity}, { exact ap1_phomotopy IH ⬝* ap1_pid} end definition apn_pconst (A B : Type*) (n : ℕ) : apn n (pconst A B) ~* pconst (Ω[n] A) (Ω[n] B) := begin induction n with n IH, { reflexivity }, { exact ap1_phomotopy IH ⬝* !ap1_pconst } end definition apn_pcompose (n : ℕ) (g : B →* C) (f : A →* B) : apn n (g ∘* f) ~* apn n g ∘* apn n f := begin induction n with n IH, { reflexivity}, { refine ap1_phomotopy IH ⬝* _, apply ap1_pcompose} end definition pcast_idp [constructor] {A : Type*} : pcast (idpath A) ~* pid A := by reflexivity definition pinverse_pinverse (A : Type*) : pinverse ∘* pinverse ~* pid (Ω A) := begin fapply phomotopy.mk, { apply inv_inv}, { reflexivity} end definition pcast_ap_loop [constructor] {A B : Type*} (p : A = B) : pcast (ap Ω p) ~* ap1 (pcast p) := begin fapply phomotopy.mk, { intro a, induction p, esimp, exact (!idp_con ⬝ !ap_id)⁻¹}, { induction p, reflexivity} end definition ap1_pmap_of_map [constructor] {A B : Type} (f : A → B) (a : A) : ap1 (pmap_of_map f a) ~* pmap_of_map (ap f) (idpath a) := begin fapply phomotopy.mk, { intro a, esimp, apply idp_con}, { reflexivity} end definition pcast_commute [constructor] {A : Type} {B C : A → Type*} (f : Πa, B a →* C a) {a₁ a₂ : A} (p : a₁ = a₂) : pcast (ap C p) ∘* f a₁ ~* f a₂ ∘* pcast (ap B p) := phomotopy.mk begin induction p, reflexivity end begin induction p, esimp, refine !idp_con ⬝ !idp_con ⬝ !ap_id⁻¹ end /- pointed equivalences -/ structure pequiv (A B : Type*) := mk' :: (to_pmap : A →* B) (to_pinv1 : B →* A) (to_pinv2 : B →* A) (pright_inv : to_pmap ∘* to_pinv1 ~* pid B) (pleft_inv : to_pinv2 ∘* to_pmap ~* pid A) infix ` ≃* `:25 := pequiv definition pmap_of_pequiv [unfold 3] [coercion] [reducible] {A B : Type*} (f : A ≃* B) : @ppi A (λa, B) pt := pequiv.to_pmap f definition to_pinv [unfold 3] (f : A ≃* B) : B →* A := pequiv.to_pinv1 f definition pleft_inv' (f : A ≃* B) : to_pinv f ∘* f ~* pid A := let g := to_pinv f in let h := pequiv.to_pinv2 f in calc g ∘* f ~* pid A ∘* (g ∘* f) : by exact !pid_pcompose⁻¹* ... ~* (h ∘* f) ∘* (g ∘* f) : by exact pwhisker_right _ (pequiv.pleft_inv f)⁻¹* ... ~* h ∘* (f ∘* g) ∘* f : by exact !passoc ⬝* pwhisker_left _ !passoc⁻¹* ... ~* h ∘* pid B ∘* f : by exact !pwhisker_left (!pwhisker_right !pequiv.pright_inv) ... ~* h ∘* f : by exact pwhisker_left _ !pid_pcompose ... ~* pid A : by exact pequiv.pleft_inv f definition equiv_of_pequiv [coercion] [constructor] (f : A ≃* B) : A ≃ B := have is_equiv f, from adjointify f (to_pinv f) (pequiv.pright_inv f) (pleft_inv' f), equiv.mk f _ attribute pointed._trans_of_equiv_of_pequiv pointed._trans_of_pmap_of_pequiv [unfold 3] definition pequiv.to_is_equiv [instance] [constructor] (f : A ≃* B) : is_equiv (pointed._trans_of_equiv_of_pequiv f) := adjointify f (to_pinv f) (pequiv.pright_inv f) (pleft_inv' f) definition pequiv.to_is_equiv' [instance] [constructor] (f : A ≃* B) : is_equiv (pointed._trans_of_pmap_of_pequiv f) := pequiv.to_is_equiv f protected definition pequiv.MK [constructor] (f : A →* B) (g : B →* A) (gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : A ≃* B := pequiv.mk' f g g fg gf definition pinv [constructor] (f : A →* B) (H : is_equiv f) : B →* A := pmap.mk f⁻¹ᶠ (ap f⁻¹ᶠ (respect_pt f)⁻¹ ⬝ (left_inv f pt)) definition pequiv_of_pmap [constructor] (f : A →* B) (H : is_equiv f) : A ≃* B := pequiv.mk' f (pinv f H) (pinv f H) abstract begin fapply phomotopy.mk, exact right_inv f, induction f with f f₀, induction B with B b₀, esimp at *, induction f₀, esimp, exact adj f pt ⬝ ap02 f !idp_con⁻¹ end end abstract begin fapply phomotopy.mk, exact left_inv f, induction f with f f₀, induction B with B b₀, esimp at *, induction f₀, esimp, exact !idp_con⁻¹ ⬝ !idp_con⁻¹ end end definition pequiv.mk [constructor] (f : A → B) (H : is_equiv f) (p : f pt = pt) : A ≃* B := pequiv_of_pmap (pmap.mk f p) H definition pequiv_of_equiv [constructor] (f : A ≃ B) (H : f pt = pt) : A ≃* B := pequiv.mk f _ H protected definition pequiv.MK' [constructor] (f : A →* B) (g : B → A) (gf : Πa, g (f a) = a) (fg : Πb, f (g b) = b) : A ≃* B := pequiv.mk f (adjointify f g fg gf) (respect_pt f) /- reflexivity and symmetry (transitivity is below) -/ protected definition pequiv.refl [refl] [constructor] (A : Type*) : A ≃* A := pequiv.mk' (pid A) (pid A) (pid A) !pid_pcompose !pcompose_pid protected definition pequiv.rfl [constructor] : A ≃* A := pequiv.refl A protected definition pequiv.symm [symm] [constructor] (f : A ≃* B) : B ≃* A := pequiv.MK (to_pinv f) f (pequiv.pright_inv f) (pleft_inv' f) postfix `⁻¹ᵉ*`:(max + 1) := pequiv.symm definition pleft_inv (f : A ≃* B) : f⁻¹ᵉ* ∘* f ~* pid A := pleft_inv' f definition pright_inv (f : A ≃* B) : f ∘* f⁻¹ᵉ* ~* pid B := pequiv.pright_inv f definition to_pmap_pequiv_of_pmap {A B : Type*} (f : A →* B) (H : is_equiv f) : pequiv.to_pmap (pequiv_of_pmap f H) = f := by reflexivity definition to_pmap_pequiv_MK [constructor] (f : A →* B) (g : B →* A) (gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : pequiv.MK f g gf fg ~* f := by reflexivity definition to_pinv_pequiv_MK [constructor] (f : A →* B) (g : B →* A) (gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : to_pinv (pequiv.MK f g gf fg) ~* g := by reflexivity /- more on pointed equivalences -/ definition pequiv_ap [constructor] {A : Type} (B : A → Type*) {a a' : A} (p : a = a') : B a ≃* B a' := pequiv_of_pmap (ptransport B p) !is_equiv_tr definition pequiv_change_fun [constructor] (f : A ≃* B) (f' : A →* B) (Heq : f ~ f') : A ≃* B := pequiv_of_pmap f' (is_equiv.homotopy_closed f Heq) definition pequiv_change_inv [constructor] (f : A ≃* B) (f' : B →* A) (Heq : to_pinv f ~ f') : A ≃* B := pequiv.MK' f f' (to_left_inv (equiv_change_inv f Heq)) (to_right_inv (equiv_change_inv f Heq)) definition pequiv_rect' (f : A ≃* B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition pua {A B : Type*} (f : A ≃* B) : A = B := pType_eq (equiv_of_pequiv f) !respect_pt definition pequiv_of_eq [constructor] {A B : Type*} (p : A = B) : A ≃* B := pequiv_of_pmap (pcast p) !is_equiv_tr definition eq_of_pequiv {A B : Type*} (p : A ≃* B) : A = B := pType_eq (equiv_of_pequiv p) !respect_pt definition peap {A B : Type*} (F : Type* → Type*) (p : A ≃* B) : F A ≃* F B := pequiv_of_pmap (pcast (ap F (eq_of_pequiv p))) begin cases eq_of_pequiv p, apply is_equiv_id end -- rename pequiv_of_eq_natural definition pequiv_of_eq_commute [constructor] {A : Type} {B C : A → Type*} (f : Πa, B a →* C a) {a₁ a₂ : A} (p : a₁ = a₂) : pequiv_of_eq (ap C p) ∘* f a₁ ~* f a₂ ∘* pequiv_of_eq (ap B p) := pcast_commute f p -- definition pequiv.eta_expand [constructor] {A B : Type*} (f : A ≃* B) : A ≃* B := -- pequiv.mk' f (to_pinv f) (pequiv.to_pinv2 f) (pright_inv f) _ /- the theorem pequiv_eq, which gives a condition for two pointed equivalences are equal is in types.equiv to avoid circular imports -/ /- computation rules of pointed homotopies, possibly combined with pointed equivalences -/ definition pcancel_left (f : B ≃* C) {g h : A →* B} (p : f ∘* g ~* f ∘* h) : g ~* h := begin refine _⁻¹* ⬝* pwhisker_left f⁻¹ᵉ* p ⬝* _: refine !passoc⁻¹* ⬝* _: refine pwhisker_right _ (pleft_inv f) ⬝* _: apply pid_pcompose end definition pcancel_right (f : A ≃* B) {g h : B →* C} (p : g ∘* f ~* h ∘* f) : g ~* h := begin refine _⁻¹* ⬝* pwhisker_right f⁻¹ᵉ* p ⬝* _: refine !passoc ⬝* _: refine pwhisker_left _ (pright_inv f) ⬝* _: apply pcompose_pid end definition phomotopy_pinv_right_of_phomotopy {f : A ≃* B} {g : B →* C} {h : A →* C} (p : g ∘* f ~* h) : g ~* h ∘* f⁻¹ᵉ* := begin refine _ ⬝* pwhisker_right _ p, symmetry, refine !passoc ⬝* _, refine pwhisker_left _ (pright_inv f) ⬝* _, apply pcompose_pid end definition phomotopy_of_pinv_right_phomotopy {f : B ≃* A} {g : B →* C} {h : A →* C} (p : g ∘* f⁻¹ᵉ* ~* h) : g ~* h ∘* f := begin refine _ ⬝* pwhisker_right _ p, symmetry, refine !passoc ⬝* _, refine pwhisker_left _ (pleft_inv f) ⬝* _, apply pcompose_pid end definition pinv_right_phomotopy_of_phomotopy {f : A ≃* B} {g : B →* C} {h : A →* C} (p : h ~* g ∘* f) : h ∘* f⁻¹ᵉ* ~* g := (phomotopy_pinv_right_of_phomotopy p⁻¹*)⁻¹* definition phomotopy_of_phomotopy_pinv_right {f : B ≃* A} {g : B →* C} {h : A →* C} (p : h ~* g ∘* f⁻¹ᵉ*) : h ∘* f ~* g := (phomotopy_of_pinv_right_phomotopy p⁻¹*)⁻¹* definition phomotopy_pinv_left_of_phomotopy {f : B ≃* C} {g : A →* B} {h : A →* C} (p : f ∘* g ~* h) : g ~* f⁻¹ᵉ* ∘* h := begin refine _ ⬝* pwhisker_left _ p, symmetry, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ (pleft_inv f) ⬝* _, apply pid_pcompose end definition phomotopy_of_pinv_left_phomotopy {f : C ≃* B} {g : A →* B} {h : A →* C} (p : f⁻¹ᵉ* ∘* g ~* h) : g ~* f ∘* h := begin refine _ ⬝* pwhisker_left _ p, symmetry, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ (pright_inv f) ⬝* _, apply pid_pcompose end definition pinv_left_phomotopy_of_phomotopy {f : B ≃* C} {g : A →* B} {h : A →* C} (p : h ~* f ∘* g) : f⁻¹ᵉ* ∘* h ~* g := (phomotopy_pinv_left_of_phomotopy p⁻¹*)⁻¹* definition phomotopy_of_phomotopy_pinv_left {f : C ≃* B} {g : A →* B} {h : A →* C} (p : h ~* f⁻¹ᵉ* ∘* g) : f ∘* h ~* g := (phomotopy_of_pinv_left_phomotopy p⁻¹*)⁻¹* definition pcompose2 {A B C : Type*} {g g' : B →* C} {f f' : A →* B} (q : g ~* g') (p : f ~* f') : g ∘* f ~* g' ∘* f' := pwhisker_right f q ⬝* pwhisker_left g' p infixr ` ◾* `:80 := pcompose2 definition phomotopy_pinv_of_phomotopy_pid {A B : Type*} {f : A →* B} {g : B ≃* A} (p : g ∘* f ~* pid A) : f ~* g⁻¹ᵉ* := phomotopy_pinv_left_of_phomotopy p ⬝* !pcompose_pid definition phomotopy_pinv_of_phomotopy_pid' {A B : Type*} {f : A →* B} {g : B ≃* A} (p : f ∘* g ~* pid B) : f ~* g⁻¹ᵉ* := phomotopy_pinv_right_of_phomotopy p ⬝* !pid_pcompose definition pinv_phomotopy_of_pid_phomotopy {A B : Type*} {f : A →* B} {g : B ≃* A} (p : pid A ~* g ∘* f) : g⁻¹ᵉ* ~* f := (phomotopy_pinv_of_phomotopy_pid p⁻¹*)⁻¹* definition pinv_phomotopy_of_pid_phomotopy' {A B : Type*} {f : A →* B} {g : B ≃* A} (p : pid B ~* f ∘* g) : g⁻¹ᵉ* ~* f := (phomotopy_pinv_of_phomotopy_pid' p⁻¹*)⁻¹* definition pinv_pcompose_cancel_left {A B C : Type*} (g : B ≃* C) (f : A →* B) : g⁻¹ᵉ* ∘* (g ∘* f) ~* f := !passoc⁻¹* ⬝* pwhisker_right f !pleft_inv ⬝* !pid_pcompose definition pcompose_pinv_cancel_left {A B C : Type*} (g : C ≃* B) (f : A →* B) : g ∘* (g⁻¹ᵉ* ∘* f) ~* f := !passoc⁻¹* ⬝* pwhisker_right f !pright_inv ⬝* !pid_pcompose definition pinv_pcompose_cancel_right {A B C : Type*} (g : B →* C) (f : B ≃* A) : (g ∘* f⁻¹ᵉ*) ∘* f ~* g := !passoc ⬝* pwhisker_left g !pleft_inv ⬝* !pcompose_pid definition pcompose_pinv_cancel_right {A B C : Type*} (g : B →* C) (f : A ≃* B) : (g ∘* f) ∘* f⁻¹ᵉ* ~* g := !passoc ⬝* pwhisker_left g !pright_inv ⬝* !pcompose_pid definition pinv_pinv {A B : Type*} (f : A ≃* B) : (f⁻¹ᵉ*)⁻¹ᵉ* ~* f := (phomotopy_pinv_of_phomotopy_pid (pleft_inv f))⁻¹* definition pinv2 {A B : Type*} {f f' : A ≃* B} (p : f ~* f') : f⁻¹ᵉ* ~* f'⁻¹ᵉ* := phomotopy_pinv_of_phomotopy_pid (pinv_right_phomotopy_of_phomotopy (!pid_pcompose ⬝* p)⁻¹*) postfix [parsing_only] `⁻²*`:(max+10) := pinv2 protected definition pequiv.trans [trans] [constructor] (f : A ≃* B) (g : B ≃* C) : A ≃* C := pequiv.MK (g ∘* f) (f⁻¹ᵉ* ∘* g⁻¹ᵉ*) abstract !passoc ⬝* pwhisker_left _ (pinv_pcompose_cancel_left g f) ⬝* pleft_inv f end abstract !passoc ⬝* pwhisker_left _ (pcompose_pinv_cancel_left f g⁻¹ᵉ*) ⬝* pright_inv g end definition pequiv_compose {A B C : Type*} (g : B ≃* C) (f : A ≃* B) : A ≃* C := pequiv.trans f g infix ` ⬝e* `:75 := pequiv.trans infixr ` ∘*ᵉ `:60 := pequiv_compose definition to_pmap_pequiv_trans {A B C : Type*} (f : A ≃* B) (g : B ≃* C) : pequiv.to_pmap (f ⬝e* g) = g ∘* f := by reflexivity definition to_fun_pequiv_trans {X Y Z : Type*} (f : X ≃* Y) (g :Y ≃* Z) : f ⬝e* g ~ g ∘ f := λx, idp definition peconcat_eq {A B C : Type*} (p : A ≃* B) (q : B = C) : A ≃* C := p ⬝e* pequiv_of_eq q definition eq_peconcat {A B C : Type*} (p : A = B) (q : B ≃* C) : A ≃* C := pequiv_of_eq p ⬝e* q infix ` ⬝e*p `:75 := peconcat_eq infix ` ⬝pe* `:75 := eq_peconcat definition trans_pinv {A B C : Type*} (f : A ≃* B) (g : B ≃* C) : (f ⬝e* g)⁻¹ᵉ* ~* f⁻¹ᵉ* ∘* g⁻¹ᵉ* := by reflexivity definition pinv_trans_pinv_left {A B C : Type*} (f : B ≃* A) (g : B ≃* C) : (f⁻¹ᵉ* ⬝e* g)⁻¹ᵉ* ~* f ∘* g⁻¹ᵉ* := by reflexivity definition pinv_trans_pinv_right {A B C : Type*} (f : A ≃* B) (g : C ≃* B) : (f ⬝e* g⁻¹ᵉ*)⁻¹ᵉ* ~* f⁻¹ᵉ* ∘* g := by reflexivity definition pinv_trans_pinv_pinv {A B C : Type*} (f : B ≃* A) (g : C ≃* B) : (f⁻¹ᵉ* ⬝e* g⁻¹ᵉ*)⁻¹ᵉ* ~* f ∘* g := by reflexivity /- pointed equivalences between particular pointed types -/ -- TODO: remove is_equiv_apn, which is proven again here definition loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B) : Ω[n] A ≃* Ω[n] B := pequiv.MK (apn n f) (apn n f⁻¹ᵉ*) abstract begin induction n with n IH, { apply pleft_inv}, { replace nat.succ n with n + 1, rewrite [+apn_succ], refine !ap1_pcompose⁻¹* ⬝* _, refine ap1_phomotopy IH ⬝* _, apply ap1_pid} end end abstract begin induction n with n IH, { apply pright_inv}, { replace nat.succ n with n + 1, rewrite [+apn_succ], refine !ap1_pcompose⁻¹* ⬝* _, refine ap1_phomotopy IH ⬝* _, apply ap1_pid} end end definition loop_pequiv_loop [constructor] (f : A ≃* B) : Ω A ≃* Ω B := loopn_pequiv_loopn 1 f definition loop_pequiv_eq_closed [constructor] {A : Type} {a a' : A} (p : a = a') : pointed.MK (a = a) idp ≃* pointed.MK (a' = a') idp := pequiv_of_equiv (loop_equiv_eq_closed p) (con.left_inv p) definition to_pmap_loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B) : loopn_pequiv_loopn n f ~* apn n f := by reflexivity definition to_pinv_loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B) : (loopn_pequiv_loopn n f)⁻¹ᵉ* ~* apn n f⁻¹ᵉ* := by reflexivity definition loopn_pequiv_loopn_con (n : ℕ) (f : A ≃* B) (p q : Ω[n+1] A) : loopn_pequiv_loopn (n+1) f (p ⬝ q) = loopn_pequiv_loopn (n+1) f p ⬝ loopn_pequiv_loopn (n+1) f q := ap1_con (loopn_pequiv_loopn n f) p q definition loop_pequiv_loop_con {A B : Type*} (f : A ≃* B) (p q : Ω A) : loop_pequiv_loop f (p ⬝ q) = loop_pequiv_loop f p ⬝ loop_pequiv_loop f q := loopn_pequiv_loopn_con 0 f p q definition loopn_pequiv_loopn_rfl (n : ℕ) (A : Type*) : loopn_pequiv_loopn n (pequiv.refl A) ~* pequiv.refl (Ω[n] A) := begin exact !to_pmap_loopn_pequiv_loopn ⬝* apn_pid n, end definition loop_pequiv_loop_rfl (A : Type*) : loop_pequiv_loop (pequiv.refl A) ~* pequiv.refl (Ω A) := loopn_pequiv_loopn_rfl 1 A definition apn_pinv (n : ℕ) {A B : Type*} (f : A ≃* B) : Ω→[n] f⁻¹ᵉ* ~* (loopn_pequiv_loopn n f)⁻¹ᵉ* := by reflexivity definition pmap_functor [constructor] {A A' B B' : Type*} (f : A' →* A) (g : B →* B') : ppmap A B →* ppmap A' B' := pmap.mk (λh, g ∘* h ∘* f) abstract begin fapply eq_of_phomotopy, fapply phomotopy.mk, { esimp, intro a, exact respect_pt g}, { rewrite [▸*, ap_constant], exact !idp_con⁻¹ } end end definition pequiv_pinverse (A : Type*) : Ω A ≃* Ω A := pequiv_of_pmap pinverse !is_equiv_eq_inverse definition pequiv_of_eq_pt [constructor] {A : Type} {a a' : A} (p : a = a') : pointed.MK A a ≃* pointed.MK A a' := pequiv_of_pmap (pmap_of_eq_pt p) !is_equiv_id definition pointed_eta_pequiv [constructor] (A : Type*) : A ≃* pointed.MK A pt := pequiv.mk id !is_equiv_id idp /- every pointed map is homotopic to one of the form `pmap_of_map _ _`, up to some pointed equivalences -/ definition phomotopy_pmap_of_map {A B : Type*} (f : A →* B) : (pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*) ∘* f ∘* (pointed_eta_pequiv A)⁻¹ᵉ* ~* pmap_of_map f pt := begin fapply phomotopy.mk, { reflexivity}, { symmetry, exact (!ap_id ⬝ !idp_con) ◾ (!idp_con ⬝ !ap_id) ⬝ !con.right_inv } end /- properties of iterated loop space -/ variable (A) definition loopn_succ_in (n : ℕ) : Ω[succ n] A ≃* Ω[n] (Ω A) := begin induction n with n IH, { reflexivity}, { exact loop_pequiv_loop IH} end definition loopn_add (n m : ℕ) : Ω[n] (Ω[m] A) ≃* Ω[m+n] (A) := begin induction n with n IH, { reflexivity}, { exact loop_pequiv_loop IH} end definition loopn_succ_out (n : ℕ) : Ω[succ n] A ≃* Ω(Ω[n] A) := by reflexivity variable {A} definition loopn_succ_in_con {n : ℕ} (p q : Ω[succ (succ n)] A) : loopn_succ_in A (succ n) (p ⬝ q) = loopn_succ_in A (succ n) p ⬝ loopn_succ_in A (succ n) q := !loop_pequiv_loop_con definition loopn_loop_irrel (p : point A = point A) : Ω(pointed.Mk p) = Ω[2] A := begin intros, fapply pType_eq, { esimp, transitivity _, apply eq_equiv_fn_eq_of_equiv (equiv_eq_closed_right _ p⁻¹), esimp, apply eq_equiv_eq_closed, apply con.right_inv, apply con.right_inv}, { esimp, apply con.left_inv} end definition loopn_space_loop_irrel (n : ℕ) (p : point A = point A) : Ω[succ n](pointed.Mk p) = Ω[succ (succ n)] A :> pType := calc Ω[succ n](pointed.Mk p) = Ω[n](Ω (pointed.Mk p)) : eq_of_pequiv !loopn_succ_in ... = Ω[n] (Ω[2] A) : loopn_loop_irrel ... = Ω[2+n] A : eq_of_pequiv !loopn_add ... = Ω[n+2] A : by rewrite [algebra.add.comm] definition apn_succ_phomotopy_in (n : ℕ) (f : A →* B) : loopn_succ_in B n ∘* Ω→[n + 1] f ~* Ω→[n] (Ω→ f) ∘* loopn_succ_in A n := begin induction n with n IH, { reflexivity}, { exact !ap1_pcompose⁻¹* ⬝* ap1_phomotopy IH ⬝* !ap1_pcompose} end definition loopn_succ_in_natural {A B : Type*} (n : ℕ) (f : A →* B) : loopn_succ_in B n ∘* Ω→[n+1] f ~* Ω→[n] (Ω→ f) ∘* loopn_succ_in A n := !apn_succ_phomotopy_in definition loopn_succ_in_inv_natural {A B : Type*} (n : ℕ) (f : A →* B) : Ω→[n + 1] f ∘* (loopn_succ_in A n)⁻¹ᵉ* ~* (loopn_succ_in B n)⁻¹ᵉ* ∘* Ω→[n] (Ω→ f):= begin apply pinv_right_phomotopy_of_phomotopy, refine _ ⬝* !passoc⁻¹*, apply phomotopy_pinv_left_of_phomotopy, apply apn_succ_phomotopy_in end end pointed
1dbdcb41eed9996be06fdf2fe5d54d240dd85d87
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/nat_bug4.lean
5aca421c3cd03e9476e186d0adf44935e163d60e
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
486
lean
import logic open eq.ops namespace experiment inductive nat : Type := zero : nat, succ : nat → nat namespace nat definition add (x y : nat) : nat := nat.rec x (λn r, succ r) y infixl `+` := add definition mul (n m : nat) := nat.rec zero (fun m x, x + n) m infixl `*` := mul axiom mul_succ_right (n m : nat) : n * succ m = n * m + n open eq theorem small2 (n m l : nat) : n * succ l + m = n * l + n + m := subst (mul_succ_right _ _) (eq.refl (n * succ l + m)) end nat end experiment
58d602a9030622dabe21d6b673b2e07559bd5580
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/lie/universal_enveloping.lean
b9a3dbd8834e036e2b9548249dda031ad0eba574
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,703
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.of_associative import algebra.ring_quot import linear_algebra.tensor_algebra.basic /-! # Universal enveloping algebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a commutative ring `R` and a Lie algebra `L` over `R`, we construct the universal enveloping algebra of `L`, together with its universal property. ## Main definitions * `universal_enveloping_algebra`: the universal enveloping algebra, endowed with an `R`-algebra structure. * `universal_enveloping_algebra.ι`: the Lie algebra morphism from `L` to its universal enveloping algebra. * `universal_enveloping_algebra.lift`: given an associative algebra `A`, together with a Lie algebra morphism `f : L →ₗ⁅R⁆ A`, `lift R L f : universal_enveloping_algebra R L →ₐ[R] A` is the unique morphism of algebras through which `f` factors. * `universal_enveloping_algebra.ι_comp_lift`: states that the lift of a morphism is indeed part of a factorisation. * `universal_enveloping_algebra.lift_unique`: states that lifts of morphisms are indeed unique. * `universal_enveloping_algebra.hom_ext`: a restatement of `lift_unique` as an extensionality lemma. ## Tags lie algebra, universal enveloping algebra, tensor algebra -/ universes u₁ u₂ u₃ variables (R : Type u₁) (L : Type u₂) variables [comm_ring R] [lie_ring L] [lie_algebra R L] local notation `ιₜ` := tensor_algebra.ι R namespace universal_enveloping_algebra /-- The quotient by the ideal generated by this relation is the universal enveloping algebra. Note that we have avoided using the more natural expression: | lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆) ⁅ιₜ x, ιₜ y⁆ so that our construction needs only the semiring structure of the tensor algebra. -/ inductive rel : tensor_algebra R L → tensor_algebra R L → Prop | lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆ + (ιₜ y) * (ιₜ x)) ((ιₜ x) * (ιₜ y)) end universal_enveloping_algebra /-- The universal enveloping algebra of a Lie algebra. -/ @[derive [inhabited, ring, algebra R]] def universal_enveloping_algebra := ring_quot (universal_enveloping_algebra.rel R L) namespace universal_enveloping_algebra /-- The quotient map from the tensor algebra to the universal enveloping algebra as a morphism of associative algebras. -/ def mk_alg_hom : tensor_algebra R L →ₐ[R] universal_enveloping_algebra R L := ring_quot.mk_alg_hom R (rel R L) variables {L} /-- The natural Lie algebra morphism from a Lie algebra to its universal enveloping algebra. -/ def ι : L →ₗ⁅R⁆ universal_enveloping_algebra R L := { map_lie' := λ x y, by { suffices : mk_alg_hom R L (ιₜ ⁅x, y⁆ + (ιₜ y) * (ιₜ x)) = mk_alg_hom R L ((ιₜ x) * (ιₜ y)), { rw alg_hom.map_mul at this, simp [lie_ring.of_associative_ring_bracket, ← this], }, exact ring_quot.mk_alg_hom_rel _ (rel.lie_compat x y), }, ..(mk_alg_hom R L).to_linear_map.comp ιₜ } variables {A : Type u₃} [ring A] [algebra R A] (f : L →ₗ⁅R⁆ A) /-- The universal property of the universal enveloping algebra: Lie algebra morphisms into associative algebras lift to associative algebra morphisms from the universal enveloping algebra. -/ def lift : (L →ₗ⁅R⁆ A) ≃ (universal_enveloping_algebra R L →ₐ[R] A) := { to_fun := λ f, ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : L →ₗ[R] A), begin intros a b h, induction h with x y, simp only [lie_ring.of_associative_ring_bracket, map_add, tensor_algebra.lift_ι_apply, lie_hom.coe_to_linear_map, lie_hom.map_lie, map_mul, sub_add_cancel], end⟩, inv_fun := λ F, (F : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R), left_inv := λ f, by { ext, simp only [ι, mk_alg_hom, tensor_algebra.lift_ι_apply, lie_hom.coe_to_linear_map, linear_map.to_fun_eq_coe, linear_map.coe_comp, lie_hom.coe_comp, alg_hom.coe_to_lie_hom, lie_hom.coe_mk, function.comp_app, alg_hom.to_linear_map_apply, ring_quot.lift_alg_hom_mk_alg_hom_apply], }, right_inv := λ F, by { ext, simp only [ι, mk_alg_hom, tensor_algebra.lift_ι_apply, lie_hom.coe_to_linear_map, linear_map.to_fun_eq_coe, linear_map.coe_comp, lie_hom.coe_linear_map_comp, alg_hom.comp_to_linear_map, function.comp_app, alg_hom.to_linear_map_apply, ring_quot.lift_alg_hom_mk_alg_hom_apply, alg_hom.coe_to_lie_hom, lie_hom.coe_mk], } } @[simp] lemma lift_symm_apply (F : universal_enveloping_algebra R L →ₐ[R] A) : (lift R).symm F = (F : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R) := rfl @[simp] lemma ι_comp_lift : (lift R f) ∘ (ι R) = f := funext $ lie_hom.ext_iff.mp $ (lift R).symm_apply_apply f @[simp] lemma lift_ι_apply (x : L) : lift R f (ι R x) = f x := by rw [←function.comp_apply (lift R f) (ι R) x, ι_comp_lift] lemma lift_unique (g : universal_enveloping_algebra R L →ₐ[R] A) : g ∘ (ι R) = f ↔ g = lift R f := begin refine iff.trans _ (lift R).symm_apply_eq, split; {intro h, ext, simp [←h] }, end /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma hom_ext {g₁ g₂ : universal_enveloping_algebra R L →ₐ[R] A} (h : (g₁ : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R) = (g₂ : universal_enveloping_algebra R L →ₗ⁅R⁆ A).comp (ι R)) : g₁ = g₂ := have h' : (lift R).symm g₁ = (lift R).symm g₂, { ext, simp [h], }, (lift R).symm.injective h' end universal_enveloping_algebra
dab3f7844b8720d095f059b98f7ce6c0906bc480
4fa161becb8ce7378a709f5992a594764699e268
/src/group_theory/subgroup.lean
5fdcb1593d1ba1443464737ef402e4c09e442fae
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
38,772
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are groups - `A` is an add_group - `H K` are subgroups of `G` or add_subgroups of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `closure k` : the minimal subgroup that includes the set `k` * `subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `gi` : `closure` forms a Galois insertion with the coercion to set * `comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive add_subgroup] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier } @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩ @[to_additive] instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {K : subgroup G} {g : G} : g ∈ (K : set G) ↔ g ∈ K := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl attribute [norm_cast] add_subgroup.mem_coe attribute [norm_cast] add_subgroup.coe_coe end subgroup @[to_additive] protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} : (∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.exists @[to_additive] protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} : (∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.forall namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /- Two subgroups are equal if the underlying set are the same. -/ @[to_additive "Two `add_group`s are equal if the underlying subsets are equal."] theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K := by { cases H, cases K, congr, exact h } /- Two subgroups are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {H K : subgroup G} : H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- A subgroup of a group inherits a group structure. -/ @[to_additive to_add_group "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := { inv := has_inv.inv, mul_left_inv := λ x, subtype.eq $ mul_left_inv x, .. H.to_submonoid.to_monoid } /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive to_add_comm_group "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group} /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ @[to_additive] instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩ @[to_additive] lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl @[simp, to_additive] lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl @[to_additive] instance : partial_order (subgroup G) := { le := (≤), .. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi } /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hK end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n - g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[instance, priority 100, to_additive] lemma normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable nH : H.normal @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[instance, priority 100, to_additive] lemma bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj', mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[instance, priority 100, to_additive] lemma center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[instance, priority 100, to_additive] lemma normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal (hK : (H.comap K.subtype).normal) (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ end subgroup namespace group variables {s : set G} /-- Given an element `a`, `conjugates a` is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} (tn : N.normal) {a : G} (h : a ∈ N) : conjugates a ⊆ N := by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} (hN : N.normal) (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal hN (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure /-- The normal closure of `s` is a normal subgroup. -/ @[instance] lemma normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} (hN : N.normal) (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset hN h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} (hN : N.normal) : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal hN, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal normal_closure_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) (h : normal N) (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, le_infi (normal_closure_le_normal hN)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.smul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.smul_mem H.to_add_submonoid hx n lemma sub_mem (H : add_subgroup A) {x y : A} (hx : x ∈ H) (hy : y ∈ H) : x - y ∈ H := H.add_mem hx (H.neg_mem hy) /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker {f : G →* N} {x : G} : x ∈ f.ker ↔ f x = 1 := subgroup.mem_bot @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom variables {N : Type*} [group N] @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[instance, priority 100, to_additive] lemma subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[instance, priority 100, to_additive] lemma monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by rw [monoid_hom.ker]; apply_instance namespace subgroup /-- The subgroup generated by an element. -/ def gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl @[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩ lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} := by { ext, exact mem_closure_singleton.symm } attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure end add_subgroup namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive add_subgroup_congr "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h } end mul_equiv
bbed9ad43daf1bcf5eb575188c745691c97c08ff
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/343.lean
c2a3500f8bb759e9b1125a27496fa133712dd4c5
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
618
lean
structure CatIsh where Obj : Type o Hom : Obj → Obj → Type m infixr:75 " ~> " => (CatIsh.Hom _) structure FunctorIsh (C D : CatIsh) where onObj : C.Obj → D.Obj onHom : ∀ {s d : C.Obj}, (s ~> d) → (onObj s ~> onObj d) def Catish : CatIsh := { Obj := CatIsh Hom := FunctorIsh } universes m o unif_hint (mvar : CatIsh) where Catish.{m,o} =?= mvar |- mvar.Obj =?= CatIsh.{m,o} structure CtxSyntaxLayerParamsObj where Ct : CatIsh def CtxSyntaxLayerParams : CatIsh := { Obj := CtxSyntaxLayerParamsObj Hom := sorry } def CtxSyntaxLayerTy := CtxSyntaxLayerParams ~> Catish
cfa51fb0c578a7cba370581806f57c9803a63bb0
367134ba5a65885e863bdc4507601606690974c1
/src/combinatorics/pigeonhole.lean
6d7fa053aee66b4588e1a0ec06552cff11b0b41b
[ "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
18,910
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller, Yury Kudryashov -/ import data.fintype.basic import algebra.big_operators.order /-! # Pigeonhole principles Given pigeons (possibly infinitely many) in pigeonholes, the pigeonhole principle states that, if there are more pigeons than pigeonholes, then there is a pigeonhole with two or more pigeons. There are a few variations on this statement, and the conclusion can be made stronger depending on how many pigeons you know you might have. The basic statements of the pigeonhole principle appear in the following locations: * `data.finset.basic` has `finset.exists_ne_map_eq_of_card_lt_of_maps_to` * `data.fintype.basic` has `fintype.exists_ne_map_eq_of_card_lt` * `data.fintype.basic` has `fintype.exists_ne_map_eq_of_infinite` * `data.fintype.basic` has `fintype.exists_infinite_fiber` This module gives access to these pigeonhole principles along with 20 more. The versions vary by: * using a function between `fintype`s or a function between possibly infinite types restricted to `finset`s; * counting pigeons by a general weight function (`∑ x in s, w x`) or by heads (`finset.card s`); * using strict or non-strict inequalities; * establishing upper or lower estimate on the number (or the total weight) of the pigeons in one pigeonhole; * in case when we count pigeons by some weight function `w` and consider a function `f` between `finset`s `s` and `t`, we can either assume that each pigeon is in one of the pigeonholes (`∀ x ∈ s, f x ∈ t`), or assume that for `y ∉ t`, the total weight of the pigeons in this pigeonhole `∑ x in s.filter (λ x, f x = y), w x` is nonpositive or nonnegative depending on the inequality we are proving. Lemma names follow `mathlib` convention (e.g., `finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`); "pigeonhole principle" is mentioned in the docstrings instead of the names. ## See also * `ordinal.infinite_pigeonhole`: pigeonhole principle for cardinals, formulated using cofinality; * `measure_theory.exists_nonempty_inter_of_measure_univ_lt_tsum_measure`, `measure_theory.exists_nonempty_inter_of_measure_univ_lt_sum_measure`: pigeonhole principle in a measure space. ## Tags pigeonhole principle -/ universes u v w variables {α : Type u} {β : Type v} {M : Type w} [linear_ordered_cancel_add_comm_monoid M] [decidable_eq β] open_locale big_operators namespace finset variables {s : finset α} {t : finset β} {f : α → β} {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `finset`s, pigeons counted by weight In this section we prove the following version of the pigeonhole principle: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greateer than `b`, and a few variations of this theorem. The principle is formalized in the following way, see `finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`: if `f : α → β` is a function which maps all elements of `s : finset α` to `t : finset β` and `card t •ℕ b < ∑ x in s, w x`, where `w : α → M` is a weight function taking values in a `linear_ordered_cancel_add_comm_monoid`, then for some `y ∈ t`, the sum of the weights of all `x ∈ s` such that `f x = y` is greater than `b`. There are a few bits we can change in this theorem: * reverse all inequalities, with obvious adjustments to the name; * replace the assumption `∀ a ∈ s, f a ∈ t` with `∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0`, and replace `of_maps_to` with `of_sum_fiber_nonpos` in the name; * use non-strict inequalities assuming `t` is nonempty. We can do all these variations independently, so we have eight versions of the theorem. -/ /-! #### Strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ lemma exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (hf : ∀ a ∈ s, f a ∈ t) (hb : t.card •ℕ b < ∑ x in s, w x) : ∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x := exists_lt_of_sum_lt $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than `b`. -/ lemma exists_sum_fiber_lt_of_maps_to_of_sum_lt_nsmul (hf : ∀ a ∈ s, f a ∈ t) (hb : (∑ x in s, w x) < t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ hf hb /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is greater than `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than `b`. -/ lemma exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum (ht : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (hb : t.card •ℕ b < ∑ x in s, w x) : ∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x := exists_lt_of_sum_lt $ calc (∑ y in t, b) < ∑ x in s, w x : by simpa ... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x : sum_le_sum_fiberwise_of_sum_fiber_nonpos ht /-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version: if the total weight of a finite set of pigeons is less than `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than `b`. -/ lemma exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (ht : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (hb : (∑ x in s, w x) < t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ ht hb /-! #### Non-strict inequality versions -/ /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n •ℕ b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ lemma exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hb : t.card •ℕ b ≤ ∑ x in s, w x) : ∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x := exists_le_of_sum_le ht $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const] /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n •ℕ b`, and they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ lemma exists_sum_fiber_le_of_maps_to_of_sum_le_nsmul (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hb : (∑ x in s, w x) ≤ t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is greater than or equal to `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is greater than or equal to `b`. -/ lemma exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum (hf : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (ht : t.nonempty) (hb : t.card •ℕ b ≤ ∑ x in s, w x) : ∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x := exists_le_of_sum_le ht $ calc (∑ y in t, b) ≤ ∑ x in s, w x : by simpa ... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x : sum_le_sum_fiberwise_of_sum_fiber_nonpos hf /-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality version: if the total weight of a finite set of pigeons is less than or equal to `n •ℕ b`, they are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole is less than or equal to `b`. -/ lemma exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (hf : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (ht : t.nonempty) (hb : (∑ x in s, w x) ≤ t.card •ℕ b) : ∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb /-! ### The pigeonhole principles on `finset`s, pigeons counted by heads In this section we formalize a few versions of the following pigeonhole principle: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. First, we can use strict or non-strict inequalities. While the versions with non-strict inequalities are weaker than those with strict inequalities, sometimes it might be more convenient to apply the weaker version. Second, we can either state that there exists a pigeonhole with at least `n` pigeons, or state that there exists a pigeonhole with at most `n` pigeons. In the latter case we do not need the assumption `∀ a ∈ s, f a ∈ t`. So, we prove four theorems: `finset.exists_lt_card_fiber_of_maps_to_of_mul_lt_card`, `finset.exists_le_card_fiber_of_maps_to_of_mul_le_card`, `finset.exists_card_fiber_lt_of_card_lt_mul`, and `finset.exists_card_fiber_le_of_card_le_mul`. -/ /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function between finite sets `s` and `t` and a natural number `n` such that `card t * n < card s`, there exists `y ∈ t` such that its preimage in `s` has more than `n` elements. -/ lemma exists_lt_card_fiber_of_mul_lt_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (hn : t.card * n < s.card) : ∃ y ∈ t, n < (s.filter (λ x, f x = y)).card := begin simp only [card_eq_sum_ones], apply exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum hf, simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `card s < card t * n`, there exists `y ∈ t` such that its preimage in `s` has less than `n` elements. -/ lemma exists_card_fiber_lt_of_card_lt_mul (hn : s.card < t.card * n) : ∃ y ∈ t, (s.filter (λ x, f x = y)).card < n:= begin simp only [card_eq_sum_ones], apply exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (λ _ _, nat.zero_le _), simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function between finite sets `s` and `t` and a natural number `n` such that `card t * n ≤ card s`, there exists `y ∈ t` such that its preimage in `s` has at least `n` elements. See also `finset.exists_lt_card_fiber_of_mul_lt_card_of_maps_to` for a stronger statement. -/ lemma exists_le_card_fiber_of_mul_le_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hn : t.card * n ≤ s.card) : ∃ y ∈ t, n ≤ (s.filter (λ x, f x = y)).card := begin simp only [card_eq_sum_ones], apply exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum hf ht, simpa end /-- The pigeonhole principle for finitely many pigeons counted by heads: given a function `f`, a finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that `card s ≤ card t * n`, there exists `y ∈ t` such that its preimage in `s` has no more than `n` elements. See also `finset.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ lemma exists_card_fiber_le_of_card_le_mul (ht : t.nonempty) (hn : s.card ≤ t.card * n) : ∃ y ∈ t, (s.filter (λ x, f x = y)).card ≤ n:= begin simp only [card_eq_sum_ones], apply exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (λ _ _, nat.zero_le _) ht, simpa end end finset namespace fintype open finset variables [fintype α] [fintype β] (f : α → β) {w : α → M} {b : M} {n : ℕ} /-! ### The pigeonhole principles on `fintypes`s, pigeons counted by weight In this section we specialize theorems from the previous section to the special case of functions between `fintype`s and `s = univ`, `t = univ`. In this case the assumption `∀ x ∈ s, f x ∈ t` always holds, so we have four theorems instead of eight. -/ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than `b` provided that the total number of pigeonholes times `b` is less than the total weight of all pigeons. -/ lemma exists_lt_sum_fiber_of_nsmul_lt_sum (hb : card β •ℕ b < ∑ x, w x) : ∃ y, b < ∑ x in univ.filter (λ x, f x = y), w x := let ⟨y, _, hy⟩ := exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (λ _ _, mem_univ _) hb in ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it greater than or equal to `b` provided that the total number of pigeonholes times `b` is less than or equal to the total weight of all pigeons. -/ lemma exists_le_sum_fiber_of_nsmul_le_sum [nonempty β] (hb : card β •ℕ b ≤ ∑ x, w x) : ∃ y, b ≤ ∑ x in univ.filter (λ x, f x = y), w x := let ⟨y, _, hy⟩ := exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (λ _ _, mem_univ _) univ_nonempty hb in ⟨y, hy⟩ /-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than `b` provided that the total number of pigeonholes times `b` is greater than the total weight of all pigeons. -/ lemma exists_sum_fiber_lt_of_sum_lt_nsmul (hb : (∑ x, w x) < card β •ℕ b) : ∃ y, (∑ x in univ.filter (λ x, f x = y), w x) < b := @exists_lt_sum_fiber_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ w b hb /-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality version: there is a pigeonhole with the total weight of pigeons in it less than or equal to `b` provided that the total number of pigeonholes times `b` is greater than or equal to the total weight of all pigeons. -/ lemma exists_sum_fiber_le_of_sum_le_nsmul [nonempty β] (hb : (∑ x, w x) ≤ card β •ℕ b) : ∃ y, (∑ x in univ.filter (λ x, f x = y), w x) ≤ b := @exists_le_sum_fiber_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ w b _ hb /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes. ("The maximum is at least the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n < card α`, there exists an element `y : β` such that its preimage has more than `n` elements. -/ lemma exists_lt_card_fiber_of_mul_lt_card (hn : card β * n < card α) : ∃ y : β, n < (univ.filter (λ x, f x = y)).card := let ⟨y, _, h⟩ := exists_lt_card_fiber_of_mul_lt_card_of_maps_to (λ _ _, mem_univ _) hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. There is a pigeonhole with at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The minimum is at most the mean" specialized to integers.) More formally, given a function `f` between finite types `α` and `β` and a number `n` such that `card α < card β * n`, there exists an element `y : β` such that its preimage has less than `n` elements. -/ lemma exists_card_fiber_lt_of_card_lt_mul (hn : card α < card β * n) : ∃ y : β, (univ.filter (λ x, f x = y)).card < n := let ⟨y, _, h⟩ := exists_card_fiber_lt_of_card_lt_mul hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card β * n ≤ card α`, there exists an element `y : β` such that its preimage has at least `n` elements. See also `fintype.exists_lt_card_fiber_of_mul_lt_card` for a stronger statement. -/ lemma exists_le_card_fiber_of_mul_le_card [nonempty β] (hn : card β * n ≤ card α) : ∃ y : β, n ≤ (univ.filter (λ x, f x = y)).card := let ⟨y, _, h⟩ := exists_le_card_fiber_of_mul_le_card_of_maps_to (λ _ _, mem_univ _) univ_nonempty hn in ⟨y, h⟩ /-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f` between finite types `α` and `β` and a number `n` such that `card α ≤ card β * n`, there exists an element `y : β` such that its preimage has at most `n` elements. See also `fintype.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/ lemma exists_card_fiber_le_of_card_le_mul [nonempty β] (hn : card α ≤ card β * n) : ∃ y : β, (univ.filter (λ x, f x = y)).card ≤ n := let ⟨y, _, h⟩ := exists_card_fiber_le_of_card_le_mul univ_nonempty hn in ⟨y, h⟩ end fintype
976aa53fc9d999890ae983f58719106112a0dbee
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/algebra/big_operators.lean
28b0f73bd19c685fea46d81ebc8acb1f1f599dec
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
35,036
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 Some big operators for lists and finite sets. -/ import tactic.tauto data.list.basic data.finset data.nat.enat import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, by simp only [disjoint_iff_ne, mem_image]; rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom $ is_monoid_hom.map_mul g) @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_ite [comm_monoid γ] {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : s.prod (λ x, h (if p x then f x else g x)) = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) := by letI := classical.dec_eq α; exact calc s.prod (λ x, h (if p x then f x else g x)) = (s.filter p ∪ s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : by rw [filter_union_filter_neg_eq] ... = (s.filter p).prod (λ x, h (if p x then f x else g x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) : congr_arg2 _ (prod_congr rfl (by simp {contextual := tt})) (prod_congr rfl (by simp {contextual := tt})) @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : β) : s.prod (λ x, (ite (a = x) b 1)) = ite (a ∈ s) b 1 := begin rw ←finset.prod_filter, split_ifs; simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton, insert_empty_eq_singleton], end @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) : (Ico m n).sum (λ l, f (k + l)) = (Ico (m + k) (n + k)).sum f := Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) : (Ico m n).prod (λ l, f (k + l)) = (Ico (m + k) (n + k)).prod f := Ico.image_add m n k ▸ eq.symm $ prod_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : (Ico m n).prod f * (Ico n k).prod f = (Ico m k).prod f := Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k @[to_additive] lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) : (range m).prod f * (Ico m n).prod f = (range n).prod f := Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h @[to_additive sum_Ico_eq_add_neg] lemma prod_Ico_eq_div {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).prod f = (range n).prod f * ((range m).prod f)⁻¹ := eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).sum f = (range n).sum f - (range m).sum f := sum_Ico_eq_add_neg f h @[to_additive] lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) : (Ico m n).prod f = (range (n - m)).prod (λ l, f (m + l)) := begin by_cases h : m ≤ n, { rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] }, { replace h : n ≤ m := le_of_not_ge h, rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] } end @[to_additive] lemma prod_range_zero (f : ℕ → β) : (range 0).prod f = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (range 1).prod f = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (range 1).sum f = f 0 := by { rw [range_one], apply @sum_singleton ℕ δ 0 f } attribute [to_additive finset.sum_range_one] prod_range_one @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid attribute [to_additive] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (prod_hom _).symm protected lemma sum_nat_coe_enat [decidable_eq α] (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end theorem dvd_sum [comm_semiring α] {a : α} {s : finset β} {f : β → α} (h : ∀ x ∈ s, a ∣ f x) : a ∣ s.sum f := multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx) lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext.2 $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_bind (by simp [disjoint_left, finset.ext] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm @[simp] lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end @[simp] lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 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) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union sdiff_disjoint).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → (s.sum f = 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 ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, 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_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero [@decidable_rel β (≤)] (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ s₂.sum f : 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_monoid section linear_ordered_comm_ring variables [decidable_eq α] [linear_ordered_comm_ring β] /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- 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) : s.prod f ≤ s.prod g := 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 end linear_ordered_comm_ring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ 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 := calc s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_image _ _ ... ≤ (s.image f).sum (λ _, n) : sum_le_sum hn ... = _ : by simp [mul_comm] @[simp] lemma prod_Ico_id_eq_fact (n : ℕ) : (Ico 1 n.succ).prod (λ x, x) = nat.fact n := calc (Ico 1 n.succ).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, by simp [*, nat.lt_succ_iff, nat.succ_le_iff] at *) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero, nat.succ_le_iff] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] @[to_additive] theorem is_group_hom.map_prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_mul_hom.map_mul f, is_group_hom.map_one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive] lemma is_group_hom.map_multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.map_prod f l] @[to_additive] lemma is_group_hom.map_finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.map_multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset namespace with_top open finset variables [decidable_eq α] /-- sum of finte numbers is still finite -/ lemma sum_lt_top [ordered_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := finset.induction_on s (by { intro h, rw sum_empty, exact coe_lt_top _ }) (λa s ha ih h, begin rw [sum_insert ha, add_lt_top], split, { apply h, apply mem_insert_self }, { apply ih, intros a ha, apply h, apply mem_insert_of_mem ha } end) /-- sum of finte numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_monoid β] {s : finset α} {f : α → with_top β} : s.sum f < ⊤ ↔ (∀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 end with_top
43750d3c977462a51016f20117f7dee0c4a5e38b
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/elab_error_recovery.lean
73035b3358a03a947b4164b76b447a98a6b3d955
[ "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
431
lean
def half_baked : ℕ → ℕ | 3 := 2 -- type mismatches | 0 := 1 + "" -- placeholders | 5 := _ + 4 -- missing typeclass instances | 42 := if 2 ∈ 3 then 3 else _ -- exceptions during tactic evaluation | 7 := by do undefined -- nested elaboration errors | _ := begin exact [] end print half_baked._main eval half_baked 3 eval half_baked 5 vm_eval half_baked 3 -- type errors in binders check ∀ x : nat.zero, x = x
c75667cf26cacb1bc292ba4d96fe3763aff087ab
4727251e0cd73359b15b664c3170e5d754078599
/src/logic/relator.lean
30aa8a5230e811e82bcb2011ab2eb2329435b06a
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,459
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 Relator for functions, pairs, sums, and lists. -/ import logic.basic namespace relator universes u₁ u₂ v₁ v₂ /- TODO(johoelzl): * should we introduce relators of datatypes as recursive function or as inductive predicate? For now we stick to the recursor approach. * relation lift for datatypes, Π, Σ, set, and subtype types * proof composition and identity laws * implement method to derive relators from datatype -/ section variables {α : Sort u₁} {β : Sort u₂} {γ : Sort v₁} {δ : Sort v₂} variables (R : α → β → Prop) (S : γ → δ → Prop) def lift_fun (f : α → γ) (g : β → δ) : Prop := ∀⦃a b⦄, R a b → S (f a) (g b) infixr ⇒ := lift_fun end section variables {α : Type u₁} {β : Type u₂} (R : α → β → Prop) def right_total : Prop := ∀ b, ∃ a, R a b def left_total : Prop := ∀ a, ∃ b, R a b def bi_total : Prop := left_total R ∧ right_total R def left_unique : Prop := ∀ ⦃a b c⦄, R a c → R b c → a = b def right_unique : Prop := ∀ ⦃a b c⦄, R a b → R a c → b = c def bi_unique : Prop := left_unique R ∧ right_unique R variable {R} lemma right_total.rel_forall (h : right_total R) : ((R ⇒ implies) ⇒ implies) (λp, ∀i, p i) (λq, ∀i, q i) := assume p q Hrel H b, exists.elim (h b) (assume a Rab, Hrel Rab (H _)) lemma left_total.rel_exists (h : left_total R) : ((R ⇒ implies) ⇒ implies) (λp, ∃i, p i) (λq, ∃i, q i) := assume p q Hrel ⟨a, pa⟩, (h a).imp $ λ b Rab, Hrel Rab pa lemma bi_total.rel_forall (h : bi_total R) : ((R ⇒ iff) ⇒ iff) (λp, ∀i, p i) (λq, ∀i, q i) := assume p q Hrel, ⟨assume H b, exists.elim (h.right b) (assume a Rab, (Hrel Rab).mp (H _)), assume H a, exists.elim (h.left a) (assume b Rab, (Hrel Rab).mpr (H _))⟩ lemma bi_total.rel_exists (h : bi_total R) : ((R ⇒ iff) ⇒ iff) (λp, ∃i, p i) (λq, ∃i, q i) := assume p q Hrel, ⟨assume ⟨a, pa⟩, (h.left a).imp $ λ b Rab, (Hrel Rab).1 pa, assume ⟨b, qb⟩, (h.right b).imp $ λ a Rab, (Hrel Rab).2 qb⟩ lemma left_unique_of_rel_eq {eq' : β → β → Prop} (he : (R ⇒ (R ⇒ iff)) eq eq') : left_unique R := λ a b c (ac : R a c) (bc : R b c), (he ac bc).mpr ((he bc bc).mp rfl) end lemma rel_imp : (iff ⇒ (iff ⇒ iff)) implies implies := assume p q h r s l, imp_congr h l lemma rel_not : (iff ⇒ iff) not not := assume p q h, not_congr h lemma bi_total_eq {α : Type u₁} : relator.bi_total (@eq α) := { left := λ a, ⟨a, rfl⟩, right := λ a, ⟨a, rfl⟩ } variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop} lemma left_unique.flip (h : left_unique r) : right_unique (flip r) := λ a b c h₁ h₂, h h₁ h₂ lemma rel_and : ((↔) ⇒ (↔) ⇒ (↔)) (∧) (∧) := assume a b h₁ c d h₂, and_congr h₁ h₂ lemma rel_or : ((↔) ⇒ (↔) ⇒ (↔)) (∨) (∨) := assume a b h₁ c d h₂, or_congr h₁ h₂ lemma rel_iff : ((↔) ⇒ (↔) ⇒ (↔)) (↔) (↔) := assume a b h₁ c d h₂, iff_congr h₁ h₂ lemma rel_eq {r : α → β → Prop} (hr : bi_unique r) : (r ⇒ r ⇒ (↔)) (=) (=) := λ a b h₁ c d h₂, ⟨λ h, hr.right h₁ $ h.symm ▸ h₂, λ h, hr.left h₁ $ h.symm ▸ h₂⟩ end relator
bb9469df6d28522e1331dfd4b89d55e8e797eb3f
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Meta/Transform.lean
240404de191706fb1666a7deb58cc4d57ff696ab
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
6,015
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic namespace Lean inductive TransformStep where | done (e : Expr) | visit (e : Expr) namespace Core /-- Tranform the expression `input` using `pre` and `post`. - `pre s` is invoked before visiting the children of subterm 's'. If the result is `TransformStep.visit sNew`, then `sNew` is traversed by transform. If the result is `TransformStep.visit sNew`, then `s` is just replaced with `sNew`. In both cases, `sNew` must be definitionally equal to `s` - `post s` is invoked after visiting the children of subterm `s`. The term `s` in both `pre s` and `post s` may contain loose bound variables. So, this method is not appropriate for if one needs to apply operations (e.g., `whnf`, `inferType`) that do not handle loose bound variables. Consider using `Meta.transform` to avoid loose bound variables. This method is useful for applying transformations such as beta-reduction and delta-reduction. -/ partial def transform {m} [Monad m] [MonadLiftT CoreM m] [MonadControlT CoreM m] (input : Expr) (pre : Expr → m TransformStep := fun e => return TransformStep.visit e) (post : Expr → m TransformStep := fun e => return TransformStep.done e) : m Expr := let inst : STWorld IO.RealWorld m := ⟨⟩ let inst : MonadLiftT (ST IO.RealWorld) m := { monadLift := fun x => liftM (m := CoreM) (liftM (m := ST IO.RealWorld) x) } let rec visit (e : Expr) : MonadCacheT Expr Expr m Expr := checkCache e fun _ => Core.withIncRecDepth do let rec visitPost (e : Expr) : MonadCacheT Expr Expr m Expr := do match (← post e) with | TransformStep.done e => pure e | TransformStep.visit e => visit e match (← pre e) with | TransformStep.done e => pure e | TransformStep.visit e => match e with | Expr.forallE _ d b _ => visitPost (e.updateForallE! (← visit d) (← visit b)) | Expr.lam _ d b _ => visitPost (e.updateLambdaE! (← visit d) (← visit b)) | Expr.letE _ t v b _ => visitPost (e.updateLet! (← visit t) (← visit v) (← visit b)) | Expr.app .. => e.withApp fun f args => do visitPost (mkAppN (← visit f) (← args.mapM visit)) | Expr.mdata _ b _ => visitPost (e.updateMData! (← visit b)) | Expr.proj _ _ b _ => visitPost (e.updateProj! (← visit b)) | _ => visitPost e visit input |>.run def betaReduce (e : Expr) : CoreM Expr := transform e (pre := fun e => return TransformStep.visit e.headBeta) end Core namespace Meta /-- Similar to `Core.transform`, but terms provided to `pre` and `post` do not contain loose bound variables. So, it is safe to use any `MetaM` method at `pre` and `post`. -/ partial def transform {m} [Monad m] [MonadLiftT MetaM m] [MonadControlT MetaM m] (input : Expr) (pre : Expr → m TransformStep := fun e => return TransformStep.visit e) (post : Expr → m TransformStep := fun e => return TransformStep.done e) : m Expr := let inst : STWorld IO.RealWorld m := ⟨⟩ let inst : MonadLiftT (ST IO.RealWorld) m := { monadLift := fun x => liftM (m := MetaM) (liftM (m := ST IO.RealWorld) x) } let rec visit (e : Expr) : MonadCacheT Expr Expr m Expr := checkCache e fun _ => Meta.withIncRecDepth do let rec visitPost (e : Expr) : MonadCacheT Expr Expr m Expr := do match (← post e) with | TransformStep.done e => pure e | TransformStep.visit e => visit e let rec visitLambda (fvars : Array Expr) (e : Expr) : MonadCacheT Expr Expr m Expr := do match e with | Expr.lam n d b c => withLocalDecl n c.binderInfo (← visit (d.instantiateRev fvars)) fun x => visitLambda (fvars.push x) b | e => visitPost (← mkLambdaFVars fvars (← visit (e.instantiateRev fvars))) let rec visitForall (fvars : Array Expr) (e : Expr) : MonadCacheT Expr Expr m Expr := do match e with | Expr.forallE n d b c => withLocalDecl n c.binderInfo (← visit (d.instantiateRev fvars)) fun x => visitForall (fvars.push x) b | e => visitPost (← mkForallFVars fvars (← visit (e.instantiateRev fvars))) let rec visitLet (fvars : Array Expr) (e : Expr) : MonadCacheT Expr Expr m Expr := do match e with | Expr.letE n t v b _ => withLetDecl n (← visit (t.instantiateRev fvars)) (← visit (v.instantiateRev fvars)) fun x => visitLet (fvars.push x) b | e => visitPost (← mkLetFVars fvars (← visit (e.instantiateRev fvars))) let visitApp (e : Expr) : MonadCacheT Expr Expr m Expr := e.withApp fun f args => do visitPost (mkAppN (← visit f) (← args.mapM visit)) match (← pre e) with | TransformStep.done e => pure e | TransformStep.visit e => match e with | Expr.forallE .. => visitForall #[] e | Expr.lam .. => visitLambda #[] e | Expr.letE .. => visitLet #[] e | Expr.app .. => visitApp e | Expr.mdata _ b _ => visitPost (e.updateMData! (← visit b)) | Expr.proj _ _ b _ => visitPost (e.updateProj! (← visit b)) | _ => visitPost e visit input |>.run def zetaReduce (e : Expr) : MetaM Expr := do let lctx ← getLCtx let pre (e : Expr) : CoreM TransformStep := do match e with | Expr.fvar fvarId _ => match lctx.find? fvarId with | none => return TransformStep.done e | some localDecl => if let some value := localDecl.value? then return TransformStep.visit value else return TransformStep.done e | e => if e.hasFVar then return TransformStep.visit e else return TransformStep.done e liftM (m := CoreM) <| Core.transform e (pre := pre) end Meta end Lean
a7e321200cd11dc927910ad75ce937b328bb0f45
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/Basic.lean
9a76d867f2867978af21a84ac0cfc6391ae80667
[ "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
44,522
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.Trace import Lean.Util.RecDepth import Lean.Util.PPExt import Lean.Util.OccursCheck import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode import Lean.Meta.DiscrTreeTypes import Lean.Eval import Lean.CoreM /- This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck structure Config where foApprox : Bool := false ctxApprox : Bool := false quasiPatternApprox : Bool := false /- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ constApprox : Bool := false /- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ isDefEqStuckEx : Bool := false transparency : TransparencyMode := TransparencyMode.default /- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ zetaNonDep : Bool := true /- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ trackZeta : Bool := false unificationHints : Bool := true structure ParamInfo where implicit : Bool := false instImplicit : Bool := false hasFwdDeps : Bool := false backDeps : Array Nat := #[] deriving Inhabited def ParamInfo.isExplicit (p : ParamInfo) : Bool := !p.implicit && !p.instImplicit structure FunInfo where paramInfo : Array ParamInfo := #[] resultDeps : Array Nat := #[] structure InfoCacheKey where transparency : TransparencyMode expr : Expr nargs? : Option Nat deriving Inhabited, BEq namespace InfoCacheKey instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩ end InfoCacheKey open Std (PersistentArray PersistentHashMap) abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) abbrev InferTypeCache := PersistentExprStructMap Expr abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo abbrev WhnfCache := PersistentExprStructMap Expr structure Cache where inferType : InferTypeCache := {} funInfo : FunInfoCache := {} synthInstance : SynthInstanceCache := {} whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default` whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all` deriving Inhabited structure PostponedEntry where lhs : Level rhs : Level structure State where mctx : MetavarContext := {} cache : Cache := {} /- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ zetaFVarIds : NameSet := {} postponed : PersistentArray PostponedEntry := {} deriving Inhabited structure Context where config : Config := {} lctx : LocalContext := {} localInstances : LocalInstances := #[] abbrev MetaM := ReaderT Context $ StateRefT State CoreM instance : Inhabited (MetaM α) where default := fun _ _ => arbitrary instance : MonadLCtx MetaM where getLCtx := return (← read).lctx instance : MonadMCtx MetaM where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : AddMessageContext MetaM where addMessageContext := addMessageContextFull @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck {α} : MetaM α := throw <| Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f <| runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase <| k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c section Methods variable [MonadControlT MetaM n] [Monad n] @[inline] def modifyCache (f : Cache → Cache) : MetaM Unit := modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩ @[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit := modifyCache fun ⟨ic, c1, c2, c3, c4⟩ => ⟨f ic, c1, c2, c3, c4⟩ def getLocalInstances : MetaM LocalInstances := return (← read).localInstances def getConfig : MetaM Config := return (← read).config def setMCtx (mctx : MetavarContext) : MetaM Unit := modify fun s => { s with mctx := mctx } def resetZetaFVarIds : MetaM Unit := modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : MetaM NameSet := return (← get).zetaFVarIds def getPostponed : MetaM (PersistentArray PostponedEntry) := return (← get).postponed def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := postponed } @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := f s.postponed } builtin_initialize whnfRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "whnf implementation was not set" builtin_initialize inferTypeRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "inferType implementation was not set" builtin_initialize isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) ← IO.mkRef fun _ _ => throwError "isDefEq implementation was not set" builtin_initialize synthPendingRef : IO.Ref (MVarId → MetaM Bool) ← IO.mkRef fun _ => pure false def whnf (e : Expr) : MetaM Expr := withIncRecDepth do (← whnfRef.get) e def whnfForall (e : Expr) : MetaM Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e def inferType (e : Expr) : MetaM Expr := withIncRecDepth do (← inferTypeRef.get) e protected def isExprDefEqAux (t s : Expr) : MetaM Bool := withIncRecDepth do (← isExprDefEqAuxRef.get) t s protected def synthPending (mvarId : MVarId) : MetaM Bool := withIncRecDepth do (← synthPendingRef.get) mvarId -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth {α} (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; return mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do let mvarId ← mkFreshId mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : MetaM Level := do let mvarId ← mkFreshId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; return mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do let lctx ← getLCtx let localInsts ← getLocalInstances mkFreshExprMVarAt lctx localInsts type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do let lctx ← getLCtx let localInsts ← getLocalInstances mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def getTransparency : MetaM TransparencyMode := return (← getConfig).transparency def shouldReduceAll : MetaM Bool := return (← getTransparency) == TransparencyMode.all def shouldReduceReducibleOnly : MetaM Bool := return (← getTransparency) == TransparencyMode.reducible def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do let mctx ← getMCtx match mctx.findDecl? mvarId with | some d => pure d | none => throwError! "unknown metavariable '{mkMVar mvarId}'" def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarKind mvarId kind /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do modifyMCtx fun mctx => mctx.setMVarType mvarId type def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← getMVarDecl mvarId let mctx ← getMCtx return mvarDecl.depth != mctx.depth def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.syntheticOpaque => pure true | _ => let mctx ← getMCtx return mvarDecl.depth != mctx.depth def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do let mctx ← getMCtx match mctx.findLevelDepth? mvarId with | some depth => return depth != mctx.depth | _ => throwError! "unknown universe metavariable '{mkLevelMVar mvarId}'" def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool := return (← getMCtx).isExprAssigned mvarId def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) := return (← getMCtx).getExprAssignment? mvarId /-- Return true if `e` contains `mvarId` directly or indirectly -/ def occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool := return (← getMCtx).occursCheck mvarId e def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit := modifyMCtx fun mctx => mctx.assignExpr mvarId val def isDelayedAssigned (mvarId : MVarId) : MetaM Bool := return (← getMCtx).isDelayedAssigned mvarId def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) := return (← getMCtx).getDelayedAssignment? mvarId def hasAssignableMVar (e : Expr) : MetaM Bool := return (← getMCtx).hasAssignableMVar e def throwUnknownFVar {α} (fvarId : FVarId) : MetaM α := throwError! "unknown free variable '{mkFVar fvarId}'" def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := return (← getLCtx).find? fvarId def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do match (← getLCtx).find? fvarId with | some d => pure d | none => throwUnknownFVar fvarId def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := getLocalDecl fvar.fvarId! def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError! "unknown local declaration '{userName}'" def instantiateLevelMVars (u : Level) : MetaM Level := MetavarContext.instantiateLevelMVars u def instantiateMVars (e : Expr) : MetaM Expr := (MetavarContext.instantiateExprMVars e).run def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl := do match localDecl with | LocalDecl.cdecl idx id n type bi => let type ← instantiateMVars type return LocalDecl.cdecl idx id n type bi | LocalDecl.ldecl idx id n type val nonDep => let type ← instantiateMVars type let val ← instantiateMVars val return LocalDecl.ldecl idx id n type val nonDep @[inline] def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α := do match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with | EStateM.Result.ok e newS => do setNGen newS.ngen; setMCtx newS.mctx; pure e | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do setMCtx newS.mctx; setNGen newS.ngen; throwError "failed to create binder due to failure when reverting variable dependencies" def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly def mkLetFVars (xs : Array Expr) (e : Expr) : MetaM Expr := mkLambdaFVars xs e def mkArrow (d b : Expr) : MetaM Expr := do let n ← mkFreshUserName `x return Lean.mkForall n BinderInfo.default d b def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder @[inline] def withConfig {α} (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta {α} (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withTransparency {α} (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) @[inline] def withDefault {α} (x : n α) : n α := withTransparency TransparencyMode.default x @[inline] def withReducible {α} (x : n α) : n α := withTransparency TransparencyMode.reducible x @[inline] def withReducibleAndInstances {α} (x : n α) : n α := withTransparency TransparencyMode.instances x @[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl {α} (x : MetaM α) : MetaM α := do let s ← get let savedCache := s.cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache {α} : n α → n α := mapMetaM savingCacheImpl def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do if (← shouldReduceAll) then return some info else return none private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← getTransparency) with | TransparencyMode.all => return some info | TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none /- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`. This method is only used to implement `isClassQuickConst?`. It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/ private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do let env ← getEnv match env.find? constName with | some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do let env ← getEnv if isClass env constName then pure (LOption.some constName) else match (← getConstTemp? constName) with | some _ => pure LOption.undef | none => pure LOption.none private partial def isClassQuick? : Expr → MetaM (LOption Name) | Expr.bvar .. => pure LOption.none | Expr.lit .. => pure LOption.none | Expr.fvar .. => pure LOption.none | Expr.sort .. => pure LOption.none | Expr.lam .. => pure LOption.none | Expr.letE .. => pure LOption.undef | Expr.proj .. => pure LOption.undef | Expr.forallE _ _ b _ => isClassQuick? b | Expr.mdata _ e _ => isClassQuick? e | Expr.const n _ _ => isClassQuickConst? n | Expr.mvar mvarId _ => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => pure LOption.none | Expr.app f _ _ => match f.getAppFn with | Expr.const n .. => isClassQuickConst? n | Expr.lam .. => pure LOption.undef | _ => pure LOption.none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let s ← get let savedSythInstance := s.cache.synthInstance modifyCache fun c => { c with synthInstance := {} } pure savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modifyCache fun c => { c with synthInstance := cache } @[inline] private def resettingSynthInstanceCacheImpl {α} (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache {α} : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/ match localDecl.binderInfo with | BinderInfo.auxDecl => k | _ => resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance {α} (className : Name) (fvar : Expr) : n α → n α := mapMetaM <| withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp {α} (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | LOption.none => withNewLocalInstancesImp fvars (i+1) k | LOption.undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k | LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux {α} (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | Expr.forallE n d b c => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? : Expr → MetaM (Option Name) | type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun xs type => do let env ← getEnv match type.getAppFn with | Expr.const c _ _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← whnf type).getAppFn with | Expr.const c _ _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | LOption.none => pure none | LOption.some c => pure (some c) | LOption.undef => isClassExpensive? type end def isClass? (type : Expr) : MetaM (Option Name) := try isClassImp? type catch _ => pure none private def withNewLocalInstancesImpAux {α} (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImp fvars j partial def withNewLocalInstances {α} (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImpAux fvars j @[inline] private def forallTelescopeImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k /-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/ private partial def lambdaTelescopeAux {α} (k : Array Expr → Expr → MetaM α) : Bool → LocalContext → Array Expr → Nat → Expr → MetaM α | consumeLet, lctx, fvars, j, Expr.lam n d b c => do let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId lambdaTelescopeAux k consumeLet lctx (fvars.push fvar) j b | true, lctx, fvars, j, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId lambdaTelescopeAux k true lctx (fvars.push fvar) j b | _, lctx, fvars, j, e => let e := e.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e private partial def lambdaTelescopeImp {α} (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, Expr.lam n d b c => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e process consumeLet (← getLCtx) #[] 0 e /-- Similar to `forallTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type true k) k /-- Similar to `forallTelescope` but for lambda expressions. -/ def lambdaTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type false k) k /-- Return the parameter names for the givel global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do let cinfo ← getConstInfo declName forallTelescopeReducing cinfo.type fun xs _ => do xs.mapM fun x => do let localDecl ← getLocalDecl x.fvarId! pure localDecl.userName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do match type with | Expr.forallE n d b c => let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let d := d.instantiateRevRange j mvars.size mvars let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b match maxMVars? with | none => cont () | some maxMVars => if mvars.size < maxMVars then cont () else let type := type.instantiateRevRange j mvars.size mvars; pure (mvars, bis, type) | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else pure (mvars, bis, type) else pure (mvars, bis, type) process #[] #[] 0 e /-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars pure (mvars, bis, type) let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do match type with | Expr.lam n d b c => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b | _ => finalize () match maxMVars? with | none => cont () | some maxMVars => if mvars.size < maxMVars then cont () else finalize () process #[] #[] 0 e private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do match (← isClass? fvarType) with | none => k fvar | some c => withNewLocalInstance c fvar <| k fvar private def withLocalDeclImp {α} (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLocalDecl {α} (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k) k def withLocalDeclD {α} (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k private def withLetDeclImp {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLetDecl {α} (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLetDeclImp name type val k) k private def withExistingLocalDeclsImp {α} (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let numLocalInstances := ctx.localInstances.size let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do let newLocalInsts ← decls.foldlM (fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do { match (← isClass? decl.type) with | none => pure newlocalInsts | some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _)) ctx.localInstances; if newLocalInsts.size == numLocalInstances then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k def withExistingLocalDecls {α} (decls : List LocalDecl) : n α → n α := mapMetaM <| withExistingLocalDeclsImp decls private def withNewMCtxDepthImp {α} (x : MetaM α) : MetaM α := do let s ← get let savedMCtx := s.mctx modifyMCtx fun mctx => mctx.incDepth try x finally setMCtx savedMCtx /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. -/ def withNewMCtxDepth {α} : n α → n α := mapMetaM withNewMCtxDepthImp private def withLocalContextImp {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM <| withLocalContextImp lctx localInsts private def withMVarContextImp {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← getMVarDecl mvarId withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def withMVarContext {α} (mvarId : MVarId) : n α → n α := mapMetaM <| withMVarContextImp mvarId private def withMCtxImp {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' def withMCtx {α} (mctx : MetavarContext) : n α → n α := mapMetaM <| withMCtxImp mctx @[inline] private def approxDefEqImp {α} (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq {α} : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp {α} (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq {α} : n α → n α := mapMetaM fullApproxDefEqImp def normalizeLevel (u : Level) : MetaM Level := do let u ← instantiateLevelMVars u pure u.normalize def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do modifyMCtx fun mctx => mctx.assignLevel mvarId u def whnfR (e : Expr) : MetaM Expr := withTransparency TransparencyMode.reducible <| whnf e def whnfD (e : Expr) : MetaM Expr := withTransparency TransparencyMode.default <| whnf e def whnfI (e : Expr) : MetaM Expr := withTransparency TransparencyMode.instances <| whnf e def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | Except.ok env => setEnv env | Except.error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ let e ← whnf e match e with | Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else pure e /- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ let e ← whnf e match e with | Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else pure e /- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateLambdaAux ps 0 e /-- Return true iff `e` depends on the free variable `fvarId` -/ def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool := return (← getMCtx).exprDependsOn e fvarId def ppExpr (e : Expr) : MetaM Format := do let env ← getEnv let mctx ← getMCtx let lctx ← getLCtx let opts ← getOptions let ctxCore ← readThe Core.Context Lean.ppExpr { env := env, mctx := mctx, lctx := lctx, opts := opts, currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e @[inline] protected def orelse {α} (x y : MetaM α) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch _ => setEnv env; setMCtx mctx; y instance {α} : OrElse (MetaM α) := ⟨Meta.orelse⟩ @[inline] private def orelseMergeErrorsImp {α} (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors {α m} [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp {α} (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw <| Exception.error ref <| f msg | ex => throw ex @[inline] def mapError {α m} [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- `commitWhenSome? x` executes `x` and keep modifications when it returns `some a`. -/ @[specialize] def commitWhenSome? {α} (x? : MetaM (Option α)) : MetaM (Option α) := do let env ← getEnv let mctx ← getMCtx try match (← x?) with | some a => pure (some a) | none => setEnv env setMCtx mctx pure none catch ex => setEnv env setMCtx mctx throw ex end Methods end Meta export Meta (MetaM) end Lean
3d094aeeb0894bff20d96c7ed8e2069e9489ae46
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/linear_algebra/multilinear/basic.lean
4a6579eddb72a12751028e1605a9b85a3f3b4f6c
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
52,298
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import linear_algebra.basic import algebra.algebra.basic import algebra.big_operators.order import algebra.big_operators.ring import data.fintype.card import data.fintype.sort /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set open_locale big_operators universes u v v' v₁ v₂ v₃ w u' variables {R : Type u} {ι : Type u'} {n : ℕ} {M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ι] /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] := (to_fun : (Πi, M₁ i) → M₂) (map_add' : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (map_smul' : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (update m i (c • x)) = c • to_fun (update m i x)) namespace multilinear_map section semiring variables [semiring R] [∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] (f f' : multilinear_map R M₁ M₂) instance : has_coe_to_fun (multilinear_map R M₁ M₂) (λ f, (Πi, M₁ i) → M₂) := ⟨to_fun⟩ initialize_simps_projections multilinear_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (Π i, M₁ i) → M₂) (h₁ h₂ ) : ⇑(⟨f, h₁, h₂⟩ : multilinear_map R M₁ M₂) = f := rfl theorem congr_fun {f g : multilinear_map R M₁ M₂} (h : f = g) (x : Π i, M₁ i) : f x = g x := congr_arg (λ h : multilinear_map R M₁ M₂, h x) h theorem congr_arg (f : multilinear_map R M₁ M₂) {x y : Π i, M₁ i} (h : x = y) : f x = f y := congr_arg (λ x : Π i, M₁ i, f x) h theorem coe_injective : injective (coe_fn : multilinear_map R M₁ M₂ → ((Π i, M₁ i) → M₂)) := by { intros f g h, cases f, cases g, cases h, refl } @[simp, norm_cast] theorem coe_inj {f g : multilinear_map R M₁ M₂} : (f : (Π i, M₁ i) → M₂) = g ↔ f = g := coe_injective.eq_iff @[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := coe_injective (funext H) theorem ext_iff {f g : multilinear_map R M₁ M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := begin have : (0 : R) • (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_update_zero (m : Πi, M₁ i) (i : ι) : f (update m i 0) = 0 := f.map_coord_zero i (update_same i 0 m) @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := begin obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ M₂) := ⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_zero (multilinear_map R M₁ M₂) := ⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl instance : add_comm_monoid (multilinear_map R M₁ M₂) := { zero := (0 : multilinear_map R M₁ M₂), 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, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, nsmul_zero' := λ f, by { ext, simp }, nsmul_succ' := λ n f, by { ext, simp [add_smul, nat.succ_eq_one_add] } } @[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ := { to_fun := λx, f (update m i x), map_add' := λx y, by simp, map_smul' := λc x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := { to_fun := λ m, (f m, g m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } /-- Combine a family of multilinear maps with the same domain and codomains `M' i` into a multilinear map taking values in the space of functions `Π i, M' i`. -/ @[simps] def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, module R (M' i)] (f : Π i, multilinear_map R M₁ (M' i)) : multilinear_map R M₁ (Π i, M' i) := { to_fun := λ m i, f i m, map_add' := λ m i x y, funext $ λ j, (f j).map_add _ _ _ _, map_smul' := λ m i c x, funext $ λ j, (f j).map_smul _ _ _ _ } section variables (R M₂) /-- The evaluation map from `ι → M₂` to `M₂` is multilinear at a given `i` when `ι` is subsingleton. -/ @[simps] def of_subsingleton [subsingleton ι] (i' : ι) : multilinear_map R (λ _ : ι, M₂) M₂ := { to_fun := function.eval i', map_add' := λ m i x y, by { rw subsingleton.elim i i', simp only [function.eval, function.update_same], }, map_smul' := λ m i r x, by { rw subsingleton.elim i i', simp only [function.eval, function.update_same], } } end /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (λ i : fin k, M') M₂ := { to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.order_iso_of_fin hk).symm ⟨j, h⟩) else z), map_add' := λ v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, map_smul' := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma snoc_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c • x)) = c • f (snoc m x) := by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last] section variables {M₁' : ι → Type*} [Π i, add_comm_monoid (M₁' i)] [Π i, module R (M₁' i)] /-- If `g` is a multilinear map and `f` is a collection of linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a multilinear map, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) : multilinear_map R M₁ M₂ := { to_fun := λ m, g $ λ i, f i (m i), map_add' := λ m i x y, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this], map_smul' := λ m i c x, have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j := λ j z, function.apply_update (λ k, f k) _ _ _ _, by simp [this] } @[simp] lemma comp_linear_map_apply (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) (m : Π i, M₁ i) : g.comp_linear_map f m = g (λ i, f i (m i)) := rfl end /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (λs hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {α : ι → Type*} (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) open_locale classical open fintype finset /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux [fintype ι] {n : ℕ} (h : ∑ i, (A i).card = n) : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := begin induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : ∃ i, A i = ∅, { rcases Ai_empty with ⟨i, hi⟩, have : ∑ j in A i, g i j = 0, by rw [hi, finset.sum_empty], rw f.map_coord_zero i this, have : pi_finset A = ∅, { apply finset.eq_empty_of_forall_not_mem (λ r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, rw [this, finset.sum_empty] }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : ∀ i, (A i).card ≤ 1, { have Ai_card : ∀ i, (A i).card = 1, { assume i, have pos : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≤ 1 := Ai_singleton i, exact le_antisymm this (nat.succ_le_of_lt (_root_.pos_iff_ne_zero.mpr pos)) }, have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, ∑ j in A i, g i j), { assume r hr, unfold_coes, congr' with i, have : ∀ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, one_nsmul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul, finset.sum_const] }, -- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2. -- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i` -- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ := finset.one_lt_card_iff.1 hi₀, let B := function.update A i₀ (A i₀ \ {j₂}), let C := function.update A i₀ {j₂}, have B_subset_A : ∀ i, B i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : ∀ i, C i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity. have A_eq_BC : (λ i, ∑ j in A i, g i j) = function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j + ∑ j in C i₀, g i₀ j), { ext i, by_cases hi : i = i₀, { rw [hi], simp only [function.update_same], have : A i₀ = B i₀ ∪ C i₀, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hj₂, finset.singleton_subset_iff, finset.union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (λ j hj, _), have : j = j₂, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j) = (λ i, ∑ j in B i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in C i₀, g i₀ j) = (λ i, ∑ j in C i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (λ i, ∑ j in B i, g i j) = ∑ r in pi_finset B, f (λ i, g i (r i)), { have : ∑ i, finset.card (B i) < ∑ i, finset.card (A i), { refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i)) ⟨i₀, finset.mem_univ _, _⟩, have : {j₂} ⊆ A i₀, by simp [hj₂], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hi₀)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (λ i, ∑ j in C i, g i j) = ∑ r in pi_finset C, f (λ i, g i (r i)), { have : ∑ i, finset.card (C i) < ∑ i, finset.card (A i) := finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i)) ⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B i₀) (C i₀), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hri₀ : r i₀ = j₂, { apply finset.mem_union_right, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ C i₀, by simp [C, hri₀], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ B i₀, by simp [B, hri₀, mem_pi_finset.1 hr i₀], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i)) (pi_finset_subset _ _ (λ i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset [fintype ι] : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.map_sum_finset_aux _ _ rfl /-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [fintype ι] [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.map_sum_finset g (λ i, finset.univ) lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M₁ i) (m : Π i, M₁ i): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := begin induction t using finset.induction with a t has ih h, { simp }, { simp [finset.sum_insert has, ih] } end end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), module A (M₁ i)] [module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved modules agree with the action of `R` on `A`. -/ def restrict_scalars (f : multilinear_map A M₁ M₂) : multilinear_map R M₁ M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := λ m i, (f.to_linear_map m i).map_smul_of_tower } @[simp] lemma coe_restrict_scalars (f : multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar section variables {ι₁ ι₂ ι₃ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] [decidable_eq ι₃] /-- Transfer the arguments to a map along an equivalence between argument indices. The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the domain of the domain. -/ @[simps apply] def dom_dom_congr (σ : ι₁ ≃ ι₂) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := λ v, m (λ i, v (σ i)), map_add' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_add, }, map_smul' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_smul, }, } lemma dom_dom_congr_trans (σ₁ : ι₁ ≃ ι₂) (σ₂ : ι₂ ≃ ι₃) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₁.trans σ₂) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl lemma dom_dom_congr_mul (σ₁ : equiv.perm ι₁) (σ₂ : equiv.perm ι₁) (m : multilinear_map R (λ i : ι₁, M₂) M₃) : m.dom_dom_congr (σ₂ * σ₁) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl /-- `multilinear_map.dom_dom_congr` as an equivalence. This is declared separately because it does not work with dot notation. -/ @[simps apply symm_apply] def dom_dom_congr_equiv (σ : ι₁ ≃ ι₂) : multilinear_map R (λ i : ι₁, M₂) M₃ ≃+ multilinear_map R (λ i : ι₂, M₂) M₃ := { to_fun := dom_dom_congr σ, inv_fun := dom_dom_congr σ.symm, left_inv := λ m, by {ext, simp}, right_inv := λ m, by {ext, simp}, map_add' := λ a b, by {ext, simp} } end end semiring end multilinear_map namespace linear_map variables [semiring R] [Πi, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M'] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := { to_fun := g ∘ f, map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } @[simp] lemma coe_comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : ⇑(g.comp_multilinear_map f) = g ∘ f := rfl lemma comp_multilinear_map_apply (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) (m : Π i, M₁ i) : g.comp_multilinear_map f m = g (f m) := rfl variables {ι₁ ι₂ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] @[simp] lemma comp_multilinear_map_dom_dom_congr (σ : ι₁ ≃ ι₂) (g : M₂ →ₗ[R] M₃) (f : multilinear_map R (λ i : ι₁, M') M₂) : (g.comp_multilinear_map f).dom_dom_congr σ = g.comp_multilinear_map (f.dom_dom_congr σ) := by { ext, simp } end linear_map namespace multilinear_map section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)] [add_comm_monoid M₂] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] (f f' : multilinear_map R M₁ M₂) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λi, c i • m i) m) = (∏ i in s, c i) • f m := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) = s.piecewise (λi, c i • m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λi, c i • m i) = (∏ i, c i) • f m := by simpa using map_piecewise_smul f c m finset.univ @[simp] lemma map_update_smul [fintype ι] (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update (c • m) i x) = c^(fintype.card ι - 1) • f (update m i x) := begin have : f ((finset.univ.erase i).piecewise (c • update m i x) (update m i x)) = (∏ i in finset.univ.erase i, c) • f (update m i x) := map_piecewise_smul f _ _ _, simpa [←function.update_smul c m] using this, end section distrib_mul_action variables {R' A : Type*} [monoid R'] [semiring A] [Π i, module A (M₁ i)] [distrib_mul_action R' M₂] [module A M₂] [smul_comm_class A R' M₂] instance : has_scalar R' (multilinear_map A M₁ M₂) := ⟨λ c f, ⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x c] ⟩⟩ @[simp] lemma smul_apply (f : multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl instance : distrib_mul_action R' (multilinear_map A M₁ M₂) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section module variables {R' A : Type*} [semiring R'] [semiring A] [Π i, module A (M₁ i)] [module A M₂] [add_comm_monoid M₃] [module R' M₃] [module A M₃] [smul_comm_class A R' M₃] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance [module R' M₂] [smul_comm_class A R' M₂] : module R' (multilinear_map A M₁ M₂) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variables (M₂ M₃ R' A) /-- `multilinear_map.dom_dom_congr` as a `linear_equiv`. -/ @[simps apply symm_apply] def dom_dom_congr_linear_equiv {ι₁ ι₂} [decidable_eq ι₁] [decidable_eq ι₂] (σ : ι₁ ≃ ι₂) : multilinear_map A (λ i : ι₁, M₂) M₃ ≃ₗ[R'] multilinear_map A (λ i : ι₂, M₂) M₃ := { map_smul' := λ c f, by { ext, simp }, .. (dom_dom_congr_equiv σ : multilinear_map A (λ i : ι₁, M₂) M₃ ≃+ multilinear_map A (λ i : ι₂, M₂) M₃) } end module section variables (R ι) (A : Type*) [comm_semiring A] [algebra R A] [fintype ι] /-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ι` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative algebra `A` but requires `ι = fin n`. -/ protected def mk_pi_algebra : multilinear_map R (λ i : ι, A) A := { to_fun := λ m, ∏ i, m i, map_add' := λ m i x y, by simp [finset.prod_update_of_mem, add_mul], map_smul' := λ m i c x, by simp [finset.prod_update_of_mem] } variables {R A ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i := rfl end section variables (R n) (A : Type*) [semiring A] [algebra R A] /-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works for `A^ι` with any finite type `ι`. -/ protected def mk_pi_algebra_fin : multilinear_map R (λ i : fin n, A) A := { to_fun := λ m, (list.of_fn m).prod, map_add' := begin intros m i x y, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, add_mul, this, mul_add, add_mul] end, map_smul' := begin intros m i c x, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, this] end } variables {R A n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod := rfl lemma mk_pi_algebra_fin_apply_const (a : A) : multilinear_map.mk_pi_algebra_fin R n A (λ _, a) = a ^ n := by simp end /-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map sending `m` to `f m • z`. -/ def smul_right (f : multilinear_map R M₁ R) (z : M₂) : multilinear_map R M₁ M₂ := (linear_map.smul_right linear_map.id z).comp_multilinear_map f @[simp] lemma smul_right_apply (f : multilinear_map R M₁ R) (z : M₂) (m : Π i, M₁ i) : f.smul_right z m = f m • z := rfl variables (R ι) /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module). See also `mk_pi_algebra` for a more general version. -/ protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ := (multilinear_map.mk_pi_algebra R ι R).smul_right z variables {R ι} @[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) : (multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = (∏ i, m i) • z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) : multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end end comm_semiring section range_add_comm_group variables [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] (f g : multilinear_map R M₁ M₂) instance : has_neg (multilinear_map R M₁ M₂) := ⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (multilinear_map R M₁ M₂) := ⟨λ f g, ⟨λ m, f m - g m, λ m i x y, by { simp only [map_add, sub_eq_add_neg, neg_add], cc }, λ m i c x, by { simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - g) m = f m - g m := rfl instance : add_comm_group (multilinear_map R M₁ M₂) := by refine { zero := (0 : multilinear_map R M₁ M₂), add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, gsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. multilinear_map.add_comm_monoid, .. }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] end range_add_comm_group section add_comm_group variables [semiring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] (f : multilinear_map R M₁ M₂) @[simp] lemma map_neg (m : Πi, M₁ i) (i : ι) (x : M₁ i) : f (update m i (-x)) = -f (update m i x) := eq_neg_of_add_eq_zero $ by rw [←map_add, add_left_neg, f.map_coord_zero i (update_same i 0 m)] @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := by rw [sub_eq_add_neg, sub_eq_add_neg, map_add, map_neg] end add_comm_group section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) := { to_fun := λ z, multilinear_map.mk_pi_ring R ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } end comm_semiring end multilinear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M M₂} [comm_semiring R] [∀i, add_comm_monoid (M i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, module R (M i)] [module R M'] [module R M₂] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : multilinear_map R M M₂ := { to_fun := λm, f (m 0) (tail m), map_add' := λm i x y, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] } end, map_smul' := λm i c x, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M M₂) : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) := { to_fun := λx, { to_fun := λm, f (cons x m), map_add' := λm i y y', by simp, map_smul' := λm i y c, by simp }, map_add' := λx y, by { ext m, exact cons_add f m x y }, map_smul' := λc x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M M₂) : f.curry_left.uncurry_left = f := by { ext m, simp, } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M M₂} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) : multilinear_map R M M₂ := { to_fun := λm, f (init m) (m (last n)), map_add' := λm i x y, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, map_smul' := λm i c x, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M M₂) : multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) := { to_fun := λm, { to_fun := λx, f (snoc m x), map_add' := λx y, by rw f.snoc_add, map_smul' := λc x, by simp only [f.snoc_smul, ring_hom.id_apply] }, map_add' := λm i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, map_smul' := λm i c x, begin ext z, change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } namespace multilinear_map variables {ι' : Type*} [decidable_eq ι'] [decidable_eq (ι ⊕ ι')] {R M₂} /-- A multilinear map on `Π i : ι ⊕ ι', M'` defines a multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := λ u, { to_fun := λ v, f (sum.elim u v), map_add' := λ v i x y, by simp only [← sum.update_elim_inr, f.map_add], map_smul' := λ v i c x, by simp only [← sum.update_elim_inr, f.map_smul] }, map_add' := λ u i x y, ext $ λ v, by simp only [multilinear_map.coe_mk, add_apply, ← sum.update_elim_inl, f.map_add], map_smul' := λ u i c x, ext $ λ v, by simp only [multilinear_map.coe_mk, smul_apply, ← sum.update_elim_inl, f.map_smul] } @[simp] lemma curry_sum_apply (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) (u : ι → M') (v : ι' → M') : f.curry_sum u v = f (sum.elim u v) := rfl /-- A multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'` defines a multilinear map on `Π i : ι ⊕ ι', M'`. -/ def uncurry_sum (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) : multilinear_map R (λ x : ι ⊕ ι', M') M₂ := { to_fun := λ u, f (u ∘ sum.inl) (u ∘ sum.inr), map_add' := λ u i x y, by cases i; simp only [map_add, add_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr], map_smul' := λ u i c x, by cases i; simp only [map_smul, smul_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr] } @[simp] lemma uncurry_sum_aux_apply (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) (u : ι ⊕ ι' → M') : f.uncurry_sum u = f (u ∘ sum.inl) (u ∘ sum.inr) := rfl variables (ι ι' R M₂ M') /-- Linear equivalence between the space of multilinear maps on `Π i : ι ⊕ ι', M'` and the space of multilinear maps on `Π i : ι, M'` taking values in the space of multilinear maps on `Π i : ι', M'`. -/ def curry_sum_equiv : multilinear_map R (λ x : ι ⊕ ι', M') M₂ ≃ₗ[R] multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) := { to_fun := curry_sum, inv_fun := uncurry_sum, left_inv := λ f, ext $ λ u, by simp, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl } } variables {ι ι' R M₂ M'} @[simp] lemma coe_curry_sum_equiv : ⇑(curry_sum_equiv R ι M₂ M' ι') = curry_sum := rfl @[simp] lemma coe_curr_sum_equiv_symm : ⇑(curry_sum_equiv R ι M₂ M' ι').symm = uncurry_sum := rfl variables (R M₂ M') /-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality `l`, then the space of multilinear maps on `λ i : fin n, M'` is isomorphic to the space of multilinear maps on `λ i : fin k, M'` taking values in the space of multilinear maps on `λ i : fin l, M'`. -/ def curry_fin_finset {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) : multilinear_map R (λ x : fin n, M') M₂ ≃ₗ[R] multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂) := (dom_dom_congr_linear_equiv M' M₂ R R (fin_sum_equiv_of_finset hk hl).symm).trans (curry_sum_equiv R (fin k) M₂ M' (fin l)) variables {R M₂ M'} @[simp] lemma curry_fin_finset_apply {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (mk : fin k → M') (ml : fin l → M') : curry_fin_finset R M₂ M' hk hl f mk ml = f (λ i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) := rfl @[simp] lemma curry_fin_finset_symm_apply {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (m : fin n → M') : (curry_fin_finset R M₂ M' hk hl).symm f m = f (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i)) (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) := rfl @[simp] lemma curry_fin_finset_symm_apply_piecewise_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x y : M') : (curry_fin_finset R M₂ M' hk hl).symm f (s.piecewise (λ _, x) (λ _, y)) = f (λ _, x) (λ _, y) := begin rw curry_fin_finset_symm_apply, congr, { ext i, rw [fin_sum_equiv_of_finset_inl, finset.piecewise_eq_of_mem], apply finset.order_emb_of_fin_mem }, { ext i, rw [fin_sum_equiv_of_finset_inr, finset.piecewise_eq_of_not_mem], exact finset.mem_compl.1 (finset.order_emb_of_fin_mem _ _ _) } end @[simp] lemma curry_fin_finset_symm_apply_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x : M') : (curry_fin_finset R M₂ M' hk hl).symm f (λ _, x) = f (λ _, x) (λ _, x) := rfl @[simp] lemma curry_fin_finset_apply_const {k l n : ℕ} {s : finset (fin n)} (hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (x y : M') : curry_fin_finset R M₂ M' hk hl f (λ _, x) (λ _, y) = f (s.piecewise (λ _, x) (λ _, y)) := begin refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails rw linear_equiv.symm_apply_apply end end multilinear_map end currying section submodule variables {R M M₂} [ring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M'] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M'] [module R M₂] namespace multilinear_map /-- The pushforward of an indexed collection of submodule `p i ⊆ M₁ i` by `f : M₁ → M₂`. Note that this is not a submodule - it is not closed under addition. -/ def map [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : sub_mul_action R M₂ := { carrier := f '' { v | ∀ i, v i ∈ p i}, smul_mem' := λ c _ ⟨x, hx, hf⟩, let ⟨i⟩ := ‹nonempty ι› in by { refine ⟨update x i (c • x i), λ j, if hij : j = i then _ else _, hf ▸ _⟩, { rw [hij, update_same], exact (p i).smul_mem _ (hx i) }, { rw [update_noteq hij], exact hx j }, { rw [f.map_smul, update_eq_self] } } } /-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/ lemma map_nonempty [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) : (map f p : set M₂).nonempty := ⟨f 0, 0, λ i, (p i).zero_mem, rfl⟩ /-- The range of a multilinear map, closed under scalar multiplication. -/ def range [nonempty ι] (f : multilinear_map R M₁ M₂) : sub_mul_action R M₂ := f.map (λ i, ⊤) end multilinear_map end submodule
9726c124ad175f03d0b676e841849dfc8df9585d
367134ba5a65885e863bdc4507601606690974c1
/test/examples.lean
840e18667b04ba734c97fc12aa8057840d2b454d
[ "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
2,149
lean
import tactic /-! ## Miscellaneous examples Please don't add further content to this file; it too easily becomes a grab bag of forgotten arcana. Tactics should have their own file in the `test/` directory. Examples verifying correct behaviour of simp sets or instances belong in `src/` near the definitions. TODO: remove or move the remaining content of this file. -/ open tactic universe u variable {α : Type u} example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true := begin dunfold has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true := begin delta has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, -- trace_state, rw [←h, ←h'] end example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, simp [h] at h', simp [*] end def my_id (x : α) := x def my_id_def (x : α) : my_id x = x := rfl example (x y z : ℕ) (h'' : true) (h : 0 + my_id y = x) (h' : 0 + y = z) : x = z + 0 := begin simp [my_id_def] at *, simp [h] at h', simp [*] end @[simp] theorem mem_set_of {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl meta example : true := begin success_if_fail { let := elim_gen_sum_aux }, trivial end import_private elim_gen_sum_aux meta example : true := begin let := elim_gen_sum_aux, trivial end /- tests of has_sep on finset -/ example {α} (s : finset α) (p : α → Prop) [decidable_pred p] : {x ∈ s | p x} = s.filter p := by simp example {α} (s : finset α) (p : α → Prop) [decidable_pred p] : {x ∈ s | p x} = @finset.filter α p (λ _, classical.prop_decidable _) s := by simp section open_locale classical example {α} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := by simp example (n m k : ℕ) : {x ∈ finset.range n | x < m ∨ x < k } = {x ∈ finset.range n | x < m } ∪ {x ∈ finset.range n | x < k } := by simp [finset.filter_or] end
661640f1404d7a4b95c936478d7231f3ed9899ef
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/excluded_middle.lean
71831fcc9e4bd5aa2546ff9df95744d3647013eb
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
4,351
lean
/- Alice is looking at Bob. Bob is looking at Charlie. Alice is married. Charlie is not. Theorem to Prove: Some (∃) married person is looking at some unmarried person (A) Yes (B) No (C) Cannot be determined (D) It depends -/ example : ∀ (P : Prop), P ∨ ¬P := begin assume P, apply or.inr _, intro p, _ end /- In constructive logic, ∀ (P : Prop), P ∨ ¬ P, is not provable. -/ axioms (Person : Type) (Married : Person → Prop) (LookingAt : Person → Person → Prop) (alice bob charlie : Person) (alab : LookingAt alice bob) (blac : LookingAt bob charlie) (am : Married alice) (ncm : ¬Married charlie) example : _ : _ /- forall p1 p2, Married p1 and not married p2 and looking at p1 p2 -/ example : ∀ (p1 p2 : Person), Married p1 → ¬ Married p2 → LookingAt p1 p2 := _ /- Every married person is looking at every unmarried person. This is not quite the right formalization. -/ /- Some married person, p1, is looking at some unmarried person, p2. This is the formalization that we want. Now the question is, can we prove it? -/ example : ∃ (p1 : Person), ∃ (p2 : Person), Married p1 ∧ ¬Married p2 ∧ LookingAt p1 p2 := begin apply exists.intro alice, apply exists.intro bob, split, apply am, split, end -- STUCK! example : ∃ (p1 : Person), ∃ (p2 : Person), Married p1 ∧ ¬Married p2 ∧ LookingAt p1 p2 := begin apply exists.intro bob, apply exists.intro charlie, split, end -- STUCK /- In constructive logic, we don't know that it's true that Bob is married or Bob is not married, whereas in classical reasoning that would always be true, even if we don't know which case holds. In constructive logic, for any proposition, P, there are three possibilities: (1) We have a proof of P (2) We have a proof of ¬P (3) We don't have a proof either way! This is the "MIDDLE!" In computer science and mathematics, there are plenty of examples where we don't know which case holds. - polynomial time (P) = non-deterministic polynomial time (NP)? TSP, Boolean SAT - Collatz conjecture -- hailstone program terminates on all inputs -/ /- meta def HS (n : nat) := if (n = 1 ∨ n = 0) return 0 else (if n%2 = 0) (HS n/2) else (if n%2 = 1) (HS n*3+1) Does this function terminate for all inputs n? 5 -> 8 -> 4 -> 2 -> 1 . 7 -> 22 -> 11 -> 34 -> 17 -> 51 -> 154 -> 77 -> ... -/ /- One might believe that constructive logic is weaker than classical logic in the sense that there are propositions that are provable in the latter but not in the former. On the other hand, we can always reason classically in constructive logic by simply introducing the "law of the excluded middle" as an axiom. What it says is that for any proposition, P, whatsoever, P ∨ ¬P is true in the sense that we can assume that we have a proof of it. The trick is then to do case analysis on such a *proof object*. -/ axiom em : ∀ (P : Prop), P ∨ ¬ P example : ∃ (p1 : Person), ∃ (p2 : Person), Married p1 ∧ ¬Married p2 ∧ LookingAt p1 p2 := begin cases (/-proof of (bim or bnm)-/ em (Married bob)), --!!! -- Married bob apply exists.intro bob, apply exists.intro charlie, split, assumption, split, exact ncm, exact blac, apply exists.intro alice, apply exists.intro bob, split, exact am, split, assumption, exact alab, end -- Yay /- The axiom of the excluded middle is defined in the Lean library. You can always apply it, but in general you will want to think about the tradeoffs that are involved. Among the losses are (1) you will no longer have any *evidence* for which case is true, (2) you will be unable to extract runnable code from a proof of a disjunction, because such a proof is just made from thin air: it contains no proof/evidence either way but only says that one of them must be true. -/ #check classical.em theorem neg_elim : ∀ (P : Prop), ¬¬P → P := begin assume P h, /- (¬ P -> false) ((P → false) → false) P? -/ have ponp := classical.em P, cases ponp, assumption, contradiction, end /- DeMorgan's laws ¬ (P ∧ Q) ↔ (¬P ∨ ¬Q) ¬ (P ∨ Q) ↔ (¬P ∧ ¬Q) -/ theorem dm1 : ∀ (P Q : Prop), ¬(P ∧ Q) ↔ (¬P ∨ ¬Q) := begin intros, split, -- forward assume h, -- have: P ∧ Q → false end theorem dm2 : ∀ (P Q : Prop), ¬ (P ∨ Q) ↔ (¬P ∧ ¬Q) := begin end
d3a662c0a43680edf6e6795d602657d95a9db937
9dc8cecdf3c4634764a18254e94d43da07142918
/src/geometry/manifold/cont_mdiff_map.lean
3f168262d5c0ce799fbd95f0562729fe15158892
[ "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,846
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.cont_mdiff import topology.continuous_function.basic /-! # Smooth bundled map In this file we define the type `cont_mdiff_map` of `n` times continuously differentiable bundled maps. -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H : Type*} [topological_space H] {H' : Type*} [topological_space H'] (I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H') (M : Type*) [topological_space M] [charted_space H M] (M' : Type*) [topological_space M'] [charted_space H' M'] {E'' : Type*} [normed_add_comm_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''] (n : ℕ∞) /-- Bundled `n` times continuously differentiable maps. -/ @[protect_proj] structure cont_mdiff_map := (to_fun : M → M') (cont_mdiff_to_fun : cont_mdiff I I' n to_fun) /-- Bundled smooth maps. -/ @[reducible] def smooth_map := cont_mdiff_map I I' M M' ⊤ localized "notation (name := cont_mdiff_map) `C^` n `⟮` I `, ` M `; ` I' `, ` M' `⟯` := cont_mdiff_map I I' M M' n" in manifold localized "notation (name := cont_mdiff_map.self) `C^` n `⟮` I `, ` M `; ` k `⟯` := cont_mdiff_map I (model_with_corners_self k k) M k n" in manifold open_locale manifold namespace cont_mdiff_map variables {I} {I'} {M} {M'} {n} instance : has_coe_to_fun C^n⟮I, M; I', M'⟯ (λ _, M → M') := ⟨cont_mdiff_map.to_fun⟩ instance : has_coe C^n⟮I, M; I', M'⟯ C(M, M') := ⟨λ f, ⟨f, f.cont_mdiff_to_fun.continuous⟩⟩ attribute [to_additive_ignore_args 21] cont_mdiff_map cont_mdiff_map.has_coe_to_fun cont_mdiff_map.continuous_map.has_coe variables {f g : C^n⟮I, M; I', M'⟯} @[simp] lemma coe_fn_mk (f : M → M') (hf : cont_mdiff I I' n f) : (mk f hf : M → M') = f := rfl protected lemma cont_mdiff (f : C^n⟮I, M; I', M'⟯) : cont_mdiff I I' n f := f.cont_mdiff_to_fun protected lemma smooth (f : C^∞⟮I, M; I', M'⟯) : smooth I I' f := f.cont_mdiff_to_fun protected lemma mdifferentiable' (f : C^n⟮I, M; I', M'⟯) (hn : 1 ≤ n) : mdifferentiable I I' f := f.cont_mdiff.mdifferentiable hn protected lemma mdifferentiable (f : C^∞⟮I, M; I', M'⟯) : mdifferentiable I I' f := f.cont_mdiff.mdifferentiable le_top protected lemma mdifferentiable_at (f : C^∞⟮I, M; I', M'⟯) {x} : mdifferentiable_at I I' f x := f.mdifferentiable x lemma coe_inj ⦃f g : C^n⟮I, M; I', M'⟯⦄ (h : (f : M → M') = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext h /-- The identity as a smooth map. -/ def id : C^n⟮I, M; I, M⟯ := ⟨id, cont_mdiff_id⟩ /-- The composition of smooth maps, as a smooth map. -/ def comp (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) : C^n⟮I, M; I'', M''⟯ := { to_fun := λ a, f (g a), cont_mdiff_to_fun := f.cont_mdiff_to_fun.comp g.cont_mdiff_to_fun, } @[simp] lemma comp_apply (f : C^n⟮I', M'; I'', M''⟯) (g : C^n⟮I, M; I', M'⟯) (x : M) : f.comp g x = f (g x) := rfl instance [inhabited M'] : inhabited C^n⟮I, M; I', M'⟯ := ⟨⟨λ _, default, cont_mdiff_const⟩⟩ /-- Constant map as a smooth map -/ def const (y : M') : C^n⟮I, M; I', M'⟯ := ⟨λ x, y, cont_mdiff_const⟩ end cont_mdiff_map instance continuous_linear_map.has_coe_to_cont_mdiff_map : has_coe (E →L[𝕜] E') C^n⟮𝓘(𝕜, E), E; 𝓘(𝕜, E'), E'⟯ := ⟨λ f, ⟨f.to_fun, f.cont_mdiff⟩⟩
ea3921db629f98f86771e57a2a2f5b4c3458ebde
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/adjunctions/hom_adjunction.lean
c755359289311c44e5f9f0651bdb6871d96e0bf4
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
1,366
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.products import category_theory.opposites import category_theory.isomorphism import category_theory.tactics.obviously open category_theory namespace category_theory.adjunctions universes u₁ v₁ -- TODO should we allow different universe levels, at the expense of some lifts? variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₁} [𝒟 : category.{u₁ v₁} D] include 𝒞 𝒟 def hom_adjunction (L : C ⥤ D) (R : D ⥤ C) := ((functor.prod L.op (functor.id D)) ⋙ (functor.hom D)) ≅ (functor.prod (functor.id (Cᵒᵖ)) R) ⋙ (functor.hom C) def mate {L : C ⥤ D} {R : D ⥤ C} (A : hom_adjunction L R) {X : C} {Y : D} (f : (L X) ⟶ Y) : X ⟶ (R Y) := ((A.hom) (X, Y)) f -- PROJECT lemmas about mates. -- PROJECT -- to do this, we need to first define whiskering of NaturalIsomorphisms -- See Remark 2.1.11 of Leinster -- def composition_of_HomAdjunctions -- {C D E : Category} {L : Functor C D} {L' : Functor D E} {R : Functor D C} {R' : Functor E D} -- (A : HomAdjunction L R) (B : HomAdjunction L' R') -- : HomAdjunction (FunctorComposition L L') (FunctorComposition R' R) := sorry end category_theory.adjunctions
ac9de7043e8126bbd8630c88c5e3f05e7131b8f5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/uniform_space/complete_separated_auto.lean
cafb0e894c524bf28d33ad1a719629a80e4d93f6
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,234
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.cauchy import Mathlib.topology.uniform_space.separation import Mathlib.topology.dense_embedding import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Theory of complete separated uniform spaces. This file is for elementary lemmas that depend on both Cauchy filters and separation. -/ /-In a separated space, a complete set is closed -/ theorem is_complete.is_closed {α : Type u_1} [uniform_space α] [separated_space α] {s : set α} (h : is_complete s) : is_closed s := sorry namespace dense_inducing theorem continuous_extend_of_cauchy {α : Type u_1} [topological_space α] {β : Type u_2} [topological_space β] {γ : Type u_3} [uniform_space γ] [complete_space γ] [separated_space γ] {e : α → β} {f : α → γ} (de : dense_inducing e) (h : ∀ (b : β), cauchy (filter.map f (filter.comap e (nhds b)))) : continuous (extend de f) := continuous_extend de fun (b : β) => complete_space.complete (h b) end Mathlib