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
beb3008e33a7c6999440b3760b542b0a6976d3b1
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/init/path.hlean
408db14e64f1c3cf62ca7d4964aa9236582150ba
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
30,545
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .function .tactic open function eq /- Path equality -/ namespace eq variables {A B C : Type} {P : A → Type} {a a' x y z t : A} {b b' : B} --notation a = b := eq a b notation x = y `:>`:50 A:49 := @eq A x y definition idp [reducible] [constructor] {a : A} := refl a definition idpath [reducible] [constructor] (a : A) := refl a -- unbased path induction definition rec_unbased [reducible] [unfold 6] {P : Π (a b : A), (a = b) → Type} (H : Π (a : A), P a a idp) {a b : A} (p : a = b) : P a b p := eq.rec (H a) p definition rec_on_unbased [reducible] [unfold 5] {P : Π (a b : A), (a = b) → Type} {a b : A} (p : a = b) (H : Π (a : A), P a a idp) : P a b p := eq.rec (H a) p /- Concatenation and inverse -/ definition concat [trans] [unfold 6] (p : x = y) (q : y = z) : x = z := by induction q; exact p definition inverse [symm] [unfold 4] (p : x = y) : y = x := by induction p; reflexivity infix ⬝ := concat postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing_only] `⁻¹ᵖ`:std.prec.max_plus := inverse /- The 1-dimensional groupoid structure -/ -- The identity path is a right unit. definition con_idp [unfold_full] (p : x = y) : p ⬝ idp = p := idp -- The identity path is a left unit. definition idp_con [unfold 4] (p : x = y) : idp ⬝ p = p := by induction p; reflexivity -- Concatenation is associative. definition con.assoc' [unfold 8] (p : x = y) (q : y = z) (r : z = t) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := by induction r; reflexivity definition con.assoc [unfold 8] (p : x = y) (q : y = z) (r : z = t) : (p ⬝ q) ⬝ r = p ⬝ (q ⬝ r) := by induction r; reflexivity definition con.assoc5 {a₁ a₂ a₃ a₄ a₅ a₆ : A} (p₁ : a₁ = a₂) (p₂ : a₂ = a₃) (p₃ : a₃ = a₄) (p₄ : a₄ = a₅) (p₅ : a₅ = a₆) : p₁ ⬝ (p₂ ⬝ p₃ ⬝ p₄) ⬝ p₅ = (p₁ ⬝ p₂) ⬝ p₃ ⬝ (p₄ ⬝ p₅) := by induction p₅; induction p₄; induction p₃; reflexivity -- The left inverse law. definition con.right_inv [unfold 4] (p : x = y) : p ⬝ p⁻¹ = idp := by induction p; reflexivity -- The right inverse law. definition con.left_inv [unfold 4] (p : x = y) : p⁻¹ ⬝ p = idp := by induction p; reflexivity /- Several auxiliary theorems about canceling inverses across associativity. These are somewhat redundant, following from earlier theorems. -/ definition inv_con_cancel_left (p : x = y) (q : y = z) : p⁻¹ ⬝ (p ⬝ q) = q := by induction q; induction p; reflexivity definition con_inv_cancel_left (p : x = y) (q : x = z) : p ⬝ (p⁻¹ ⬝ q) = q := by induction q; induction p; reflexivity definition con_inv_cancel_right (p : x = y) (q : y = z) : (p ⬝ q) ⬝ q⁻¹ = p := by induction q; reflexivity definition inv_con_cancel_right (p : x = z) (q : y = z) : (p ⬝ q⁻¹) ⬝ q = p := by induction q; reflexivity -- Inverse distributes over concatenation definition con_inv (p : x = y) (q : y = z) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ := by induction q; induction p; reflexivity definition inv_con_inv_left (p : y = x) (q : y = z) : (p⁻¹ ⬝ q)⁻¹ = q⁻¹ ⬝ p := by induction q; induction p; reflexivity definition inv_con_inv_right (p : x = y) (q : z = y) : (p ⬝ q⁻¹)⁻¹ = q ⬝ p⁻¹ := by induction q; induction p; reflexivity definition inv_con_inv_inv (p : y = x) (q : z = y) : (p⁻¹ ⬝ q⁻¹)⁻¹ = q ⬝ p := by induction q; induction p; reflexivity -- Inverse is an involution. definition inv_inv [unfold 4] (p : x = y) : p⁻¹⁻¹ = p := by induction p; reflexivity -- auxiliary definition used by 'cases' tactic definition elim_inv_inv [unfold 5] {A : Type} {a b : A} {C : a = b → Type} (H₁ : a = b) (H₂ : C (H₁⁻¹⁻¹)) : C H₁ := eq.rec_on (inv_inv H₁) H₂ /- Theorems for moving things around in equations -/ definition con_eq_of_eq_inv_con {p : x = z} {q : y = z} {r : y = x} : p = r⁻¹ ⬝ q → r ⬝ p = q := begin induction r, intro h, exact !idp_con ⬝ h ⬝ !idp_con end definition con_eq_of_eq_con_inv [unfold 5] {p : x = z} {q : y = z} {r : y = x} : r = q ⬝ p⁻¹ → r ⬝ p = q := by induction p; exact id definition inv_con_eq_of_eq_con {p : x = z} {q : y = z} {r : x = y} : p = r ⬝ q → r⁻¹ ⬝ p = q := by induction r; intro h; exact !idp_con ⬝ h ⬝ !idp_con definition con_inv_eq_of_eq_con [unfold 5] {p : z = x} {q : y = z} {r : y = x} : r = q ⬝ p → r ⬝ p⁻¹ = q := by induction p; exact id definition eq_con_of_inv_con_eq {p : x = z} {q : y = z} {r : y = x} : r⁻¹ ⬝ q = p → q = r ⬝ p := by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹ definition eq_con_of_con_inv_eq [unfold 5] {p : x = z} {q : y = z} {r : y = x} : q ⬝ p⁻¹ = r → q = r ⬝ p := by induction p; exact id definition eq_inv_con_of_con_eq {p : x = z} {q : y = z} {r : x = y} : r ⬝ q = p → q = r⁻¹ ⬝ p := by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹ definition eq_con_inv_of_con_eq [unfold 5] {p : z = x} {q : y = z} {r : y = x} : q ⬝ p = r → q = r ⬝ p⁻¹ := by induction p; exact id definition eq_of_con_inv_eq_idp [unfold 5] {p q : x = y} : p ⬝ q⁻¹ = idp → p = q := by induction q; exact id definition eq_of_inv_con_eq_idp {p q : x = y} : q⁻¹ ⬝ p = idp → p = q := by induction q; intro h; exact !idp_con⁻¹ ⬝ h definition eq_inv_of_con_eq_idp' [unfold 5] {p : x = y} {q : y = x} : p ⬝ q = idp → p = q⁻¹ := by induction q; exact id definition eq_inv_of_con_eq_idp {p : x = y} {q : y = x} : q ⬝ p = idp → p = q⁻¹ := by induction q; intro h; exact !idp_con⁻¹ ⬝ h definition eq_of_idp_eq_inv_con {p q : x = y} : idp = p⁻¹ ⬝ q → p = q := by induction p; intro h; exact h ⬝ !idp_con definition eq_of_idp_eq_con_inv [unfold 4] {p q : x = y} : idp = q ⬝ p⁻¹ → p = q := by induction p; exact id definition inv_eq_of_idp_eq_con [unfold 4] {p : x = y} {q : y = x} : idp = q ⬝ p → p⁻¹ = q := by induction p; exact id definition inv_eq_of_idp_eq_con' {p : x = y} {q : y = x} : idp = p ⬝ q → p⁻¹ = q := by induction p; intro h; exact h ⬝ !idp_con definition con_inv_eq_idp [unfold 6] {p q : x = y} (r : p = q) : p ⬝ q⁻¹ = idp := by cases r; apply con.right_inv definition inv_con_eq_idp [unfold 6] {p q : x = y} (r : p = q) : q⁻¹ ⬝ p = idp := by cases r; apply con.left_inv definition con_eq_idp {p : x = y} {q : y = x} (r : p = q⁻¹) : p ⬝ q = idp := by cases q; exact r definition idp_eq_inv_con {p q : x = y} (r : p = q) : idp = p⁻¹ ⬝ q := by cases r; exact !con.left_inv⁻¹ definition idp_eq_con_inv {p q : x = y} (r : p = q) : idp = q ⬝ p⁻¹ := by cases r; exact !con.right_inv⁻¹ definition idp_eq_con {p : x = y} {q : y = x} (r : p⁻¹ = q) : idp = q ⬝ p := by cases p; exact r definition eq_idp_of_con_right {p : x = x} {q : x = y} (r : p ⬝ q = q) : p = idp := by cases q; exact r definition eq_idp_of_con_left {p : x = x} {q : y = x} (r : q ⬝ p = q) : p = idp := by cases q; exact (idp_con p)⁻¹ ⬝ r definition idp_eq_of_con_right {p : x = x} {q : x = y} (r : q = p ⬝ q) : idp = p := by cases q; exact r definition idp_eq_of_con_left {p : x = x} {q : y = x} (r : q = q ⬝ p) : idp = p := by cases q; exact r ⬝ idp_con p /- Transport -/ definition transport [subst] [reducible] [unfold 5] (P : A → Type) {x y : A} (p : x = y) (u : P x) : P y := by induction p; exact u -- This idiom makes the operation right associative. infixr ` ▸ ` := transport _ definition cast [reducible] [unfold 3] {A B : Type} (p : A = B) (a : A) : B := p ▸ a definition cast_def [reducible] [unfold_full] {A B : Type} (p : A = B) (a : A) : cast p a = p ▸ a := idp definition tr_rev [reducible] [unfold 6] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition ap [unfold 6] ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x = y) : f x = f y := by induction p; reflexivity abbreviation ap01 [parsing_only] := ap definition homotopy [reducible] (f g : Πx, P x) : Type := Πx : A, f x = g x infix ~ := homotopy protected definition homotopy.refl [refl] [reducible] [unfold_full] (f : Πx, P x) : f ~ f := λ x, idp protected definition homotopy.symm [symm] [reducible] [unfold_full] {f g : Πx, P x} (H : f ~ g) : g ~ f := λ x, (H x)⁻¹ protected definition homotopy.trans [trans] [reducible] [unfold_full] {f g h : Πx, P x} (H1 : f ~ g) (H2 : g ~ h) : f ~ h := λ x, H1 x ⬝ H2 x definition hwhisker_left [unfold_full] (g : B → C) {f f' : A → B} (H : f ~ f') : g ∘ f ~ g ∘ f' := λa, ap g (H a) definition hwhisker_right [unfold_full] (f : A → B) {g g' : B → C} (H : g ~ g') : g ∘ f ~ g' ∘ f := λa, H (f a) definition homotopy_of_eq {f g : Πx, P x} (H1 : f = g) : f ~ g := H1 ▸ homotopy.refl f definition apd10 [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g := λx, by induction H; reflexivity --the next theorem is useful if you want to write "apply (apd10' a)" definition apd10' [unfold 6] {f g : Πx, P x} (a : A) (H : f = g) : f a = g a := by induction H; reflexivity --apd10 is also ap evaluation definition apd10_eq_ap_eval {f g : Πx, P x} (H : f = g) (a : A) : apd10 H a = ap (λs : Πx, P x, s a) H := by induction H; reflexivity definition ap10 [reducible] [unfold 5] {f g : A → B} (H : f = g) : f ~ g := apd10 H definition ap11 {f g : A → B} (H : f = g) {x y : A} (p : x = y) : f x = g y := by induction H; exact ap f p -- [apd] is defined in init.pathover using pathover instead of an equality with transport. definition apdt [unfold 6] (f : Πa, P a) {x y : A} (p : x = y) : p ▸ f x = f y := by induction p; reflexivity definition ap011 [unfold 9] (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := by cases Ha; exact ap (f a) Hb definition ap_eq_ap011_left (f : A → B → C) (Ha : a = a') (b : B) : ap (λa, f a b) Ha = ap011 f Ha idp := by induction Ha; reflexivity definition ap_eq_ap011_right (f : A → B → C) (a : A) (Hb : b = b') : ap (f a) Hb = ap011 f idp Hb := by reflexivity /- More theorems for moving things around in equations -/ definition tr_eq_of_eq_inv_tr {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : u = p⁻¹ ▸ v → p ▸ u = v := by induction p; exact id definition inv_tr_eq_of_eq_tr {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : u = p ▸ v → p⁻¹ ▸ u = v := by induction p; exact id definition eq_inv_tr_of_tr_eq {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : p ▸ u = v → u = p⁻¹ ▸ v := by induction p; exact id definition eq_tr_of_inv_tr_eq {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : p⁻¹ ▸ u = v → u = p ▸ v := by induction p; exact id /- Transporting along the diagonal of a type family -/ definition tr_diag_eq_tr_tr {A : Type} (P : A → A → Type) {x y : A} (p : x = y) (a : P x x) : transport (λ x, P x x) p a = transport (λ x, P _ x) p (transport (λ x, P x _) p a) := by induction p; reflexivity /- Functoriality of functions -/ -- Here we prove that functions behave like functors between groupoids, and that [ap] itself is -- functorial. -- Functions take identity paths to identity paths definition ap_idp [unfold_full] (x : A) (f : A → B) : ap f idp = idp :> (f x = f x) := idp -- Functions commute with concatenation. definition ap_con [unfold 8] (f : A → B) {x y z : A} (p : x = y) (q : y = z) : ap f (p ⬝ q) = ap f p ⬝ ap f q := by induction q; reflexivity definition con_ap_con_eq_con_ap_con_ap (f : A → B) {w x y z : A} (r : f w = f x) (p : x = y) (q : y = z) : r ⬝ ap f (p ⬝ q) = (r ⬝ ap f p) ⬝ ap f q := by induction q; induction p; reflexivity definition ap_con_con_eq_ap_con_ap_con (f : A → B) {w x y z : A} (p : x = y) (q : y = z) (r : f z = f w) : ap f (p ⬝ q) ⬝ r = ap f p ⬝ (ap f q ⬝ r) := by induction q; induction p; apply con.assoc -- Functions commute with path inverses. definition ap_inv' [unfold 6] (f : A → B) {x y : A} (p : x = y) : (ap f p)⁻¹ = ap f p⁻¹ := by induction p; reflexivity definition ap_inv [unfold 6] (f : A → B) {x y : A} (p : x = y) : ap f p⁻¹ = (ap f p)⁻¹ := by induction p; reflexivity -- [ap] itself is functorial in the first argument. definition ap_id [unfold 4] (p : x = y) : ap id p = p := by induction p; reflexivity definition ap_compose [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (g ∘ f) p = ap g (ap f p) := by induction p; reflexivity -- Sometimes we don't have the actual function [compose]. definition ap_compose' [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (λa, g (f a)) p = ap g (ap f p) := by induction p; reflexivity -- The action of constant maps. definition ap_constant [unfold 5] (p : x = y) (z : B) : ap (λu, z) p = idp := by induction p; reflexivity -- Naturality of [ap]. -- see also natural_square in cubical.square definition ap_con_eq_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ ap g q := by induction q; apply idp_con -- Naturality of [ap] at identity. definition ap_con_eq_con {f : A → A} (p : Πx, f x = x) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ q := by induction q; apply idp_con definition con_ap_eq_con {f : A → A} (p : Πx, x = f x) {x y : A} (q : x = y) : p x ⬝ ap f q = q ⬝ p y := by induction q; exact !idp_con⁻¹ -- Naturality of [ap] with constant function definition ap_con_eq {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q ⬝ p y = p x := by induction q; apply idp_con -- Naturality with other paths hanging around. definition con_ap_con_con_eq_con_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w z : B} (r : w = f x) (s : g y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (ap g q ⬝ s) := by induction s; induction q; reflexivity definition con_ap_con_eq_con_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w : B} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ ap g q := by induction q; reflexivity -- TODO: try this using the simplifier, and compare proofs definition ap_con_con_eq_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {z : B} (s : g y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (ap g q ⬝ s) := begin induction s, induction q, apply idp_con end definition con_ap_con_con_eq_con_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w z : A} (r : w = f x) (s : y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (q ⬝ s) := by induction s; induction q; reflexivity definition con_con_ap_con_eq_con_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w z : A} (r : w = x) (s : g y = z) : (r ⬝ p x) ⬝ (ap g q ⬝ s) = (r ⬝ q) ⬝ (p y ⬝ s) := by induction s; induction q; reflexivity definition con_ap_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w : A} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ q := by induction q; reflexivity definition ap_con_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {z : A} (s : y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (q ⬝ s) := by induction s; induction q; apply idp_con definition con_con_ap_eq_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w : A} (r : w = x) : (r ⬝ p x) ⬝ ap g q = (r ⬝ q) ⬝ p y := begin cases q, exact idp end definition con_ap_con_eq_con_con' {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {z : A} (s : g y = z) : p x ⬝ (ap g q ⬝ s) = q ⬝ (p y ⬝ s) := by induction s; induction q; exact !idp_con⁻¹ /- Action of [apd10] and [ap10] on paths -/ -- Application of paths between functions preserves the groupoid structure definition apd10_idp (f : Πx, P x) (x : A) : apd10 (refl f) x = idp := idp definition apd10_con {f f' f'' : Πx, P x} (h : f = f') (h' : f' = f'') (x : A) : apd10 (h ⬝ h') x = apd10 h x ⬝ apd10 h' x := by induction h; induction h'; reflexivity definition apd10_inv {f g : Πx : A, P x} (h : f = g) (x : A) : apd10 h⁻¹ x = (apd10 h x)⁻¹ := by induction h; reflexivity definition ap10_idp {f : A → B} (x : A) : ap10 (refl f) x = idp := idp definition ap10_con {f f' f'' : A → B} (h : f = f') (h' : f' = f'') (x : A) : ap10 (h ⬝ h') x = ap10 h x ⬝ ap10 h' x := apd10_con h h' x definition ap10_inv {f g : A → B} (h : f = g) (x : A) : ap10 h⁻¹ x = (ap10 h x)⁻¹ := apd10_inv h x -- [ap10] also behaves nicely on paths produced by [ap] definition ap_ap10 (f g : A → B) (h : B → C) (p : f = g) (a : A) : ap h (ap10 p a) = ap10 (ap (λ f', h ∘ f') p) a:= by induction p; reflexivity /- Transport and the groupoid structure of paths -/ definition idp_tr {P : A → Type} {x : A} (u : P x) : idp ▸ u = u := idp definition con_tr [unfold 7] {P : A → Type} {x y z : A} (p : x = y) (q : y = z) (u : P x) : p ⬝ q ▸ u = q ▸ p ▸ u := by induction q; reflexivity definition tr_inv_tr {P : A → Type} {x y : A} (p : x = y) (z : P y) : p ▸ p⁻¹ ▸ z = z := (con_tr p⁻¹ p z)⁻¹ ⬝ ap (λr, transport P r z) (con.left_inv p) definition inv_tr_tr {P : A → Type} {x y : A} (p : x = y) (z : P x) : p⁻¹ ▸ p ▸ z = z := (con_tr p p⁻¹ z)⁻¹ ⬝ ap (λr, transport P r z) (con.right_inv p) definition cast_cast_inv {A : Type} {P : A → Type} {x y : A} (p : x = y) (z : P y) : cast (ap P p) (cast (ap P p⁻¹) z) = z := by induction p; reflexivity definition cast_inv_cast {A : Type} {P : A → Type} {x y : A} (p : x = y) (z : P x) : cast (ap P p⁻¹) (cast (ap P p) z) = z := by induction p; reflexivity definition fn_tr_eq_tr_fn {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (p ▸ z) = p ▸ f x z := by induction p; reflexivity definition fn_cast_eq_cast_fn {A : Type} {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (cast (ap P p) z) = cast (ap Q p) (f x z) := by induction p; reflexivity definition con_con_tr {P : A → Type} {x y z w : A} (p : x = y) (q : y = z) (r : z = w) (u : P x) : ap (λe, e ▸ u) (con.assoc' p q r) ⬝ (con_tr (p ⬝ q) r u) ⬝ ap (transport P r) (con_tr p q u) = (con_tr p (q ⬝ r) u) ⬝ (con_tr q r (p ▸ u)) :> ((p ⬝ (q ⬝ r)) ▸ u = r ▸ q ▸ p ▸ u) := by induction r; induction q; induction p; reflexivity -- Here is another coherence lemma for transport. definition tr_inv_tr_lemma {P : A → Type} {x y : A} (p : x = y) (z : P x) : tr_inv_tr p (transport P p z) = ap (transport P p) (inv_tr_tr p z) := by induction p; reflexivity /- some properties for apdt -/ definition apdt_idp (x : A) (f : Πx, P x) : apdt f idp = idp :> (f x = f x) := idp definition apdt_con (f : Πx, P x) {x y z : A} (p : x = y) (q : y = z) : apdt f (p ⬝ q) = con_tr p q (f x) ⬝ ap (transport P q) (apdt f p) ⬝ apdt f q := by cases p; cases q; apply idp definition apdt_inv (f : Πx, P x) {x y : A} (p : x = y) : apdt f p⁻¹ = (eq_inv_tr_of_tr_eq (apdt f p))⁻¹ := by cases p; apply idp -- Dependent transport in a doubly dependent type. -- This is a special case of transporto in init.pathover definition transportD [unfold 6] {P : A → Type} (Q : Πa, P a → Type) {a a' : A} (p : a = a') (b : P a) (z : Q a b) : Q a' (p ▸ b) := by induction p; exact z -- In Coq the variables P, Q and b are explicit, but in Lean we can probably have them implicit -- using the following notation notation p ` ▸D `:65 x:64 := transportD _ p _ x -- transporting over 2 one-dimensional paths -- This is a special case of transporto in init.pathover definition transport11 {A B : Type} (P : A → B → Type) {a a' : A} {b b' : B} (p : a = a') (q : b = b') (z : P a b) : P a' b' := transport (P a') q (p ▸ z) -- Transporting along higher-dimensional paths definition transport2 [unfold 7] (P : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : P x) : p ▸ z = q ▸ z := ap (λp', p' ▸ z) r notation p ` ▸2 `:65 x:64 := transport2 _ p _ x -- An alternative definition. definition tr2_eq_ap10 (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r z = ap10 (ap (transport Q) r) z := by induction r; reflexivity definition tr2_con {P : A → Type} {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) (z : P x) : transport2 P (r1 ⬝ r2) z = transport2 P r1 z ⬝ transport2 P r2 z := by induction r1; induction r2; reflexivity definition tr2_inv (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r⁻¹ z = (transport2 Q r z)⁻¹ := by induction r; reflexivity definition transportD2 [unfold 7] {B C : A → Type} (D : Π(a:A), B a → C a → Type) {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z) : D x2 (p ▸ y) (p ▸ z) := by induction p; exact w notation p ` ▸D2 `:65 x:64 := transportD2 _ p _ _ x definition ap_tr_con_tr2 (P : A → Type) {x y : A} {p q : x = y} {z w : P x} (r : p = q) (s : z = w) : ap (transport P p) s ⬝ transport2 P r w = transport2 P r z ⬝ ap (transport P q) s := by induction r; exact !idp_con⁻¹ /- Transporting in particular fibrations -/ /- From the Coq HoTT library: One frequently needs lemmas showing that transport in a certain dependent type is equal to some more explicitly defined operation, defined according to the structure of that dependent type. For most dependent types, we prove these lemmas in the appropriate file in the types/ subdirectory. Here we consider only the most basic cases. -/ -- Transporting in a constant fibration. definition tr_constant (p : x = y) (z : B) : transport (λx, B) p z = z := by induction p; reflexivity definition tr2_constant {p q : x = y} (r : p = q) (z : B) : tr_constant p z = transport2 (λu, B) r z ⬝ tr_constant q z := by induction r; exact !idp_con⁻¹ -- Transporting in a pulled back fibration. definition tr_compose (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport (P ∘ f) p z = transport P (ap f p) z := by induction p; reflexivity definition tr_ap (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport P (ap f p) z = transport (P ∘ f) p z := (tr_compose P f p z)⁻¹ definition ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : ap (λh, h ∘ f) p = transport (λh : B → C, g ∘ f = h ∘ f) p idp := by induction p; reflexivity definition apd10_ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : apd10 (ap (λh : B → C, h ∘ f) p) = λa, apd10 p (f a) := by induction p; reflexivity definition apd10_ap_precompose_dependent {C : B → Type} (f : A → B) {g g' : Πb : B, C b} (p : g = g') : apd10 (ap (λ(h : (Πb : B, C b))(a : A), h (f a)) p) = λa, apd10 p (f a) := by induction p; reflexivity definition apd10_ap_postcompose (f : B → C) (g g' : A → B) (p : g = g') : apd10 (ap (λh : A → B, f ∘ h) p) = λa, ap f (apd10 p a) := by induction p; reflexivity -- A special case of [tr_compose] which seems to come up a lot. definition tr_eq_cast_ap {P : A → Type} {x y} (p : x = y) (u : P x) : p ▸ u = cast (ap P p) u := by induction p; reflexivity definition tr_eq_cast_ap_fn {P : A → Type} {x y} (p : x = y) : transport P p = cast (ap P p) := by induction p; reflexivity /- The behavior of [ap] and [apdt] -/ -- In a constant fibration, [apdt] reduces to [ap], modulo [transport_const]. definition apdt_eq_tr_constant_con_ap (f : A → B) (p : x = y) : apdt f p = tr_constant p (f x) ⬝ ap f p := by induction p; reflexivity /- The 2-dimensional groupoid structure -/ -- Horizontal composition of 2-dimensional paths. definition concat2 [unfold 9 10] {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q') : p ⬝ q = p' ⬝ q' := ap011 concat h h' -- 2-dimensional path inversion definition inverse2 [unfold 6] {p q : x = y} (h : p = q) : p⁻¹ = q⁻¹ := ap inverse h infixl ` ◾ `:80 := concat2 postfix [parsing_only] `⁻²`:(max+10) := inverse2 --this notation is abusive, should we use it? /- Whiskering -/ definition whisker_left [unfold 8] (p : x = y) {q r : y = z} (h : q = r) : p ⬝ q = p ⬝ r := idp ◾ h definition whisker_right [unfold 8] {p q : x = y} (r : y = z) (h : p = q) : p ⬝ r = q ⬝ r := h ◾ idp -- Unwhiskering, a.k.a. cancelling definition cancel_left {x y z : A} (p : x = y) {q r : y = z} : (p ⬝ q = p ⬝ r) → (q = r) := λs, !inv_con_cancel_left⁻¹ ⬝ whisker_left p⁻¹ s ⬝ !inv_con_cancel_left definition cancel_right {x y z : A} {p q : x = y} (r : y = z) : (p ⬝ r = q ⬝ r) → (p = q) := λs, !con_inv_cancel_right⁻¹ ⬝ whisker_right r⁻¹ s ⬝ !con_inv_cancel_right -- Whiskering and identity paths. definition whisker_right_idp {p q : x = y} (h : p = q) : whisker_right idp h = h := by induction h; induction p; reflexivity definition whisker_right_idp_left [unfold_full] (p : x = y) (q : y = z) : whisker_right q idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp_right [unfold_full] (p : x = y) (q : y = z) : whisker_left p idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp {p q : x = y} (h : p = q) : (idp_con p)⁻¹ ⬝ whisker_left idp h ⬝ idp_con q = h := by induction h; induction p; reflexivity definition whisker_left_idp2 {A : Type} {a : A} (p : idp = idp :> a = a) : whisker_left idp p = p := begin refine _ ⬝ whisker_left_idp p, exact !idp_con⁻¹ end definition con2_idp [unfold_full] {p q : x = y} (h : p = q) : h ◾ idp = whisker_right idp h :> (p ⬝ idp = q ⬝ idp) := idp definition idp_con2 [unfold_full] {p q : x = y} (h : p = q) : idp ◾ h = whisker_left idp h :> (idp ⬝ p = idp ⬝ q) := idp definition inv2_con2 {p p' : x = y} (h : p = p') : h⁻² ◾ h = con.left_inv p ⬝ (con.left_inv p')⁻¹ := by induction h; induction p; reflexivity -- The interchange law for concatenation. definition con2_con_con2 {p p' p'' : x = y} {q q' q'' : y = z} (a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') : a ◾ c ⬝ b ◾ d = (a ⬝ b) ◾ (c ⬝ d) := by induction d; induction c; induction b;induction a; reflexivity definition con2_eq_rl {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : a ◾ b = whisker_right q a ⬝ whisker_left p' b := by induction b; induction a; reflexivity definition con2_eq_lf {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : a ◾ b = whisker_left p b ⬝ whisker_right q' a := by induction b; induction a; reflexivity definition whisker_right_con_whisker_left {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : (whisker_right q a) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right q' a) := by induction b; induction a; reflexivity -- Structure corresponding to the coherence equations of a bicategory. -- The "pentagonator": the 3-cell witnessing the associativity pentagon. definition pentagon {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z) : whisker_left p (con.assoc' q r s) ⬝ con.assoc' p (q ⬝ r) s ⬝ whisker_right s (con.assoc' p q r) = con.assoc' p q (r ⬝ s) ⬝ con.assoc' (p ⬝ q) r s := by induction s;induction r;induction q;induction p;reflexivity -- The 3-cell witnessing the left unit triangle. definition triangulator (p : x = y) (q : y = z) : con.assoc' p idp q ⬝ whisker_right q (con_idp p) = whisker_left p (idp_con q) := by induction q; induction p; reflexivity definition eckmann_hilton (p q : idp = idp :> a = a) : p ⬝ q = q ⬝ p := begin refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _, refine !whisker_right_con_whisker_left ⬝ _, refine !whisker_left_idp2 ◾ !whisker_right_idp end definition con_eq_con2 (p q : idp = idp :> a = a) : p ⬝ q = p ◾ q := begin refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _, exact !con2_eq_rl⁻¹ end definition inv_eq_inv2 (p : idp = idp :> a = a) : p⁻¹ = p⁻² := begin apply eq.cancel_right p, refine !con.left_inv ⬝ _, refine _ ⬝ !con_eq_con2⁻¹, exact !inv2_con2⁻¹, end -- The action of functions on 2-dimensional paths definition ap02 [unfold 8] [reducible] (f : A → B) {x y : A} {p q : x = y} (r : p = q) : ap f p = ap f q := ap (ap f) r definition ap02_con (f : A → B) {x y : A} {p p' p'' : x = y} (r : p = p') (r' : p' = p'') : ap02 f (r ⬝ r') = ap02 f r ⬝ ap02 f r' := by induction r; induction r'; reflexivity definition ap02_con2 (f : A → B) {x y z : A} {p p' : x = y} {q q' :y = z} (r : p = p') (s : q = q') : ap02 f (r ◾ s) = ap_con f p q ⬝ (ap02 f r ◾ ap02 f s) ⬝ (ap_con f p' q')⁻¹ := by induction r; induction s; induction q; induction p; reflexivity definition apdt02 [unfold 8] {p q : x = y} (f : Π x, P x) (r : p = q) : apdt f p = transport2 P r (f x) ⬝ apdt f q := by induction r; exact !idp_con⁻¹ end eq /- an auxillary namespace for concatenation and inversion for homotopies. We put this is a separate namespace because ⁻¹ʰ is also used as the inverse of a homomorphism -/ open eq namespace homotopy infix ` ⬝h `:75 := homotopy.trans postfix `⁻¹ʰ`:(max+1) := homotopy.symm end homotopy
b1e0a2fcb742c5f8b91da0740f667c53831aa309
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/protected.lean
a077fc3e33928cdbfe0dd5340d3af426dc9f1518
[ "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
1,023
lean
namespace Foo protected def x := 10 end Foo open Foo #check x -- error unknown identifier `x` #check Foo.x namespace Bla.Foo protected def y := 20 def z := 30 end Bla.Foo open Bla #check Foo.y open Bla.Foo #check y -- error unknown identifier `y` #check z protected def x := 0 -- Error protected partial def Foo.f (x : Nat) := if x > 0 then f (x-1) * 2 else 1 -- Error protected partial def Bla.f (x : Nat) := if x > 0 then Bla.f (x-1) * 2 else 1 #eval Bla.f 3 namespace Foo protected partial def g (x : Nat) := if x > 0 then g (x-1) * 2 else 1 -- error end Foo namespace Bla protected partial def g (x : Nat) := if x > 0 then Bla.g (x-1) * 2 else 1 #eval g 3 -- error #eval Bla.g 3 end Bla def S (σ : Type) (m : Type → Type) (α : Type) := σ → m (α × σ) namespace S variables {σ : Type} {m : Type → Type} [Monad m] {α : Type} protected def pure (a : α) : S σ m α := fun s => pure (a, s) -- This `pure` is the top-level one. The `pure` being defined here is called `S.pure`. end S
7111a98b4bb5f7770e230331bd0658eeb18d8f22
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eq22.lean
1ea1a5daf338eff653f8fcce8539f0c34e31fcf5
[ "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
221
lean
open list definition head {A : Type} : Π (l : list A), l ≠ nil → A | nil h := absurd rfl h | (a :: l) h := a theorem head_cons {A : Type} (a : A) (l : list A) (h : a :: l ≠ nil) : head (a :: l) h = a := rfl
bfaab4bfef969422298a02a12343e79a3a7104e9
90bd8c2a52dbaaba588bdab57b155a7ec1532de0
/src/instances/real_vector_space.lean
dfedc8483c272a58b66192cd24bbf3930a3a0b11
[ "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
703
lean
import contractible.basic import homotopy.straight_line import analysis.normed_space.basic /-! # Instances on finite dimensional `ℝ`-vector spaces In this file, we prove that for a `fintype` `ι`, `ι → ℝ` is contractible. -/ noncomputable theory variables {ι : Type _} [fintype ι] instance real_vector_space.contractible : contractible (ι → ℝ) := { hequiv := ⟨{ to_fun := { to_fun := λ p, () }, inv_fun := { to_fun := λ p, 0 }, left_inv := ⟨straight_line_homotopy _ _⟩, right_inv := ⟨{ to_fun := { to_fun := λ p, () }, to_fun_zero' := by norm_num, to_fun_one' := by norm_num, prop := λ t, trivial }⟩ }⟩ } .
74a59a18815b5c9b0049bd168275927300bed25a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/arithmetic_function.lean
319e827b487e9df4956ecc3089e94e1396c65428
[ "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
33,127
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.big_operators.ring import number_theory.divisors import algebra.squarefree import algebra.invertible import data.nat.factorization /-! # Arithmetic Functions and Dirichlet Convolution This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition, to form the Dirichlet ring. ## Main Definitions * `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`. * An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`. * The pointwise operations `pmul` and `ppow` differ from the multiplication and power instances on `arithmetic_function R`, which use Dirichlet multiplication. * `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`. * `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`. * `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`. * `id` is the identity arithmetic function on `ℕ`. * `ω n` is the number of distinct prime factors of `n`. * `Ω n` is the number of prime factors of `n` counted with multiplicity. * `μ` is the Möbius function. ## Main Results * Several forms of Möbius inversion: * `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring` * `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group` * `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group` * `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero` ## Notation The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in the namespace `arithmetic_function`. ## Tags arithmetic functions, dirichlet convolution, divisors -/ open finset open_locale big_operators namespace nat variable (R : Type*) /-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by Dirichlet convolution. -/ @[derive [has_zero, inhabited]] def arithmetic_function [has_zero R] := zero_hom ℕ R variable {R} namespace arithmetic_function section has_zero variable [has_zero R] instance : has_coe_to_fun (arithmetic_function R) (λ _, ℕ → R) := zero_hom.has_coe_to_fun @[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl @[simp] lemma map_zero {f : arithmetic_function R} : f 0 = 0 := zero_hom.map_zero' f theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g := ⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩ @[simp] lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 := zero_hom.zero_apply x @[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g := zero_hom.ext h theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x := zero_hom.ext_iff section has_one variable [has_one R] instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩ @[simp] lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl @[simp] lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h end has_one end has_zero instance nat_coe [has_zero R] [has_one R] [has_add R] : has_coe (arithmetic_function ℕ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma nat_coe_nat (f : arithmetic_function ℕ) : (↑f : arithmetic_function ℕ) = f := ext $ λ _, cast_id _ @[simp] lemma nat_coe_apply [has_zero R] [has_one R] [has_add R] {f : arithmetic_function ℕ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl instance int_coe [has_zero R] [has_one R] [has_add R] [has_neg R] : has_coe (arithmetic_function ℤ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma int_coe_int (f : arithmetic_function ℤ) : (↑f : arithmetic_function ℤ) = f := ext $ λ _, int.cast_id _ @[simp] lemma int_coe_apply [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℤ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl @[simp] lemma coe_coe [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℕ} : ((f : arithmetic_function ℤ) : arithmetic_function R) = f := by { ext, simp, } section add_monoid variable [add_monoid R] instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩ @[simp] lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl instance : add_monoid (arithmetic_function R) := { add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _), zero_add := λ _, ext (λ _, zero_add _), add_zero := λ _, ext (λ _, add_zero _), .. arithmetic_function.has_zero R, .. arithmetic_function.has_add } end add_monoid instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) := { add_comm := λ _ _, ext (λ _, add_comm _ _), .. arithmetic_function.add_monoid } instance [add_group R] : add_group (arithmetic_function R) := { neg := λ f, ⟨λ n, - f n, by simp⟩, add_left_neg := λ _, ext (λ _, add_left_neg _), .. arithmetic_function.add_monoid } instance [add_comm_group R] : add_comm_group (arithmetic_function R) := { .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_group } section has_scalar variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_scalar R M] /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance : has_scalar (arithmetic_function R) (arithmetic_function M) := ⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩ @[simp] lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} : (f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl end has_scalar /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩ @[simp] lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} : (f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl section module variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M] lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) : (f * g) • h = f • g • h := begin ext n, simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'], apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩, refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨i0.2, n0.2⟩, }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_divisors_antidiagonal, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, rintros rfl h2 rfl rfl, exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩, { simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩, refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨n0.1, j0.1⟩ }, { simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true, ne.def, mem_sigma, heq_iff_eq] at H ⊢, rw H.2.1 } } end lemma one_smul' (b : arithmetic_function M) : (1 : arithmetic_function R) • b = b := begin ext, rw smul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y1ne : y.fst ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y1ne], end end module section semiring variable [semiring R] instance : monoid (arithmetic_function R) := { one_mul := one_smul', mul_one := λ f, begin ext, rw mul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y2ne : y.snd ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y2ne], end, mul_assoc := mul_smul', .. arithmetic_function.has_one, .. arithmetic_function.has_mul } instance : semiring (arithmetic_function R) := { zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] }, mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] }, left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] }, right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] }, .. arithmetic_function.has_zero R, .. arithmetic_function.has_mul, .. arithmetic_function.has_add, .. arithmetic_function.add_comm_monoid, .. arithmetic_function.monoid } end semiring instance [comm_semiring R] : comm_semiring (arithmetic_function R) := { mul_comm := λ f g, by { ext, rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map], simp [mul_comm] }, .. arithmetic_function.semiring } instance [comm_ring R] : comm_ring (arithmetic_function R) := { .. arithmetic_function.add_comm_group, .. arithmetic_function.comm_semiring } instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : module (arithmetic_function R) (arithmetic_function M) := { one_smul := one_smul', mul_smul := mul_smul', smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] }, smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] }, add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] }, zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, } section zeta /-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/ def zeta : arithmetic_function ℕ := ⟨λ x, ite (x = 0) 0 1, rfl⟩ localized "notation `ζ` := nat.arithmetic_function.zeta" in arithmetic_function @[simp] lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h @[simp] theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (↑ζ * f) x = ∑ i in divisors x, f i := begin rw mul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M] {f : arithmetic_function M} {x : ℕ} : ((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i := begin rw smul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end @[simp] theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := begin apply mul_opposite.op_injective, rw [op_sum], convert @coe_zeta_mul_apply Rᵐᵒᵖ _ { to_fun := mul_opposite.op ∘ f, map_zero' := by simp} x, rw [mul_apply, mul_apply, op_sum], conv_lhs { rw ← map_swap_divisors_antidiagonal, }, rw sum_map, apply sum_congr rfl, intros y hy, by_cases h1 : y.fst = 0, { simp [function.comp_apply, h1] }, { simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap, if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] } end theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} : (ζ * f) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_zeta_mul_apply] theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_mul_zeta_apply] end zeta open_locale arithmetic_function section pmul /-- This is the pointwise product of `arithmetic_function`s. -/ def pmul [mul_zero_class R] (f g : arithmetic_function R) : arithmetic_function R := ⟨λ x, f x * g x, by simp⟩ @[simp] lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} : f.pmul g x = f x * g x := rfl lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) : f.pmul g = g.pmul f := by { ext, simp [mul_comm] } variable [semiring R] @[simp] lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f := begin ext x, cases x; simp [nat.succ_ne_zero], end @[simp] lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f := begin ext x, cases x; simp [nat.succ_ne_zero], end /-- This is the pointwise power of `arithmetic_function`s. -/ def ppow (f : arithmetic_function R) (k : ℕ) : arithmetic_function R := if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k, by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩ @[simp] lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ := by rw [ppow, dif_pos rfl] @[simp] lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) : f.ppow k x = (f x) ^ k := by { rw [ppow, dif_neg (ne_of_gt kpos)], refl } lemma ppow_succ {f : arithmetic_function R} {k : ℕ} : f.ppow (k + 1) = f.pmul (f.ppow k) := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ], induction k; simp, end lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} : f.ppow (k + 1) = (f.ppow k).pmul f := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ'], induction k; simp, end end pmul /-- Multiplicative functions -/ def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop := f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n) namespace is_multiplicative section monoid_with_zero variable [monoid_with_zero R] @[simp] lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 := h.1 @[simp] lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative) {m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n := hf.2 h end monoid_with_zero lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma mul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f * g) := ⟨by { simp [hf, hg], }, begin simp only [mul_apply], intros m n cop, rw sum_mul_sum, symmetry, apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)), { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def], split, {ring}, rw nat.mul_eq_zero at *, apply not_or ha hb }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, dsimp only, rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right, hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right], ring, }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab, rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd, simp only [prod.mk.inj_iff] at h, ext; dsimp only, { transitivity nat.gcd (a1 * a2) (a1 * b1), { rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.1, nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (a1 * a2) (a2 * b2), { rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a1 * b1), { rw [mul_comm, nat.gcd_mul_right, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a2 * b2), { rw [nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.2, nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } }, { rintros ⟨b1, b2⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)), simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal], rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _], { rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] }, rw [mul_comm n m, h.1] } end⟩ lemma pmul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f.pmul g) := ⟨by { simp [hf, hg], }, λ m n cop, begin simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop], ring, end⟩ /-- For any multiplicative function `f` and any `n > 0`, we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/ lemma multiplicative_factorization [comm_monoid_with_zero R] (f : arithmetic_function R) (hf : f.is_multiplicative) : ∀ {n : ℕ}, n ≠ 0 → f n = n.factorization.prod (λ p k, f (p ^ k)) := λ n hn, multiplicative_factorization f hf.2 hf.1 hn end is_multiplicative section special_functions /-- The identity on `ℕ` as an `arithmetic_function`. -/ def id : arithmetic_function ℕ := ⟨id, rfl⟩ @[simp] lemma id_apply {x : ℕ} : id x = x := rfl /-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/ def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k @[simp] lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k := begin cases k, { simp [pow] }, simp [pow, (ne_of_lt (nat.succ_pos k)).symm], end /-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/ def sigma (k : ℕ) : arithmetic_function ℕ := ⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩ localized "notation `σ` := nat.arithmetic_function.sigma" in arithmetic_function @[simp] lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl lemma sigma_one_apply {n : ℕ} : σ 1 n = ∑ d in divisors n, d := by simp lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k := begin ext, rw [sigma, zeta_mul_apply], apply sum_congr rfl, intros x hx, rw [pow_apply, if_neg (not_and_of_not_right _ _)], contrapose! hx, simp [hx], end lemma is_multiplicative_zeta : is_multiplicative ζ := ⟨by simp, λ m n cop, begin cases m, {simp}, cases n, {simp}, simp [nat.succ_ne_zero] end⟩ lemma is_multiplicative_id : is_multiplicative arithmetic_function.id := ⟨rfl, λ _ _ _, rfl⟩ lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R} (hf : f.is_multiplicative) {k : ℕ} : is_multiplicative (f.ppow k) := begin induction k with k hi, { exact is_multiplicative_zeta.nat_cast }, { rw ppow_succ, apply hf.pmul hi }, end lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) := is_multiplicative_id.ppow lemma is_multiplicative_sigma {k : ℕ} : is_multiplicative (sigma k) := begin rw [← zeta_mul_pow_eq_sigma], apply ((is_multiplicative_zeta).mul is_multiplicative_pow) end /-- `Ω n` is the number of prime factors of `n`. -/ def card_factors : arithmetic_function ℕ := ⟨λ n, n.factors.length, by simp⟩ localized "notation `Ω` := nat.arithmetic_function.card_factors" in arithmetic_function lemma card_factors_apply {n : ℕ} : Ω n = n.factors.length := rfl @[simp] lemma card_factors_one : Ω 1 = 0 := by simp [card_factors] lemma card_factors_eq_one_iff_prime {n : ℕ} : Ω n = 1 ↔ n.prime := begin refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩, cases n, { contrapose! h, simp }, rcases list.length_eq_one.1 h with ⟨x, hx⟩, rw [← prod_factors n.succ_pos, hx, list.prod_singleton], apply prime_of_mem_factors, rw [hx, list.mem_singleton] end lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) : Ω (m * n) = Ω m + Ω n := by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card, ← factors_eq, unique_factorization_monoid.normalized_factors_mul m0 n0, factors_eq, factors_eq, multiset.card_add, multiset.coe_card, multiset.coe_card] lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) : Ω s.prod = (multiset.map Ω s).sum := begin revert h0, apply s.induction_on, by simp, intros a t h h0, rw [multiset.prod_cons, mul_ne_zero_iff] at h0, simp [h0, card_factors_mul, h], end /-- `ω n` is the number of distinct prime factors of `n`. -/ def card_distinct_factors : arithmetic_function ℕ := ⟨λ n, n.factors.erase_dup.length, by simp⟩ localized "notation `ω` := nat.arithmetic_function.card_distinct_factors" in arithmetic_function lemma card_distinct_factors_zero : ω 0 = 0 := by simp lemma card_distinct_factors_apply {n : ℕ} : ω n = n.factors.erase_dup.length := rfl lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) : ω n = Ω n ↔ squarefree n := begin rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply], split; intro h, { rw ← list.eq_of_sublist_of_length_eq n.factors.erase_dup_sublist h, apply list.nodup_erase_dup }, { rw h.erase_dup, refl } end /-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors, `μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`. If `n` is not squarefree, `μ n = 0`. -/ def moebius : arithmetic_function ℤ := ⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩ localized "notation `μ` := nat.arithmetic_function.moebius" in arithmetic_function @[simp] lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n): μ n = (-1) ^ (card_factors n) := if_pos h @[simp] lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n): μ n = 0 := if_neg h lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n := begin split; intro h, { contrapose! h, simp [h] }, { simp [h, pow_ne_zero] } end lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 := begin split; intro h, { rw moebius_ne_zero_iff_squarefree at h, rw moebius_apply_of_squarefree h, apply neg_one_pow_eq_or }, { rcases h with h | h; simp [h] } end open unique_factorization_monoid @[simp] lemma coe_moebius_mul_coe_zeta [comm_ring R] : (μ * ζ : arithmetic_function R) = 1 := begin ext x, cases x, { simp only [divisors_zero, sum_empty, ne.def, not_false_iff, coe_mul_zeta_apply, zero_ne_one, one_apply_ne] }, cases x, { simp only [moebius_apply_of_squarefree, card_factors_one, squarefree_one, divisors_one, int.cast_one, sum_singleton, coe_mul_zeta_apply, one_one, int_coe_apply, pow_zero] }, rw [coe_mul_zeta_apply, one_apply_ne (ne_of_gt (succ_lt_succ (nat.succ_pos _)))], simp_rw [int_coe_apply], rw [←int.cast_sum, ← sum_filter_ne_zero], convert int.cast_zero, simp only [moebius_ne_zero_iff_squarefree], suffices : ∑ (y : finset ℕ) in (unique_factorization_monoid.normalized_factors x.succ.succ).to_finset.powerset, ite (squarefree y.val.prod) ((-1:ℤ) ^ Ω y.val.prod) 0 = 0, { have h : ∑ i in _, ite (squarefree i) ((-1:ℤ) ^ Ω i) 0 = _ := (sum_divisors_filter_squarefree (nat.succ_ne_zero _)), exact (eq.trans (by congr') h).trans this }, apply eq.trans (sum_congr rfl _) (sum_powerset_neg_one_pow_card_of_nonempty _), { intros y hy, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hy, have h : unique_factorization_monoid.normalized_factors y.val.prod = y.val, { apply factors_multiset_prod_of_irreducible, intros z hz, apply irreducible_of_normalized_factor _ (multiset.subset_of_le (le_trans hy (multiset.erase_dup_le _)) hz) }, rw [if_pos], { rw [card_factors_apply, ← multiset.coe_card, ← factors_eq, h, finset.card] }, rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors, h], { apply y.nodup }, rw [ne.def, multiset.prod_eq_zero_iff], intro con, rw ← h at con, exact not_irreducible_zero (irreducible_of_normalized_factor 0 con) }, { rw finset.nonempty, rcases wf_dvd_monoid.exists_irreducible_factor _ (nat.succ_ne_zero _) with ⟨i, hi⟩, { rcases exists_mem_normalized_factors_of_dvd (nat.succ_ne_zero _) hi.1 hi.2 with ⟨j, hj, hj2⟩, use j, apply multiset.mem_to_finset.2 hj }, rw nat.is_unit_iff, norm_num }, end @[simp] lemma coe_zeta_mul_coe_moebius [comm_ring R] : (ζ * μ : arithmetic_function R) = 1 := by rw [mul_comm, coe_moebius_mul_coe_zeta] @[simp] lemma moebius_mul_coe_zeta : (μ * ζ : arithmetic_function ℤ) = 1 := by rw [← int_coe_int μ, coe_moebius_mul_coe_zeta] @[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 := by rw [← int_coe_int μ, coe_zeta_mul_coe_moebius] section comm_ring variable [comm_ring R] instance : invertible (ζ : arithmetic_function R) := { inv_of := μ, inv_of_mul_self := coe_moebius_mul_coe_zeta, mul_inv_of_self := coe_zeta_mul_coe_moebius} /-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/ def zeta_unit : (arithmetic_function R)ˣ := ⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩ @[simp] lemma coe_zeta_unit : ((zeta_unit : (arithmetic_function R)ˣ) : arithmetic_function R) = ζ := rfl @[simp] lemma inv_zeta_unit : ((zeta_unit⁻¹ : (arithmetic_function R)ˣ) : arithmetic_function R) = μ := rfl end comm_ring /-- Möbius inversion for functions to an `add_comm_group`. -/ theorem sum_eq_iff_sum_smul_moebius_eq [add_comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n := begin let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩, let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩, transitivity (ζ : arithmetic_function ℤ) • f' = g', { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, rw coe_zeta_smul_apply, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) }, transitivity μ • g' = f', { split; intro h, { rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] }, { rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } }, { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply, if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) }, end /-- Möbius inversion for functions to a `comm_ring`. -/ theorem sum_eq_iff_sum_mul_moebius_eq [comm_ring R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n := begin rw sum_eq_iff_sum_smul_moebius_eq, apply forall_congr, intro a, apply imp_congr (iff.refl _) (eq.congr_left (sum_congr rfl (λ x hx, _))), rw [zsmul_eq_mul], end /-- Möbius inversion for functions to a `comm_group`. -/ theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := @sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _ /-- Möbius inversion for functions to a `comm_group_with_zero`. -/ theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R} (hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := begin refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq Rˣ _ (λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1) (λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _)); refine imp_congr_right (λ hn, _), { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] }, { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)), units.coe_hom_apply, units.coe_zpow₀, units.coe_mk0] } end end special_functions end arithmetic_function end nat
da68c43e71c3edfa2ea9184d178ef97523835308
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/category/state.lean
ec51669c616de9d45338c42fa369e7a488caf151
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,140
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.category.monad def state (σ : Type) (α : Type) : Type := σ → α × σ section variables {σ : Type} {α β : Type} @[inline] def state_fmap (f : α → β) (a : state σ α) : state σ β := λ s, match (a s) with (a', s') := (f a', s') end @[inline] def state_return (a : α) : state σ α := λ s, (a, s) @[inline] def state_bind (a : state σ α) (b : α → state σ β) : state σ β := λ s, match (a s) with (a', s') := b a' s' end instance (σ : Type) : monad (state σ) := { map := @state_fmap σ, ret := @state_return σ, bind := @state_bind σ } end namespace state @[inline] def read {σ : Type} : state σ σ := λ s, (s, s) @[inline] def write {σ : Type} : σ → state σ unit := λ s' s, ((), s') end state def state_t (σ : Type) (m : Type → Type) [monad m] (α : Type) : Type := σ → m (α × σ) section variable {σ : Type} variable {m : Type → Type} variable [monad m] variables {α β : Type} def state_t_fmap (f : α → β) (act : state_t σ m α) : state_t σ m β := λ s, show m (β × σ), from do (a, new_s) ← act s, return (f a, new_s) def state_t_return (a : α) : state_t σ m α := λ s, show m (α × σ), from return (a, s) def state_t_bind (act₁ : state_t σ m α) (act₂ : α → state_t σ m β) : state_t σ m β := λ s, show m (β × σ), from do (a, new_s) ← act₁ s, act₂ a new_s end instance (σ : Type) (m : Type → Type) [monad m] : monad (state_t σ m) := { map := @state_t_fmap σ m _, ret := @state_t_return σ m _, bind := @state_t_bind σ m _} namespace state_t def read {σ : Type} {m : Type → Type} [monad m] : state_t σ m σ := λ s, return (s, s) def write {σ : Type} {m : Type → Type} [monad m] : σ → state_t σ m unit := λ s' s, return ((), s') def modify {σ : Type} {m : Type → Type} [monad m] (f : σ → σ) : state_t σ m unit := do s ← read, write (f s) end state_t
1f3e8053186e94fdabd99f0aecc479fb40a36db8
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/KyleAlg.lean
4237febb3b813f74f975b0c9d66961f996947e75
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
8,448
lean
import Lean /- from core: class OfNat (α : Type u) (n : Nat) where ofNat : α class Mul (α : Type u) where mul : α → α → α class Add (α : Type u) where add : α → α → α -/ class Inv (α : Type u) where inv : α → α postfix:max "⁻¹" => Inv.inv class One (α : Type u) where one : α export One (one) instance [One α] : OfNat α (nat_lit 1) where ofNat := one class Zero (α : Type u) where zero : α export Zero (zero) instance [Zero α] : OfNat α (nat_lit 0) where ofNat := zero class MulComm (α : Type u) [Mul α] : Prop where mulComm : {a b : α} → a * b = b * a export MulComm (mulComm) class MulAssoc (α : Type u) [Mul α] : Prop where mulAssoc : {a b c : α} → a * b * c = a * (b * c) export MulAssoc (mulAssoc) class OneUnit (α : Type u) [Mul α] [One α] : Prop where oneMul : {a : α} → 1 * a = a mulOne : {a : α} → a * 1 = a export OneUnit (oneMul mulOne) class AddComm (α : Type u) [Add α] : Prop where addComm : {a b : α} → a + b = b + a export AddComm (addComm) class AddAssoc (α : Type u) [Add α] : Prop where addAssoc : {a b c : α} → a + b + c = a + (b + c) export AddAssoc (addAssoc) class ZeroUnit (α : Type u) [Add α] [Zero α] : Prop where zeroAdd : {a : α} → 0 + a = a addZero : {a : α} → a + 0 = a export ZeroUnit (zeroAdd addZero) class InvMul (α : Type u) [Mul α] [One α] [Inv α] : Prop where invMul : {a : α} → a⁻¹ * a = 1 export InvMul (invMul) class NegAdd (α : Type u) [Add α] [Zero α] [Neg α] : Prop where negAdd : {a : α} → -a + a = 0 export NegAdd (negAdd) class ZeroMul (α : Type u) [Mul α] [Zero α] : Prop where zeroMul : {a : α} → 0 * a = 0 export ZeroMul (zeroMul) class Distrib (α : Type u) [Add α] [Mul α] : Prop where leftDistrib : {a b c : α} → a * (b + c) = a * b + a * c rightDistrib : {a b c : α} → (a + b) * c = a * c + b * c export Distrib (leftDistrib rightDistrib) class Domain (α : Type u) [Mul α] [Zero α] : Prop where eqZeroOrEqZeroOfMulEqZero : {a b : α} → a * b = 0 → a = 0 ∨ b = 0 export Domain (eqZeroOrEqZeroOfMulEqZero) class Semigroup (α : Type u) extends Mul α, MulAssoc α attribute [instance] Semigroup.mk class AddSemigroup (α : Type u) extends Add α, AddAssoc α attribute [instance] AddSemigroup.mk class Monoid (α : Type u) extends Semigroup α, One α, OneUnit α attribute [instance] Monoid.mk class AddMonoid (α : Type u) extends AddSemigroup α, Zero α, ZeroUnit α attribute [instance] AddMonoid.mk class CommSemigroup (α : Type u) extends Semigroup α, MulComm α attribute [instance] CommSemigroup.mk class CommMonoid (α : Type u) extends Monoid α, MulComm α attribute [instance] CommMonoid.mk class Group (α : Type u) extends Monoid α, Inv α, InvMul α attribute [instance] Group.mk class AddGroup (α : Type u) extends AddMonoid α, Neg α, NegAdd α attribute [instance] AddGroup.mk class Semiring (α : Type u) extends AddMonoid α, Monoid α, AddComm α, ZeroMul α, Distrib α attribute [instance] Semiring.mk class Ring (α : Type u) extends AddGroup α, Monoid α, AddComm α, Distrib α attribute [instance] Ring.mk class CommRing (α : Type u) extends Ring α, MulComm α attribute [instance] CommRing.mk class IntegralDomain (α : Type u) extends CommRing α, Domain α attribute [instance] IntegralDomain.mk section test1 variable (α : Type u) [h : CommMonoid α] example : Semigroup α := inferInstance example : Monoid α := inferInstance example : CommSemigroup α := inferInstance end test1 section test2 variable (β : Type u) [CommSemigroup β] [One β] [OneUnit β] example : Monoid β := inferInstance example : CommMonoid β := inferInstance example : Semigroup β := inferInstance end test2 section test3 variable (β : Type u) [Mul β] [One β] [MulAssoc β] [OneUnit β] example : Monoid β := inferInstance example : Semigroup β := inferInstance end test3 theorem negZero [AddGroup α] : -(0 : α) = 0 := by rw [←addZero (a := -(0 : α)), negAdd] theorem subZero [AddGroup α] {a : α} : a + -(0 : α) = a := by rw [←addZero (a := a), addAssoc, negZero, addZero] theorem negNeg [AddGroup α] {a : α} : -(-a) = a := by { rw [←addZero (a := - -a)]; rw [←negAdd (a := a)]; rw [←addAssoc]; rw [negAdd]; rw [zeroAdd]; } theorem addNeg [AddGroup α] {a : α} : a + -a = 0 := by { have h : - -a + -a = 0 := by { rw [negAdd] }; rw [negNeg] at h; exact h } theorem addIdemIffZero [AddGroup α] {a : α} : a + a = a ↔ a = 0 := by apply Iff.intro focus intro h have h' := congrArg (λ x => x + -a) h simp at h' rw [addAssoc, addNeg, addZero] at h' exact h' focus intro h subst a rw [addZero] instance [Ring α] : ZeroMul α := by { apply ZeroMul.mk; intro a; have h : 0 * a + 0 * a = 0 * a := by { rw [←rightDistrib, addZero] }; rw [addIdemIffZero (a := 0 * a)] at h; rw [h]; } example [Ring α] : Semiring α := inferInstance section prod instance [Mul α] [Mul β] : Mul (α × β) where mul p p' := (p.1 * p'.1, p.2 * p'.2) instance [Inv α] [Inv β] : Inv (α × β) where inv p := (p.1⁻¹, p.2⁻¹) instance [One α] [One β] : One (α × β) where one := (1, 1) theorem Product.ext : {p q : α × β} → p.1 = q.1 → p.2 = q.2 → p = q | (a, b), (c, d) => by simp_all instance [Semigroup α] [Semigroup β] : Semigroup (α × β) where mulAssoc := by intros apply Product.ext apply mulAssoc apply mulAssoc instance [Monoid α] [Monoid β] : Monoid (α × β) where oneMul := by intros apply Product.ext apply oneMul apply oneMul mulOne := by intros apply Product.ext apply mulOne apply mulOne instance [Group α] [Group β] : Group (α × β) where invMul := by intros apply Product.ext apply invMul apply invMul end prod def test1 {G : Type _} [Group G]: Group (G) := inferInstance def test2 {G : Type _} [Group G]: Group (G × G) := inferInstance def test3 {G : Type _} [Group G]: Group (G × G × G) := inferInstance def test4 {G : Type _} [Group G]: Group (G × G × G × G) := inferInstance def test5 {G : Type _} [Group G]: Group (G × G × G × G × G) := inferInstance def test6 {G : Type _} [Group G]: Group (G × G × G × G × G × G) := inferInstance def test7 {G : Type _} [Group G]: Group (G × G × G × G × G × G × G) := inferInstance def test8 {G : Type _} [Group G]: Group (G × G × G × G × G × G × G × G) := inferInstance namespace Lean unsafe def Expr.dagSizeUnsafe (e : Expr) : IO Nat := do let (_, s) ← visit e |>.run ({}, 0) return s.2 where visit (e : Expr) : StateRefT (Std.HashSet USize × Nat) IO Unit := do let addr := ptrAddrUnsafe e unless (← get).1.contains addr do modify fun (s, c) => (s.insert addr, c+1) match e with | Expr.proj _ _ s _ => visit s | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | _ => return () @[implementedBy Expr.dagSizeUnsafe] constant Expr.dagSize (e : Expr) : IO Nat def getDeclTypeValueDagSize (declName : Name) : CoreM Nat := do let info ← getConstInfo declName let n ← info.type.dagSize match info.value? with | none => return n | some v => return n + (← v.dagSize) #eval getDeclTypeValueDagSize `test2 #eval getDeclTypeValueDagSize `test3 #eval getDeclTypeValueDagSize `test4 #eval getDeclTypeValueDagSize `test5 #eval getDeclTypeValueDagSize `test6 #eval getDeclTypeValueDagSize `test7 #eval getDeclTypeValueDagSize `test8 def reduceAndGetDagSize (declName : Name) : MetaM Nat := do let c := mkConst declName [levelOne] let e ← Meta.reduce c trace[Meta.debug] "{e}" e.dagSize #eval reduceAndGetDagSize `test1 #eval reduceAndGetDagSize `test2 #eval reduceAndGetDagSize `test3 #eval reduceAndGetDagSize `test4 #eval reduceAndGetDagSize `test5 #eval reduceAndGetDagSize `test6 #eval reduceAndGetDagSize `test7 -- Use `set_option` to trace the reduced term set_option pp.all true in set_option trace.Meta.debug true in #eval reduceAndGetDagSize `test8
eb6d34ac235ce8d7b88c2433b0f40055589e1f4b
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/hmulDefaultIntance.lean
fa53cd9334f668ffc49e57db3914094a3e651eef
[ "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
319
lean
class HMul (α β : Type _) (γ : outParam (Type _)) where hmul : α → β → γ @[defaultInstance] instance [Mul α] : HMul α α α where hmul a b := a * b infix:70 "*'" => HMul.hmul instance : HMul Nat Bool Nat where hmul | x, true => x | x, false => 0 #check 10 *' true #check fun x => x *' 1
1cfc7076142fa89b1c9cdb0f30966cda33ba7119
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/predicate_logic/propositions_as_types.lean
46e4ec8454f6434215e98cf7328197d91288ac36
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
3,336
lean
-- Computational domain #check nat #check 1 #check string #check "hello" #check bool #check tt -- "computational" types of type, Type (aka Sort 1) -- Logical domain #check true #print true def a_proof_of_nat : ℕ := 8 theorem a_proof_of_true : true := true.intro #check false #check (eq 1) 1 -- eq predicate applied to 1 and 2 #check (eq 1) #check 1 = 1 -- infix notation for eq #print eq lemma pf_one_eq_one : 1 = 1 := eq.refl 1 lemma pf_one_eq_two : 1 = 2 := (eq.refl 2) #check eq.refl 3 #check 3 ∈ { n : ℕ | n % 2 = 1} #check ∃ (a b c : ℕ), a^2 + b^2 = c^2 -- propositions formalized as logical types: of type, Prop (Sort 0) -- Values of computational types #check 1 #check "hello" #check tt -- values of computational types are just ordinary data -- Values of logical types (aka propositions) #check (eq.refl 1) -- values of logical types are accepted as proofs -- eq defined as polymorphic *logical* type -- takes two values, v1 and v2, of any type, α -- yields a proposition, eq v1 v2, of type Prop -- this type has just on constructor, called refl -- takes argument, a : α, returns a value of type a=a -- this value is accepted as a *proof* #print eq -- exercises involving proofs of equality def pf1 : 1 = 1 := eq.refl 1 def pf2 : "hello" = "hello" := eq.refl "hello" #reduce 2 = nat.pred 3 lemma pf3 : 2 = nat.pred 3 := eq.refl (nat.pred 3) -- vocabulary: minor result theorem pf4 : tt = tt := eq.refl tt -- vocabulary: major result theorem pf5 : 1 = 0 := _ -- StUCk!!! def sq (n : ℕ) : ℕ := n^2 #reduce (sq 3 = 9) lemma pf6 : sq 3 = 9 := eq.refl 9 -- equality of reduced values lemma pf7 : sq 5 = 25 := eq.refl 25 example : sq 3 = 9 := eq.refl _ example : ℕ := 8 -- A logical type that has no values is false. -- That's why the proposition, "false", in Lean is false. -- a type with no constructors/values is said to be uninhabited #print false theorem pf8 : false := _ -- The proposition, "true", has one constant constructor/value/proof #print true theorem pf9 : true := true.intro /- What we've seen so far is that some propositions are formalized as inductive types, the values of which, as built using available constructors, are taken to be proofs. Indeed you can represent a wide variety of propositions and proofs this way. -/ inductive MaryIsASoftwareEngineer : Prop | knowsFormalMethods | crackProgrammer open MaryIsASoftwareEngineer def me1 : MaryIsASoftwareEngineer := knowsFormalMethods theorem me2 : MaryIsASoftwareEngineer := crackProgrammer /- Lean implements a logic in which all proofs of a given proposition are considered to be not only equally good but actually equal. This treatment of logical values is fundamentally different from that of computational data values, where values built by different constructors are *never* equal. The principle that Lean implements here is called the principle of "proof irrelevance." To show that a proposition is true, you just have to exhibit *any* proof/value of the given proposition/type. -/ lemma m1 : me1 = me2 := eq.refl me1 theorem bad_news : 0 = 1 := _ /- Not every logical proposition or predicate is implemented as an inductive type. In particular, proofs of ∀, →, and ¬ propositions are not elementary data values functions. -/ -- more to come
20a98ee86befd050972b365df001691a12427055
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/ring_theory/subsemiring.lean
551ebc6deed1e9e1bf8934aa5af0f850d5c74b74
[ "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
32,366
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 algebra.ring.prod import group_theory.submonoid import data.equiv.ring /-! # Bundled subsemirings We define bundled subsemirings and some standard constructions: `complete_lattice` structure, `subtype` and `inclusion` ring homomorphisms, subsemiring `map`, `comap` and range (`srange`) of a `ring_hom` etc. -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [non_assoc_semiring R] [non_assoc_semiring S] [non_assoc_semiring T] (M : submonoid R) set_option old_structure_cmd true /-- A subsemiring of a semiring `R` is a subset `s` that is both a multiplicative and an additive submonoid. -/ structure subsemiring (R : Type u) [non_assoc_semiring R] extends submonoid R, add_submonoid R /-- Reinterpret a `subsemiring` as a `submonoid`. -/ add_decl_doc subsemiring.to_submonoid /-- Reinterpret a `subsemiring` as an `add_submonoid`. -/ add_decl_doc subsemiring.to_add_submonoid namespace subsemiring instance : set_like (subsemiring R) R := ⟨subsemiring.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {s : subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two subsemirings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a subsemiring with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : subsemiring R := { carrier := s, ..S.to_add_submonoid.copy s hs, ..S.to_submonoid.copy s hs } lemma to_submonoid_injective : function.injective (to_submonoid : subsemiring R → submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subsemiring R → submonoid R) := λ _ _, id @[mono] lemma to_submonoid_mono : monotone (to_submonoid : subsemiring R → submonoid R) := to_submonoid_strict_mono.monotone lemma to_add_submonoid_injective : function.injective (to_add_submonoid : subsemiring R → add_submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : subsemiring R → add_submonoid R) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : subsemiring R → add_submonoid R) := to_add_submonoid_strict_mono.monotone /-- Construct a `subsemiring R` from a set `s`, a submonoid `sm`, and an additive submonoid `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (hm : ↑sm = s) (sa : add_submonoid R) (ha : ↑sa = s) : subsemiring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) : (subsemiring.mk' s sm hm sa ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) {x : R} : x ∈ subsemiring.mk' s sm hm sa ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) : (subsemiring.mk' s sm hm sa ha).to_submonoid = sm := set_like.coe_injective hm.symm @[simp] lemma mk'_to_add_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa =s) : (subsemiring.mk' s sm hm sa ha).to_add_submonoid = sa := set_like.coe_injective ha.symm end subsemiring namespace subsemiring variables (s : subsemiring R) /-- A subsemiring contains the semiring's 1. -/ theorem one_mem : (1 : R) ∈ s := s.one_mem' /-- A subsemiring contains the semiring's 0. -/ theorem zero_mem : (0 : R) ∈ s := s.zero_mem' /-- A subsemiring is closed under multiplication. -/ theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem' /-- A subsemiring is closed under addition. -/ theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem' /-- Product of a list of elements in a `subsemiring` is in the `subsemiring`. -/ lemma list_prod_mem {R : Type*} [semiring R] (s : subsemiring R) {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := s.to_submonoid.list_prod_mem /-- Sum of a list of elements in a `subsemiring` is in the `subsemiring`. -/ lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := s.to_add_submonoid.list_sum_mem /-- Product of a multiset of elements in a `subsemiring` of a `comm_semiring` is in the `subsemiring`. -/ lemma multiset_prod_mem {R} [comm_semiring R] (s : subsemiring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := s.to_submonoid.multiset_prod_mem m /-- Sum of a multiset of elements in a `subsemiring` of a `semiring` is in the `add_subsemiring`. -/ lemma multiset_sum_mem (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := s.to_add_submonoid.multiset_sum_mem m /-- Product of elements of a subsemiring of a `comm_semiring` indexed by a `finset` is in the subsemiring. -/ lemma prod_mem {R : Type*} [comm_semiring R] (s : subsemiring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := s.to_submonoid.prod_mem h /-- Sum of elements in an `subsemiring` of an `semiring` indexed by a `finset` is in the `add_subsemiring`. -/ lemma sum_mem (s : subsemiring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := s.to_add_submonoid.sum_mem h lemma pow_mem {R : Type*} [semiring R] (s : subsemiring R) {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n lemma nsmul_mem {x : R} (hx : x ∈ s) (n : ℕ) : n • x ∈ s := s.to_add_submonoid.nsmul_mem hx n lemma coe_nat_mem (n : ℕ) : (n : R) ∈ s := by simp only [← nsmul_one, nsmul_mem, one_mem] /-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/ instance to_non_assoc_semiring : non_assoc_semiring s := { mul_zero := λ x, subtype.eq $ mul_zero x, zero_mul := λ x, subtype.eq $ zero_mul x, right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, .. s.to_submonoid.to_mul_one_class, .. s.to_add_submonoid.to_add_comm_monoid } @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = (1 : R) := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl @[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl instance nontrivial [nontrivial R] : nontrivial s := nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H) instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h, or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h) (λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) } /-- A subsemiring of a `semiring` is a `semiring`. -/ instance to_semiring {R} [semiring R] (s : subsemiring R) : semiring s := { ..s.to_non_assoc_semiring, ..s.to_submonoid.to_monoid } @[simp, norm_cast] lemma coe_pow {R} [semiring R] (s : subsemiring R) (x : s) (n : ℕ) : ((x^n : s) : R) = (x^n : R) := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end /-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/ instance to_comm_semiring {R} [comm_semiring R] (s : subsemiring R) : comm_semiring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..s.to_semiring} /-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/ def subtype : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_submonoid.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl /-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/ instance to_ordered_semiring {R} [ordered_semiring R] (s : subsemiring R) : ordered_semiring s := subtype.coe_injective.ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/ instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] (s : subsemiring R) : ordered_comm_semiring s := subtype.coe_injective.ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/ instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] (s : subsemiring R) : linear_ordered_semiring s := subtype.coe_injective.linear_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) /-! Note: currently, there is no `linear_ordered_comm_semiring`. -/ @[simp] lemma mem_to_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subsemiring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_submonoid (s : subsemiring R) : (s.to_add_submonoid : set R) = s := rfl /-- The subsemiring `R` of the semiring `R`. -/ instance : has_top (subsemiring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_submonoid R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subsemiring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subsemiring R) : set R) = set.univ := rfl /-- The preimage of a subsemiring along a ring homomorphism is a subsemiring. -/ def comap (f : R →+* S) (s : subsemiring S) : subsemiring R := { carrier := f ⁻¹' s, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_submonoid.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subsemiring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subsemiring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subsemiring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-- The image of a subsemiring along a ring homomorphism is a subsemiring. -/ def map (f : R →+* S) (s : subsemiring R) : subsemiring S := { carrier := f '' s, .. s.to_submonoid.map (f : R →* S), .. s.to_add_submonoid.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subsemiring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subsemiring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subsemiring R} {t : subsemiring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap /-- A subsemiring is isomorphic to its image under an injective function -/ noncomputable def equiv_map_of_injective (f : R →+* S) (hf : function.injective f) : s ≃+* s.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), map_add' := λ _ _, subtype.ext (f.map_add _ _), ..equiv.set.image f s hf } @[simp] lemma coe_equiv_map_of_injective_apply (f : R →+* S) (hf : function.injective f) (x : s) : (equiv_map_of_injective s f hf x : S) = f x := rfl end subsemiring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-- The range of a ring homomorphism is a subsemiring. See Note [range copy pattern]. -/ def srange : subsemiring S := ((⊤ : subsemiring R).map f).copy (set.range f) set.image_univ.symm @[simp] lemma coe_srange : (f.srange : set S) = set.range f := rfl @[simp] lemma mem_srange {f : R →+* S} {y : S} : y ∈ f.srange ↔ ∃ x, f x = y := iff.rfl lemma srange_eq_map (f : R →+* S) : f.srange = (⊤ : subsemiring R).map f := by { ext, simp } lemma mem_srange_self (f : R →+* S) (x : R) : f x ∈ f.srange := mem_srange.mpr ⟨x, rfl⟩ lemma map_srange : f.srange.map g = (g.comp f).srange := by simpa only [srange_eq_map] using (⊤ : subsemiring R).map_map g f /-- The range of a morphism of semirings is a fintype, if the domain is a fintype. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype S`.-/ instance fintype_srange [fintype R] [decidable_eq S] (f : R →+* S) : fintype (srange f) := set.fintype_range f end ring_hom namespace subsemiring instance : has_bot (subsemiring R) := ⟨(nat.cast_ring_hom R).srange⟩ instance : inhabited (subsemiring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subsemiring R) : set R) = set.range (coe : ℕ → R) := (nat.cast_ring_hom R).coe_srange lemma mem_bot {x : R} : x ∈ (⊥ : subsemiring R) ↔ ∃ n : ℕ, ↑n=x := ring_hom.mem_srange /-- The inf of two subsemirings is their intersection. -/ instance : has_inf (subsemiring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩ @[simp] lemma coe_inf (p p' : subsemiring R) : ((p ⊓ p' : subsemiring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subsemiring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subsemiring R) := ⟨λ s, subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subsemiring.to_submonoid t) (by simp) (⨅ t ∈ s, subsemiring.to_add_submonoid t) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subsemiring R)) : ((Inf S : subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[simp] lemma Inf_to_submonoid (s : set (subsemiring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subsemiring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_submonoid (s : set (subsemiring R)) : (Inf s).to_add_submonoid = ⨅ t ∈ s, subsemiring.to_add_submonoid t := mk'_to_add_submonoid _ _ /-- Subsemirings of a semiring form a complete lattice. -/ instance : complete_lattice (subsemiring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_nat_mem n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subsemiring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)} lemma eq_top_iff' (A : subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ /-- The `subsemiring` generated by a set. -/ def closure (s : set R) : subsemiring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subsemiring R, s ⊆ S → x ∈ S := mem_Inf /-- The subsemiring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx /-- A subsemiring `S` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subsemiring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ lemma mem_map_equiv {f : R ≃+* S} {K : subsemiring R} {x : S} : x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subsemiring R) : K.map (f : R →+* S) = K.comap f.symm := set_like.coe_injective (f.to_equiv.image_eq_preimage K) lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subsemiring S) : K.comap (f : R →+* S) = K.map f.symm := (map_equiv_eq_comap_symm f.symm K).symm end subsemiring namespace submonoid /-- The additive closure of a submonoid is a subsemiring. -/ def subsemiring_closure (M : submonoid R) : subsemiring R := { one_mem' := add_submonoid.mem_closure.mpr (λ y hy, hy M.one_mem), mul_mem' := λ x y, M.mul_mem_add_closure, ..add_submonoid.closure (M : set R)} lemma subsemiring_closure_coe : (M.subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl lemma subsemiring_closure_to_add_submonoid : M.subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl /-- The `subsemiring` generated by a multiplicative submonoid coincides with the `subsemiring.closure` of the submonoid itself . -/ lemma subsemiring_closure_eq_closure : M.subsemiring_closure = subsemiring.closure (M : set R) := begin ext, refine ⟨λ hx, _, λ hx, (subsemiring.mem_closure.mp hx) M.subsemiring_closure (λ s sM, _)⟩; rintros - ⟨H1, rfl⟩; rintros - ⟨H2, rfl⟩, { exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 }, { exact H2 sM } end end submonoid namespace subsemiring @[simp] lemma closure_submonoid_closure (s : set R) : closure ↑(submonoid.closure s) = closure s := le_antisymm (closure_le.mpr (λ y hy, (submonoid.mem_closure.mp hy) (closure s).to_submonoid subset_closure)) (closure_mono (submonoid.subset_closure)) /-- The elements of the subsemiring closure of `M` are exactly the elements of the additive closure of a multiplicative submonoid `M`. -/ lemma coe_closure_eq (s : set R) : (closure s : set R) = add_submonoid.closure (submonoid.closure s : set R) := by simp [← submonoid.subsemiring_closure_to_add_submonoid, submonoid.subsemiring_closure_eq_closure] lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_submonoid.closure (submonoid.closure s : set R) := set.ext_iff.mp (coe_closure_eq s) x @[simp] lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s := begin ext x, refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩, rintros - ⟨H, rfl⟩, rintros - ⟨J, rfl⟩, refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _), refine (submonoid.mem_closure.mp hy) H.to_submonoid (λ z hz, _), exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw), end /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd⟩).2 Hs h lemma mem_closure_iff_exists_list {R} [semiring R] {s : set R} {x} : x ∈ closure s ↔ ∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s) ∧ (L.map list.prod).sum = x := ⟨λ hx, add_submonoid.closure_induction (mem_closure_iff.1 hx) (λ x hx, suffices ∃ t : list R, (∀ y ∈ t, y ∈ s) ∧ t.prod = x, from let ⟨t, ht1, ht2⟩ := this in ⟨[t], list.forall_mem_singleton.2 ht1, by rw [list.map_singleton, list.sum_singleton, ht2]⟩, submonoid.closure_induction hx (λ x hx, ⟨[x], list.forall_mem_singleton.2 hx, one_mul x⟩) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x y ⟨t, ht1, ht2⟩ ⟨u, hu1, hu2⟩, ⟨t ++ u, list.forall_mem_append.2 ⟨ht1, hu1⟩, by rw [list.prod_append, ht2, hu2]⟩)) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x y ⟨L, HL1, HL2⟩ ⟨M, HM1, HM2⟩, ⟨L ++ M, list.forall_mem_append.2 ⟨HL1, HM1⟩, by rw [list.map_append, list.sum_append, HL2, HM2]⟩), λ ⟨L, HL1, HL2⟩, HL2 ▸ list_sum_mem _ (λ r hr, let ⟨t, ht1, ht2⟩ := list.mem_map.1 hr in ht2 ▸ list_prod_mem _ (λ y hy, subset_closure $ HL1 t ht1 y hy))⟩ variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subsemiring `S` equals `S`. -/ lemma closure_eq (s : subsemiring R) : closure (s : set R) = s := (subsemiring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subsemiring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subsemiring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subsemiring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subsemiring.gi R).gc.l_Sup lemma map_sup (s t : subsemiring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subsemiring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subsemiring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subsemiring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subsemiring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subsemiring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t` as a subsemiring of `R × S`. -/ def prod (s : subsemiring R) (t : subsemiring S) : subsemiring (R × S) := { carrier := (s : set R).prod t, .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_submonoid.prod t.to_add_submonoid} @[norm_cast] lemma coe_prod (s : subsemiring R) (t : subsemiring S) : (s.prod t : set (R × S)) = (s : set R).prod (t : set S) := rfl lemma mem_prod {s : subsemiring R} {t : subsemiring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subsemiring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subsemiring R) : monotone (λ t : subsemiring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subsemiring S) : monotone (λ s : subsemiring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subsemiring R) : s.prod (⊤ : subsemiring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subsemiring S) : (⊤ : subsemiring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subsemiring R).prod (⊤ : subsemiring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subsemirings is isomorphic to their product as monoids. -/ def prod_equiv (s : subsemiring R) (t : subsemiring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, let U : subsemiring R := subsemiring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) : ((⨆ i, S i : subsemiring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subsemiring namespace ring_hom variables [non_assoc_semiring T] {s : subsemiring R} open subsemiring /-- Restriction of a ring homomorphism to a subsemiring of the domain. -/ def srestrict (f : R →+* S) (s : subsemiring R) : s →+* S := f.comp s.subtype @[simp] lemma srestrict_apply (f : R →+* S) (x : s) : f.srestrict s x = f x := rfl /-- Restriction of a ring homomorphism to a subsemiring of the codomain. -/ def cod_srestrict (f : R →+* S) (s : subsemiring S) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ n, ⟨f n, h n⟩, .. (f : R →* S).cod_mrestrict s.to_submonoid h, .. (f : R →+ S).cod_mrestrict s.to_add_submonoid h } /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. This is the bundled version of `set.range_factorization`. -/ def srange_restrict (f : R →+* S) : R →+* f.srange := f.cod_srestrict f.srange f.mem_srange_self @[simp] lemma coe_srange_restrict (f : R →+* S) (x : R) : (f.srange_restrict x : S) = f x := rfl lemma srange_restrict_surjective (f : R →+* S) : function.surjective f.srange_restrict := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩ lemma srange_top_iff_surjective {f : R →+* S} : f.srange = (⊤ : subsemiring S) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma srange_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.srange = (⊤ : subsemiring S) := srange_top_iff_surjective.2 hf /-- The subsemiring of elements `x : R` such that `f x = g x` -/ def eq_slocus (f g : R →+* S) : subsemiring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_mlocus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subsemiring closure. -/ lemma eq_on_sclosure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_slocus g, from closure_le.2 h lemma eq_of_eq_on_stop {f g : R →+* S} (h : set.eq_on f g (⊤ : subsemiring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h lemma sclosure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subsemiring generated by a set equals the subsemiring generated by the image of the set. -/ lemma map_sclosure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (sclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subsemiring open ring_hom /-- The ring homomorphism associated to an inclusion of subsemirings. -/ def inclusion {S T : subsemiring R} (h : S ≤ T) : S →* T := S.subtype.cod_srestrict _ (λ x, h x.2) @[simp] lemma srange_subtype (s : subsemiring R) : s.subtype.srange = s := set_like.coe_injective $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subsemiring R) (t : subsemiring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩) end subsemiring namespace ring_equiv variables {s t : subsemiring R} /-- Makes the identity isomorphism from a proof two subsemirings of a multiplicative monoid are equal. -/ def subsemiring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its `ring_hom.srange`. -/ def sof_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) : R ≃+* f.srange := { to_fun := λ x, f.srange_restrict x, inv_fun := λ x, (g ∘ f.srange.subtype) x, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := ring_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.srange_restrict } @[simp] lemma sof_left_inverse_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) : ↑(sof_left_inverse h x) = f x := rfl @[simp] lemma sof_left_inverse_symm_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.srange) : (sof_left_inverse h).symm x = g x := rfl end ring_equiv /-! ### Actions by `subsemiring`s These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`. The only new result is `subsemiring.module`. When `R` is commutative, `algebra.of_subsemiring` provides a stronger result than those found in this file, which uses the same scalar action. -/ section actions namespace subsemiring variables {R' α β : Type*} [semiring R'] /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [mul_action R' α] (S : subsemiring R') : mul_action S α := S.to_submonoid.mul_action lemma smul_def [mul_action R' α] {S : subsemiring R'} (g : S) (m : α) : g • m = (g : R') • m := rfl instance smul_comm_class_left [mul_action R' β] [has_scalar α β] [smul_comm_class R' α β] (S : subsemiring R') : smul_comm_class S α β := S.to_submonoid.smul_comm_class_left instance smul_comm_class_right [has_scalar α β] [mul_action R' β] [smul_comm_class α R' β] (S : subsemiring R') : smul_comm_class α S β := S.to_submonoid.smul_comm_class_right /-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/ instance [has_scalar α β] [mul_action R' α] [mul_action R' β] [is_scalar_tower R' α β] (S : subsemiring R') : is_scalar_tower S α β := S.to_submonoid.is_scalar_tower instance [mul_action R' α] [has_faithful_scalar R' α] (S : subsemiring R') : has_faithful_scalar S α := S.to_submonoid.has_faithful_scalar /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [add_monoid α] [distrib_mul_action R' α] (S : subsemiring R') : distrib_mul_action S α := S.to_submonoid.distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [add_comm_monoid α] [module R' α] (S : subsemiring R') : module S α := { smul := (•), .. module.comp_hom _ S.subtype } end subsemiring end actions
86a9f8ab41f9cf8105ffc051193b9ec914b99395
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/local_properties.lean
55d84571f12dffa67295b186d52200bd097c3ccd
[ "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
23,552
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import group_theory.submonoid.pointwise import logic.equiv.transfer_instance import ring_theory.finiteness import ring_theory.localization.at_prime import ring_theory.localization.away import ring_theory.localization.integer import ring_theory.localization.submodule import ring_theory.nilpotent /-! # Local properties of commutative rings In this file, we provide the proofs of various local properties. ## Naming Conventions * `localization_P` : `P` holds for `S⁻¹R` if `P` holds for `R`. * `P_of_localization_maximal` : `P` holds for `R` if `P` holds for `Aₘ` for all maximal `m`. * `P_of_localization_span` : `P` holds for `R` if given a spanning set `{fᵢ}`, `P` holds for all `A_{fᵢ}`. ## Main results The following properties are covered: * The triviality of an ideal or an element: `ideal_eq_zero_of_localization`, `eq_zero_of_localization` * `is_reduced` : `localization_is_reduced`, `is_reduced_of_localization_maximal`. * `finite`: `localization_finite`, `finite_of_localization_span` * `finite_type`: `localization_finite_type`, `finite_type_of_localization_span` -/ open_locale pointwise classical big_operators universe u variables {R S : Type u} [comm_ring R] [comm_ring S] (M : submonoid R) variables (N : submonoid S) (R' S' : Type u) [comm_ring R'] [comm_ring S'] (f : R →+* S) variables [algebra R R'] [algebra S S'] section properties section comm_ring variable (P : ∀ (R : Type u) [comm_ring R], Prop) include P /-- A property `P` of comm rings is said to be preserved by localization if `P` holds for `M⁻¹R` whenever `P` holds for `R`. -/ def localization_preserves : Prop := ∀ {R : Type u} [hR : comm_ring R] (M : by exactI submonoid R) (S : Type u) [hS : comm_ring S] [by exactI algebra R S] [by exactI is_localization M S], @P R hR → @P S hS /-- A property `P` of comm rings satisfies `of_localization_maximal` if if `P` holds for `R` whenever `P` holds for `Rₘ` for all maximal ideal `m`. -/ def of_localization_maximal : Prop := ∀ (R : Type u) [comm_ring R], by exactI (∀ (J : ideal R) (hJ : J.is_maximal), by exactI P (localization.at_prime J)) → P R end comm_ring section ring_hom variable (P : ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop) include P /-- A property `P` of ring homs is said to be preserved by localization if `P` holds for `M⁻¹R →+* M⁻¹S` whenever `P` holds for `R →+* S`. -/ def ring_hom.localization_preserves := ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (M : by exactI submonoid R) (R' S' : Type u) [comm_ring R'] [comm_ring S'] [by exactI algebra R R'] [by exactI algebra S S'] [by exactI is_localization M R'] [by exactI is_localization (M.map (f : R →* S)) S'], by exactI (P f → P (is_localization.map S' f (submonoid.le_comap_map M) : R' →+* S')) /-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span` if `P` holds for `R →+* S` whenever there exists a finite set `{ r }` that spans `R` such that `P` holds for `Rᵣ →+* Sᵣ`. Note that this is equivalent to `ring_hom.of_localization_span` via `ring_hom.of_localization_span_iff_finite`, but this is easier to prove. -/ def ring_hom.of_localization_finite_span := ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (s : finset R) (hs : by exactI ideal.span (s : set R) = ⊤) (H : by exactI (∀ (r : s), P (localization.away_map f r))), by exactI P f /-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span` if `P` holds for `R →+* S` whenever there exists a set `{ r }` that spans `R` such that `P` holds for `Rᵣ →+* Sᵣ`. Note that this is equivalent to `ring_hom.of_localization_finite_span` via `ring_hom.of_localization_span_iff_finite`, but this has less restrictions when applying. -/ def ring_hom.of_localization_span := ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (s : set R) (hs : by exactI ideal.span s = ⊤) (H : by exactI (∀ (r : s), P (localization.away_map f r))), by exactI P f lemma ring_hom.of_localization_span_iff_finite : ring_hom.of_localization_span @P ↔ ring_hom.of_localization_finite_span @P := begin delta ring_hom.of_localization_span ring_hom.of_localization_finite_span, apply forall₅_congr, -- TODO: Using `refine` here breaks `resetI`. introsI, split, { intros h s, exact h s }, { intros h s hs hs', obtain ⟨s', h₁, h₂⟩ := (ideal.span_eq_top_iff_finite s).mp hs, exact h s' h₂ (λ x, hs' ⟨_, h₁ x.prop⟩) } end variables {P f R' S'} -- Almost all arguments are implicit since this is not intended to use mid-proof. lemma ring_hom.localization_away_of_localization_preserves (H : ring_hom.localization_preserves @P) {r : R} [is_localization.away r R'] [is_localization.away (f r) S'] (hf : P f) : P (by exactI is_localization.away.map R' S' f r) := begin resetI, haveI : is_localization ((submonoid.powers r).map (f : R →* S)) S', { rw submonoid.map_powers, assumption }, exact H f (submonoid.powers r) R' S' hf, end end ring_hom end properties section ideal -- This proof should work for all modules, but we do not know how to localize a module yet. /-- An ideal is trivial if its localization at every maximal ideal is trivial. -/ lemma ideal_eq_zero_of_localization (I : ideal R) (h : ∀ (J : ideal R) (hJ : J.is_maximal), by exactI is_localization.coe_submodule (localization.at_prime J) I = 0) : I = 0 := begin by_contradiction hI, obtain ⟨x, hx, hx'⟩ := set.exists_of_ssubset (bot_lt_iff_ne_bot.mpr hI), rw [submodule.bot_coe, set.mem_singleton_iff] at hx', have H : (ideal.span ({x} : set R)).annihilator ≠ ⊤, { rw [ne.def, submodule.annihilator_eq_top_iff], by_contra, apply hx', rw [← set.mem_singleton_iff, ← @submodule.bot_coe R, ← h], exact ideal.subset_span (set.mem_singleton x) }, obtain ⟨p, hp₁, hp₂⟩ := ideal.exists_le_maximal _ H, resetI, specialize h p hp₁, have : algebra_map R (localization.at_prime p) x = 0, { rw ← set.mem_singleton_iff, change algebra_map R (localization.at_prime p) x ∈ (0 : submodule R (localization.at_prime p)), rw ← h, exact submodule.mem_map_of_mem hx }, rw is_localization.map_eq_zero_iff p.prime_compl at this, obtain ⟨m, hm⟩ := this, apply m.prop, refine hp₂ _, erw submodule.mem_annihilator_span_singleton, rwa mul_comm at hm, end lemma eq_zero_of_localization (r : R) (h : ∀ (J : ideal R) (hJ : J.is_maximal), by exactI algebra_map R (localization.at_prime J) r = 0) : r = 0 := begin rw ← ideal.span_singleton_eq_bot, apply ideal_eq_zero_of_localization, intros J hJ, delta is_localization.coe_submodule, erw [submodule.map_span, submodule.span_eq_bot], rintro _ ⟨_, h', rfl⟩, cases set.mem_singleton_iff.mpr h', exact h J hJ, end end ideal section reduced lemma localization_is_reduced : localization_preserves (λ R hR, by exactI is_reduced R) := begin introv R _ _, resetI, constructor, rintro x ⟨(_|n), e⟩, { simpa using congr_arg (*x) e }, obtain ⟨⟨y, m⟩, hx⟩ := is_localization.surj M x, dsimp only at hx, let hx' := congr_arg (^ n.succ) hx, simp only [mul_pow, e, zero_mul, ← ring_hom.map_pow] at hx', rw [← (algebra_map R S).map_zero] at hx', obtain ⟨m', hm'⟩ := (is_localization.eq_iff_exists M S).mp hx', apply_fun (*m'^n) at hm', simp only [mul_assoc, zero_mul] at hm', rw [mul_comm, ← pow_succ, ← mul_pow] at hm', replace hm' := is_nilpotent.eq_zero ⟨_, hm'.symm⟩, rw [← (is_localization.map_units S m).mul_left_inj, hx, zero_mul, is_localization.map_eq_zero_iff M], exact ⟨m', by rw [← hm', mul_comm]⟩ end instance [is_reduced R] : is_reduced (localization M) := localization_is_reduced M _ infer_instance lemma is_reduced_of_localization_maximal : of_localization_maximal (λ R hR, by exactI is_reduced R) := begin introv R h, constructor, intros x hx, apply eq_zero_of_localization, intros J hJ, specialize h J hJ, resetI, exact (hx.map $ algebra_map R $ localization.at_prime J).eq_zero, end end reduced section finite /-- If `S` is a finite `R`-algebra, then `S' = M⁻¹S` is a finite `R' = M⁻¹R`-algebra. -/ lemma localization_finite : ring_hom.localization_preserves @ring_hom.finite := begin introv R hf, -- Setting up the `algebra` and `is_scalar_tower` instances needed classical, letI := f.to_algebra, letI := ((algebra_map S S').comp f).to_algebra, let f' : R' →+* S' := is_localization.map S' f (submonoid.le_comap_map M), letI := f'.to_algebra, haveI : is_scalar_tower R R' S' := is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm, let fₐ : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, ring_hom.map_mul _ _ _), -- We claim that if `S` is generated by `T` as an `R`-module, -- then `S'` is generated by `T` as an `R'`-module. unfreezingI { obtain ⟨T, hT⟩ := hf }, use T.image (algebra_map S S'), rw eq_top_iff, rintro x -, -- By the hypotheses, for each `x : S'`, we have `x = y / (f r)` for some `y : S` and `r : M`. -- Since `S` is generated by `T`, the image of `y` should fall in the span of the image of `T`. obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ := is_localization.mk'_surjective (M.map (f : R →* S)) x, rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, finset.coe_image], have hy : y ∈ submodule.span R ↑T, by { rw hT, trivial }, replace hy : algebra_map S S' y ∈ submodule.map fₐ.to_linear_map (submodule.span R T) := submodule.mem_map_of_mem hy, rw submodule.map_span fₐ.to_linear_map T at hy, have H : submodule.span R ((algebra_map S S') '' T) ≤ (submodule.span R' ((algebra_map S S') '' T)).restrict_scalars R, { rw submodule.span_le, exact submodule.subset_span }, -- Now, since `y ∈ span T`, and `(f r)⁻¹ ∈ R'`, `x / (f r)` is in `span T` as well. convert (submodule.span R' ((algebra_map S S') '' T)).smul_mem (is_localization.mk' R' (1 : R) ⟨r, hr⟩) (H hy) using 1, rw algebra.smul_def, erw is_localization.map_mk', rw map_one, refl, end lemma localization_away_map_finite (r : R) [is_localization.away r R'] [is_localization.away (f r) S'] (hf : f.finite) : (is_localization.away.map R' S' f r).finite := ring_hom.localization_away_of_localization_preserves @localization_finite hf /-- Let `S` be an `R`-algebra, `M` an submonoid of `R`, and `S' = M⁻¹S`. If the image of some `x : S` falls in the span of some finite `s ⊆ S'` over `R`, then there exists some `m : M` such that `m • x` falls in the span of `finset_integer_multiple _ s` over `R`. -/ lemma is_localization.smul_mem_finset_integer_multiple_span [algebra R S] [algebra R S'] [is_scalar_tower R S S'] [is_localization (M.map (algebra_map R S : R →* S)) S'] (x : S) (s : finset S') (hx : algebra_map S S' x ∈ submodule.span R (s : set S')) : ∃ m : M, m • x ∈ submodule.span R (is_localization.finset_integer_multiple (M.map (algebra_map R S : R →* S)) s : set S) := begin let g : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, by simp [algebra.algebra_map_eq_smul_one]), -- We first obtain the `y' ∈ M` such that `s' = y' • s` is falls in the image of `S` in `S'`. let y := is_localization.common_denom_of_finset (M.map (algebra_map R S : R →* S)) s, have hx₁ : (y : S) • ↑s = g '' _ := (is_localization.finset_integer_multiple_image _ s).symm, obtain ⟨y', hy', e : algebra_map R S y' = y⟩ := y.prop, have : algebra_map R S y' • (s : set S') = y' • s := by simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul], rw [← e, this] at hx₁, replace hx₁ := congr_arg (submodule.span R) hx₁, rw submodule.span_smul_eq at hx₁, replace hx : _ ∈ y' • submodule.span R (s : set S') := set.smul_mem_smul_set hx, rw hx₁ at hx, erw [← g.map_smul, ← submodule.map_span (g : S →ₗ[R] S')] at hx, -- Since `x` falls in the span of `s` in `S'`, `y' • x : S` falls in the span of `s'` in `S'`. -- That is, there exists some `x' : S` in the span of `s'` in `S` and `x' = y' • x` in `S'`. -- Thus `a • (y' • x) = a • x' ∈ span s'` in `S` for some `a ∈ M`. obtain ⟨x', hx', hx'' : algebra_map _ _ _ = _⟩ := hx, obtain ⟨⟨_, a, ha₁, rfl⟩, ha₂⟩ := (is_localization.eq_iff_exists (M.map (algebra_map R S : R →* S)) S').mp hx'', use (⟨a, ha₁⟩ : M) * (⟨y', hy'⟩ : M), convert (submodule.span R (is_localization.finset_integer_multiple (submonoid.map (algebra_map R S : R →* S) M) s : set S)).smul_mem a hx' using 1, convert ha₂.symm, { rw [mul_comm (y' • x), subtype.coe_mk, submonoid.smul_def, submonoid.coe_mul, ← smul_smul], exact algebra.smul_def _ _ }, { rw mul_comm, exact algebra.smul_def _ _ } end /-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ span R' s`, then `t • x ∈ span R s` for some `t : M`.-/ lemma multiple_mem_span_of_mem_localization_span [algebra R' S] [algebra R S] [is_scalar_tower R R' S] [is_localization M R'] (s : set S) (x : S) (hx : x ∈ submodule.span R' s) : ∃ t : M, t • x ∈ submodule.span R s := begin classical, obtain ⟨s', hss', hs'⟩ := submodule.mem_span_finite_of_mem_span hx, suffices : ∃ t : M, t • x ∈ submodule.span R (s' : set S), { obtain ⟨t, ht⟩ := this, exact ⟨t, submodule.span_mono hss' ht⟩ }, clear hx hss' s, revert x, apply s'.induction_on, { intros x hx, use 1, simpa using hx }, rintros a s ha hs x hx, simp only [finset.coe_insert, finset.image_insert, finset.coe_image, subtype.coe_mk, submodule.mem_span_insert] at hx ⊢, rcases hx with ⟨y, z, hz, rfl⟩, rcases is_localization.surj M y with ⟨⟨y', s'⟩, e⟩, replace e : _ * a = _ * a := (congr_arg (λ x, algebra_map R' S x * a) e : _), simp_rw [ring_hom.map_mul, ← is_scalar_tower.algebra_map_apply, mul_comm (algebra_map R' S y), mul_assoc, ← algebra.smul_def] at e, rcases hs _ hz with ⟨t, ht⟩, refine ⟨t*s', t*y', _, (submodule.span R (s : set S)).smul_mem s' ht, _⟩, rw [smul_add, ← smul_smul, mul_comm, ← smul_smul, ← smul_smul, ← e], refl, end /-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ adjoin R' s`, then `t • x ∈ adjoin R s` for some `t : M`.-/ lemma multiple_mem_adjoin_of_mem_localization_adjoin [algebra R' S] [algebra R S] [is_scalar_tower R R' S] [is_localization M R'] (s : set S) (x : S) (hx : x ∈ algebra.adjoin R' s) : ∃ t : M, t • x ∈ algebra.adjoin R s := begin change ∃ (t : M), t • x ∈ (algebra.adjoin R s).to_submodule, change x ∈ (algebra.adjoin R' s).to_submodule at hx, simp_rw [algebra.adjoin_eq_span] at hx ⊢, exact multiple_mem_span_of_mem_localization_span M R' _ _ hx end lemma finite_of_localization_span : ring_hom.of_localization_span @ring_hom.finite := begin rw ring_hom.of_localization_span_iff_finite, introv R hs H, -- We first setup the instances classical, letI := f.to_algebra, letI := λ (r : s), (localization.away_map f r).to_algebra, haveI : ∀ r : s, is_localization ((submonoid.powers (r : R)).map (algebra_map R S : R →* S)) (localization.away (f r)), { intro r, rw submonoid.map_powers, exact localization.is_localization }, haveI : ∀ r : s, is_scalar_tower R (localization.away (r : R)) (localization.away (f r)) := λ r, is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm, -- By the hypothesis, we may find a finite generating set for each `Sᵣ`. This set can then be -- lifted into `R` by multiplying a sufficiently large power of `r`. I claim that the union of -- these generates `S`. constructor, replace H := λ r, (H r).1, choose s₁ s₂ using H, let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (f x)) (s₁ x), use s.attach.bUnion sf, rw [submodule.span_attach_bUnion, eq_top_iff], -- It suffices to show that `r ^ n • x ∈ span T` for each `r : s`, since `{ r ^ n }` spans `R`. -- This then follows from the fact that each `x : R` is a linear combination of the generating set -- of `Sᵣ`. By multiplying a sufficiently large power of `r`, we can cancel out the `r`s in the -- denominators of both the generating set and the coefficients. rintro x -, apply submodule.mem_of_span_eq_top_of_smul_pow_mem _ (s : set R) hs _ _, intro r, obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ := multiple_mem_span_of_mem_localization_span (submonoid.powers (r : R)) (localization.away (r : R)) (s₁ r : set (localization.away (f r))) (algebra_map S _ x) (by { rw s₂ r, trivial }), rw [submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R S, subtype.coe_mk, ← map_mul] at hn₁, obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.smul_mem_finset_integer_multiple_span (submonoid.powers (r : R)) (localization.away (f r)) _ (s₁ r) hn₁, rw [submonoid.smul_def, ← algebra.smul_def, smul_smul, subtype.coe_mk, ← pow_add] at hn₂, use n₂ + n₁, refine le_supr (λ (x : s), submodule.span R (sf x : set S)) r _, change _ ∈ submodule.span R ((is_localization.finset_integer_multiple _ (s₁ r) : finset S) : set S), convert hn₂, rw submonoid.map_powers, refl, end end finite section finite_type lemma localization_finite_type : ring_hom.localization_preserves @ring_hom.finite_type := begin introv R hf, -- mirrors the proof of `localization_map_finite` classical, letI := f.to_algebra, letI := ((algebra_map S S').comp f).to_algebra, let f' : R' →+* S' := is_localization.map S' f (submonoid.le_comap_map M), letI := f'.to_algebra, haveI : is_scalar_tower R R' S' := is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm, let fₐ : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, ring_hom.map_mul _ _ _), obtain ⟨T, hT⟩ := id hf, use T.image (algebra_map S S'), rw eq_top_iff, rintro x -, obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ := is_localization.mk'_surjective (M.map (f : R →* S)) x, rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, finset.coe_image], have hy : y ∈ algebra.adjoin R (T : set S), by { rw hT, trivial }, replace hy : algebra_map S S' y ∈ (algebra.adjoin R (T : set S)).map fₐ := subalgebra.mem_map.mpr ⟨_, hy, rfl⟩, rw fₐ.map_adjoin T at hy, have H : algebra.adjoin R ((algebra_map S S') '' T) ≤ (algebra.adjoin R' ((algebra_map S S') '' T)).restrict_scalars R, { rw algebra.adjoin_le_iff, exact algebra.subset_adjoin }, convert (algebra.adjoin R' ((algebra_map S S') '' T)).smul_mem (H hy) (is_localization.mk' R' (1 : R) ⟨r, hr⟩) using 1, rw algebra.smul_def, erw is_localization.map_mk', rw map_one, refl, end lemma localization_away_map_finite_type (r : R) [is_localization.away r R'] [is_localization.away (f r) S'] (hf : f.finite_type) : (is_localization.away.map R' S' f r).finite_type := ring_hom.localization_away_of_localization_preserves @localization_finite_type hf /-- Let `S` be an `R`-algebra, `M` an submonoid of `R`, and `S' = M⁻¹S`. If the image of some `x : S` falls in the adjoin of some finite `s ⊆ S'` over `R`, then there exists some `m : M` such that `m • x` falls in the adjoin of `finset_integer_multiple _ s` over `R`. -/ lemma is_localization.lift_mem_adjoin_finset_integer_multiple [algebra R S] [algebra R S'] [is_scalar_tower R S S'] [is_localization (M.map (algebra_map R S : R →* S)) S'] (x : S) (s : finset S') (hx : algebra_map S S' x ∈ algebra.adjoin R (s : set S')) : ∃ m : M, m • x ∈ algebra.adjoin R (is_localization.finset_integer_multiple (M.map (algebra_map R S : R →* S)) s : set S) := begin -- mirrors the proof of `is_localization.smul_mem_finset_integer_multiple_span` let g : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, by simp [algebra.algebra_map_eq_smul_one]), let y := is_localization.common_denom_of_finset (M.map (algebra_map R S : R →* S)) s, have hx₁ : (y : S) • ↑s = g '' _ := (is_localization.finset_integer_multiple_image _ s).symm, obtain ⟨y', hy', e : algebra_map R S y' = y⟩ := y.prop, have : algebra_map R S y' • (s : set S') = y' • s := by simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul], rw [← e, this] at hx₁, replace hx₁ := congr_arg (algebra.adjoin R) hx₁, obtain ⟨n, hn⟩ := algebra.pow_smul_mem_adjoin_smul _ y' (s : set S') hx, specialize hn n (le_of_eq rfl), erw [hx₁, ← g.map_smul, ← g.map_adjoin] at hn, obtain ⟨x', hx', hx''⟩ := hn, obtain ⟨⟨_, a, ha₁, rfl⟩, ha₂⟩ := (is_localization.eq_iff_exists (M.map (algebra_map R S : R →* S)) S').mp hx'', use (⟨a, ha₁⟩ : M) * (⟨y', hy'⟩ : M) ^ n, convert (algebra.adjoin R (is_localization.finset_integer_multiple (submonoid.map (algebra_map R S : R →* S) M) s : set S)).smul_mem hx' a using 1, convert ha₂.symm, { rw [mul_comm (y' ^ n • x), subtype.coe_mk, submonoid.smul_def, submonoid.coe_mul, ← smul_smul, algebra.smul_def, submonoid_class.coe_pow], refl }, { rw mul_comm, exact algebra.smul_def _ _ } end lemma finite_type_of_localization_span : ring_hom.of_localization_span @ring_hom.finite_type := begin rw ring_hom.of_localization_span_iff_finite, introv R hs H, -- mirrors the proof of `finite_of_localization_span` classical, letI := f.to_algebra, letI := λ (r : s), (localization.away_map f r).to_algebra, haveI : ∀ r : s, is_localization ((submonoid.powers (r : R)).map (algebra_map R S : R →* S)) (localization.away (f r)), { intro r, rw submonoid.map_powers, exact localization.is_localization }, haveI : ∀ r : s, is_scalar_tower R (localization.away (r : R)) (localization.away (f r)) := λ r, is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm, constructor, replace H := λ r, (H r).1, choose s₁ s₂ using H, let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (f x)) (s₁ x), use s.attach.bUnion sf, convert (algebra.adjoin_attach_bUnion sf).trans _, rw eq_top_iff, rintro x -, apply (⨆ (x : s), algebra.adjoin R (sf x : set S)).to_submodule .mem_of_span_eq_top_of_smul_pow_mem _ hs _ _, intro r, obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ := multiple_mem_adjoin_of_mem_localization_adjoin (submonoid.powers (r : R)) (localization.away (r : R)) (s₁ r : set (localization.away (f r))) (algebra_map S (localization.away (f r)) x) (by { rw s₂ r, trivial }), rw [submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R S, subtype.coe_mk, ← map_mul] at hn₁, obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.lift_mem_adjoin_finset_integer_multiple (submonoid.powers (r : R)) (localization.away (f r)) _ (s₁ r) hn₁, rw [submonoid.smul_def, ← algebra.smul_def, smul_smul, subtype.coe_mk, ← pow_add] at hn₂, use n₂ + n₁, refine le_supr (λ (x : s), algebra.adjoin R (sf x : set S)) r _, change _ ∈ algebra.adjoin R ((is_localization.finset_integer_multiple _ (s₁ r) : finset S) : set S), convert hn₂, rw submonoid.map_powers, refl, end end finite_type
7b95f5be28ad6131c99b5721c0a1bacf28c19896
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/simpInv.lean
61f8dc9082deef8e75b60222b9ee4c0f67ad86c8
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
391
lean
constant g (x y : Nat) : Nat constant f (x y : Nat) : Nat axiom f_def (x y : Nat) : f x y = g x y axiom f_ax (x : Nat) : f x x = x theorem ex1 (x : Nat) : g x x = x := by simp [← f_def, f_ax] constant p (x y : Nat) : Prop constant q (x y : Nat) : Prop axiom p_def (x y : Nat) : p x y ↔ q x y axiom p_ax (x : Nat) : p x x theorem ex2 (x : Nat) : q x x := by simp [← p_def, p_ax]
235b93b88581fef6d3664eb5a2b3be732ec960bd
367134ba5a65885e863bdc4507601606690974c1
/src/data/hash_map.lean
71b9ddd75660d478cee72d337aba17b2b11634f7
[ "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
29,705
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, Mario Carneiro -/ import data.pnat.basic import data.list.range import data.array.lemmas import algebra.group import data.sigma.basic /-! # Hash maps Defines a hash map data structure, representing a finite key-value map with a value type that may depend on the key type. The structure requires a `nat`-valued hash function to associate keys to buckets. ## Main definitions * `hash_map`: constructed with `mk_hash_map`. ## Implementation details A hash map with key type `α` and (dependent) value type `β : α → Type*` consists of an array of *buckets*, which are lists containing key/value pairs for that bucket. The hash function is taken modulo `n` to assign keys to their respective bucket. Because of this, some care should be put into the hash function to ensure it evenly distributes keys. The bucket array is an `array`. These have special VM support for in-place modification if there is only ever one reference to them. If one takes special care to never keep references to old versions of a hash map alive after updating it, then the hash map will be modified in-place. In this documentation, when we say a hash map is modified in-place, we are assuming the API is being used in this manner. When inserting (`hash_map.insert`), if the number of stored pairs (the *size*) is going to exceed the number of buckets, then a new hash map is first created with double the number of buckets and everything in the old hash map is reinserted along with the new key/value pair. Otherwise, the bucket array is modified in-place. The amortized running time of inserting $$n$$ elements into a hash map is $$O(n)$$. When removing (`hash_map.erase`), the hash map is modified in-place. The implementation does not reduce the number of buckets in the hash map if the size gets too low. ## Tags hash map -/ universes u v w /-- `bucket_array α β` is the underlying data type for `hash_map α β`, an array of linked lists of key-value pairs. -/ def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) := array n (list Σ a, β a) /-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/ def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n := ⟨i % n, nat.mod_lt _ n.2⟩ namespace bucket_array section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) variables {n : ℕ+} (data : bucket_array α β n) instance : inhabited (bucket_array α β n) := ⟨mk_array _ []⟩ /-- Read the bucket corresponding to an element -/ def read (a : α) : list Σ a, β a := let bidx := hash_map.mk_idx n (hash_fn a) in data.read bidx /-- Write the bucket corresponding to an element -/ def write (a : α) (l : list Σ a, β a) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in data.write bidx l /-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/ def modify (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in array.write data bidx (f (array.read data bidx)) /-- The list of all key-value pairs in the bucket list -/ def as_list : list Σ a, β a := data.to_list.join theorem mem_as_list {a : Σ a, β a} : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i := have (∃ (l : list (Σ (a : α), β a)) (i : fin (n.val)), a ∈ l ∧ array.read data i = l) ↔ ∃ (i : fin (n.val)), a ∈ array.read data i, by rw exists_swap; exact exists_congr (λ i, by simp), by simp [as_list]; simpa [array.mem.def, and_comm] /-- Fold a function `f` over the key-value pairs in the bucket list -/ def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ := data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d) theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d := by rw [foldl, as_list, list.foldl_join, ← array.to_list_foldl] end end bucket_array namespace hash_map section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) /-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array (without checking for duplication) -/ def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n := data.modify hash_fn a (λl, ⟨a, b⟩ :: l) theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n [] : bucket_array α β n) = [] := list.eq_nil_iff_forall_not_mem.mpr $ λ x m, let ⟨i, h⟩ := (bucket_array.mem_as_list _).1 m in h parameter [decidable_eq α] /-- Search a bucket for a key `a` and return the value -/ def find_aux (a : α) : list (Σ a, β a) → option (β a) | [] := none | (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t theorem find_aux_iff {a : α} {b : β a} : Π {l : list Σ a, β a}, (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l) | [] nd := ⟨λn, by injection n, false.elim⟩ | (⟨a',b'⟩::t) nd := begin by_cases a' = a, { clear find_aux_iff, subst h, suffices : b' = b ↔ b' = b ∨ sigma.mk a' b ∈ t, {simpa [find_aux, eq_comm]}, refine (or_iff_left_of_imp (λ m, _)).symm, have : a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd, exact this.elim (list.mem_map_of_mem sigma.fst m) }, { have : sigma.mk a b ≠ ⟨a', b'⟩, { intro e, injection e with e, exact h e.symm }, simp at nd, simp [find_aux, h, ne.symm h, find_aux_iff, nd] } end /-- Returns `tt` if the bucket `l` contains the key `a` -/ def contains_aux (a : α) (l : list Σ a, β a) : bool := (find_aux a l).is_some theorem contains_aux_iff {a : α} {l : list Σ a, β a} (nd : (l.map sigma.fst).nodup) : contains_aux a l ↔ a ∈ l.map sigma.fst := begin unfold contains_aux, cases h : find_aux a l with b; simp, { assume (b : β a) (m : sigma.mk a b ∈ l), rw (find_aux_iff nd).2 m at h, contradiction }, { show ∃ (b : β a), sigma.mk a b ∈ l, exact ⟨_, (find_aux_iff nd).1 h⟩ }, end /-- Modify a bucket to replace a value in the list. Leaves the list unchanged if the key is not found. -/ def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t /-- Modify a bucket to remove a key, if it exists. -/ def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t /-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map` invariants: There are exactly `sz` elements in it, every pair is in the bucket determined by its key and the hash function, and no key appears multiple times in the list. -/ structure valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop := (len : bkts.as_list.length = sz) (idx : ∀ {i} {a : Σ a, β a}, a ∈ array.read bkts i → mk_idx n (hash_fn a.1) = i) (nodup : ∀i, ((array.read bkts i).map sigma.fst).nodup) theorem valid.idx_enum {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : ∃ h, mk_idx n (hash_fn a) = ⟨i, h⟩ := (array.mem_to_list_enum.mp he).imp (λ h e, by subst e; exact v.idx hl) theorem valid.idx_enum_1 {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : (mk_idx n (hash_fn a)).1 = i := let ⟨h, e⟩ := v.idx_enum _ he hl in by rw e; refl theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : (bkts.as_list.map sigma.fst).nodup := begin suffices : (bkts.to_list.map (list.map sigma.fst)).pairwise list.disjoint, { suffices : ∀ l, array.mem l bkts → (l.map sigma.fst).nodup, by simpa [bucket_array.as_list, list.nodup_join, *], rintros l ⟨i, rfl⟩, apply v.nodup }, rw [← list.enum_map_snd bkts.to_list, list.pairwise_map, list.pairwise_map], have : (bkts.to_list.enum.map prod.fst).nodup := by simp [list.nodup_range], refine list.pairwise.imp_of_mem _ ((list.pairwise_map _).1 this), rw prod.forall, intros i l₁, rw prod.forall, intros j l₂ me₁ me₂ ij, simp [list.disjoint], intros a b ml₁ b' ml₂, apply ij, rwa [← v.idx_enum_1 _ me₁ ml₁, ← v.idx_enum_1 _ me₂ ml₂] end theorem mk_valid (n : ℕ+) : @valid n (mk_array n []) 0 := ⟨by simp [mk_as_list], λ i a h, by cases h, λ i, list.nodup_nil⟩ theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {a : α} {b : β a} : find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list := (find_aux_iff (v.nodup _)).trans $ by rw bkts.mem_as_list; exact ⟨λ h, ⟨_, h⟩, λ ⟨i, h⟩, (v.idx h).symm ▸ h⟩ theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) : contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst := by simp [contains_aux, option.is_some_iff_exists, v.find_aux_iff hash_fn] section parameters {n : ℕ+} {bkts : bucket_array α β n} {bidx : fin n} {f : list (Σ a, β a) → list (Σ a, β a)} (u v1 v2 w : list Σ a, β a) local notation `L` := array.read bkts bidx private def bkts' : bucket_array α β n := array.write bkts bidx (f L) variables (hl : L = u ++ v1 ++ w) (hfl : f L = u ++ v2 ++ w) include hl hfl theorem append_of_modify : ∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' := begin unfold bucket_array.as_list, have h : (bidx : ℕ) < bkts.to_list.length, { simp only [bidx.is_lt, array.to_list_length] }, refine ⟨(bkts.to_list.take bidx).join ++ u, w ++ (bkts.to_list.drop (bidx+1)).join, _, _⟩, { conv { to_lhs, rw [← list.take_append_drop bidx bkts.to_list, list.drop_eq_nth_le_cons h], simp [hl] }, simp }, { conv { to_lhs, rw [bkts', array.write_to_list, list.update_nth_eq_take_cons_drop _ h], simp [hfl] }, simp } end variables (hvnd : (v2.map sigma.fst).nodup) (hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx) (djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst)) (djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst)) include hvnd hal djuv djwv theorem valid.modify {sz : ℕ} (v : valid bkts sz) : v1.length ≤ sz + v2.length ∧ valid bkts' (sz + v2.length - v1.length) := begin rcases append_of_modify u v1 v2 w hl hfl with ⟨u', w', e₁, e₂⟩, rw [← v.len, e₁], suffices : valid bkts' (u' ++ v2 ++ w').length, { simpa [ge, add_comm, add_left_comm, nat.le_add_right, nat.add_sub_cancel_left] }, refine ⟨congr_arg _ e₂, λ i a, _, λ i, _⟩, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.idx _ _ _ v bidx a, simp only [hl, list.mem_append, or_imp_distrib, forall_and_distrib] at this ⊢, exact ⟨⟨this.1.1, hal _⟩, this.2⟩ }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.idx } }, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.nodup _ _ _ v bidx, simp [hl, list.nodup_append] at this, simp [list.nodup_append, this, hvnd, djuv, djwv.symm] }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.nodup } } end end theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', suffices : ∃ (u w : list Σ a, β a) (b'' : β a), (sigma.mk a b') :: t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b (⟨a, b'⟩ :: t) = u ++ ⟨a, b⟩ :: w, {simpa}, refine ⟨[], t, b', _⟩, simp [replace_aux] }, { suffices : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), (sigma.mk a' b') :: t = u ++ ⟨a, b''⟩ :: w ∧ (sigma.mk a' b') :: (replace_aux a b t) = u ++ ⟨a, b⟩ :: w, { simpa [replace_aux, ne.symm e, e] }, intros x m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b t = u ++ ⟨a, b⟩ :: w, { simpa using valid.replace_aux t }, rcases IH x m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm, ne.symm e]⟩ } end theorem valid.replace {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b', hl, hfl⟩, simp [hl, list.nodup_append] at nd, refine (v.modify hash_fn u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa' e1 e2, _) (λa' e1 e2, _)).2; { revert e1, simp [-sigma.exists] at e2, subst a', simp [nd] } end theorem valid.insert {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hnc : ¬ contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), refine (v.modify hash_fn [] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa', false.elim) (λa' e1 e2, _)).2, simp [-sigma.exists] at e2, subst a', exact Hnc ((contains_aux_iff nd).2 e1) end theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', simpa [erase_aux, and_comm] using show ∃ u w (x : β a), t = u ++ w ∧ (sigma.mk a b') :: t = u ++ ⟨a, x⟩ :: w, from ⟨[], t, b', by simp⟩ }, { simp [erase_aux, e, ne.symm e], suffices : ∀ (b : β a) (_ : sigma.mk a b ∈ t), ∃ u w (x : β a), (sigma.mk a' b') :: t = u ++ ⟨a, x⟩ :: w ∧ (sigma.mk a' b') :: (erase_aux a t) = u ++ w, { simpa [replace_aux, ne.symm e, e] }, intros b m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (x : β a), t = u ++ ⟨a, x⟩ :: w ∧ erase_aux a t = u ++ w, { simpa using valid.erase_aux t }, rcases IH b m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm]⟩ } end theorem valid.erase {n} {bkts : bucket_array α β n} {sz} (a : α) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b, hl, hfl⟩, refine (v.modify hash_fn u [⟨a, b⟩] [] w hl hfl list.nodup_nil _ _ _).2; simp end end end hash_map /-- A hash map data structure, representing a finite key-value map with key type `α` and value type `β` (which may depend on `α`). -/ structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) := (hash_fn : α → nat) (size : ℕ) (nbuckets : ℕ+) (buckets : bucket_array α β nbuckets) (is_valid : hash_map.valid hash_fn buckets size) /-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/ def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) : hash_map α β := let n := if nbuckets = 0 then 8 else nbuckets in let nz : n > 0 := by abstract { cases nbuckets; simp [if_pos, nat.succ_ne_zero] } in { hash_fn := hash_fn, size := 0, nbuckets := ⟨n, nz⟩, buckets := mk_array n [], is_valid := hash_map.mk_valid _ _ } namespace hash_map variables {α : Type u} {β : α → Type v} [decidable_eq α] /-- Return the value corresponding to a key, or `none` if not found -/ def find (m : hash_map α β) (a : α) : option (β a) := find_aux a (m.buckets.read m.hash_fn a) /-- Return `tt` if the key exists in the map -/ def contains (m : hash_map α β) (a : α) : bool := (m.find a).is_some instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩ /-- Fold a function over the key-value pairs in the map -/ def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ := m.buckets.foldl d f /-- The list of key-value pairs in the map -/ def entries (m : hash_map α β) : list Σ a, β a := m.buckets.as_list /-- The list of keys in the map -/ def keys (m : hash_map α β) : list α := m.entries.map sigma.fst theorem find_iff (m : hash_map α β) (a : α) (b : β a) : m.find a = some b ↔ sigma.mk a b ∈ m.entries := m.is_valid.find_aux_iff _ theorem contains_iff (m : hash_map α β) (a : α) : m.contains a ↔ a ∈ m.keys := m.is_valid.contains_aux_iff _ _ theorem entries_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).entries = [] := mk_as_list _ theorem keys_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).keys = [] := by dsimp [keys]; rw entries_empty; refl theorem find_empty (hash_fn : α → nat) (n a) : (@mk_hash_map α _ β hash_fn n).find a = none := by induction h : (@mk_hash_map α _ β hash_fn n).find a; [refl, { have := (find_iff _ _ _).1 h, rw entries_empty at this, contradiction }] theorem not_contains_empty (hash_fn : α → nat) (n a) : ¬ (@mk_hash_map α _ β hash_fn n).contains a := by apply bool_iff_false.2; dsimp [contains]; rw [find_empty]; refl theorem insert_lemma (hash_fn : α → nat) {n n'} {bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) : valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz := begin suffices : ∀ (l : list Σ a, β a) (t : bucket_array α β n') sz, valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup → valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length), { have p := this bkts.as_list _ _ (mk_valid _ _), rw [mk_as_list, list.append_nil, zero_add, v.len] at p, rw bucket_array.foldl_eq, exact p (v.as_list_nodup _) }, intro l, induction l with c l IH; intros t sz v nd, {exact v}, rw show sz + (c :: l).length = sz + 1 + l.length, by simp [add_comm, add_assoc], rcases (show (l.map sigma.fst).nodup ∧ ((bucket_array.as_list t).map sigma.fst).nodup ∧ c.fst ∉ l.map sigma.fst ∧ c.fst ∉ (bucket_array.as_list t).map sigma.fst ∧ (l.map sigma.fst).disjoint ((bucket_array.as_list t).map sigma.fst), by simpa [list.nodup_append, not_or_distrib, and_comm, and.left_comm] using nd) with ⟨nd1, nd2, nm1, nm2, dj⟩, have v' := v.insert _ _ c.2 (λHc, nm2 $ (v.contains_aux_iff _ c.1).1 Hc), apply IH _ _ v', suffices : ∀ ⦃a : α⦄ (b : β a), sigma.mk a b ∈ l → ∀ (b' : β a), sigma.mk a b' ∈ (reinsert_aux hash_fn t c.1 c.2).as_list → false, { simpa [list.nodup_append, nd1, v'.as_list_nodup _, list.disjoint] }, intros a b m1 b' m2, rcases (reinsert_aux hash_fn t c.1 c.2).mem_as_list.1 m2 with ⟨i, im⟩, have : sigma.mk a b' ∉ array.read t i, { intro m3, have : a ∈ list.map sigma.fst t.as_list := list.mem_map_of_mem sigma.fst (t.mem_as_list.2 ⟨_, m3⟩), exact dj (list.mem_map_of_mem sigma.fst m1) this }, by_cases h : mk_idx n' (hash_fn c.1) = i, { subst h, have e : sigma.mk a b' = ⟨c.1, c.2⟩, { simpa [reinsert_aux, bucket_array.modify, array.read_write, this] using im }, injection e with e, subst a, exact nm1.elim (@list.mem_map_of_mem _ _ sigma.fst _ _ m1) }, { apply this, simpa [reinsert_aux, bucket_array.modify, array.read_write_of_ne _ _ h] using im } end /-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/ def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β | ⟨hash_fn, size, n, buckets, v⟩ a b := let bkt := buckets.read hash_fn a in if hc : contains_aux a bkt then { hash_fn := hash_fn, size := size, nbuckets := n, buckets := buckets.modify hash_fn a (replace_aux a b), is_valid := v.replace _ a b hc } else let size' := size + 1, buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l), valid' := v.insert _ a b hc in if size' ≤ n then { hash_fn := hash_fn, size := size', nbuckets := n, buckets := buckets', is_valid := valid' } else let n' : ℕ+ := ⟨n * 2, mul_pos n.2 dec_trivial⟩, buckets'' : bucket_array α β n' := buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in { hash_fn := hash_fn, size := size', nbuckets := n', buckets := buckets'', is_valid := insert_lemma _ valid' } theorem mem_insert : Π (m : hash_map α β) (a b a' b'), (sigma.mk a' b' : sigma β) ∈ (m.insert a b).entries ↔ if a = a' then b == b' else sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a b a' b' := begin let bkt := bkts.read hash_fn a, have nd : (bkt.map sigma.fst).nodup := v.nodup (mk_idx n (hash_fn a)), have lem : Π (bkts' : bucket_array α β n) (v1 u w) (hl : bucket_array.as_list bkts = u ++ v1 ++ w) (hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w) (veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]), sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list, { intros bkts' v1 u w hl hfl veq, rw [hl, hfl], by_cases h : a = a', { subst a', suffices : b = b' ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b = b', { simpa [eq_comm, or.left_comm] }, refine or_iff_left_of_imp (not.elim $ not_or_distrib.2 _), rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩, { have na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc, simp [hl, not_or_distrib] at na, simp [na] }, { have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] } }, { suffices : sigma.mk a' b' ∉ v1, {simp [h, ne.symm h, this]}, rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩; simp [ne.symm h] } }, by_cases Hc : (contains_aux a bkt : Prop), { rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u', w', b'', hl', hfl'⟩, rcases (append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl') with ⟨u, w, hl, hfl⟩, simpa [insert, @dif_pos (contains_aux a bkt) _ Hc] using lem _ _ u w hl hfl (or.inr ⟨b'', rfl⟩) }, { let size' := size + 1, let bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l), have mi : sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list := let ⟨u, w, hl, hfl⟩ := append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hc⟩, simp [insert, @dif_neg (contains_aux a bkt) _ Hc], by_cases h : size' ≤ n, -- TODO(Mario): Why does the by_cases assumption look different than the stated one? { simpa [show size' ≤ n, from h] using mi }, { let n' : ℕ+ := ⟨n * 2, mul_pos n.2 dec_trivial⟩, let bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn), suffices : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse, { simpa [show ¬ size' ≤ n, from h, mi] }, rw [show bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _, ← list.foldr_reverse], induction bkts'.as_list.reverse with a l IH, { simp [mk_as_list] }, { cases a with a'' b'', let B := l.foldr (λ (y : sigma β) (x : bucket_array α β n'), reinsert_aux hash_fn x y.1 y.2) (mk_array n' []), rcases append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl with ⟨u, w, hl, hfl⟩, simp [IH.symm, or.left_comm, show B.as_list = _, from hl, show (reinsert_aux hash_fn B a'' b'').as_list = _, from hfl] } } } end theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b := (find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') : (m.insert a b).find a' = m.find a' := option.eq_of_eq_some $ λb', let t := mem_insert m a b a' b' in (find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) : (m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' := if h : a = a' then by rw dif_pos h; exact match a', h with ._, rfl := find_insert_eq m a b end else by rw dif_neg h; exact find_insert_ne m a a' b h /-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/ def insert_all (l : list (Σ a, β a)) (m : hash_map α β) : hash_map α β := l.foldl (λ m ⟨a, b⟩, insert m a b) m /-- Construct a hash map from a list of key-value pairs. -/ def of_list (l : list (Σ a, β a)) (hash_fn) : hash_map α β := insert_all l (mk_hash_map hash_fn (2 * l.length)) /-- Remove a key from the map. (Modifies `m` in-place when applicable) -/ def erase (m : hash_map α β) (a : α) : hash_map α β := match m with ⟨hash_fn, size, n, buckets, v⟩ := if hc : contains_aux a (buckets.read hash_fn a) then { hash_fn := hash_fn, size := size - 1, nbuckets := n, buckets := buckets.modify hash_fn a (erase_aux a), is_valid := v.erase _ a hc } else m end theorem mem_erase : Π (m : hash_map α β) (a a' b'), (sigma.mk a' b' : sigma β) ∈ (m.erase a).entries ↔ a ≠ a' ∧ sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a a' b' := begin let bkt := bkts.read hash_fn a, by_cases Hc : (contains_aux a bkt : Prop), { let bkts' := bkts.modify hash_fn a (erase_aux a), suffices : sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list, { simpa [erase, @dif_pos (contains_aux a bkt) _ Hc] }, have nd := v.nodup (mk_idx n (hash_fn a)), rcases valid.erase_aux a bkt ((contains_aux_iff nd).1 Hc) with ⟨u', w', b, hl', hfl'⟩, rcases append_of_modify u' [⟨a, b⟩] [] _ hl' hfl' with ⟨u, w, hl, hfl⟩, suffices : ∀_:sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w, a ≠ a', { have : sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w ↔ (¬a = a' ∧ a' = a) ∧ b' == b ∨ ¬a = a' ∧ (sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w), { simp [eq_comm, not_and_self_iff, and_iff_right_of_imp this] }, simpa [hl, show bkts'.as_list = _, from hfl, and_or_distrib_left, and_comm, and.left_comm, or.left_comm] }, intros m e, subst a', revert m, apply not_or_distrib.2, have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] }, { suffices : ∀_:sigma.mk a' b' ∈ bucket_array.as_list bkts, a ≠ a', { simp [erase, @dif_neg (contains_aux a bkt) _ Hc, entries, and_iff_right_of_imp this] }, intros m e, subst a', exact Hc ((v.contains_aux_iff _ _).2 (list.mem_map_of_mem sigma.fst m)) } end theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none := begin cases h : (m.erase a).find a with b, {refl}, exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left end theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') : (m.erase a).find a' = m.find a' := option.eq_of_eq_some $ λb', (find_iff _ _ _).trans $ (mem_erase m a a' b').trans $ (and_iff_right h).trans (find_iff _ _ _).symm theorem find_erase (m : hash_map α β) (a' a : α) : (m.erase a).find a' = if a = a' then none else m.find a' := if h : a = a' then by subst a'; simp [find_erase_eq m a] else by rw if_neg h; exact find_erase_ne m a a' h section string variables [has_to_string α] [∀ a, has_to_string (β a)] open prod private def key_data_to_string (a : α) (b : β a) (first : bool) : string := (if first then "" else ", ") ++ sformat!"{a} ← {b}" private def to_string (m : hash_map α β) : string := "⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩" instance : has_to_string (hash_map α β) := ⟨to_string⟩ end string section format open format prod variables [has_to_format α] [∀ a, has_to_format (β a)] private meta def format_key_data (a : α) (b : β a) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b private meta def to_format (m : hash_map α β) : format := group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++ to_fmt "⟩" meta instance : has_to_format (hash_map α β) := ⟨to_format⟩ end format /-- `hash_map` with key type `nat` and value type that may vary. -/ instance {β : ℕ → Type*} : inhabited (hash_map ℕ β) := ⟨mk_hash_map id⟩ end hash_map
a9957488094eae20f874477ef863de2606a6ce70
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.27.lean
3e0d72964f6203fd6075c99a046e2624b499d493
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
290
lean
/- page 86 -/ import standard namespace hide inductive nat : Type := | zero : nat | succ : nat → nat -- BEGIN namespace nat definition add (m n : nat) : nat := nat.rec_on n m (λ n add_m_n, succ add_m_n) -- try it out eval add (succ zero) (succ (succ zero)) end nat -- END end hide
076d46dd843a90eed4b9777f20b035d2c6ad3490
abd85493667895c57a7507870867b28124b3998f
/src/data/set/basic.lean
2b446a7dd3874eaf73343d0cba8273ff95b789a9
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
67,214
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import tactic.basic import tactic.finish import data.subtype import logic.unique import data.prod /-! # Basic properties of sets Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements have type `X` are thus defined as `set X := X → Prop`. Note that this function need not be decidable. The definition is in the core library. This file provides some basic definitions related to sets and functions not present in the core library, as well as extra lemmas for functions in the core library (empty set, univ, union, intersection, insert, singleton, set-theoretic difference, complement, and powerset). Note that a set is a term, not a type. There is a coersion from `set α` to `Type*` sending `s` to the corresponding subtype `↑s`. See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean. ## Main definitions Notation used here: - `f : α → β` is a function, - `s : set α` and `s₁ s₂ : set α` are subsets of `α` - `t : set β` is a subset of `β`. Definitions in the file: * `strict_subset s₁ s₂ : Prop` : the predicate `s₁ ⊆ s₂` but `s₁ ≠ s₂`. * `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the fact that `s` has an element (see the Implementation Notes). * `preimage f t : set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β. * `subsingleton s : Prop` : the predicate saying that `s` has at most one element. * `range f : set β` : the image of `univ` under `f`. Also works for `{p : Prop} (f : p → α)` (unlike `image`) * `prod s t : set (α × β)` : the subset `s × t`. * `inclusion s₁ s₂ : ↑s₁ → ↑s₂` : the map `↑s₁ → ↑s₂` induced by an inclusion `s₁ ⊆ s₂`. ## Notation * `f ⁻¹' t` for `preimage f t` * `f '' s` for `image f s` ## Implementation notes `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that the `s.nonempty` dot notation can be used. ## Tags set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert, singleton, complement, powerset -/ /-! ### Set coercion to a type -/ open function namespace set /-- Coercion from a set to the corresponding subtype. -/ instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ end set section set_coe universe u variables {α : Type u} theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} : (∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x.1 x.2) := (@set_coe.exists _ _ $ λ x, p x.1 x.2).symm @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.property namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[ext] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /-! ### Lemmas about `mem` and `set_of` -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl lemma set_of_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := iff.rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {α} {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl /-! ### Lemmas about subsets -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alternative name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp [subset_def, classical.not_forall] /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ ¬ (t ⊆ s) instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ ¬ (t ⊆ s)) := rfl theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := classical.by_cases (λ H : t ⊆ s, or.inl $ subset.antisymm h H) (λ H, or.inr ⟨h, H⟩) lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := not_subset.1 h.2 lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := by { classical, exact not_not } /-! ### Non-empty sets -/ /-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩ theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅) | ⟨x, hx⟩ hs := hs hx theorem nonempty.ne_empty : s.nonempty → s ≠ ∅ | ⟨x, hx⟩ hs := by { rw hs at hx, exact hx } /-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/ protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := let ⟨x, xt, xs⟩ := exists_of_ssubset ht in ⟨x, xt, xs⟩ lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr @[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty := ⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩ @[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty | ⟨x⟩ := ⟨x, trivial⟩ lemma nonempty.to_subtype (h : s.nonempty) : nonempty s := nonempty_subtype.2 h /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ := by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists] lemma empty_not_nonempty : ¬(∅ : set α).nonempty := not_nonempty_iff_eq_empty.2 rfl lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inr (λ h, or.inl $ not_nonempty_iff_eq_empty.1 h) theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := (not_congr not_nonempty_iff_eq_empty.symm).trans classical.not_not theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /-! ### Universal set. In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : nonempty α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 @[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ ¬ nonempty α := eq_empty_iff_forall_not_mem.trans ⟨λ H ⟨x⟩, H x trivial, λ H x _, H ⟨x⟩⟩ lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ instance univ_decidable : decidable_pred (@set.univ α) := λ x, is_true trivial /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_iff_subset_ne, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} : (∃ x ∈ insert a s, P x) ↔ (∃ x ∈ s, P x) ∨ P a := by finish [iff_def] theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /-! ### Lemmas about singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := (insert_emptyc_eq _).symm @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := iff.rfl @[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := set.ext $ λ n, (set.mem_singleton_iff).symm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := ⟨a, rfl⟩ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := ext $ by simp @[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl @[simp] theorem union_singleton : s ∪ {a} = insert a s := by rw [union_comm, singleton_union] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty := by rw [mem_singleton_iff, ← ne.def, ne_empty_iff_nonempty] instance unique_singleton (a : α) : unique ↥({a} : set α) := { default := ⟨a, mem_singleton a⟩, uniq := begin intros x, apply subtype.coe_ext.2, apply eq_of_mem_singleton (subtype.mem x), end} /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := set.ext $ by simp /-! ### Lemmas about complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h lemma compl_set_of {α} (p : α → Prop) : - {a | p a} = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] local attribute [simp] -- Will be generalized to lattices in `compl_compl'` theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] lemma compl_empty_iff {s : set α} : -s = ∅ ↔ s = univ := by { split, intro h, rw [←compl_compl s, h, compl_empty], intro h, rw [h, compl_univ] } lemma compl_univ_iff {s : set α} : -s = univ ↔ s = ∅ := by rw [←compl_empty_iff, compl_compl] lemma nonempty_compl {s : set α} : (-s : set α).nonempty ↔ s ≠ univ := ne_empty_iff_nonempty.symm.trans $ not_congr $ compl_empty_iff lemma mem_compl_singleton_iff {a x : α} : x ∈ -({a} : set α) ↔ x ≠ a := not_iff_not_of_iff mem_singleton_iff lemma compl_singleton_eq (a : α) : -({a} : set α) = {x | x ≠ a} := ext $ λ x, mem_compl_singleton_iff theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ -({a} : set α) ↔ a ∉ s := by { rw subset_compl_comm, simp } theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ -b ∪ c := begin classical, split, { intros h x xa, by_cases h' : x ∈ b, simp [h ⟨xa, h'⟩], simp [h'] }, intros h x, rintro ⟨xa, xb⟩, cases h xa, contradiction, assumption end /-! ### Lemmas about set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := ⟨λ ⟨x, xs, xt⟩, not_subset.2 ⟨x, xs, xt⟩, λ h, let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩⟩ theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := set.ext $ λ _, and_or_distrib_left theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := set.ext $ λ _, and_or_distrib_right theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := set.ext $ λ _, or_and_distrib_left theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := set.ext $ λ _, or_and_distrib_right theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] @[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ := eq_empty_of_subset_empty $ assume x ⟨hx, _⟩, hx theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t := by rw [union_comm, ←diff_subset_iff] @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} := subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := ext $ λ x, by simp [classical.not_and_distrib, and_or_distrib_left] lemma diff_compl : s \ -t = s ∩ t := by rw [diff_eq, compl_compl] lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) := by rw [diff_eq t u, diff_inter, diff_compl] @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := begin classical, ext x, by_cases h' : x ∈ t, { have : x ≠ a, { assume H, rw H at h', exact h h' }, simp [h, h', this] }, { simp [h, h'] } end theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := ext $ by simp lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s := by simp only [diff_diff_right, diff_self, inter_eq_self_of_subset_right h, empty_union] lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) := iff.rfl lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} : s ∈ t \ {∅} ↔ (s ∈ t ∧ s.nonempty) := mem_diff_singleton.trans $ and_congr iff.rfl ne_empty_iff_nonempty /-! ### Powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /-! ### Inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _ @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl @[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ lemma if_preimage (s : set α) [decidable_pred s] (f g : α → β) (t : set β) : (λa, if a ∈ s then f a else g a)⁻¹' t = (s ∩ f ⁻¹' t) ∪ (-s ∩ g ⁻¹' t) := begin ext, simp only [mem_inter_eq, mem_union_eq, mem_preimage], split_ifs; simp [mem_def, h] end end preimage /-! ### Image of a set under a function -/ section image infix ` '' `:80 := image -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem bex_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∃ y ∈ f '' s, p y) ↔ (∃ x ∈ s, p (f x)) := by simp theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /-- A common special case of `image_congr` -/ lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s := image_congr (λx _, h x) theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s := (image_comp g f s).symm /-- Image is monotone with respect to `⊆`. See `set.monotone_image` for the statement in terms of `≤`. -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp lemma image_inter_subset (f : α → β) (s t : set α) : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := subset_inter (image_subset _ $ inter_subset_left _ _) (image_subset _ $ inter_subset_right _ _) theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (image_inter_subset _ _ _) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := ext $ λ x, by simp [image]; rw eq_comm theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} := ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _, λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩ @[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ := by simp only [eq_empty_iff_forall_not_mem]; exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ lemma inter_singleton_nonempty {s : set α} {a : α} : (s ∩ {a}).nonempty ↔ a ∈ s := by finish [set.nonempty] theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := ext $ by simp theorem image_id (s : set α) : id '' s = s := by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} := by simp only [image_insert_eq, image_singleton] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) lemma nonempty.image (f : α → β) {s : set α} : s.nonempty → (f '' s).nonempty | ⟨x, hx⟩ := ⟨f x, mem_image_of_mem f hx⟩ lemma nonempty.of_image {f : α → β} {s : set α} : (f '' s).nonempty → s.nonempty | ⟨y, x, hx, _⟩ := ⟨x, hx⟩ @[simp] lemma nonempty_image_iff {f : α → β} {s : set α} : (f '' s).nonempty ↔ s.nonempty := ⟨nonempty.of_image, λ h, h.image f⟩ /-- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq]) (assume eq, eq ▸ rfl) protected lemma push_pull (f : α → β) (s : set α) (t : set β) : f '' (s ∩ f ⁻¹' t) = f '' s ∩ t := begin apply subset.antisymm, { calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ (f '' (f⁻¹' t)) : image_inter_subset _ _ _ ... ⊆ f '' s ∩ t : inter_subset_inter_right _ (image_preimage_subset f t) }, { rintros _ ⟨⟨x, h', rfl⟩, h⟩, exact ⟨x, ⟨h', h⟩, rfl⟩ } end protected lemma push_pull' (f : α → β) (s : set α) (t : set β) : f '' (f ⁻¹' t ∩ s) = t ∩ f '' s := by simp only [inter_comm, set.push_pull] theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {p : set α → Prop} : compl '' {s | p s} = {s | p (- s)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma injective_image {f : α → β} (hf : injective f) : injective (('') f) := assume s t, (image_eq_image hf).1 lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) /-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/ def image_factorization (f : α → β) (s : set α) : s → f '' s := λ p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : α → β} {s : set α} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ λ p, rfl lemma surjective_onto_image {f : α → β} {s : set α} : surjective (image_factorization f s) := λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ end image /-! ### Subsingleton -/ /-- A set `s` is a `subsingleton`, if it has at most one element. -/ protected def subsingleton (s : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y lemma subsingleton.mono (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton := λ x hx y hy, ht (hst hx) (hst hy) lemma subsingleton.image (hs : s.subsingleton) (f : α → β) : (f '' s).subsingleton := λ _ ⟨x, hx, Hx⟩ _ ⟨y, hy, Hy⟩, Hx ▸ Hy ▸ congr_arg f (hs hx hy) lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) : s = {x} := ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩ lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim lemma subsingleton_singleton {a} : ({a} : set α).subsingleton := λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) : s = ∅ ∨ ∃ x, s = {x} := s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩) lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton := λ x hx y hy, subsingleton.elim x y theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) /-! ### Lemmas about range of a function. -/ section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := by simp lemma exists_range_iff' {p : α → Prop} : (∃ a, a ∈ range f ∧ p a) ↔ ∃ i, p (f i) := by simpa only [exists_prop] using exists_range_iff theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id theorem range_inl_union_range_inr : range (@sum.inl α β) ∪ range sum.inr = univ := ext $ λ x, by cases x; simp @[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ := range_iff_surjective.2 quot.exists_rep @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := ext $ by simp [image, range] theorem image_subset_range {ι : Type*} (f : ι → β) (s : set ι) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {s : set α} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g := by rw range_comp; apply image_subset_range lemma range_nonempty_iff_nonempty : (range f).nonempty ↔ nonempty ι := ⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩ lemma range_nonempty [h : nonempty ι] (f : ι → α) : (range f).nonempty := range_nonempty_iff_nonempty.2 h @[simp] lemma range_eq_empty {f : ι → α} : range f = ∅ ↔ ¬ nonempty ι := not_nonempty_iff_eq_empty.symm.trans $ not_congr range_nonempty_iff_nonempty theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma range_const_subset {c : α} : range (λx:ι, c) ⊆ {c} := range_subset_iff.2 $ λ x, rfl @[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c} | ⟨x⟩ c := subset.antisymm range_const_subset $ assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x /-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/ def range_factorization (f : ι → β) : ι → range f := λ i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ι → β} : subtype.val ∘ range_factorization f = f := funext $ λ i, rfl lemma surjective_onto_range : surjective (range_factorization f) := λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x.1) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } @[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) : range (sum.elim f g) = range f ∪ range g := by simp [set.ext_iff, mem_range] lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} : range (if p then f else g) ⊆ range f ∪ range g := begin by_cases h : p, {rw if_pos h, exact subset_union_left _ _}, {rw if_neg h, exact subset_union_right _ _} end lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} : range (λ x, if p x then f x else g x) ⊆ range f ∪ range g := begin rw range_subset_iff, intro x, by_cases h : p x, simp [if_pos h, mem_union, mem_range_self], simp [if_neg h, mem_union, mem_range_self] end end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y theorem pairwise_on.mono {s t : set α} {r} (h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r := λ x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop} (H : ∀ a b, r a b → r' a b) (hp : pairwise_on s r) : pairwise_on s r' := λ x xs y ys h, H _ _ (hp x xs y ys h) end set open set /-! ### Image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ @[simp] lemma val_range {p : α → Prop} : set.range (@subtype.val _ p) = {x | p x} := by rw ← set.image_univ; simp [-set.image_univ, val_image] lemma range_val (s : set α) : range (subtype.val : s → α) = s := val_range theorem val_image_subset (s : set α) (t : set (subtype s)) : t.image val ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem val_image_univ (s : set α) : @val _ s '' set.univ = s := set.eq_of_subset_of_subset (val_image_subset _ _) (λ x xs, ⟨⟨x, xs⟩, ⟨set.mem_univ _, rfl⟩⟩) theorem image_preimage_val (s t : set α) : (@subtype.val _ s) '' ((@subtype.val _ s) ⁻¹' t) = t ∩ s := begin ext x, simp, split, { rintros ⟨y, ys, yt, yx⟩, rw ←yx, exact ⟨yt, ys⟩ }, rintros ⟨xt, xs⟩, exact ⟨x, xs, xt, rfl⟩ end theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((@subtype.val _ s) ⁻¹' t = (@subtype.val _ s) ⁻¹' u) ↔ (t ∩ s = u ∩ s) := begin rw [←image_preimage_val, ←image_preimage_val], split, { intro h, rw h }, intro h, exact set.injective_image (val_injective) h end lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (subtype.val '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨subtype.val '' s, _, hs⟩, convert image_subset_range _ _, rw [range_val] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨subtype.val ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_val], exact hs₁ end end subtype namespace set section range variable {α : Type*} @[simp] lemma range_coe_subtype (s : set α) : range (coe : s → α) = s := subtype.val_range theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} : ((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s := subtype.preimage_val_eq_preimage_val_iff _ _ _ end range /-! ### Lemmas about cartesian product of sets -/ section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma prod_eq (s : set α) (t : set β) : set.prod s t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ lemma prod_subset_iff {P : set (α × β)} : (set.prod s t ⊆ P) ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ xin _ yin, h (mk_mem_prod xin yin), λ h _ pin, by { cases mem_prod.1 pin with hs ht, simpa using h _ hs _ ht }⟩ @[simp] theorem prod_empty : set.prod s ∅ = (∅ : set (α × β)) := ext $ by simp [set.prod] @[simp] theorem empty_prod : set.prod ∅ t = (∅ : set (α × β)) := ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] theorem prod_range_univ_eq {α β γ} {m₁ : α → γ} : set.prod (range m₁) (univ : set β) = range (λp:α×β, (m₁ p.1, p.2)) := ext $ by simp [range] theorem prod_univ_range_eq {α β δ} {m₂ : β → δ} : set.prod (univ : set α) (range m₂) = range (λp:α×β, (p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := ext $ by simp [set.prod] theorem nonempty.prod : s.nonempty → t.nonempty → (s.prod t).nonempty | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨(x, y), ⟨hx, hy⟩⟩ theorem nonempty.fst : (s.prod t).nonempty → s.nonempty | ⟨p, hp⟩ := ⟨p.1, hp.1⟩ theorem nonempty.snd : (s.prod t).nonempty → t.nonempty | ⟨p, hp⟩ := ⟨p.2, hp.2⟩ theorem prod_nonempty_iff : (s.prod t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, nonempty.prod h.1 h.2⟩ theorem prod_eq_empty_iff {s : set α} {t : set β} : set.prod s t = ∅ ↔ (s = ∅ ∨ t = ∅) := by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, classical.not_and_distrib] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' (set.prod s t) ⊆ s := λ _ h, let ⟨_, ⟨h₂, _⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_fst (s : set α) (t : set β) : set.prod s t ⊆ prod.fst ⁻¹' s := image_subset_iff.1 (fst_image_prod_subset s t) lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) : prod.fst '' (set.prod s t) = s := set.subset.antisymm (fst_image_prod_subset _ _) $ λ y y_in, let ⟨x, x_in⟩ := ht in ⟨(y, x), ⟨y_in, x_in⟩, rfl⟩ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' (set.prod s t) ⊆ t := λ _ h, let ⟨_, ⟨_, h₂⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_snd (s : set α) (t : set β) : set.prod s t ⊆ prod.snd ⁻¹' t := image_subset_iff.1 (snd_image_prod_subset s t) lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) : prod.snd '' (set.prod s t) = t := set.subset.antisymm (snd_image_prod_subset _ _) $ λ y y_in, let ⟨x, x_in⟩ := hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : (set.prod s t ⊆ set.prod s₁ t₁) ↔ (s ⊆ s₁ ∧ t ⊆ t₁) ∨ (s = ∅) ∨ (t = ∅) := begin classical, cases (set.prod s t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, by rwa [prod_nonempty_iff] at h, split, { assume H : set.prod s t ⊆ set.prod s₁ t₁, have h' : s₁.nonempty ∧ t₁.nonempty := prod_nonempty_iff.1 (h.mono H), refine or.inl ⟨_, _⟩, show s ⊆ s₁, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ h'.2] at this }, show t ⊆ t₁, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod h'.1] at this } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H, exact prod_mono H.1 H.2 } } end end prod /-! ### Lemmas about set-indexed products of sets -/ section pi variables {α : Type*} {π : α → Type*} /-- Given an index set `i` and a family of sets `s : Πa, set (π a)`, `pi i s` is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `π a` whenever `a ∈ i`. -/ def pi (i : set α) (s : Πa, set (π a)) : set (Πa, π a) := { f | ∀a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Πa, set (π a)) : pi ∅ s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : α) (i : set α) (s : Πa, set (π a)) : pi (insert a i) s = ((λf, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : α) (s : Πa, set (π a)) : pi {a} s = ((λf:(Πa, π a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : α → Prop} [h : decidable_pred p] (i : set α) (s t : Πa, set (π a)) : pi i (λa, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | ¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi /-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/ section inclusion variable {α : Type*} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion {s t : set α} (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self {s : set α} (x : s) : inclusion (set.subset.refl _) x = x := by cases x; refl @[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x := by cases x; refl lemma inclusion_injective {s t : set α} (h : s ⊆ t) : function.injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext.2 ∘ subtype.ext.1 lemma range_inclusion {s t : set α} (h : s ⊆ t) : range (inclusion h) = {x : t | (x:α) ∈ s} := ext $ λ ⟨x, hx⟩ , by simp [inclusion] end inclusion end set namespace subsingleton variables {α : Type*} [subsingleton α] lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ := λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx @[elab_as_eliminator] lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1 end subsingleton namespace function variables {ι : Sort*} {α : Type*} {β : Type*} lemma surjective.injective_preimage {f : β → α} (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 lemma surjective.range_eq {f : ι → α} (hf : surjective f) : range f = univ := range_iff_surjective.2 hf lemma surjective.range_comp (g : α → β) {f : ι → α} (hf : surjective f) : range (g ∘ f) = range g := by rw [range_comp, hf.range_eq, image_univ] end function
483c1abf908cb2eef31756cc70898770ef1d452c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/finsupp/basic.lean
fb4b0f580a38bd6cd77c27dd947904440599f53e
[]
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
79,782
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, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.pi import Mathlib.algebra.big_operators.order import Mathlib.algebra.module.basic import Mathlib.group_theory.submonoid.basic import Mathlib.data.fintype.card import Mathlib.data.finset.preimage import Mathlib.data.multiset.antidiagonal import Mathlib.data.indicator_function import Mathlib.PostPort universes u_13 u_14 l u_1 u_5 u_7 u_2 u_8 u_6 u_11 u_12 u_9 u_4 u_3 namespace Mathlib /-! # Type of functions with finite support For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## TODO * This file is currently ~2K lines long, so possibly it should be splitted into smaller chunks; * Add the list of definitions and important lemmas to the module docstring. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## Notation This file defines `α →₀ β` as notation for `finsupp α β`. -/ /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type u_13) (M : Type u_14) [HasZero M] where support : finset α to_fun : α → M mem_support_to_fun : ∀ (a : α), a ∈ support ↔ to_fun a ≠ 0 infixr:25 " →₀ " => Mathlib.finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ protected instance has_coe_to_fun {α : Type u_1} {M : Type u_5} [HasZero M] : has_coe_to_fun (α →₀ M) := has_coe_to_fun.mk (fun (_x : α →₀ M) => α → M) to_fun @[simp] theorem coe_mk {α : Type u_1} {M : Type u_5} [HasZero M] (f : α → M) (s : finset α) (h : ∀ (a : α), a ∈ s ↔ f a ≠ 0) : ⇑(mk s f h) = f := rfl protected instance has_zero {α : Type u_1} {M : Type u_5} [HasZero M] : HasZero (α →₀ M) := { zero := mk ∅ (fun (_x : α) => 0) sorry } @[simp] theorem coe_zero {α : Type u_1} {M : Type u_5} [HasZero M] : ⇑0 = fun (_x : α) => 0 := rfl theorem zero_apply {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} : coe_fn 0 a = 0 := rfl @[simp] theorem support_zero {α : Type u_1} {M : Type u_5} [HasZero M] : support 0 = ∅ := rfl protected instance inhabited {α : Type u_1} {M : Type u_5} [HasZero M] : Inhabited (α →₀ M) := { default := 0 } @[simp] theorem mem_support_iff {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {a : α} : a ∈ support f ↔ coe_fn f a ≠ 0 := mem_support_to_fun f @[simp] theorem fun_support_eq {α : Type u_1} {M : Type u_5} [HasZero M] (f : α →₀ M) : function.support ⇑f = ↑(support f) := set.ext fun (x : α) => iff.symm mem_support_iff theorem not_mem_support_iff {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {a : α} : ¬a ∈ support f ↔ coe_fn f a = 0 := iff.mp not_iff_comm (iff.symm mem_support_iff) theorem coe_fn_injective {α : Type u_1} {M : Type u_5} [HasZero M] : function.injective fun (f : α →₀ M) (x : α) => coe_fn f x := sorry theorem ext {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {g : α →₀ M} (h : ∀ (a : α), coe_fn f a = coe_fn g a) : f = g := coe_fn_injective (funext h) theorem ext_iff {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {g : α →₀ M} : f = g ↔ ∀ (a : α), coe_fn f a = coe_fn g a := { mp := fun (ᾰ : f = g) (a : α) => Eq._oldrec (Eq.refl (coe_fn f a)) ᾰ, mpr := ext } theorem ext_iff' {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {g : α →₀ M} : f = g ↔ support f = support g ∧ ∀ (x : α), x ∈ support f → coe_fn f x = coe_fn g x := sorry @[simp] theorem support_eq_empty {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} : support f = ∅ ↔ f = 0 := sorry theorem card_support_eq_zero {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} : finset.card (support f) = 0 ↔ f = 0 := sorry protected instance finsupp.decidable_eq {α : Type u_1} {M : Type u_5} [HasZero M] [DecidableEq α] [DecidableEq M] : DecidableEq (α →₀ M) := fun (f g : α →₀ M) => decidable_of_iff (support f = support g ∧ ∀ (a : α), a ∈ support f → coe_fn f a = coe_fn g a) sorry theorem finite_supp {α : Type u_1} {M : Type u_5} [HasZero M] (f : α →₀ M) : set.finite (set_of fun (a : α) => coe_fn f a ≠ 0) := Nonempty.intro (fintype.of_finset (support f) fun (_x : α) => mem_support_iff) theorem support_subset_iff {α : Type u_1} {M : Type u_5} [HasZero M] {s : set α} {f : α →₀ M} : ↑(support f) ⊆ s ↔ ∀ (a : α), ¬a ∈ s → coe_fn f a = 0 := sorry /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ def equiv_fun_on_fintype {α : Type u_1} {M : Type u_5} [HasZero M] [fintype α] : (α →₀ M) ≃ (α → M) := equiv.mk (fun (f : α →₀ M) (a : α) => coe_fn f a) (fun (f : α → M) => mk (finset.filter (fun (a : α) => f a ≠ 0) finset.univ) f sorry) sorry sorry /-! ### Declarations about `single` -/ /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single {α : Type u_1} {M : Type u_5} [HasZero M] (a : α) (b : M) : α →₀ M := mk (ite (b = 0) ∅ (singleton a)) (fun (a' : α) => ite (a = a') b 0) sorry theorem single_apply {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {a' : α} {b : M} : coe_fn (single a b) a' = ite (a = a') b 0 := rfl theorem single_eq_indicator {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} : ⇑(single a b) = set.indicator (singleton a) fun (_x : α) => b := sorry @[simp] theorem single_eq_same {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} : coe_fn (single a b) a = b := if_pos rfl @[simp] theorem single_eq_of_ne {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {a' : α} {b : M} (h : a ≠ a') : coe_fn (single a b) a' = 0 := if_neg h theorem single_eq_update {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} : ⇑(single a b) = function.update 0 a b := sorry @[simp] theorem single_zero {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} : single a 0 = 0 := sorry theorem single_of_single_apply {α : Type u_1} {M : Type u_5} [HasZero M] (a : α) (a' : α) (b : M) : single a (coe_fn (single a' b) a) = coe_fn (single a' (single a' b)) a := sorry theorem support_single_ne_zero {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} (hb : b ≠ 0) : support (single a b) = singleton a := if_neg hb theorem support_single_subset {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} : support (single a b) ⊆ singleton a := sorry theorem single_apply_mem {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} (x : α) : coe_fn (single a b) x ∈ insert 0 (singleton b) := sorry theorem range_single_subset {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} : set.range ⇑(single a b) ⊆ insert 0 (singleton b) := iff.mpr set.range_subset_iff single_apply_mem theorem single_injective {α : Type u_1} {M : Type u_5} [HasZero M] (a : α) : function.injective (single a) := sorry theorem single_apply_eq_zero {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {x : α} {b : M} : coe_fn (single a b) x = 0 ↔ x = a → b = 0 := sorry theorem mem_support_single {α : Type u_1} {M : Type u_5} [HasZero M] (a : α) (a' : α) (b : M) : a ∈ support (single a' b) ↔ a = a' ∧ b ≠ 0 := sorry theorem eq_single_iff {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {a : α} {b : M} : f = single a b ↔ support f ⊆ singleton a ∧ coe_fn f a = b := sorry theorem single_eq_single_iff {α : Type u_1} {M : Type u_5} [HasZero M] (a₁ : α) (a₂ : α) (b₁ : M) (b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ b₁ = 0 ∧ b₂ = 0 := sorry theorem single_left_inj {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {a' : α} {b : M} (h : b ≠ 0) : single a b = single a' b ↔ a = a' := sorry @[simp] theorem single_eq_zero {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} : single a b = 0 ↔ b = 0 := sorry theorem single_swap {α : Type u_1} {M : Type u_5} [HasZero M] (a₁ : α) (a₂ : α) (b : M) : coe_fn (single a₁ b) a₂ = coe_fn (single a₂ b) a₁ := sorry protected instance nontrivial {α : Type u_1} {M : Type u_5} [HasZero M] [Nonempty α] [nontrivial M] : nontrivial (α →₀ M) := nonempty.elim_to_inhabited fun (inst : Inhabited α) => Exists.dcases_on (exists_ne 0) fun (x : M) (hx : x ≠ 0) => nontrivial_of_ne (single Inhabited.default x) 0 (mt (iff.mp single_eq_zero) hx) theorem unique_single {α : Type u_1} {M : Type u_5} [HasZero M] [unique α] (x : α →₀ M) : x = single Inhabited.default (coe_fn x Inhabited.default) := ext (iff.mpr unique.forall_iff (Eq.symm single_eq_same)) theorem unique_ext {α : Type u_1} {M : Type u_5} [HasZero M] [unique α] {f : α →₀ M} {g : α →₀ M} (h : coe_fn f Inhabited.default = coe_fn g Inhabited.default) : f = g := ext fun (a : α) => eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f a = coe_fn g a)) (unique.eq_default a))) h theorem unique_ext_iff {α : Type u_1} {M : Type u_5} [HasZero M] [unique α] {f : α →₀ M} {g : α →₀ M} : f = g ↔ coe_fn f Inhabited.default = coe_fn g Inhabited.default := { mp := fun (h : f = g) => h ▸ rfl, mpr := unique_ext } @[simp] theorem unique_single_eq_iff {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {a' : α} {b : M} [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := sorry theorem support_eq_singleton {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {a : α} : support f = singleton a ↔ coe_fn f a ≠ 0 ∧ f = single a (coe_fn f a) := sorry theorem support_eq_singleton' {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {a : α} : support f = singleton a ↔ ∃ (b : M), ∃ (H : b ≠ 0), f = single a b := sorry theorem card_support_eq_one {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} : finset.card (support f) = 1 ↔ ∃ (a : α), coe_fn f a ≠ 0 ∧ f = single a (coe_fn f a) := sorry theorem card_support_eq_one' {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} : finset.card (support f) = 1 ↔ ∃ (a : α), ∃ (b : M), ∃ (H : b ≠ 0), f = single a b := sorry /-! ### Declarations about `on_finset` -/ /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset {α : Type u_1} {M : Type u_5} [HasZero M] (s : finset α) (f : α → M) (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : α →₀ M := mk (finset.filter (fun (a : α) => f a ≠ 0) s) f sorry @[simp] theorem on_finset_apply {α : Type u_1} {M : Type u_5} [HasZero M] {s : finset α} {f : α → M} {hf : ∀ (a : α), f a ≠ 0 → a ∈ s} {a : α} : coe_fn (on_finset s f hf) a = f a := rfl @[simp] theorem support_on_finset_subset {α : Type u_1} {M : Type u_5} [HasZero M] {s : finset α} {f : α → M} {hf : ∀ (a : α), f a ≠ 0 → a ∈ s} : support (on_finset s f hf) ⊆ s := finset.filter_subset (fun (a : α) => f a ≠ 0) s @[simp] theorem mem_support_on_finset {α : Type u_1} {M : Type u_5} [HasZero M] {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ support (on_finset s f hf) ↔ f a ≠ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ support (on_finset s f hf) ↔ f a ≠ 0)) (propext mem_support_iff))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (on_finset s f hf) a ≠ 0 ↔ f a ≠ 0)) on_finset_apply)) (iff.refl (f a ≠ 0))) theorem support_on_finset {α : Type u_1} {M : Type u_5} [HasZero M] {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : support (on_finset s f hf) = finset.filter (fun (a : α) => f a ≠ 0) s := rfl /-! ### Declarations about `map_range` -/ /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. -/ def map_range {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [HasZero N] (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset (support g) (f ∘ ⇑g) sorry @[simp] theorem map_range_apply {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [HasZero N] {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : coe_fn (map_range f hf g) a = f (coe_fn g a) := rfl @[simp] theorem map_range_zero {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [HasZero N] {f : M → N} {hf : f 0 = 0} : map_range f hf 0 = 0 := sorry theorem support_map_range {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [HasZero N] {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : support (map_range f hf g) ⊆ support g := support_on_finset_subset @[simp] theorem map_range_single {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [HasZero N] {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := sorry /-! ### Declarations about `emb_domain` -/ /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (f : α ↪ β) (v : α →₀ M) : β →₀ M := mk (finset.map f (support v)) (fun (a₂ : β) => dite (a₂ ∈ finset.map f (support v)) (fun (h : a₂ ∈ finset.map f (support v)) => coe_fn v (finset.choose (fun (a₁ : α) => coe_fn f a₁ = a₂) (support v) sorry)) fun (h : ¬a₂ ∈ finset.map f (support v)) => 0) sorry @[simp] theorem support_emb_domain {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (f : α ↪ β) (v : α →₀ M) : support (emb_domain f v) = finset.map f (support v) := rfl @[simp] theorem emb_domain_zero {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (f : α ↪ β) : emb_domain f 0 = 0 := rfl @[simp] theorem emb_domain_apply {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (f : α ↪ β) (v : α →₀ M) (a : α) : coe_fn (emb_domain f v) (coe_fn f a) = coe_fn v a := sorry theorem emb_domain_notin_range {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (f : α ↪ β) (v : α →₀ M) (a : β) (h : ¬a ∈ set.range ⇑f) : coe_fn (emb_domain f v) a = 0 := sorry theorem emb_domain_injective {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (f : α ↪ β) : function.injective (emb_domain f) := sorry @[simp] theorem emb_domain_inj {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] {f : α ↪ β} {l₁ : α →₀ M} {l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := function.injective.eq_iff (emb_domain_injective f) @[simp] theorem emb_domain_eq_zero {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := function.injective.eq_iff' (emb_domain_injective f) (emb_domain_zero f) theorem emb_domain_map_range {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [HasZero M] [HasZero N] (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := sorry theorem single_of_emb_domain_single {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : emb_domain f l = single a b) : ∃ (x : α), l = single x b ∧ coe_fn f x = a := sorry /-! ### Declarations about `zip_with` -/ /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with {α : Type u_1} {M : Type u_5} {N : Type u_7} {P : Type u_8} [HasZero M] [HasZero N] [HasZero P] (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ P := on_finset (support g₁ ∪ support g₂) (fun (a : α) => f (coe_fn g₁ a) (coe_fn g₂ a)) sorry @[simp] theorem zip_with_apply {α : Type u_1} {M : Type u_5} {N : Type u_7} {P : Type u_8} [HasZero M] [HasZero N] [HasZero P] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : coe_fn (zip_with f hf g₁ g₂) a = f (coe_fn g₁ a) (coe_fn g₂ a) := rfl theorem support_zip_with {α : Type u_1} {M : Type u_5} {N : Type u_7} {P : Type u_8} [HasZero M] [HasZero N] [HasZero P] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : support (zip_with f hf g₁ g₂) ⊆ support g₁ ∪ support g₂ := support_on_finset_subset /-! ### Declarations about `erase` -/ /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase {α : Type u_1} {M : Type u_5} [HasZero M] (a : α) (f : α →₀ M) : α →₀ M := mk (finset.erase (support f) a) (fun (a' : α) => ite (a' = a) 0 (coe_fn f a')) sorry @[simp] theorem support_erase {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {f : α →₀ M} : support (erase a f) = finset.erase (support f) a := rfl @[simp] theorem erase_same {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {f : α →₀ M} : coe_fn (erase a f) a = 0 := if_pos rfl @[simp] theorem erase_ne {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {a' : α} {f : α →₀ M} (h : a' ≠ a) : coe_fn (erase a f) a' = coe_fn f a' := if_neg h @[simp] theorem erase_single {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {b : M} : erase a (single a b) = 0 := sorry theorem erase_single_ne {α : Type u_1} {M : Type u_5} [HasZero M] {a : α} {a' : α} {b : M} (h : a ≠ a') : erase a (single a' b) = single a' b := sorry @[simp] theorem erase_zero {α : Type u_1} {M : Type u_5} [HasZero M] (a : α) : erase a 0 = 0 := sorry /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ -- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := finset.sum (support f) fun (a : α) => g a (coe_fn f a) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ def prod {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := finset.prod (support f) fun (a : α) => g a (coe_fn f a) theorem sum_of_support_subset {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] (f : α →₀ M) {s : finset α} (hs : support f ⊆ s) (g : α → M → N) (h : ∀ (i : α), i ∈ s → g i 0 = 0) : sum f g = finset.sum s fun (x : α) => g x (coe_fn f x) := finset.sum_subset hs fun (x : α) (hxs : x ∈ s) (hx : ¬x ∈ support f) => Eq.subst (h x hxs) (congr_arg (g x)) (iff.mp not_mem_support_iff hx) theorem prod_fintype {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [comm_monoid N] [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ (i : α), g i 0 = 1) : prod f g = finset.prod finset.univ fun (i : α) => g i (coe_fn f i) := prod_of_support_subset f (finset.subset_univ (support f)) g fun (x : α) (_x : x ∈ finset.univ) => h x @[simp] theorem prod_single_index {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [comm_monoid N] {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : prod (single a b) h = h a b := sorry theorem prod_map_range_index {α : Type u_1} {M : Type u_5} {M' : Type u_6} {N : Type u_7} [HasZero M] [HasZero M'] [comm_monoid N] {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀ (a : α), h a 0 = 1) : prod (map_range f hf g) h = prod g fun (a : α) (b : M) => h a (f b) := sorry @[simp] theorem sum_zero_index {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] {h : α → M → N} : sum 0 h = 0 := rfl theorem sum_comm {α : Type u_1} {β : Type u_2} {M : Type u_5} {M' : Type u_6} {N : Type u_7} [HasZero M] [HasZero M'] [add_comm_monoid N] (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : (sum f fun (x : α) (v : M) => sum g fun (x' : β) (v' : M') => h x v x' v') = sum g fun (x' : β) (v' : M') => sum f fun (x : α) (v : M) => h x v x' v' := finset.sum_comm @[simp] theorem prod_ite_eq {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [comm_monoid N] [DecidableEq α] (f : α →₀ M) (a : α) (b : α → M → N) : (prod f fun (x : α) (v : M) => ite (a = x) (b x v) 1) = ite (a ∈ support f) (b a (coe_fn f a)) 1 := sorry @[simp] theorem sum_ite_self_eq {α : Type u_1} [DecidableEq α] {N : Type u_2} [add_comm_monoid N] (f : α →₀ N) (a : α) : (sum f fun (x : α) (v : N) => ite (a = x) v 0) = coe_fn f a := sorry /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp] theorem sum_ite_eq' {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] [DecidableEq α] (f : α →₀ M) (a : α) (b : α → M → N) : (sum f fun (x : α) (v : M) => ite (x = a) (b x v) 0) = ite (a ∈ support f) (b a (coe_fn f a)) 0 := sorry @[simp] theorem sum_ite_self_eq' {α : Type u_1} [DecidableEq α] {N : Type u_2} [add_comm_monoid N] (f : α →₀ N) (a : α) : (sum f fun (x : α) (v : N) => ite (x = a) v 0) = coe_fn f a := sorry @[simp] theorem prod_pow {α : Type u_1} {N : Type u_7} [comm_monoid N] [fintype α] (f : α →₀ ℕ) (g : α → N) : (prod f fun (a : α) (b : ℕ) => g a ^ b) = finset.prod finset.univ fun (a : α) => g a ^ coe_fn f a := prod_fintype f (fun (a : α) (b : ℕ) => g a ^ b) fun (a : α) => pow_zero (g a) /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ theorem on_finset_sum {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) (hg : ∀ (a : α), g a 0 = 0) : sum (on_finset s f hf) g = finset.sum s fun (a : α) => g a (f a) := sorry /-! ### Additive monoid structure on `α →₀ M` -/ protected instance has_add {α : Type u_1} {M : Type u_5} [add_monoid M] : Add (α →₀ M) := { add := zip_with Add.add sorry } @[simp] theorem coe_add {α : Type u_1} {M : Type u_5} [add_monoid M] (f : α →₀ M) (g : α →₀ M) : ⇑(f + g) = ⇑f + ⇑g := rfl theorem add_apply {α : Type u_1} {M : Type u_5} [add_monoid M] {g₁ : α →₀ M} {g₂ : α →₀ M} {a : α} : coe_fn (g₁ + g₂) a = coe_fn g₁ a + coe_fn g₂ a := rfl theorem support_add {α : Type u_1} {M : Type u_5} [add_monoid M] {g₁ : α →₀ M} {g₂ : α →₀ M} : support (g₁ + g₂) ⊆ support g₁ ∪ support g₂ := support_zip_with theorem support_add_eq {α : Type u_1} {M : Type u_5} [add_monoid M] {g₁ : α →₀ M} {g₂ : α →₀ M} (h : disjoint (support g₁) (support g₂)) : support (g₁ + g₂) = support g₁ ∪ support g₂ := sorry @[simp] theorem single_add {α : Type u_1} {M : Type u_5} [add_monoid M] {a : α} {b₁ : M} {b₂ : M} : single a (b₁ + b₂) = single a b₁ + single a b₂ := sorry protected instance add_monoid {α : Type u_1} {M : Type u_5} [add_monoid M] : add_monoid (α →₀ M) := add_monoid.mk Add.add sorry 0 sorry sorry /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` for the stronger version as a linear map. -/ def single_add_hom {α : Type u_1} {M : Type u_5} [add_monoid M] (a : α) : M →+ α →₀ M := add_monoid_hom.mk (single a) sorry sorry /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` for the stronger version as a linear map. -/ @[simp] theorem apply_add_hom_apply {α : Type u_1} {M : Type u_5} [add_monoid M] (a : α) (g : α →₀ M) : coe_fn (apply_add_hom a) g = coe_fn g a := Eq.refl (coe_fn (apply_add_hom a) g) theorem single_add_erase {α : Type u_1} {M : Type u_5} [add_monoid M] (a : α) (f : α →₀ M) : single a (coe_fn f a) + erase a f = f := sorry theorem erase_add_single {α : Type u_1} {M : Type u_5} [add_monoid M] (a : α) (f : α →₀ M) : erase a f + single a (coe_fn f a) = f := sorry @[simp] theorem erase_add {α : Type u_1} {M : Type u_5} [add_monoid M] (a : α) (f : α →₀ M) (f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := sorry protected theorem induction {α : Type u_1} {M : Type u_5} [add_monoid M] {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀ (a : α) (b : M) (f : α →₀ M), ¬a ∈ support f → b ≠ 0 → p f → p (single a b + f)) : p f := sorry theorem induction₂ {α : Type u_1} {M : Type u_5} [add_monoid M] {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀ (a : α) (b : M) (f : α →₀ M), ¬a ∈ support f → b ≠ 0 → p f → p (f + single a b)) : p f := sorry @[simp] theorem add_closure_Union_range_single {α : Type u_1} {M : Type u_5} [add_monoid M] : add_submonoid.closure (set.Union fun (a : α) => set.range (single a)) = ⊤ := sorry /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ theorem add_hom_ext {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_monoid M] [add_monoid N] {f : (α →₀ M) →+ N} {g : (α →₀ M) →+ N} (H : ∀ (x : α) (y : M), coe_fn f (single x y) = coe_fn g (single x y)) : f = g := sorry /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ theorem add_hom_ext' {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_monoid M] [add_monoid N] {f : (α →₀ M) →+ N} {g : (α →₀ M) →+ N} (H : ∀ (x : α), add_monoid_hom.comp f (single_add_hom x) = add_monoid_hom.comp g (single_add_hom x)) : f = g := add_hom_ext fun (x : α) => add_monoid_hom.congr_fun (H x) theorem mul_hom_ext {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_monoid M] [monoid N] {f : multiplicative (α →₀ M) →* N} {g : multiplicative (α →₀ M) →* N} (H : ∀ (x : α) (y : M), coe_fn f (coe_fn multiplicative.of_add (single x y)) = coe_fn g (coe_fn multiplicative.of_add (single x y))) : f = g := monoid_hom.ext (add_monoid_hom.congr_fun (add_hom_ext H)) theorem mul_hom_ext' {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_monoid M] [monoid N] {f : multiplicative (α →₀ M) →* N} {g : multiplicative (α →₀ M) →* N} (H : ∀ (x : α), monoid_hom.comp f (coe_fn add_monoid_hom.to_multiplicative (single_add_hom x)) = monoid_hom.comp g (coe_fn add_monoid_hom.to_multiplicative (single_add_hom x))) : f = g := mul_hom_ext fun (x : α) => monoid_hom.congr_fun (H x) theorem map_range_add {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_monoid M] [add_monoid N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ (x y : M), f (x + y) = f x + f y) (v₁ : α →₀ M) (v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := sorry end finsupp theorem mul_equiv.map_finsupp_prod {α : Type u_1} {M : Type u_5} {N : Type u_7} {P : Type u_8} [HasZero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : coe_fn h (finsupp.prod f g) = finsupp.prod f fun (a : α) (b : M) => coe_fn h (g a b) := mul_equiv.map_prod h (fun (a : α) => g a (coe_fn f a)) (finsupp.support f) theorem add_monoid_hom.map_finsupp_sum {α : Type u_1} {M : Type u_5} {N : Type u_7} {P : Type u_8} [HasZero M] [add_comm_monoid N] [add_comm_monoid P] (h : N →+ P) (f : α →₀ M) (g : α → M → N) : coe_fn h (finsupp.sum f g) = finsupp.sum f fun (a : α) (b : M) => coe_fn h (g a b) := add_monoid_hom.map_sum h (fun (a : α) => g a (coe_fn f a)) (finsupp.support f) theorem ring_hom.map_finsupp_sum {α : Type u_1} {M : Type u_5} {R : Type u_11} {S : Type u_12} [HasZero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : coe_fn h (finsupp.sum f g) = finsupp.sum f fun (a : α) (b : M) => coe_fn h (g a b) := ring_hom.map_sum h (fun (a : α) => g a (coe_fn f a)) (finsupp.support f) theorem ring_hom.map_finsupp_prod {α : Type u_1} {M : Type u_5} {R : Type u_11} {S : Type u_12} [HasZero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : coe_fn h (finsupp.prod f g) = finsupp.prod f fun (a : α) (b : M) => coe_fn h (g a b) := ring_hom.map_prod h (fun (a : α) => g a (coe_fn f a)) (finsupp.support f) theorem monoid_hom.coe_finsupp_prod {α : Type u_1} {β : Type u_2} {N : Type u_7} {P : Type u_8} [HasZero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(finsupp.prod f g) = finsupp.prod f fun (i : α) (fi : β) => ⇑(g i fi) := monoid_hom.coe_prod (fun (a : α) => g a (coe_fn f a)) (finsupp.support f) @[simp] theorem add_monoid_hom.finsupp_sum_apply {α : Type u_1} {β : Type u_2} {N : Type u_7} {P : Type u_8} [HasZero β] [add_monoid N] [add_comm_monoid P] (f : α →₀ β) (g : α → β → N →+ P) (x : N) : coe_fn (finsupp.sum f g) x = finsupp.sum f fun (i : α) (fi : β) => coe_fn (g i fi) x := add_monoid_hom.finset_sum_apply (fun (a : α) => g a (coe_fn f a)) (finsupp.support f) x namespace finsupp protected instance nat_sub {α : Type u_1} : Sub (α →₀ ℕ) := { sub := zip_with (fun (m n : ℕ) => m - n) sorry } @[simp] theorem nat_sub_apply {α : Type u_1} {g₁ : α →₀ ℕ} {g₂ : α →₀ ℕ} {a : α} : coe_fn (g₁ - g₂) a = coe_fn g₁ a - coe_fn g₂ a := rfl @[simp] theorem single_sub {α : Type u_1} {a : α} {n₁ : ℕ} {n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ := sorry -- These next two lemmas are used in developing -- the partial derivative on `mv_polynomial`. theorem sub_single_one_add {α : Type u_1} {a : α} {u : α →₀ ℕ} {u' : α →₀ ℕ} (h : coe_fn u a ≠ 0) : u - single a 1 + u' = u + u' - single a 1 := sorry theorem add_sub_single_one {α : Type u_1} {a : α} {u : α →₀ ℕ} {u' : α →₀ ℕ} (h : coe_fn u' a ≠ 0) : u + (u' - single a 1) = u + u' - single a 1 := sorry @[simp] theorem nat_zero_sub {α : Type u_1} (f : α →₀ ℕ) : 0 - f = 0 := ext fun (x : α) => nat.zero_sub (coe_fn f x) protected instance add_comm_monoid {α : Type u_1} {M : Type u_5} [add_comm_monoid M] : add_comm_monoid (α →₀ M) := add_comm_monoid.mk add_monoid.add sorry add_monoid.zero sorry sorry sorry protected instance has_sub {α : Type u_1} {G : Type u_9} [add_group G] : Sub (α →₀ G) := { sub := zip_with Sub.sub sorry } protected instance add_group {α : Type u_1} {G : Type u_9} [add_group G] : add_group (α →₀ G) := add_group.mk add_monoid.add sorry add_monoid.zero sorry sorry (map_range Neg.neg neg_zero) Sub.sub sorry protected instance add_comm_group {α : Type u_1} {G : Type u_9} [add_comm_group G] : add_comm_group (α →₀ G) := add_comm_group.mk add_group.add sorry add_group.zero sorry sorry add_group.neg add_group.sub sorry sorry theorem single_multiset_sum {α : Type u_1} {M : Type u_5} [add_comm_monoid M] (s : multiset M) (a : α) : single a (multiset.sum s) = multiset.sum (multiset.map (single a) s) := sorry theorem single_finset_sum {α : Type u_1} {ι : Type u_4} {M : Type u_5} [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (finset.sum s fun (b : ι) => f b) = finset.sum s fun (b : ι) => single a (f b) := sorry theorem single_sum {α : Type u_1} {ι : Type u_4} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (sum s f) = sum s fun (d : ι) (c : M) => single a (f d c) := single_finset_sum (support s) (fun (a : ι) => f a (coe_fn s a)) a theorem sum_neg_index {α : Type u_1} {M : Type u_5} {G : Type u_9} [add_group G] [add_comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀ (a : α), h a 0 = 0) : sum (-g) h = sum g fun (a : α) (b : G) => h a (-b) := sum_map_range_index h0 @[simp] theorem neg_apply {α : Type u_1} {G : Type u_9} [add_group G] {g : α →₀ G} {a : α} : coe_fn (-g) a = -coe_fn g a := rfl @[simp] theorem sub_apply {α : Type u_1} {G : Type u_9} [add_group G] {g₁ : α →₀ G} {g₂ : α →₀ G} {a : α} : coe_fn (g₁ - g₂) a = coe_fn g₁ a - coe_fn g₂ a := rfl @[simp] theorem support_neg {α : Type u_1} {G : Type u_9} [add_group G] {f : α →₀ G} : support (-f) = support f := finset.subset.antisymm support_map_range (trans_rel_right has_subset.subset (congr_arg support (Eq.symm (neg_neg f))) support_map_range) @[simp] theorem sum_apply {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : coe_fn (sum f g) a₂ = sum f fun (a₁ : α) (b : M) => coe_fn (g a₁ b) a₂ := add_monoid_hom.map_sum (apply_add_hom a₂) (fun (a : α) => g a (coe_fn f a)) (support f) theorem support_sum {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} : support (sum f g) ⊆ finset.bUnion (support f) fun (a : α) => support (g a (coe_fn f a)) := sorry @[simp] theorem sum_zero {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] {f : α →₀ M} : (sum f fun (a : α) (b : M) => 0) = 0 := finset.sum_const_zero @[simp] theorem prod_mul {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [comm_monoid N] {f : α →₀ M} {h₁ : α → M → N} {h₂ : α → M → N} : (prod f fun (a : α) (b : M) => h₁ a b * h₂ a b) = prod f h₁ * prod f h₂ := finset.prod_mul_distrib @[simp] theorem sum_neg {α : Type u_1} {M : Type u_5} {G : Type u_9} [HasZero M] [add_comm_group G] {f : α →₀ M} {h : α → M → G} : (sum f fun (a : α) (b : M) => -h a b) = -sum f h := Eq.symm (add_monoid_hom.map_sum (-add_monoid_hom.id G) (fun (x : α) => h x (coe_fn f x)) (support f)) @[simp] theorem sum_sub {α : Type u_1} {M : Type u_5} {G : Type u_9} [HasZero M] [add_comm_group G] {f : α →₀ M} {h₁ : α → M → G} {h₂ : α → M → G} : (sum f fun (a : α) (b : M) => h₁ a b - h₂ a b) = sum f h₁ - sum f h₂ := finset.sum_sub_distrib theorem prod_add_index {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [comm_monoid N] {f : α →₀ M} {g : α →₀ M} {h : α → M → N} (h_zero : ∀ (a : α), h a 0 = 1) (h_add : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ * h a b₂) : prod (f + g) h = prod f h * prod g h := sorry @[simp] theorem sum_add_index' {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] {f : α →₀ M} {g : α →₀ M} (h : α → M →+ N) : (sum (f + g) fun (x : α) => ⇑(h x)) = (sum f fun (x : α) => ⇑(h x)) + sum g fun (x : α) => ⇑(h x) := sum_add_index (fun (a : α) => add_monoid_hom.map_zero (h a)) fun (a : α) => add_monoid_hom.map_add (h a) @[simp] theorem prod_add_index' {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [comm_monoid N] {f : α →₀ M} {g : α →₀ M} (h : α → multiplicative M →* N) : (prod (f + g) fun (a : α) (b : M) => coe_fn (h a) (coe_fn multiplicative.of_add b)) = (prod f fun (a : α) (b : M) => coe_fn (h a) (coe_fn multiplicative.of_add b)) * prod g fun (a : α) (b : M) => coe_fn (h a) (coe_fn multiplicative.of_add b) := prod_add_index (fun (a : α) => monoid_hom.map_one (h a)) fun (a : α) => monoid_hom.map_mul (h a) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := add_equiv.mk (fun (F : α → M →+ N) => add_monoid_hom.mk (fun (f : α →₀ M) => sum f fun (x : α) => ⇑(F x)) sorry sorry) (fun (F : (α →₀ M) →+ N) (x : α) => add_monoid_hom.comp F (single_add_hom x)) sorry sorry sorry @[simp] theorem lift_add_hom_apply {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : coe_fn (coe_fn lift_add_hom F) f = sum f fun (x : α) => ⇑(F x) := rfl @[simp] theorem lift_add_hom_symm_apply {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : coe_fn (add_equiv.symm lift_add_hom) F x = add_monoid_hom.comp F (single_add_hom x) := rfl theorem lift_add_hom_symm_apply_apply {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : coe_fn (coe_fn (add_equiv.symm lift_add_hom) F x) y = coe_fn F (single x y) := rfl @[simp] theorem lift_add_hom_single_add_hom {α : Type u_1} {M : Type u_5} [add_comm_monoid M] : coe_fn lift_add_hom single_add_hom = add_monoid_hom.id (α →₀ M) := iff.mpr (equiv.apply_eq_iff_eq_symm_apply (add_equiv.to_equiv lift_add_hom)) rfl @[simp] theorem sum_single {α : Type u_1} {M : Type u_5} [add_comm_monoid M] (f : α →₀ M) : sum f single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] theorem lift_add_hom_apply_single {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : coe_fn (coe_fn lift_add_hom f) (single a b) = coe_fn (f a) b := sum_single_index (add_monoid_hom.map_zero (f a)) @[simp] theorem lift_add_hom_comp_single {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : add_monoid_hom.comp (coe_fn lift_add_hom f) (single_add_hom a) = f a := add_monoid_hom.ext fun (b : M) => lift_add_hom_apply_single f a b theorem comp_lift_add_hom {α : Type u_1} {M : Type u_5} {N : Type u_7} {P : Type u_8} [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : add_monoid_hom.comp g (coe_fn lift_add_hom f) = coe_fn lift_add_hom fun (a : α) => add_monoid_hom.comp g (f a) := sorry theorem sum_sub_index {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group β] [add_comm_group γ] {f : α →₀ β} {g : α →₀ β} {h : α → β → γ} (h_sub : ∀ (a : α) (b₁ b₂ : β), h a (b₁ - b₂) = h a b₁ - h a b₂) : sum (f - g) h = sum f h - sum g h := add_monoid_hom.map_sub (coe_fn lift_add_hom fun (a : α) => add_monoid_hom.of_map_sub (h a) (h_sub a)) f g theorem sum_emb_domain {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : sum (emb_domain f v) g = sum v fun (a : α) (b : M) => g (coe_fn f a) b := sorry theorem sum_finset_sum_index {α : Type u_1} {ι : Type u_4} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀ (a : α), h a 0 = 0) (h_add : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (finset.sum s fun (i : ι) => sum (g i) h) = sum (finset.sum s fun (i : ι) => g i) h := sorry theorem prod_sum_index {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} {P : Type u_8} [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀ (a : β), h a 0 = 1) (h_add : ∀ (a : β) (b₁ b₂ : N), h a (b₁ + b₂) = h a b₁ * h a b₂) : prod (sum f g) h = prod f fun (a : α) (b : M) => prod (g a b) h := Eq.symm (prod_finset_sum_index h_zero h_add) theorem multiset_sum_sum_index {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀ (a : α), h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : sum (multiset.sum f) h = multiset.sum (multiset.map (fun (g : α →₀ M) => sum g h) f) := sorry theorem multiset_map_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} {M : Type u_5} [HasZero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (sum f h) = sum f fun (a : α) (b : M) => multiset.map m (h a b) := Eq.symm (finset.sum_hom (support f) (multiset.map m)) theorem multiset_sum_sum {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (sum f h) = sum f fun (a : α) (b : M) => multiset.sum (h a b) := Eq.symm (finset.sum_hom (support f) multiset.sum) /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ def map_range.add_monoid_hom {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (f : M →+ N) : (α →₀ M) →+ α →₀ N := add_monoid_hom.mk (map_range ⇑f sorry) sorry sorry theorem map_range_multiset_sum {α : Type u_1} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (f : M →+ N) (m : multiset (α →₀ M)) : map_range (⇑f) (add_monoid_hom.map_zero f) (multiset.sum m) = multiset.sum (multiset.map (fun (x : α →₀ M) => map_range (⇑f) (add_monoid_hom.map_zero f) x) m) := Eq.symm (multiset.sum_hom m (map_range.add_monoid_hom f)) theorem map_range_finset_sum {α : Type u_1} {ι : Type u_4} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (f : M →+ N) (s : finset ι) (g : ι → α →₀ M) : map_range (⇑f) (add_monoid_hom.map_zero f) (finset.sum s fun (x : ι) => g x) = finset.sum s fun (x : ι) => map_range (⇑f) (add_monoid_hom.map_zero f) (g x) := sorry /-! ### Declarations about `map_domain` -/ /-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (f : α → β) (v : α →₀ M) : β →₀ M := sum v fun (a : α) => single (f a) theorem map_domain_apply {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) : coe_fn (map_domain f x) (f a) = coe_fn x a := sorry theorem map_domain_notin_range {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] {f : α → β} (x : α →₀ M) (a : β) (h : ¬a ∈ set.range f) : coe_fn (map_domain f x) a = 0 := sorry theorem map_domain_id {α : Type u_1} {M : Type u_5} [add_comm_monoid M] {v : α →₀ M} : map_domain id v = v := sum_single v theorem map_domain_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {M : Type u_5} [add_comm_monoid M] {v : α →₀ M} {f : α → β} {g : β → γ} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := Eq.symm (Eq.trans (sum_sum_index (fun (a : β) => single_zero) fun (a : β) (b₁ b₂ : M) => single_add) (finset.sum_congr rfl fun (_x : α) (_x_1 : _x ∈ support v) => sum_single_index single_zero)) theorem map_domain_single {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] theorem map_domain_zero {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] {f : α → β} : map_domain f 0 = 0 := sum_zero_index theorem map_domain_congr {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] {v : α →₀ M} {f : α → β} {g : α → β} (h : ∀ (x : α), x ∈ support v → f x = g x) : map_domain f v = map_domain g v := sorry theorem map_domain_add {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] {v₁ : α →₀ M} {v₂ : α →₀ M} {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (fun (_x : α) => single_zero) fun (_x : α) (_x_1 _x_2 : M) => single_add theorem map_domain_finset_sum {α : Type u_1} {β : Type u_2} {ι : Type u_4} {M : Type u_5} [add_comm_monoid M] {f : α → β} {s : finset ι} {v : ι → α →₀ M} : map_domain f (finset.sum s fun (i : ι) => v i) = finset.sum s fun (i : ι) => map_domain f (v i) := Eq.symm (sum_finset_sum_index (fun (_x : α) => single_zero) fun (_x : α) (_x_1 _x_2 : M) => single_add) theorem map_domain_sum {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [HasZero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : map_domain f (sum s v) = sum s fun (a : α) (b : N) => map_domain f (v a b) := Eq.symm (sum_finset_sum_index (fun (_x : α) => single_zero) fun (_x : α) (_x_1 _x_2 : M) => single_add) theorem map_domain_support {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] {f : α → β} {s : α →₀ M} : support (map_domain f s) ⊆ finset.image f (support s) := sorry theorem sum_map_domain_index {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀ (a : β), h a 0 = 0) (h_add : ∀ (a : β) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : sum (map_domain f s) h = sum s fun (a : α) (b : M) => h (f a) b := Eq.trans (sum_sum_index h_zero h_add) (finset.sum_congr rfl fun (_x : α) (_x_1 : _x ∈ support s) => sum_single_index (h_zero (f _x))) theorem emb_domain_eq_map_domain {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (f : α ↪ β) (v : α →₀ M) : emb_domain f v = map_domain (⇑f) v := sorry theorem sum_map_domain_index_inj {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : function.injective f) : sum (map_domain f s) h = sum s fun (a : α) (b : M) => h (f a) b := sorry theorem map_domain_injective {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] {f : α → β} (hf : function.injective f) : function.injective (map_domain f) := sorry /-! ### Declarations about `comap_domain` -/ /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ def comap_domain {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑(support l))) : α →₀ M := mk (finset.preimage (support l) f hf) (fun (a : α) => coe_fn l (f a)) sorry @[simp] theorem comap_domain_apply {α : Type u_1} {β : Type u_2} {M : Type u_5} [HasZero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑(support l))) (a : α) : coe_fn (comap_domain f l hf) a = coe_fn l (f a) := rfl theorem sum_comap_domain {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [HasZero M] [add_comm_monoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : set.bij_on f (f ⁻¹' ↑(support l)) ↑(support l)) : sum (comap_domain f l (set.bij_on.inj_on hf)) (g ∘ f) = sum l g := sorry theorem eq_zero_of_comap_domain_eq_zero {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑(support l)) ↑(support l)) : comap_domain f l (set.bij_on.inj_on hf) = 0 → l = 0 := sorry theorem map_domain_comap_domain {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : function.injective f) (hl : ↑(support l) ⊆ set.range f) : map_domain f (comap_domain f l (function.injective.inj_on hf (f ⁻¹' ↑(support l)))) = l := sorry /-! ### Declarations about `filter` -/ /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) (f : α →₀ M) : α →₀ M := mk (finset.filter (fun (a : α) => p a) (support f)) (fun (a : α) => ite (p a) (coe_fn f a) 0) sorry theorem filter_apply {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) (f : α →₀ M) (a : α) : coe_fn (filter p f) a = ite (p a) (coe_fn f a) 0 := rfl theorem filter_eq_indicator {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) (f : α →₀ M) : ⇑(filter p f) = set.indicator (set_of fun (x : α) => p x) ⇑f := rfl @[simp] theorem filter_apply_pos {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) (f : α →₀ M) {a : α} (h : p a) : coe_fn (filter p f) a = coe_fn f a := if_pos h @[simp] theorem filter_apply_neg {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) (f : α →₀ M) {a : α} (h : ¬p a) : coe_fn (filter p f) a = 0 := if_neg h @[simp] theorem support_filter {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) (f : α →₀ M) : support (filter p f) = finset.filter p (support f) := rfl theorem filter_zero {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) : filter p 0 = 0 := sorry @[simp] theorem filter_single_of_pos {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) {a : α} {b : M} (h : p a) : filter p (single a b) = single a b := sorry @[simp] theorem filter_single_of_neg {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) {a : α} {b : M} (h : ¬p a) : filter p (single a b) = 0 := sorry theorem filter_pos_add_filter_neg {α : Type u_1} {M : Type u_5} [add_monoid M] (f : α →₀ M) (p : α → Prop) : filter p f + filter (fun (a : α) => ¬p a) f = f := coe_fn_injective (set.indicator_self_add_compl (set_of fun (x : α) => p x) ⇑f) /-! ### Declarations about `frange` -/ /-- `frange f` is the image of `f` on the support of `f`. -/ def frange {α : Type u_1} {M : Type u_5} [HasZero M] (f : α →₀ M) : finset M := finset.image (⇑f) (support f) theorem mem_frange {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} {y : M} : y ∈ frange f ↔ y ≠ 0 ∧ ∃ (x : α), coe_fn f x = y := sorry theorem zero_not_mem_frange {α : Type u_1} {M : Type u_5} [HasZero M] {f : α →₀ M} : ¬0 ∈ frange f := fun (H : 0 ∈ frange f) => and.left (iff.mp mem_frange H) rfl theorem frange_single {α : Type u_1} {M : Type u_5} [HasZero M] {x : α} {y : M} : frange (single x y) ⊆ singleton y := sorry /-! ### Declarations about `subtype_domain` -/ /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain {α : Type u_1} {M : Type u_5} [HasZero M] (p : α → Prop) (f : α →₀ M) : Subtype p →₀ M := mk (finset.subtype p (support f)) (⇑f ∘ coe) sorry @[simp] theorem support_subtype_domain {α : Type u_1} {M : Type u_5} [HasZero M] {p : α → Prop} {f : α →₀ M} : support (subtype_domain p f) = finset.subtype p (support f) := rfl @[simp] theorem subtype_domain_apply {α : Type u_1} {M : Type u_5} [HasZero M] {p : α → Prop} {a : Subtype p} {v : α →₀ M} : coe_fn (subtype_domain p v) a = coe_fn v (subtype.val a) := rfl @[simp] theorem subtype_domain_zero {α : Type u_1} {M : Type u_5} [HasZero M] {p : α → Prop} : subtype_domain p 0 = 0 := rfl theorem subtype_domain_eq_zero_iff' {α : Type u_1} {M : Type u_5} [HasZero M] {p : α → Prop} {f : α →₀ M} : subtype_domain p f = 0 ↔ ∀ (x : α), p x → coe_fn f x = 0 := sorry theorem subtype_domain_eq_zero_iff {α : Type u_1} {M : Type u_5} [HasZero M] {p : α → Prop} {f : α →₀ M} (hf : ∀ (x : α), x ∈ support f → p x) : subtype_domain p f = 0 ↔ f = 0 := sorry theorem prod_subtype_domain_index {α : Type u_1} {M : Type u_5} {N : Type u_7} [HasZero M] {p : α → Prop} [comm_monoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀ (x : α), x ∈ support v → p x) : (prod (subtype_domain p v) fun (a : Subtype p) (b : M) => h (↑a) b) = prod v h := sorry @[simp] theorem subtype_domain_add {α : Type u_1} {M : Type u_5} [add_monoid M] {p : α → Prop} {v : α →₀ M} {v' : α →₀ M} : subtype_domain p (v + v') = subtype_domain p v + subtype_domain p v' := ext fun (_x : Subtype p) => rfl protected instance subtype_domain.is_add_monoid_hom {α : Type u_1} {M : Type u_5} [add_monoid M] {p : α → Prop} : is_add_monoid_hom (subtype_domain p) := is_add_monoid_hom.mk subtype_domain_zero /-- `finsupp.filter` as an `add_monoid_hom`. -/ def filter_add_hom {α : Type u_1} {M : Type u_5} [add_monoid M] (p : α → Prop) : (α →₀ M) →+ α →₀ M := add_monoid_hom.mk (filter p) sorry sorry @[simp] theorem filter_add {α : Type u_1} {M : Type u_5} [add_monoid M] {p : α → Prop} {v : α →₀ M} {v' : α →₀ M} : filter p (v + v') = filter p v + filter p v' := add_monoid_hom.map_add (filter_add_hom p) v v' theorem subtype_domain_sum {α : Type u_1} {ι : Type u_4} {M : Type u_5} [add_comm_monoid M] {p : α → Prop} {s : finset ι} {h : ι → α →₀ M} : subtype_domain p (finset.sum s fun (c : ι) => h c) = finset.sum s fun (c : ι) => subtype_domain p (h c) := Eq.symm (finset.sum_hom s (subtype_domain p)) theorem subtype_domain_finsupp_sum {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] {p : α → Prop} [HasZero N] {s : β →₀ N} {h : β → N → α →₀ M} : subtype_domain p (sum s h) = sum s fun (c : β) (d : N) => subtype_domain p (h c d) := subtype_domain_sum theorem filter_sum {α : Type u_1} {ι : Type u_4} {M : Type u_5} [add_comm_monoid M] {p : α → Prop} (s : finset ι) (f : ι → α →₀ M) : filter p (finset.sum s fun (a : ι) => f a) = finset.sum s fun (a : ι) => filter p (f a) := add_monoid_hom.map_sum (filter_add_hom p) f s theorem filter_eq_sum {α : Type u_1} {M : Type u_5} [add_comm_monoid M] (p : α → Prop) (f : α →₀ M) : filter p f = finset.sum (finset.filter p (support f)) fun (i : α) => single i (coe_fn f i) := sorry @[simp] theorem subtype_domain_neg {α : Type u_1} {G : Type u_9} [add_group G] {p : α → Prop} {v : α →₀ G} : subtype_domain p (-v) = -subtype_domain p v := ext fun (_x : Subtype p) => rfl @[simp] theorem subtype_domain_sub {α : Type u_1} {G : Type u_9} [add_group G] {p : α → Prop} {v : α →₀ G} {v' : α →₀ G} : subtype_domain p (v - v') = subtype_domain p v - subtype_domain p v' := ext fun (_x : Subtype p) => rfl /-! ### Declarations relating `finsupp` to `multiset` -/ /-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of `f` on the elements of `α`. We define this function as an `add_equiv`. -/ def to_multiset {α : Type u_1} : (α →₀ ℕ) ≃+ multiset α := add_equiv.mk (fun (f : α →₀ ℕ) => sum f fun (a : α) (n : ℕ) => n •ℕ singleton a) (fun (s : multiset α) => mk (multiset.to_finset s) (fun (a : α) => multiset.count a s) sorry) sorry sorry sorry theorem to_multiset_zero {α : Type u_1} : coe_fn to_multiset 0 = 0 := rfl theorem to_multiset_add {α : Type u_1} (m : α →₀ ℕ) (n : α →₀ ℕ) : coe_fn to_multiset (m + n) = coe_fn to_multiset m + coe_fn to_multiset n := add_equiv.map_add to_multiset m n theorem to_multiset_apply {α : Type u_1} (f : α →₀ ℕ) : coe_fn to_multiset f = sum f fun (a : α) (n : ℕ) => n •ℕ singleton a := rfl @[simp] theorem to_multiset_single {α : Type u_1} (a : α) (n : ℕ) : coe_fn to_multiset (single a n) = n •ℕ singleton a := sorry theorem card_to_multiset {α : Type u_1} (f : α →₀ ℕ) : coe_fn multiset.card (coe_fn to_multiset f) = sum f fun (a : α) => id := sorry theorem to_multiset_map {α : Type u_1} {β : Type u_2} (f : α →₀ ℕ) (g : α → β) : multiset.map g (coe_fn to_multiset f) = coe_fn to_multiset (map_domain g f) := sorry @[simp] theorem prod_to_multiset {M : Type u_5} [comm_monoid M] (f : M →₀ ℕ) : multiset.prod (coe_fn to_multiset f) = prod f fun (a : M) (n : ℕ) => a ^ n := sorry @[simp] theorem to_finset_to_multiset {α : Type u_1} (f : α →₀ ℕ) : multiset.to_finset (coe_fn to_multiset f) = support f := sorry @[simp] theorem count_to_multiset {α : Type u_1} (f : α →₀ ℕ) (a : α) : multiset.count a (coe_fn to_multiset f) = coe_fn f a := sorry theorem mem_support_multiset_sum {α : Type u_1} {M : Type u_5} [add_comm_monoid M] {s : multiset (α →₀ M)} (a : α) : a ∈ support (multiset.sum s) → ∃ (f : α →₀ M), ∃ (H : f ∈ s), a ∈ support f := sorry theorem mem_support_finset_sum {α : Type u_1} {ι : Type u_4} {M : Type u_5} [add_comm_monoid M] {s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ support (finset.sum s fun (c : ι) => h c)) : ∃ (c : ι), ∃ (H : c ∈ s), a ∈ support (h c) := sorry @[simp] theorem mem_to_multiset {α : Type u_1} (f : α →₀ ℕ) (i : α) : i ∈ coe_fn to_multiset f ↔ i ∈ support f := sorry /-! ### Declarations about `curry` and `uncurry` -/ /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (f : α × β →₀ M) : α →₀ β →₀ M := sum f fun (p : α × β) (c : M) => single (prod.fst p) (single (prod.snd p) c) theorem sum_curry_index {α : Type u_1} {β : Type u_2} {M : Type u_5} {N : Type u_7} [add_comm_monoid M] [add_comm_monoid N] (f : α × β →₀ M) (g : α → β → M → N) (hg₀ : ∀ (a : α) (b : β), g a b 0 = 0) (hg₁ : ∀ (a : α) (b : β) (c₀ c₁ : M), g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : (sum (finsupp.curry f) fun (a : α) (f : β →₀ M) => sum f (g a)) = sum f fun (p : α × β) (c : M) => g (prod.fst p) (prod.snd p) c := sorry /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (f : α →₀ β →₀ M) : α × β →₀ M := sum f fun (a : α) (g : β →₀ M) => sum g fun (b : β) (c : M) => single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsupp_prod_equiv {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] : (α × β →₀ M) ≃ (α →₀ β →₀ M) := equiv.mk finsupp.curry finsupp.uncurry sorry sorry theorem filter_curry {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (f : α × β →₀ M) (p : α → Prop) : finsupp.curry (filter (fun (a : α × β) => p (prod.fst a)) f) = filter p (finsupp.curry f) := sorry theorem support_curry {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (f : α × β →₀ M) : support (finsupp.curry f) ⊆ finset.image prod.fst (support f) := sorry /-- Scalar multiplication by a group element g, given by precomposition with the action of g⁻¹ on the domain. -/ def comap_has_scalar {α : Type u_1} {M : Type u_5} {G : Type u_9} [group G] [mul_action G α] [add_comm_monoid M] : has_scalar G (α →₀ M) := has_scalar.mk fun (g : G) (f : α →₀ M) => comap_domain (fun (a : α) => g⁻¹ • a) f sorry /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is multiplicative in g. -/ def comap_mul_action {α : Type u_1} {M : Type u_5} {G : Type u_9} [group G] [mul_action G α] [add_comm_monoid M] : mul_action G (α →₀ M) := mul_action.mk sorry sorry /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is additive in the second argument. -/ def comap_distrib_mul_action {α : Type u_1} {M : Type u_5} {G : Type u_9} [group G] [mul_action G α] [add_comm_monoid M] : distrib_mul_action G (α →₀ M) := distrib_mul_action.mk sorry sorry /-- Scalar multiplication by a group element on finitely supported functions on a group, given by precomposition with the action of g⁻¹. -/ def comap_distrib_mul_action_self {M : Type u_5} {G : Type u_9} [group G] [add_comm_monoid M] : distrib_mul_action G (G →₀ M) := comap_distrib_mul_action @[simp] theorem comap_smul_single {α : Type u_1} {M : Type u_5} {G : Type u_9} [group G] [mul_action G α] [add_comm_monoid M] (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := sorry @[simp] theorem comap_smul_apply {α : Type u_1} {M : Type u_5} {G : Type u_9} [group G] [mul_action G α] [add_comm_monoid M] (g : G) (f : α →₀ M) (a : α) : coe_fn (g • f) a = coe_fn f (g⁻¹ • a) := rfl protected instance has_scalar {α : Type u_1} {M : Type u_5} {R : Type u_11} [semiring R] [add_comm_monoid M] [semimodule R M] : has_scalar R (α →₀ M) := has_scalar.mk fun (a : R) (v : α →₀ M) => map_range (has_scalar.smul a) sorry v /-! Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] theorem smul_apply' (α : Type u_1) (M : Type u_5) {R : Type u_11} {_x : semiring R} [add_comm_monoid M] [semimodule R M] {a : α} {b : R} {v : α →₀ M} : coe_fn (b • v) a = b • coe_fn v a := rfl protected instance semimodule (α : Type u_1) (M : Type u_5) {R : Type u_11} [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule R (α →₀ M) := semimodule.mk sorry sorry theorem support_smul {α : Type u_1} {M : Type u_5} {R : Type u_11} {_x : semiring R} [add_comm_monoid M] [semimodule R M] {b : R} {g : α →₀ M} : support (b • g) ⊆ support g := sorry @[simp] theorem filter_smul {α : Type u_1} {M : Type u_5} {R : Type u_11} {p : α → Prop} {_x : semiring R} [add_comm_monoid M] [semimodule R M] {b : R} {v : α →₀ M} : filter p (b • v) = b • filter p v := coe_fn_injective (set.indicator_smul (set_of fun (x : α) => p x) b ⇑v) theorem map_domain_smul {α : Type u_1} {β : Type u_2} {M : Type u_5} {R : Type u_11} {_x : semiring R} [add_comm_monoid M] [semimodule R M] {f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v := sorry @[simp] theorem smul_single {α : Type u_1} {M : Type u_5} {R : Type u_11} {_x : semiring R} [add_comm_monoid M] [semimodule R M] (c : R) (a : α) (b : M) : c • single a b = single a (c • b) := map_range_single @[simp] theorem smul_single' {α : Type u_1} {R : Type u_11} {_x : semiring R} (c : R) (a : α) (b : R) : c • single a b = single a (c * b) := smul_single c a b theorem smul_single_one {α : Type u_1} {R : Type u_11} [semiring R] (a : α) (b : R) : b • single a 1 = single a b := eq.mpr (id (Eq._oldrec (Eq.refl (b • single a 1 = single a b)) (smul_single b a 1))) (eq.mpr (id (Eq._oldrec (Eq.refl (single a (b • 1) = single a b)) smul_eq_mul)) (eq.mpr (id (Eq._oldrec (Eq.refl (single a (b * 1) = single a b)) (mul_one b))) (Eq.refl (single a b)))) @[simp] theorem smul_apply {α : Type u_1} {R : Type u_11} [semiring R] {a : α} {b : R} {v : α →₀ R} : coe_fn (b • v) a = b • coe_fn v a := rfl theorem sum_smul_index {α : Type u_1} {M : Type u_5} {R : Type u_11} [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀ (i : α), h i 0 = 0) : sum (b • g) h = sum g fun (i : α) (a : R) => h i (b * a) := sum_map_range_index h0 theorem sum_smul_index' {α : Type u_1} {M : Type u_5} {N : Type u_7} {R : Type u_11} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀ (i : α), h i 0 = 0) : sum (b • g) h = sum g fun (i : α) (c : M) => h i (b • c) := sum_map_range_index h0 theorem sum_mul {α : Type u_1} {R : Type u_11} {S : Type u_12} [semiring R] [semiring S] (b : S) (s : α →₀ R) {f : α → R → S} : sum s f * b = sum s fun (a : α) (c : R) => f a c * b := sorry theorem mul_sum {α : Type u_1} {R : Type u_11} {S : Type u_12} [semiring R] [semiring S] (b : S) (s : α →₀ R) {f : α → R → S} : b * sum s f = sum s fun (a : α) (c : R) => b * f a c := sorry protected instance unique_of_right {α : Type u_1} {R : Type u_11} [semiring R] [subsingleton R] : unique (α →₀ R) := unique.mk { default := Inhabited.default } sorry /-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv {α : Type u_1} (s : set α) (M : Type u_2) [add_comm_monoid M] : (Subtype fun (f : α →₀ M) => ↑(support f) ⊆ s) ≃ (↥s →₀ M) := equiv.mk (fun (f : Subtype fun (f : α →₀ M) => ↑(support f) ⊆ s) => subtype_domain (fun (x : α) => x ∈ s) (subtype.val f)) (fun (f : ↥s →₀ M) => { val := map_domain subtype.val f, property := sorry }) sorry sorry /-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between `α →₀ M` and `β →₀ M`. -/ protected def dom_congr {α : Type u_1} {β : Type u_2} {M : Type u_5} [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) := add_equiv.mk (map_domain ⇑e) (map_domain ⇑(equiv.symm e)) sorry sorry sorry end finsupp namespace finsupp /-! ### Declarations about sigma types -/ /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. -/ def split {ι : Type u_4} {M : Type u_5} {αs : ι → Type u_13} [HasZero M] (l : (sigma fun (i : ι) => αs i) →₀ M) (i : ι) : αs i →₀ M := comap_domain (sigma.mk i) l sorry theorem split_apply {ι : Type u_4} {M : Type u_5} {αs : ι → Type u_13} [HasZero M] (l : (sigma fun (i : ι) => αs i) →₀ M) (i : ι) (x : αs i) : coe_fn (split l i) x = coe_fn l (sigma.mk i x) := sorry /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support {ι : Type u_4} {M : Type u_5} {αs : ι → Type u_13} [HasZero M] (l : (sigma fun (i : ι) => αs i) →₀ M) : finset ι := finset.image sigma.fst (support l) theorem mem_split_support_iff_nonzero {ι : Type u_4} {M : Type u_5} {αs : ι → Type u_13} [HasZero M] (l : (sigma fun (i : ι) => αs i) →₀ M) (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := sorry /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp {ι : Type u_4} {M : Type u_5} {N : Type u_7} {αs : ι → Type u_13} [HasZero M] (l : (sigma fun (i : ι) => αs i) →₀ M) [HasZero N] (g : (i : ι) → (αs i →₀ M) → N) (hg : ∀ (i : ι) (x : αs i →₀ M), x = 0 ↔ g i x = 0) : ι →₀ N := mk (split_support l) (fun (i : ι) => g i (split l i)) sorry theorem sigma_support {ι : Type u_4} {M : Type u_5} {αs : ι → Type u_13} [HasZero M] (l : (sigma fun (i : ι) => αs i) →₀ M) : support l = finset.sigma (split_support l) fun (i : ι) => support (split l i) := sorry theorem sigma_sum {ι : Type u_4} {M : Type u_5} {N : Type u_7} {αs : ι → Type u_13} [HasZero M] (l : (sigma fun (i : ι) => αs i) →₀ M) [add_comm_monoid N] (f : (sigma fun (i : ι) => αs i) → M → N) : sum l f = finset.sum (split_support l) fun (i : ι) => sum (split l i) fun (a : αs i) (b : M) => f (sigma.mk i a) b := sorry end finsupp /-! ### Declarations relating `multiset` to `finsupp` -/ namespace multiset /-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by the multiplicities of the elements of `s`. -/ def to_finsupp {α : Type u_1} : multiset α ≃+ (α →₀ ℕ) := add_equiv.symm finsupp.to_multiset @[simp] theorem to_finsupp_support {α : Type u_1} (s : multiset α) : finsupp.support (coe_fn to_finsupp s) = to_finset s := rfl @[simp] theorem to_finsupp_apply {α : Type u_1} (s : multiset α) (a : α) : coe_fn (coe_fn to_finsupp s) a = count a s := rfl theorem to_finsupp_zero {α : Type u_1} : coe_fn to_finsupp 0 = 0 := add_equiv.map_zero to_finsupp theorem to_finsupp_add {α : Type u_1} (s : multiset α) (t : multiset α) : coe_fn to_finsupp (s + t) = coe_fn to_finsupp s + coe_fn to_finsupp t := add_equiv.map_add to_finsupp s t @[simp] theorem to_finsupp_singleton {α : Type u_1} (a : α) : coe_fn to_finsupp (a ::ₘ 0) = finsupp.single a 1 := sorry @[simp] theorem to_finsupp_to_multiset {α : Type u_1} (s : multiset α) : coe_fn finsupp.to_multiset (coe_fn to_finsupp s) = s := add_equiv.apply_symm_apply finsupp.to_multiset s theorem to_finsupp_eq_iff {α : Type u_1} {s : multiset α} {f : α →₀ ℕ} : coe_fn to_finsupp s = f ↔ s = coe_fn finsupp.to_multiset f := add_equiv.symm_apply_eq finsupp.to_multiset end multiset @[simp] theorem finsupp.to_multiset_to_finsupp {α : Type u_1} (f : α →₀ ℕ) : coe_fn multiset.to_finsupp (coe_fn finsupp.to_multiset f) = f := add_equiv.symm_apply_apply finsupp.to_multiset f /-! ### Declarations about order(ed) instances on `finsupp` -/ namespace finsupp protected instance preorder {α : Type u_1} {M : Type u_5} [preorder M] [HasZero M] : preorder (α →₀ M) := preorder.mk (fun (f g : α →₀ M) => ∀ (s : α), coe_fn f s ≤ coe_fn g s) (fun (a b : α →₀ M) => (∀ (s : α), coe_fn a s ≤ coe_fn b s) ∧ ¬∀ (s : α), coe_fn b s ≤ coe_fn a s) sorry sorry protected instance partial_order {α : Type u_1} {M : Type u_5} [partial_order M] [HasZero M] : partial_order (α →₀ M) := partial_order.mk preorder.le preorder.lt sorry sorry sorry protected instance add_left_cancel_semigroup {α : Type u_1} {M : Type u_5} [ordered_cancel_add_comm_monoid M] : add_left_cancel_semigroup (α →₀ M) := add_left_cancel_semigroup.mk add_monoid.add sorry sorry protected instance add_right_cancel_semigroup {α : Type u_1} {M : Type u_5} [ordered_cancel_add_comm_monoid M] : add_right_cancel_semigroup (α →₀ M) := add_right_cancel_semigroup.mk add_monoid.add sorry sorry protected instance ordered_cancel_add_comm_monoid {α : Type u_1} {M : Type u_5} [ordered_cancel_add_comm_monoid M] : ordered_cancel_add_comm_monoid (α →₀ M) := ordered_cancel_add_comm_monoid.mk add_comm_monoid.add sorry sorry add_comm_monoid.zero sorry sorry sorry sorry partial_order.le partial_order.lt sorry sorry sorry sorry sorry theorem le_def {α : Type u_1} {M : Type u_5} [preorder M] [HasZero M] {f : α →₀ M} {g : α →₀ M} : f ≤ g ↔ ∀ (x : α), coe_fn f x ≤ coe_fn g x := iff.rfl theorem le_iff {α : Type u_1} {M : Type u_5} [canonically_ordered_add_monoid M] (f : α →₀ M) (g : α →₀ M) : f ≤ g ↔ ∀ (s : α), s ∈ support f → coe_fn f s ≤ coe_fn g s := sorry @[simp] theorem add_eq_zero_iff {α : Type u_1} {M : Type u_5} [canonically_ordered_add_monoid M] (f : α →₀ M) (g : α →₀ M) : f + g = 0 ↔ f = 0 ∧ g = 0 := sorry /-- `finsupp.to_multiset` as an order isomorphism. -/ def order_iso_multiset {α : Type u_1} : (α →₀ ℕ) ≃o multiset α := rel_iso.mk (add_equiv.to_equiv to_multiset) sorry @[simp] theorem coe_order_iso_multiset {α : Type u_1} : ⇑order_iso_multiset = ⇑to_multiset := rfl @[simp] theorem coe_order_iso_multiset_symm {α : Type u_1} : ⇑(order_iso.symm order_iso_multiset) = ⇑multiset.to_finsupp := rfl theorem to_multiset_strict_mono {α : Type u_1} : strict_mono ⇑to_multiset := order_iso.strict_mono order_iso_multiset theorem sum_id_lt_of_lt {α : Type u_1} (m : α →₀ ℕ) (n : α →₀ ℕ) (h : m < n) : (sum m fun (_x : α) => id) < sum n fun (_x : α) => id := sorry /-- The order on `σ →₀ ℕ` is well-founded.-/ theorem lt_wf (α : Type u_1) : well_founded Less := subrelation.wf sum_id_lt_of_lt (inv_image.wf (fun (x : α →₀ ℕ) => sum x fun (_x : α) => id) nat.lt_wf) protected instance decidable_le (α : Type u_1) : DecidableRel LessEq := fun (m n : α →₀ ℕ) => eq.mpr sorry finset.decidable_dforall_finset @[simp] theorem nat_add_sub_cancel {α : Type u_1} (f : α →₀ ℕ) (g : α →₀ ℕ) : f + g - g = f := ext fun (a : α) => nat.add_sub_cancel (coe_fn f a) (coe_fn g a) @[simp] theorem nat_add_sub_cancel_left {α : Type u_1} (f : α →₀ ℕ) (g : α →₀ ℕ) : f + g - f = g := ext fun (a : α) => nat.add_sub_cancel_left (coe_fn f a) (coe_fn g a) theorem nat_add_sub_of_le {α : Type u_1} {f : α →₀ ℕ} {g : α →₀ ℕ} (h : f ≤ g) : f + (g - f) = g := ext fun (a : α) => nat.add_sub_of_le (h a) theorem nat_sub_add_cancel {α : Type u_1} {f : α →₀ ℕ} {g : α →₀ ℕ} (h : f ≤ g) : g - f + f = g := ext fun (a : α) => nat.sub_add_cancel (h a) protected instance canonically_ordered_add_monoid {α : Type u_1} : canonically_ordered_add_monoid (α →₀ ℕ) := canonically_ordered_add_monoid.mk ordered_add_comm_monoid.add sorry ordered_add_comm_monoid.zero sorry sorry sorry ordered_add_comm_monoid.le ordered_add_comm_monoid.lt sorry sorry sorry sorry sorry 0 sorry sorry /-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/ def antidiagonal {α : Type u_1} (f : α →₀ ℕ) : (α →₀ ℕ) × (α →₀ ℕ) →₀ ℕ := coe_fn multiset.to_finsupp (multiset.map (prod.map ⇑multiset.to_finsupp ⇑multiset.to_finsupp) (multiset.antidiagonal (coe_fn to_multiset f))) @[simp] theorem mem_antidiagonal_support {α : Type u_1} {f : α →₀ ℕ} {p : (α →₀ ℕ) × (α →₀ ℕ)} : p ∈ support (antidiagonal f) ↔ prod.fst p + prod.snd p = f := sorry theorem swap_mem_antidiagonal_support {α : Type u_1} {n : α →₀ ℕ} {f : (α →₀ ℕ) × (α →₀ ℕ)} : prod.swap f ∈ support (antidiagonal n) ↔ f ∈ support (antidiagonal n) := sorry theorem antidiagonal_support_filter_fst_eq {α : Type u_1} (f : α →₀ ℕ) (g : α →₀ ℕ) : finset.filter (fun (p : (α →₀ ℕ) × (α →₀ ℕ)) => prod.fst p = g) (support (antidiagonal f)) = ite (g ≤ f) (singleton (g, f - g)) ∅ := sorry theorem antidiagonal_support_filter_snd_eq {α : Type u_1} (f : α →₀ ℕ) (g : α →₀ ℕ) : finset.filter (fun (p : (α →₀ ℕ) × (α →₀ ℕ)) => prod.snd p = g) (support (antidiagonal f)) = ite (g ≤ f) (singleton (f - g, g)) ∅ := sorry @[simp] theorem antidiagonal_zero {α : Type u_1} : antidiagonal 0 = single (0, 0) 1 := eq.mpr (id (Eq._oldrec (Eq.refl (antidiagonal 0 = single (0, 0) 1)) (Eq.symm (multiset.to_finsupp_singleton (0, 0))))) (Eq.refl (antidiagonal 0)) theorem sum_antidiagonal_support_swap {α : Type u_1} {M : Type u_2} [add_comm_monoid M] (n : α →₀ ℕ) (f : (α →₀ ℕ) → (α →₀ ℕ) → M) : (finset.sum (support (antidiagonal n)) fun (p : (α →₀ ℕ) × (α →₀ ℕ)) => f (prod.fst p) (prod.snd p)) = finset.sum (support (antidiagonal n)) fun (p : (α →₀ ℕ) × (α →₀ ℕ)) => f (prod.snd p) (prod.fst p) := sorry /-- The set `{m : α →₀ ℕ | m ≤ n}` as a `finset`. -/ def Iic_finset {α : Type u_1} (n : α →₀ ℕ) : finset (α →₀ ℕ) := finset.image prod.fst (support (antidiagonal n)) @[simp] theorem mem_Iic_finset {α : Type u_1} {m : α →₀ ℕ} {n : α →₀ ℕ} : m ∈ Iic_finset n ↔ m ≤ n := sorry @[simp] theorem coe_Iic_finset {α : Type u_1} (n : α →₀ ℕ) : ↑(Iic_finset n) = set.Iic n := sorry /-- Let `n : α →₀ ℕ` be a finitely supported function. The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`, is a finite set. -/ theorem finite_le_nat {α : Type u_1} (n : α →₀ ℕ) : set.finite (set_of fun (m : α →₀ ℕ) => m ≤ n) := sorry /-- Let `n : α →₀ ℕ` be a finitely supported function. The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`, but not equal to `n` everywhere, is a finite set. -/ theorem finite_lt_nat {α : Type u_1} (n : α →₀ ℕ) : set.finite (set_of fun (m : α →₀ ℕ) => m < n) := set.finite.subset (finite_le_nat n) fun (m : α →₀ ℕ) => le_of_lt end finsupp namespace multiset theorem to_finsuppstrict_mono {α : Type u_1} : strict_mono ⇑to_finsupp := order_iso.strict_mono (order_iso.symm finsupp.order_iso_multiset)
e636465d1b2491dddea9286b8269070627708d65
9a0b1b3a653ea926b03d1495fef64da1d14b3174
/tidy/rewrite_search/core/engine.lean
a20f33891405c3ae967133e14f5663609bdd0d42
[ "Apache-2.0" ]
permissive
khoek/mathlib-tidy
8623b27b4e04e7d598164e7eaf248610d58f768b
866afa6ab597c47f1b72e8fe2b82b97fff5b980f
refs/heads/master
1,585,598,975,772
1,538,659,544,000
1,538,659,544,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,748
lean
import tidy.lib.pretty_print import tidy.rewrite_search.discovery.collect import .types import .debug import .explain open tactic universe u namespace tidy.rewrite_search variables {α β γ δ : Type} (i : inst α β γ δ) (g : search_state α β γ δ) (m : metric α β γ δ) namespace search_state meta def unmark_all_visited : tactic (search_state α β γ δ) := do return { g with vertices := g.vertices.map $ λ v, {v with visited := ff} } meta def reset_estimate (init : init_bound_fn α β γ δ) (de : dist_estimate γ) : tactic (dist_estimate γ) := do (vl, vr) ← g.get_estimate_verts de, return de meta def reset_all_estimates (init : init_bound_fn α β γ δ) : tactic (search_state α β γ δ) := do new_estimates ← g.estimates.mmap $ g.reset_estimate init, return { g with estimates := new_estimates } private meta def register_tokens_aux (s : side) : table token → list string → table token × list table_ref | tokens [] := (tokens, []) | tokens (tstr :: rest) := do let (tokens, t) := find_or_create_token tokens s tstr, let (tokens, l) := register_tokens_aux tokens rest, (tokens, t.id :: l) meta def register_tokens (s : side) (strs : list string) : search_state α β γ δ × list table_ref := let (new_tokens, refs) := register_tokens_aux s g.tokens strs in ({g with tokens := new_tokens}, refs) private meta def find_vertex_aux (pp : string) : list vertex → option vertex | [] := none | (a :: rest) := if a.pp = pp then some a else find_vertex_aux rest -- Find the vertex with the given (e : expr), or return the null verterx if not -- found. meta def find_vertex (e : expr) : tactic (option vertex) := do pp ← pretty_print e, return (g.vertices.find_key pp) -- Forcibly add a new vertex to the vertex table. You probably actually want to call -- add_vertex, which will check that we haven't seen the vertex before first. meta def alloc_vertex (e : expr) (root : bool) (s : side) : tactic (search_state α β γ δ × vertex) := do (pp, tokens) ← tokenise_expr e, let (g, token_refs) := g.register_tokens s tokens, let v : vertex := vertex.create g.vertices.next_id e pp token_refs root s, return ({ g with vertices := g.vertices.alloc v }, v) -- Look up the given vertex associated to (e : expr), or create it if it is -- not already present. meta def add_vertex_aux (e : expr) (root : bool) (s : side) : tactic (search_state α β γ δ × vertex) := do maybe_v ← g.find_vertex e, match maybe_v with | none := do (g, v) ← g.alloc_vertex e root s, g.tracer_vertex_added v, return (g, v) | (some v) := return (g, v) end meta def add_vertex (e : expr) (s : side) := g.add_vertex_aux e ff s meta def add_root_vertex (e : expr) (s : side) := g.add_vertex_aux e tt s meta def register_solved (e : edge) : search_state α β γ δ := { g with solving_edge := some e } meta def add_adj (v : vertex) (e : edge) : search_state α β γ δ × vertex := g.set_vertex { v with adj := v.adj.alloc e } meta def publish_parent (f t : vertex) (e : edge) : search_state α β γ δ × vertex := if t.root then (g, t) else match t.parent with | some parent := (g, t) | none := g.set_vertex { t with parent := some e } end meta def mark_vertex_visited (v : vertex) : tactic (search_state α β γ δ × vertex) := do return $ g.set_vertex { v with visited := tt } meta def add_edge (f t : vertex) (proof : tactic expr) (how : how) : tactic (search_state α β γ δ × vertex × vertex × edge) := do let new_edge : edge := ⟨ f.id, t.id, proof, how ⟩, g.tracer_edge_added new_edge, let (g, f) := g.add_adj f new_edge, let (g, t) := g.add_adj t new_edge, let (g, t) := g.publish_parent f t new_edge, if ¬(vertex.same_side f t) then return (g.register_solved new_edge, f, t, new_edge) else return (g, f, t, new_edge) meta def commit_rewrite (f : vertex) (r : rewrite) : tactic (search_state α β γ δ × vertex × (vertex × edge)) := do (g, v) ← g.add_vertex r.e f.s, (g, f, v, e) ← g.add_edge f v r.prf r.how, return (g, f, (v, e)) meta def reveal_more_rewrites (v : vertex) : tactic (search_state α β γ δ × vertex × option rewrite) := do (rw_prog, new_rws) ← discover_more_rewrites g.conf.rs v.exp g.conf.to_rewrite_all_cfg v.s v.rw_prog, (g, v) ← pure $ g.set_vertex {v with rw_prog := rw_prog, rws := v.rws.alloc_list new_rws}, return (g, v, new_rws.nth 0) -- TODO implement a table-backed queue? meta def reveal_more_adjs (o : vertex) : tactic (search_state α β γ δ × vertex × option (vertex × edge)) := do (g, o, rw) ← match o.rws.at_ref o.rw_front with | none := g.reveal_more_rewrites o | some rw := pure (g, o, some rw) end, match rw with | none := return (g, o, none) | some rw := do (g, o, (v, e)) ← g.commit_rewrite o rw, (g, o) ← pure $ g.set_vertex {o with rw_front := o.rw_front.next}, return (g, o, some (v, e)) end meta def visit_vertex (v : vertex) : tactic (search_state α β γ δ × rewriterator) := do (g, v) ← if ¬v.visited then do g.tracer_visited v, g.mark_vertex_visited v else pure (g, v), return ⟨g, ⟨v.id, table_ref.first⟩⟩ meta def improve_estimate_over (threshold : ℚ) (de : dist_estimate γ) : tactic (search_state α β γ δ × dist_estimate γ) := do (vl, vr) ← g.get_estimate_verts de, let new_bnd := m.improve_estimate_over g threshold vl vr de.bnd, let new_de := {de with bnd := new_bnd}, return ({g with estimates := g.estimates.update new_de}, new_de) meta def alloc_estimate (p : pair) : tactic (search_state α β γ δ × table_ref) := do (vl, vr) ← g.lookup_pair p, let ref := g.estimates.next_id, let new_estimates := g.estimates.alloc ⟨p, ref, m.init_bound g vl vr⟩, return ({g with estimates := new_estimates}, ref) /-- Check if `eq.refl _` suffices to prove the two sides are equal. -/ meta def try_unify (p : pair) : tactic (search_state α β γ δ × bool) := do (lhs, rhs) ← g.lookup_pair p, prf ← try_core $ attempt_refl lhs.exp rhs.exp, match prf with | none := return (g, ff) | some prf := do (g, _) ← g.add_edge lhs rhs (pure prf) how.defeq, return (g, tt) end -- Currently, we guarentee that if the boolean we return is true, then there is at least -- one new rewrite possible in the environment which we not accessible before. This follows -- here since it is (currently) guarenteed that each element of `discovery.more_candidates` -- has an application *somewhere*. meta def be_desperate (goals : list pair) : tactic (search_state α β γ δ × bool) := if g.stats.num_discovers > g.conf.max_discovers then return (g, ff) else do let g := g.mutate_stats {g.stats with num_discovers := g.stats.num_discovers + 1}, let verts := (goals.map sided_pair.to_list).join, exprs ← list.erase_duplicates <$> (verts.mmap $ λ v, vertex.exp <$> g.vertices.get v), (prog, new_cands) ← discovery.collect_more g.conf g.prog exprs, let g := {g with prog := prog, conf := {g.conf with rs := g.conf.rs.append new_cands}}, g ← if new_cands.length = 0 then pure g else g.unmark_all_visited, return (g, new_cands.length > 0) end search_state namespace rewriterator private meta def advance (it : rewriterator) : rewriterator := {it with front := it.front.next} meta def next (it : rewriterator) (g : search_state α β γ δ) : tactic (search_state α β γ δ × rewriterator × option (vertex × edge)) := do o ← g.vertices.get it.orig, match o.adj.at_ref it.front with | some e := do v ← g.vertices.get e.t, return (g, advance it, some (v, e)) | none := do (g, o, ret) ← g.reveal_more_adjs o, match ret with | some (v, e) := return (g, advance it, some (v, e)) | none := return (g, it, none) end end meta def exhaust : rewriterator → search_state α β γ δ → tactic (search_state α β γ δ × rewriterator × list (vertex × edge)) | it g := do (g, it, ret) ← it.next g, match ret with | none := return (g, it, []) | some (v, e) := do (g, it, rest) ← exhaust it g, return (g, it, ((v, e) :: rest)) end end rewriterator namespace search_state meta def exhaust_vertex (v : vertex) : tactic (search_state α β γ δ) := do (g, it) ← g.visit_vertex v, (g, it) ← it.exhaust g, return g meta def exhaust_all_visited_aux : search_state α β γ δ → list vertex → tactic (search_state α β γ δ) | g [] := return g | g (v :: rest) := do g ← g.exhaust_vertex v, exhaust_all_visited_aux g rest meta def exhaust_all_visited : tactic (search_state α β γ δ) := g.exhaust_all_visited_aux g.vertices.to_list -- Find a vertex we haven't visited, and visit it. The bool is true if there might -- be other unvisited vertices. meta def exhaust_one_unvisited : list vertex → tactic (search_state α β γ δ × bool) | [] := return (g, ff) | (v :: rest) := if v.visited then exhaust_one_unvisited rest else do g ← g.exhaust_vertex v, return (g, tt) meta def exhaust_all_unvisited : search_state α β γ δ → tactic (search_state α β γ δ) | g := do (g, more_left) ← g.exhaust_one_unvisited g.vertices.to_list, if more_left then g.exhaust_all_unvisited else return g meta def exhaust_all : tactic (search_state α β γ δ) := do g ← g.exhaust_all_visited, g ← g.exhaust_all_unvisited, return g end search_state namespace inst meta def mutate : inst α β γ δ := { i with g := g } meta def step_once (itr : ℕ) : tactic (inst α β γ δ × status) := match i.g.solving_edge with | some e := return (i, status.done e) | none := do if itr > i.g.conf.max_iterations then return (i, status.abort "max iterations reached!") else do g ← i.metric.update i.g itr, (g, s) ← i.strategy.step g i.metric itr, return (i.mutate g, s) end meta def backtrack : vertex → option edge → tactic (option expr × list edge) | v e := match e with | none := return (none, []) | (some e) := do proof ← e.proof, w ← i.g.vertices.get e.f, (prf_o, edges) ← backtrack w w.parent, match prf_o with | none := return (some proof, [e]) | (some prf) := do new_prf ← tactic.mk_eq_trans prf proof, return (some new_prf, e :: edges) end end meta def combine_proofs : option expr → option expr → tactic expr | none none := fail "unreachable code!" | (some a) none := return a | none (some b) := mk_eq_symm b | (some a) (some b) := do b' ← mk_eq_symm b, mk_eq_trans a b' meta def build_proof (e : edge) : tactic (expr × list edge) := do (from_vertex, to_vertex) ← i.g.get_endpoints e, (from_prf, from_edges) ← i.backtrack to_vertex e, (to_prf, to_edges) ← i.backtrack to_vertex to_vertex.parent, proof ← match from_vertex.s with | side.L := combine_proofs from_prf to_prf | side.R := combine_proofs to_prf from_prf end, let edges := match from_vertex.s with | side.L := (to_edges ++ from_edges).reverse | side.R := (from_edges ++ to_edges).reverse end, -- This must be called before i.exhaust_all i.g.tracer_search_finished edges, i.g.trace from_vertex.to_string, i.g.trace to_vertex.to_string, if i.g.conf.trace_summary then do let vl := i.g.vertices.to_list, let saw := vl.length, let visited := (vl.filter (λ v : vertex, v.visited)).length, name ← decl_name, tactic.trace format!"rewrite_search (saw/visited/used) {saw}/{visited}/{edges.length} expressions during proof of {name}" else skip, i ← if i.g.conf.exhaustive then do g ← i.g.exhaust_all, pure $ i.mutate g else pure i, return (proof, edges) meta def search_until_solved_aux : inst α β γ δ → ℕ → tactic (inst α β γ δ × search_result) | i itr := do (i, s) ← i.step_once itr, match s with | status.continue := search_until_solved_aux i (itr + 1) | status.repeat := search_until_solved_aux i itr | status.abort r := return (i, search_result.failure ("aborted: " ++ r)) | status.done e := do (proof, edges) ← i.build_proof e, return (i, search_result.success proof (edges.map edge.how)) end meta def search_until_solved : tactic (inst α β γ δ × search_result) := i.search_until_solved_aux 0 meta def explain (proof : expr) (steps : list how) : tactic string := explain_search_result i.g.conf proof steps end inst end tidy.rewrite_search
b0c9213f36c267158c2e043266046f0db2780999
367134ba5a65885e863bdc4507601606690974c1
/src/data/nat/basic.lean
9c0e6668f32180fab090f81fedc3d5baf3f7d522
[ "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
65,377
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import algebra.group_power.basic import algebra.order_functions import algebra.ordered_monoid /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ universes u v /-! ### instances -/ instance : nontrivial ℕ := ⟨⟨0, 1, nat.zero_ne_one⟩⟩ instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm } instance : linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_le_one := nat.le_of_lt (nat.zero_lt_succ 0), mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, exists_pair_ne := ⟨0, 1, ne_of_lt nat.zero_lt_one⟩, ..nat.comm_semiring, ..nat.linear_order } -- all the fields are already included in the linear_ordered_semiring instance instance : linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.linear_ordered_semiring } instance : linear_ordered_comm_monoid_with_zero ℕ := { mul_le_mul_left := λ a b h c, nat.mul_le_mul_left c h, ..nat.linear_ordered_semiring, ..(infer_instance : comm_monoid_with_zero ℕ)} /-! Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, eq_zero_or_eq_zero_of_mul_eq_zero := assume a b, nat.eq_zero_of_mul_eq_zero, bot := 0, bot_le := nat.zero_le, .. nat.nontrivial, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } instance : canonically_linear_ordered_add_monoid ℕ := { .. (infer_instance : canonically_ordered_add_monoid ℕ), .. nat.linear_order } instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] : semilattice_sup_bot s := { bot := ⟨nat.find (nonempty_subtype.1 h), nat.find_spec (nonempty_subtype.1 h)⟩, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice_of_linear_order } theorem nat.eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact nat.eq_of_mul_eq_mul_left Hm H instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ := { mul_left_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_left (nat.pos_of_ne_zero h1) h2, mul_right_cancel_of_ne_zero := λ _ _ _ h1 h2, nat.eq_of_mul_eq_mul_right (nat.pos_of_ne_zero h1) h2, .. (infer_instance : comm_monoid_with_zero ℕ) } attribute [simp] nat.not_lt_zero /-! Inject some simple facts into the type class system. This `fact` should not be confused with the factorial function `nat.fact`! -/ section facts instance succ_pos'' (n : ℕ) : fact (0 < n.succ) := n.succ_pos instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := lt_trans zero_lt_one h end facts variables {m n k : ℕ} namespace nat /-! ### Recursion and `set.range` -/ section set open set theorem zero_union_range_succ : {0} ∪ range succ = univ := by { ext n, cases n; simp } variables {α : Type*} theorem range_of_succ (f : ℕ → α) : {f 0} ∪ range (f ∘ succ) = range f := by rw [← image_singleton, range_comp, ← image_union, zero_union_range_succ, image_univ] theorem range_rec {α : Type*} (x : α) (f : ℕ → α → α) : (set.range (λ n, nat.rec x f n) : set α) = {x} ∪ set.range (λ n, nat.rec (f 0 x) (f ∘ succ) n) := begin convert (range_of_succ _).symm, ext n, induction n with n ihn, { refl }, { dsimp at ihn ⊢, rw ihn } end theorem range_cases_on {α : Type*} (x : α) (f : ℕ → α) : (set.range (λ n, nat.cases_on n x f) : set α) = {x} ∪ set.range f := (range_of_succ _).symm end set /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) /-! ### Equalities and inequalities involving zero and one -/ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ lemma zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le _) lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h theorem eq_one_of_mul_eq_one_right {m n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one ⟨n, H.symm⟩ theorem eq_one_of_mul_eq_one_left {m n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (by rwa mul_comm) /-! ### `succ` -/ theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) lemma eq_of_le_of_lt_succ {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n + 1) : m = n := nat.le_antisymm (le_of_succ_le_succ h₂) h₁ theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ.inj, congr_arg _⟩ theorem succ_injective : function.injective nat.succ := λ x y, succ.inj theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := (lt_or_eq_of_le H).imp le_of_lt_succ id lemma succ_lt_succ_iff {m n : ℕ} : succ m < succ n ↔ m < n := ⟨lt_of_succ_lt_succ, succ_lt_succ⟩ /-! ### `add` -/ -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ lemma add_succ_lt_add {a b c d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := begin rw add_assoc, exact add_lt_add_of_lt_of_le hab (nat.succ_le_iff.2 hcd) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℕ} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℕ} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } /-! ### `pred` -/ @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] /-! ### `sub` -/ protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem add_sub_eq_max (n m : ℕ) : n + (m - n) = max n m := by rw [add_comm, max_comm, sub_add_eq_max] theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_add_sub_cancel {a b c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := by rw [←nat.add_sub_assoc hbc, ←nat.sub_add_comm hab, nat.add_sub_cancel] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := (nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $ by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) /-! ### `mul` -/ theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, λh, decidable.by_contradiction $ λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $ iff.symm (lt_iff_not_ge _ _) theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by rw [add_comm, add_mul_mod_self_left, mul_mod_right]; exact dec_trivial) lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], by clear_aux_decl; finish⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ lemma mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, x * a) := λ _ _, eq_of_mul_eq_mul_right ha lemma mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective (λ x, a * x) := λ _ _, eq_of_mul_eq_mul_left ha lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] lemma rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) : (nat.rec h0 h : Π n, C n) 0 = h0 := rfl @[simp] lemma rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : ∀ n, C n → C (n + 1)) (n : ℕ) : (nat.rec h0 h : Π n, C n) (n + 1) = h n ((nat.rec h0 h : Π n, C n) n) := rfl /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } /-! ### `div` -/ attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (decidable.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := le_div_iff_mul_le x y k0 theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self _ _) h lemma lt_of_div_lt_div {m n k : ℕ} (h : m / k < n / k) : m < n := by_contradiction $ λ h₁, absurd h (not_lt_of_ge (nat.div_le_div_right (not_lt.1 h₁))) protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ protected lemma div_eq_zero {a b : ℕ} (hb : a < b) : a / b = 0 := (nat.div_eq_zero_iff $ (zero_le a).trans_lt hb).mpr hb lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] /-! ### `mod`, `dvd` -/ lemma div_add_mod (m k : ℕ) : k * (m / k) + m % k = m := (nat.add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc] else by conv {to_rhs, rw ← mod_add_div a (b * c)}; rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))] lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬ 2 ∣ bit1 n := mt (nat.dvd_add_right two_dvd_bit0).1 dec_trivial /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) lemma not_dvd_of_pos_of_lt {a b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬ a ∣ b := begin rintros ⟨c, rfl⟩, rcases eq_zero_or_pos c with (rfl | hc), { exact lt_irrefl 0 h1 }, { exact not_lt.2 (le_mul_of_pos_right hc) h2 }, end protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := rfl | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] @[simp] lemma one_mod (n : ℕ) : 1 % (n + 2) = 1 := nat.mod_eq_of_lt (add_lt_add_right n.succ_pos 1) lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc, add_mul_mod_self_right] } end lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end @[simp] lemma div_div_div_eq_div : ∀ {a b c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c), (c / (a / b)) / b = c / a | 0 _ := by simp | (a + 1) 0 := λ _ dvd _, by simpa using dvd | (a + 1) (c + 1) := have a_split : a + 1 ≠ 0 := succ_ne_zero a, have c_split : c + 1 ≠ 0 := succ_ne_zero c, λ b dvd dvd2, begin rcases dvd2 with ⟨k, rfl⟩, rcases dvd with ⟨k2, pr⟩, have k2_nonzero : k2 ≠ 0 := λ k2_zero, by simpa [k2_zero] using pr, rw [nat.mul_div_cancel_left k (nat.pos_of_ne_zero a_split), pr, nat.mul_div_cancel_left k2 (nat.pos_of_ne_zero c_split), nat.mul_comm ((c + 1) * k2) k, ←nat.mul_assoc k (c + 1) k2, nat.mul_div_cancel _ (nat.pos_of_ne_zero k2_nonzero), nat.mul_div_cancel _ (nat.pos_of_ne_zero c_split)], end lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end /-! ### `pow` -/ -- This is redundant with `canonically_ordered_semiring.pow_le_pow_of_le_left`, -- but `canonically_ordered_semiring` is not such an obvious abstraction, and also quite long. -- So, we leave a version in the `nat` namespace as well. -- (The global `pow_le_pow_of_le_left` needs an extra hypothesis `0 ≤ x`.) protected theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i : ℕ, x^i ≤ y^i := canonically_ordered_semiring.pow_le_pow_of_le_left H theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} : ∀ {j}, i ≤ j → x^i ≤ x^j | 0 h := by rw eq_zero_of_le_zero h; apply le_refl | (succ j) h := (lt_or_eq_of_le h).elim (λhl, by rw [pow_succ', ← nat.mul_one (x^i)]; exact nat.mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H) (λe, by rw e; refl) theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : 0 < i) : x^i < y^i := begin cases i with i, { exact absurd h (not_lt_zero _) }, rw [pow_succ', pow_succ'], exact nat.mul_lt_mul' (nat.pow_le_pow_of_le_left (le_of_lt H) _) H (pow_pos (lt_of_le_of_lt (zero_le _) H) _) end theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j : ℕ} (h : i < j) : x^i < x^j := begin have xpos := lt_of_succ_lt H, refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h), rw [← nat.mul_one (x^i), pow_succ'], exact nat.mul_lt_mul_of_pos_left H (pow_pos xpos _) end -- TODO: Generalize? lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) := suffices 1*p^n < p*p^n, by simpa, nat.mul_lt_mul_of_pos_right h (pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma lt_two_pow (n : ℕ) : n < 2^n := lt_pow_self dec_trivial n lemma one_le_pow (n m : ℕ) (h : 0 < m) : 1 ≤ m^n := by { rw ←one_pow n, exact nat.pow_le_pow_of_le_left h n } lemma one_le_pow' (n m : ℕ) : 1 ≤ (m+1)^n := one_le_pow n (m+1) (succ_pos m) lemma one_le_two_pow (n : ℕ) : 1 ≤ 2^n := one_le_pow n 2 dec_trivial lemma one_lt_pow (n m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m^n := by { rw ←one_pow n, exact pow_lt_pow_of_lt_left h₁ h₀ } lemma one_lt_pow' (n m : ℕ) : 1 < (m+2)^(n+1) := one_lt_pow (n+1) (m+2) (succ_pos n) (nat.lt_of_sub_eq_succ rfl) lemma one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < 2^n := one_lt_pow n 2 h₀ dec_trivial lemma one_lt_two_pow' (n : ℕ) : 1 < 2^(n+1) := one_lt_pow (n+1) 2 (succ_pos n) dec_trivial lemma pow_right_strict_mono {x : ℕ} (k : 2 ≤ x) : strict_mono (λ (n : ℕ), x^n) := λ _ _, pow_lt_pow_of_lt_right k lemma pow_le_iff_le_right {x m n : ℕ} (k : 2 ≤ x) : x^m ≤ x^n ↔ m ≤ n := strict_mono.le_iff_le (pow_right_strict_mono k) lemma pow_lt_iff_lt_right {x m n : ℕ} (k : 2 ≤ x) : x^m < x^n ↔ m < n := strict_mono.lt_iff_lt (pow_right_strict_mono k) lemma pow_right_injective {x : ℕ} (k : 2 ≤ x) : function.injective (λ (n : ℕ), x^n) := strict_mono.injective (pow_right_strict_mono k) lemma pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono (λ (x : ℕ), x^m) := λ _ _ h, pow_lt_pow_of_lt_left h k lemma mul_lt_mul_pow_succ {n a q : ℕ} (a0 : 0 < a) (q1 : 1 < q) : n * q < a * q ^ (n + 1) := begin rw [pow_succ', ← mul_assoc, mul_lt_mul_right (zero_lt_one.trans q1)], exact lt_mul_of_one_le_of_lt' (nat.succ_le_iff.mpr a0) (nat.lt_pow_self q1 n), end end nat lemma strict_mono.nat_pow {n : ℕ} (hn : 1 ≤ n) {f : ℕ → ℕ} (hf : strict_mono f) : strict_mono (λ m, (f m) ^ n) := (nat.pow_left_strict_mono hn).comp hf namespace nat lemma pow_le_iff_le_left {m x y : ℕ} (k : 1 ≤ m) : x^m ≤ y^m ↔ x ≤ y := strict_mono.le_iff_le (pow_left_strict_mono k) lemma pow_lt_iff_lt_left {m x y : ℕ} (k : 1 ≤ m) : x^m < y^m ↔ x < y := strict_mono.lt_iff_lt (pow_left_strict_mono k) lemma pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective (λ (x : ℕ), x^m) := strict_mono.injective (pow_left_strict_mono k) /-! ### `pow` and `mod` / `dvd` -/ theorem mod_pow_succ {b : ℕ} (b_pos : 0 < b) (w m : ℕ) : m % (b^succ w) = b * (m/b % b^w) + m % b := begin apply nat.strong_induction_on m, clear m, intros p IH, cases lt_or_ge p (b^succ w) with h₁ h₁, -- base case: p < b^succ w { have h₂ : p / b < b^w, { rw [div_lt_iff_lt_mul p _ b_pos], simpa [pow_succ'] using h₁ }, rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂], simp [div_add_mod] }, -- step: p ≥ b^succ w { -- Generate condition for induction hypothesis have h₂ : p - b^succ w < p, { apply sub_lt_of_pos_le _ _ (pow_pos b_pos _) h₁ }, -- Apply induction rw [mod_eq_sub_mod h₁, IH _ h₂], -- Normalize goal and h1 simp only [pow_succ], simp only [ge, pow_succ] at h₁, -- Pull subtraction outside mod and div rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁], -- Cancel subtraction inside mod b^w have p_b_ge : b^w ≤ p / b, { rw [le_div_iff_mul_le _ _ b_pos, mul_comm], exact h₁ }, rw [eq.symm (mod_eq_sub_mod p_b_ge)] } end lemma pow_dvd_pow_iff_pow_le_pow {k l : ℕ} : Π {x : ℕ} (w : 0 < x), x^k ∣ x^l ↔ x^k ≤ x^l | (x+1) w := begin split, { intro a, exact le_of_dvd (pow_pos (succ_pos x) l) a, }, { intro a, cases x with x, { simp only [one_pow], }, { have le := (pow_le_iff_le_right (le_add_left _ _)).mp a, use (x+2)^(l-k), rw [←pow_add, add_comm k, nat.sub_add_cancel le], } } end /-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/ lemma pow_dvd_pow_iff_le_right {x k l : ℕ} (w : 1 < x) : x^k ∣ x^l ↔ k ≤ l := by rw [pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w), pow_le_iff_le_right w] lemma pow_dvd_pow_iff_le_right' {b k l : ℕ} : (b+2)^k ∣ (b+2)^l ↔ k ≤ l := pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl) lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have succ p * (succ p)^k ∣ succ p * 1, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_left (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 < 1, by rwa [this] at hk, absurd this dec_trivial lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk lemma pow_div {x m n : ℕ} (h : n ≤ m) (hx : 0 < x) : x ^ m / x ^ n = x ^ (m - n) := by rw [nat.div_eq_iff_eq_mul_left (pow_pos hx n) (pow_dvd_pow _ h), pow_sub_mul_pow _ h] /-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ lemma exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) : (∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m := begin split, { rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k, rw [lt_succ_iff, ← not_lt] at h2k, exact h2k h1k }, { intro h, rw [dvd_iff_mod_eq_zero, ← ne.def, ← pos_iff_ne_zero] at h, simp only [← mod_add_div m n] {single_pass := tt}, refine ⟨m / n, lt_add_of_pos_left _ h, _⟩, rw [add_comm _ 1, left_distrib, mul_one], exact add_lt_add_right (mod_lt _ hn) _ } end /-! ### `find` -/ section find variables {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] lemma find_eq_iff (h : ∃ n : ℕ, p n) : nat.find h = m ↔ p m ∧ ∀ n < m, ¬ p n := begin split, { rintro rfl, exact ⟨nat.find_spec h, λ _, nat.find_min h⟩ }, { rintro ⟨hm, hlt⟩, exact le_antisymm (nat.find_min' h hm) (not_lt.1 $ imp_not_comm.1 (hlt _) $ nat.find_spec h) } end @[simp] lemma find_lt_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h < n ↔ ∃ m < n, p m := ⟨λ h2, ⟨nat.find h, h2, nat.find_spec h⟩, λ ⟨m, hmn, hm⟩, (nat.find_min' h hm).trans_lt hmn⟩ @[simp] lemma find_le_iff (h : ∃ n : ℕ, p n) (n : ℕ) : nat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_succ_iff, find_lt_iff] @[simp] lemma le_find_iff (h : ∃ (n : ℕ), p n) (n : ℕ) : n ≤ nat.find h ↔ ∀ m < n, ¬ p m := by simp_rw [← not_lt, not_iff_comm, not_forall, not_not, find_lt_iff] @[simp] lemma lt_find_iff (h : ∃ n : ℕ, p n) (n : ℕ) : n < nat.find h ↔ ∀ m ≤ n, ¬ p m := by simp only [← succ_le_iff, le_find_iff, succ_le_succ_iff] @[simp] lemma find_eq_zero (h : ∃ n : ℕ, p n) : nat.find h = 0 ↔ p 0 := by simp [find_eq_iff] @[simp] lemma find_pos (h : ∃ n : ℕ, p n) : 0 < nat.find h ↔ ¬ p 0 := by rw [pos_iff_ne_zero, not_iff_not, nat.find_eq_zero] theorem find_le (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ (h _ (nat.find_spec hq)) lemma find_comp_succ (h₁ : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h0 : ¬ p 0) : nat.find h₁ = nat.find h₂ + 1 := begin refine (find_eq_iff _).2 ⟨nat.find_spec h₂, λ n hn, _⟩, cases n with n, exacts [h0, @nat.find_min (λ n, p (n + 1)) _ h₂ _ (succ_lt_succ_iff.1 hn)] end end find /-! ### `find_greatest` -/ section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_eq_iff {b m} : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ (∀ ⦃n⦄, m < n → n ≤ b → ¬P n) := begin induction b with b ihb generalizing m, { rw [eq_comm, iff.comm], simp only [nonpos_iff_eq_zero, ne.def, and_iff_left_iff_imp, find_greatest_zero], rintro rfl, exact ⟨λ h, (h rfl).elim, λ n hlt heq, (hlt.ne heq.symm).elim⟩ }, { by_cases hb : P (b + 1), { rw [find_greatest_eq hb], split, { rintro rfl, exact ⟨le_refl _, λ _, hb, λ n hlt hle, (hlt.not_le hle).elim⟩ }, { rintros ⟨hle, h0, hm⟩, rcases hle.eq_or_lt with rfl|hlt, exacts [rfl, (hm hlt (le_refl _) hb).elim] } }, { rw [find_greatest_of_not hb, ihb], split, { rintros ⟨hle, hP, hm⟩, refine ⟨hle.trans b.le_succ, hP, λ n hlt hle, _⟩, rcases hle.eq_or_lt with rfl|hlt', exacts [hb, hm hlt $ lt_succ_iff.1 hlt'] }, { rintros ⟨hle, hP, hm⟩, refine ⟨lt_succ_iff.1 (hle.lt_of_ne _), hP, λ n hlt hle, hm hlt (hle.trans b.le_succ)⟩, rintro rfl, exact hb (hP b.succ_ne_zero) } } } end lemma find_greatest_eq_zero_iff {b} : nat.find_greatest P b = 0 ↔ ∀ ⦃n⦄, 0 < n → n ≤ b → ¬P n := by simp [find_greatest_eq_iff] lemma find_greatest_spec {b} (h : ∃m, m ≤ b ∧ P m) : P (nat.find_greatest P b) := begin rcases h with ⟨m, hmb, hm⟩, by_cases h : nat.find_greatest P b = 0, { cases m, { rwa h }, exact ((find_greatest_eq_zero_iff.1 h) m.zero_lt_succ hmb hm).elim }, { exact (find_greatest_eq_iff.1 rfl).2.1 h } end lemma find_greatest_le {b} : nat.find_greatest P b ≤ b := (find_greatest_eq_iff.1 rfl).1 lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt $ λ hlt, (find_greatest_eq_iff.1 rfl).2.2 hlt hmb hm lemma find_greatest_is_greatest {b k} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬ P k := (find_greatest_eq_iff.1 rfl).2.2 hk hkb lemma find_greatest_of_ne_zero {b m} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := (find_greatest_eq_iff.1 h).2.1 h0 end find_greatest /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 @[simp] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } @[simp] lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /-! ### `shiftl` and `shiftr` -/ lemma shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n | 0 := (nat.mul_one _).symm | (k+1) := show bit0 (shiftl m k) = m * (2 * 2 ^ k), by rw [bit0_val, shiftl_eq_mul_pow, mul_left_comm] lemma shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n | 0 := by simp [shiftl, shiftl', pow_zero, nat.one_mul] | (k+1) := begin change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2 * 2 ^ k), rw bit1_val, change 2 * (shiftl' tt m k + 1) = _, rw [shiftl'_tt_eq_mul_pow, mul_left_comm] end lemma one_shiftl (n) : shiftl 1 n = 2 ^ n := (shiftl_eq_mul_pow _ _).trans (nat.one_mul _) @[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 := (shiftl_eq_mul_pow _ _).trans (nat.zero_mul _) lemma shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n | 0 := (nat.div_one _).symm | (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $ by rw [div2_val, nat.div_div_eq_div_mul, mul_comm]; refl @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := (shiftr_eq_div_pow _ _).trans (nat.zero_div _) theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ /-! ### `size` -/ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ.inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /-! ### decidability of predicates -/ instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred (λ n, ∃ (m : ℕ), m < n ∧ P m) | 0 := is_false (by simp) | (n + 1) := decidable_of_decidable_of_iff (@or.decidable _ _ (decidable_exists_lt n) (h n)) (by simp only [lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, exists_eq_left]) end nat
8d9598b23d0b623bb797d72966f0fd736e8a201d
f9d775fd3e03626a42bf00ec5d0bc27ab0f77a4e
/src/Post 3 - Preorders.lean
dc0f841cb12d9669c05b11078ae4617e7ef38bf9
[]
no_license
Nolrai/SummerCategory
d03d8340d431eb2b37c742dbe65f2611ba548430
ce74ae4487ca7c0791bde8d14da4e0ca0ff838af
refs/heads/master
1,588,316,039,936
1,553,374,940,000
1,553,374,940,000
177,340,028
0
0
null
null
null
null
UTF-8
Lean
false
false
777
lean
/- Okay, let's get started! Fong and Spivak start out by explaining preorders, which is short for "preordered sets". Whenever you have a set of things and a reasonable way deciding when anything in that set is "bigger" than some other thing, or "more expensive", or "taller", or "heavier", or "better" in any well-defined sense, or... anything like that, you've got a poset. When y is bigger than x we write x≤y. (You can also write y≥x, of course.) What do I mean by "reasonable"? We demand that the ≤ relation obey these rules: What do I mean by "reasonable"? We demand that the ≤ relation obey these rules: reflexivity: x≤x transitivity x≤y and y≤z imply x≤z. A set with a relation obeying these rules is called a preorder. -/ #print preorder
9d74e795de3dfe4432b41b72e3f00290726d2e31
38a6d5def645a1887e1306ceb4da06ff71452096
/_5_The_Physical_Layer/optical_fiber/capacity_of_bosonic_channels.lean
cdc7fca6e439b2a5634667af93a50077b625125d
[]
no_license
QTM3x/Quantum-Internet
bcc2d61e2ae7233bb2b369fedaed22a1feb6fba1
f90e09fb6c03d35043654d8b1bec1c63d6012268
refs/heads/master
1,609,224,401,937
1,599,911,583,000
1,599,911,583,000
238,495,221
45
33
null
1,603,625,079,000
1,580,919,815,000
Jupyter Notebook
UTF-8
Lean
false
false
529
lean
import .capacity /- The two-way capacity of this lossy channel for any repeaterless implementation of the channel can be shown to be C = - log(1-η) per mode, where η represents the physical channel's transmissivity. η varies with distance exponentially with a constant loss (α) in dbm units. -/ theorem two_way_capacity_Gaussian_channel : two_way_capacity Gaussian_channel = - real.log(1-η) := begin -- One of the main idea of the proof to establish -- bounds is σ-stretching of the channel. sorry end
63cfe4c009139b8c6905cdd52721094325e9c2ab
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/dual.lean
43d7cb948764d855999c22bccc2e58d2b7791aa2
[ "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,334
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Fabian Glöckle -/ import linear_algebra.finite_dimensional import linear_algebra.projection /-! # Dual vector spaces The dual space of an R-module M is the R-module of linear maps `M → R`. ## Main definitions * `dual R M` defines the dual space of M over R. * Given a basis for a K-vector space `V`, `is_basis.to_dual` produces a map from `V` to `dual K V`. * Given families of vectors `e` and `ε`, `dual_pair e ε` states that these families have the characteristic properties of a basis and a dual. * `dual_annihilator W` is the submodule of `dual R M` where every element annihilates `W`. ## Main results * `to_dual_equiv` : the dual space is linearly equivalent to the primal space. * `dual_pair.is_basis` and `dual_pair.eq_dual`: if `e` and `ε` form a dual pair, `e` is a basis and `ε` is its dual basis. * `quot_equiv_annihilator`: the quotient by a subspace is isomorphic to its dual annihilator. ## Notation We sometimes use `V'` as local notation for `dual K V`. ## TODO Erdös-Kaplansky theorem about the dimension of a dual vector space in case of infinite dimension. -/ noncomputable theory namespace module variables (R : Type*) (M : Type*) variables [comm_ring R] [add_comm_group M] [module R M] /-- The dual space of an R-module M is the R-module of linear maps `M → R`. -/ @[derive [add_comm_group, module R]] def dual := M →ₗ[R] R namespace dual instance : inhabited (dual R M) := by dunfold dual; apply_instance instance : has_coe_to_fun (dual R M) := ⟨_, linear_map.to_fun⟩ /-- Maps a module M to the dual of the dual of M. See `vector_space.erange_coe` and `vector_space.eval_equiv`. -/ def eval : M →ₗ[R] (dual R (dual R M)) := linear_map.flip linear_map.id @[simp] lemma eval_apply (v : M) (a : dual R M) : eval R M v a = a v := begin dunfold eval, rw [linear_map.flip_apply, linear_map.id_apply] end variables {R M} {M' : Type*} [add_comm_group M'] [module R M'] /-- The transposition of linear maps, as a linear map from `M →ₗ[R] M'` to `dual R M' →ₗ[R] dual R M`. -/ def transpose : (M →ₗ[R] M') →ₗ[R] (dual R M' →ₗ[R] dual R M) := (linear_map.llcomp R M M' R).flip lemma transpose_apply (u : M →ₗ[R] M') (l : dual R M') : transpose u l = l.comp u := rfl variables {M'' : Type*} [add_comm_group M''] [module R M''] lemma transpose_comp (u : M' →ₗ[R] M'') (v : M →ₗ[R] M') : transpose (u.comp v) = (transpose v).comp (transpose u) := rfl end dual end module namespace is_basis universes u v w variables {K : Type u} {V : Type v} {ι : Type w} variables [field K] [add_comm_group V] [vector_space K V] open vector_space module module.dual submodule linear_map cardinal function variables [de : decidable_eq ι] variables (B : ι → V) (h : is_basis K B) include de h /-- The linear map from a vector space equipped with basis to its dual vector space, taking basis elements to corresponding dual basis elements. -/ def to_dual : V →ₗ[K] module.dual K V := h.constr $ λ v, h.constr $ λ w, if w = v then 1 else 0 variable {B} lemma to_dual_apply (i j : ι) : h.to_dual B (B i) (B j) = if i = j then 1 else 0 := by { erw [constr_basis h, constr_basis h], ac_refl } @[simp] lemma to_dual_total_left (f : ι →₀ K) (i : ι) : h.to_dual B (finsupp.total ι V K B f) (B i) = f i := begin rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum, linear_map.sum_apply], simp_rw [linear_map.map_smul, linear_map.smul_apply, to_dual_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq'], split_ifs with h, { refl }, { rw finsupp.not_mem_support_iff.mp h } end @[simp] lemma to_dual_total_right (f : ι →₀ K) (i : ι) : h.to_dual B (B i) (finsupp.total ι V K B f) = f i := begin rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum], simp_rw [linear_map.map_smul, to_dual_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq], split_ifs with h, { refl }, { rw finsupp.not_mem_support_iff.mp h } end lemma to_dual_apply_left (v : V) (i : ι) : h.to_dual B v (B i) = h.repr v i := by rw [← h.to_dual_total_left, h.total_repr] lemma to_dual_apply_right (i : ι) (v : V) : h.to_dual B (B i) v = h.repr v i := by rw [← h.to_dual_total_right, h.total_repr] variable (B) /-- `h.to_dual_flip v` is the linear map sending `w` to `h.to_dual w v`. -/ def to_dual_flip (v : V) : (V →ₗ[K] K) := (h.to_dual B).flip v variable {B} omit de /-- `h.coord_fun i` sends vectors to their `i`'th coordinate with respect to the basis `h`. -/ def coord_fun (i : ι) : (V →ₗ[K] K) := (finsupp.lapply i).comp h.repr lemma coord_fun_eq_repr (v : V) (i : ι) : h.coord_fun i v = h.repr v i := rfl include de -- TODO: this lemma should be called something like `to_dual_flip_apply` lemma to_dual_swap_eq_to_dual (v w : V) : h.to_dual_flip B v w = h.to_dual B w v := rfl lemma to_dual_eq_repr (v : V) (i : ι) : h.to_dual B v (B i) = h.repr v i := h.to_dual_apply_left v i lemma to_dual_eq_equiv_fun [fintype ι] (v : V) (i : ι) : h.to_dual B v (B i) = h.equiv_fun v i := by rw [h.equiv_fun_apply, to_dual_eq_repr] lemma to_dual_inj (v : V) (a : h.to_dual B v = 0) : v = 0 := begin rw [← mem_bot K, ← h.repr_ker, mem_ker], apply finsupp.ext, intro b, rw [←to_dual_eq_repr _ _ _, a], refl end theorem to_dual_ker : (h.to_dual B).ker = ⊥ := ker_eq_bot'.mpr h.to_dual_inj theorem to_dual_range [fin : fintype ι] : (h.to_dual B).range = ⊤ := begin rw eq_top_iff', intro f, rw linear_map.mem_range, let lin_comb : ι →₀ K := finsupp.on_finset fin.elems (λ i, f.to_fun (B i)) _, { use finsupp.total ι V K B lin_comb, apply h.ext, { intros i, rw [h.to_dual_eq_repr _ i, repr_total h], { refl }, { rw [finsupp.mem_supported], exact λ _ _, set.mem_univ _ } } }, { intros a _, apply fin.complete } end /-- Maps a basis for `V` to a basis for the dual space. -/ def dual_basis : ι → dual K V := λ i, h.to_dual B (B i) theorem dual_lin_independent : linear_independent K h.dual_basis := h.1.map' _ (to_dual_ker _) @[simp] lemma dual_basis_apply_self (i j : ι) : h.dual_basis i (B j) = if i = j then 1 else 0 := h.to_dual_apply i j variable (B) /-- A vector space is linearly equivalent to its dual space. -/ def to_dual_equiv [fintype ι] : V ≃ₗ[K] (dual K V) := linear_equiv.of_bijective (h.to_dual B) h.to_dual_ker h.to_dual_range variable {B} theorem dual_basis_is_basis [fintype ι] : is_basis K h.dual_basis := (h.to_dual_equiv B).is_basis h @[simp] lemma total_dual_basis [fintype ι] (f : ι →₀ K) (i : ι) : finsupp.total ι (dual K V) K h.dual_basis f (B i) = f i := begin rw [finsupp.total_apply, finsupp.sum_fintype, linear_map.sum_apply], { simp_rw [smul_apply, smul_eq_mul, dual_basis_apply_self, mul_boole, finset.sum_ite_eq', if_pos (finset.mem_univ i)] }, { intro, rw zero_smul }, end lemma dual_basis_repr [fintype ι] (l : dual K V) (i : ι) : h.dual_basis_is_basis.repr l i = l (B i) := by rw [← total_dual_basis h, is_basis.total_repr h.dual_basis_is_basis l ] lemma dual_basis_equiv_fun [fintype ι] (l : dual K V) (i : ι) : h.dual_basis_is_basis.equiv_fun l i = l (B i) := by rw [is_basis.equiv_fun_apply, dual_basis_repr] lemma dual_basis_apply [fintype ι] (i : ι) (v : V) : h.dual_basis i v = h.equiv_fun v i := h.to_dual_apply_right i v @[simp] lemma to_dual_to_dual [fintype ι] : (h.dual_basis_is_basis.to_dual _).comp (h.to_dual B) = eval K V := begin refine h.ext (λ i, h.dual_basis_is_basis.ext (λ j, _)), suffices : @ite K _ (classical.prop_decidable _) 1 0 = @ite K _ (de j i) 1 0, by simpa [h.dual_basis_is_basis.to_dual_apply_left, h.dual_basis_repr, h.to_dual_apply_right], split_ifs; refl end omit de theorem dual_dim_eq [fintype ι] : cardinal.lift.{v u} (dim K V) = dim K (dual K V) := begin classical, have := linear_equiv.dim_eq_lift (h.to_dual_equiv B), simp only [cardinal.lift_umax] at this, rw [this, ← cardinal.lift_umax], apply cardinal.lift_id, end end is_basis namespace vector_space universes u v variables {K : Type u} {V : Type v} variables [field K] [add_comm_group V] [vector_space K V] open module module.dual submodule linear_map cardinal is_basis finite_dimensional theorem eval_ker : (eval K V).ker = ⊥ := begin classical, rw ker_eq_bot', intros v h, rw linear_map.ext_iff at h, by_contradiction H, rcases exists_subset_is_basis (linear_independent_singleton H) with ⟨b, hv, hb⟩, swap 4, assumption, have hv' : v = (coe : b → V) ⟨v, hv (set.mem_singleton v)⟩ := rfl, let hx := h (hb.to_dual _ v), rw [eval_apply, hv', to_dual_apply, if_pos rfl, zero_apply] at hx, exact one_ne_zero hx end theorem dual_dim_eq [finite_dimensional K V] : cardinal.lift.{v u} (dim K V) = dim K (dual K V) := begin classical, rcases exists_is_basis_fintype (dim_lt_omega K V) with ⟨b, hb, ⟨hf⟩⟩, resetI, exact hb.dual_dim_eq end lemma erange_coe [finite_dimensional K V] : (eval K V).range = ⊤ := begin classical, rcases exists_is_basis_fintype (dim_lt_omega K V) with ⟨b, hb, ⟨hf⟩⟩, unfreezingI { rw [← hb.to_dual_to_dual, range_comp, hb.to_dual_range, map_top, to_dual_range _] }, apply_instance end /-- A vector space is linearly equivalent to the dual of its dual space. -/ def eval_equiv [finite_dimensional K V] : V ≃ₗ[K] dual K (dual K V) := linear_equiv.of_bijective (eval K V) eval_ker (erange_coe) end vector_space section dual_pair open vector_space module module.dual linear_map function universes u v w variables {K : Type u} {V : Type v} {ι : Type w} [decidable_eq ι] variables [field K] [add_comm_group V] [vector_space K V] local notation `V'` := dual K V /-- `e` and `ε` have characteristic properties of a basis and its dual -/ @[nolint has_inhabited_instance] structure dual_pair (e : ι → V) (ε : ι → V') := (eval : ∀ i j : ι, ε i (e j) = if i = j then 1 else 0) (total : ∀ {v : V}, (∀ i, ε i v = 0) → v = 0) [finite : ∀ v : V, fintype {i | ε i v ≠ 0}] end dual_pair namespace dual_pair open vector_space module module.dual linear_map function universes u v w variables {K : Type u} {V : Type v} {ι : Type w} [dι : decidable_eq ι] variables [field K] [add_comm_group V] [vector_space K V] variables {e : ι → V} {ε : ι → dual K V} (h : dual_pair e ε) include h /-- The coefficients of `v` on the basis `e` -/ def coeffs (v : V) : ι →₀ K := { to_fun := λ i, ε i v, support := by { haveI := h.finite v, exact {i : ι | ε i v ≠ 0}.to_finset }, mem_support_to_fun := by {intro i, rw set.mem_to_finset, exact iff.rfl } } @[simp] lemma coeffs_apply (v : V) (i : ι) : h.coeffs v i = ε i v := rfl omit h /-- linear combinations of elements of `e`. This is a convenient abbreviation for `finsupp.total _ V K e l` -/ def lc (e : ι → V) (l : ι →₀ K) : V := l.sum (λ (i : ι) (a : K), a • (e i)) include h lemma dual_lc (l : ι →₀ K) (i : ι) : ε i (dual_pair.lc e l) = l i := begin erw linear_map.map_sum, simp only [h.eval, map_smul, smul_eq_mul], rw finset.sum_eq_single i, { simp }, { intros q q_in q_ne, simp [q_ne.symm] }, { intro p_not_in, simp [finsupp.not_mem_support_iff.1 p_not_in] }, end @[simp] lemma coeffs_lc (l : ι →₀ K) : h.coeffs (dual_pair.lc e l) = l := by { ext i, rw [h.coeffs_apply, h.dual_lc] } /-- For any v : V n, \sum_{p ∈ Q n} (ε p v) • e p = v -/ lemma decomposition (v : V) : dual_pair.lc e (h.coeffs v) = v := begin refine eq_of_sub_eq_zero (h.total _), intros i, simp [-sub_eq_add_neg, linear_map.map_sub, h.dual_lc, sub_eq_zero_iff_eq] end lemma mem_of_mem_span {H : set ι} {x : V} (hmem : x ∈ submodule.span K (e '' H)) : ∀ i : ι, ε i x ≠ 0 → i ∈ H := begin intros i hi, rcases (finsupp.mem_span_iff_total _).mp hmem with ⟨l, supp_l, sum_l⟩, change dual_pair.lc e l = x at sum_l, rw finsupp.mem_supported' at supp_l, apply classical.by_contradiction, intro i_not, apply hi, rw ← sum_l, simpa [h.dual_lc] using supp_l i i_not end lemma is_basis : is_basis K e := begin split, { rw linear_independent_iff, intros l H, change dual_pair.lc e l = 0 at H, ext i, apply_fun ε i at H, simpa [h.dual_lc] using H }, { rw submodule.eq_top_iff', intro v, rw [← set.image_univ, finsupp.mem_span_iff_total], exact ⟨h.coeffs v, by simp, h.decomposition v⟩ }, end lemma eq_dual : ε = is_basis.dual_basis h.is_basis := begin funext i, refine h.is_basis.ext (λ _, _), erw [is_basis.to_dual_apply, h.eval] end end dual_pair namespace submodule universes u v w variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variable {W : submodule R M} /-- The `dual_restrict` of a submodule `W` of `M` is the linear map from the dual of `M` to the dual of `W` such that the domain of each linear map is restricted to `W`. -/ def dual_restrict (W : submodule R M) : module.dual R M →ₗ[R] module.dual R W := linear_map.dom_restrict' W @[simp] lemma dual_restrict_apply (W : submodule R M) (φ : module.dual R M) (x : W) : W.dual_restrict φ x = φ (x : M) := rfl /-- The `dual_annihilator` of a submodule `W` is the set of linear maps `φ` such that `φ w = 0` for all `w ∈ W`. -/ def dual_annihilator {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] (W : submodule R M) : submodule R $ module.dual R M := W.dual_restrict.ker @[simp] lemma mem_dual_annihilator (φ : module.dual R M) : φ ∈ W.dual_annihilator ↔ ∀ w ∈ W, φ w = 0 := begin refine linear_map.mem_ker.trans _, simp_rw [linear_map.ext_iff, dual_restrict_apply], exact ⟨λ h w hw, h ⟨w, hw⟩, λ h w, h w.1 w.2⟩ end lemma dual_restrict_ker_eq_dual_annihilator (W : submodule R M) : W.dual_restrict.ker = W.dual_annihilator := rfl end submodule namespace subspace open submodule linear_map universes u v w -- We work in vector spaces because `exists_is_compl` only hold for vector spaces variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] /-- Given a subspace `W` of `V` and an element of its dual `φ`, `dual_lift W φ` is the natural extension of `φ` to an element of the dual of `V`. That is, `dual_lift W φ` sends `w ∈ W` to `φ x` and `x` in the complement of `W` to `0`. -/ noncomputable def dual_lift (W : subspace K V) : module.dual K W →ₗ[K] module.dual K V := let h := classical.indefinite_description _ W.exists_is_compl in (linear_map.of_is_compl_prod h.2).comp (linear_map.inl _ _ _) variable {W : subspace K V} @[simp] lemma dual_lift_of_subtype {φ : module.dual K W} (w : W) : W.dual_lift φ (w : V) = φ w := by { erw of_is_compl_left_apply _ w, refl } lemma dual_lift_of_mem {φ : module.dual K W} {w : V} (hw : w ∈ W) : W.dual_lift φ w = φ ⟨w, hw⟩ := dual_lift_of_subtype ⟨w, hw⟩ @[simp] lemma dual_restrict_comp_dual_lift (W : subspace K V) : W.dual_restrict.comp W.dual_lift = 1 := by { ext φ x, simp } lemma dual_restrict_left_inverse (W : subspace K V) : function.left_inverse W.dual_restrict W.dual_lift := λ x, show W.dual_restrict.comp W.dual_lift x = x, by { rw [dual_restrict_comp_dual_lift], refl } lemma dual_lift_right_inverse (W : subspace K V) : function.right_inverse W.dual_lift W.dual_restrict := W.dual_restrict_left_inverse lemma dual_restrict_surjective : function.surjective W.dual_restrict := W.dual_lift_right_inverse.surjective lemma dual_lift_injective : function.injective W.dual_lift := W.dual_restrict_left_inverse.injective /-- The quotient by the `dual_annihilator` of a subspace is isomorphic to the dual of that subspace. -/ noncomputable def quot_annihilator_equiv (W : subspace K V) : W.dual_annihilator.quotient ≃ₗ[K] module.dual K W := (quot_equiv_of_eq _ _ W.dual_restrict_ker_eq_dual_annihilator).symm.trans $ W.dual_restrict.quot_ker_equiv_of_surjective dual_restrict_surjective /-- The natural isomorphism forom the dual of a subspace `W` to `W.dual_lift.range`. -/ noncomputable def dual_equiv_dual (W : subspace K V) : module.dual K W ≃ₗ[K] W.dual_lift.range := linear_equiv.of_injective _ $ ker_eq_bot.2 dual_lift_injective lemma dual_equiv_dual_def (W : subspace K V) : W.dual_equiv_dual.to_linear_map = W.dual_lift.range_restrict := rfl @[simp] lemma dual_equiv_dual_apply (φ : module.dual K W) : W.dual_equiv_dual φ = ⟨W.dual_lift φ, mem_range.2 ⟨φ, rfl⟩⟩ := rfl section open_locale classical open finite_dimensional variables {V₁ : Type*} [add_comm_group V₁] [vector_space K V₁] instance [H : finite_dimensional K V] : finite_dimensional K (module.dual K V) := begin refine @linear_equiv.finite_dimensional _ _ _ _ _ _ _ _ _ H, have hB := classical.some_spec (exists_is_basis_finite K V), haveI := classical.choice hB.2, exact is_basis.to_dual_equiv _ hB.1 end variables [finite_dimensional K V] [finite_dimensional K V₁] @[simp] lemma dual_findim_eq : findim K (module.dual K V) = findim K V := begin obtain ⟨n, hn, hf⟩ := exists_is_basis_finite K V, refine linear_equiv.findim_eq _, haveI : fintype n := set.finite.fintype hf, refine (hn.to_dual_equiv _).symm, end /-- The quotient by the dual is isomorphic to its dual annihilator. -/ noncomputable def quot_dual_equiv_annihilator (W : subspace K V) : W.dual_lift.range.quotient ≃ₗ[K] W.dual_annihilator := linear_equiv.quot_equiv_of_quot_equiv $ linear_equiv.trans W.quot_annihilator_equiv W.dual_equiv_dual /-- The quotient by a subspace is isomorphic to its dual annihilator. -/ noncomputable def quot_equiv_annihilator (W : subspace K V) : W.quotient ≃ₗ[K] W.dual_annihilator := begin refine linear_equiv.trans _ W.quot_dual_equiv_annihilator, refine linear_equiv.quot_equiv_of_equiv _ _, { refine linear_equiv.trans _ W.dual_equiv_dual, have hB := classical.some_spec (exists_is_basis_finite K W), haveI := classical.choice hB.2, exact is_basis.to_dual_equiv _ hB.1 }, { have hB := classical.some_spec (exists_is_basis_finite K V), haveI := classical.choice hB.2, exact is_basis.to_dual_equiv _ hB.1 }, end end end subspace
26057dd19b44a3e05d471cdd71fabdc97c86d643
7cef822f3b952965621309e88eadf618da0c8ae9
/test/lint.lean
6154e013d862bd43be92b48310a0cbec312c8a81
[ "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
2,226
lean
import tactic.lint def foo1 (n m : ℕ) : ℕ := n + 1 def foo2 (n m : ℕ) : m = m := by refl lemma foo3 (n m : ℕ) : ℕ := n - m lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances -- section -- local attribute [instance, priority 1001] classical.prop_decidable -- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) -- end open tactic run_cmd do let t := name × list ℕ, e ← get_env, l ← e.mfilter (λ d, return $ e.in_current_file' d.to_name && ¬ d.to_name.is_internal && ¬ d.is_auto_generated e), l2 ← fold_over_with_cond l (return ∘ check_unused_arguments), guard $ l2.length = 3, let l2 : list t := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ (⟨`foo1, [2]⟩ : t) ∈ l2, guard $ (⟨`foo2, [1]⟩ : t) ∈ l2, guard $ (⟨`foo.foo, [2]⟩ : t) ∈ l2, l2 ← fold_over_with_cond l incorrect_def_lemma, guard $ l2.length = 2, let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3, l3 ← fold_over_with_cond l dup_namespace, guard $ l3.length = 1, guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo, l4 ← fold_over_with_cond l illegal_constants_in_statement, guard $ l4.length = 1, guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo, -- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4, (_, s) ← lint ff, guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string, (_, s2) ← lint tt, guard $ s.to_string ≠ s2.to_string, skip /- check customizability and nolint -/ @[nolint] def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) meta def dummy_check (d : declaration) : tactic (option string) := return $ if d.to_name.last = "foo" then some "gotcha!" else none meta def linter.dummy_linter : linter := { test := dummy_check, no_errors_found := "found nothing", errors_found := "found something" } run_cmd do (_, s) ← lint tt tt [`linter.dummy_linter] tt, guard $ "/- found something: -/\n#print foo.foo /- gotcha! -/\n\n".is_suffix_of s.to_string
c2cb4637bec22cf17f87afbdf3dbeb36d6cd0b69
32317185abf7e7c963f4c67c190aec61af6b3628
/library/data/int/power.lean
a97d654611b599b9d222029b35eab88a8ecac7cf
[ "Apache-2.0" ]
permissive
Andrew-Zipperer-unorganized/lean
198a2317f21198cd8d26e7085e484b86277f17f7
dcb35008e1474a0abebe632b1dced120e5f8c009
refs/heads/master
1,622,526,520,945
1,453,576,559,000
1,454,612,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
774
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The power function on the integers. -/ import data.int.basic data.int.order data.int.div algebra.group_power data.nat.power namespace int definition int_has_pow_nat [reducible] [instance] [priority int.prio] : has_pow_nat int := has_pow_nat.mk has_pow_nat.pow_nat /- definition nmul (n : ℕ) (a : ℤ) : ℤ := algebra.nmul n a infix [priority int.prio] ⬝ := nmul definition imul (i : ℤ) (a : ℤ) : ℤ := algebra.imul i a -/ open nat theorem of_nat_pow (a n : ℕ) : of_nat (a^n) = (of_nat a)^n := begin induction n with n ih, apply eq.refl, rewrite [pow_succ, pow_succ, of_nat_mul, ih] end end int
4998c294eac7334625eeae1aced79a11e51420f4
fffbc47930dc6615e66ece42324ce57a21d5b64b
/src/algebra/pi_instances.lean
e0923723506f88af0600738bdfe1dfcc4d366cbb
[ "Apache-2.0" ]
permissive
skbaek/mathlib
3caae8ae413c66862293a95fd2fbada3647b1228
f25340175631cdc85ad768a262433f968d0d6450
refs/heads/master
1,588,130,123,636
1,558,287,609,000
1,558,287,609,000
160,935,713
0
0
Apache-2.0
1,544,271,146,000
1,544,271,146,000
null
UTF-8
Lean
false
false
17,585
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot Pi instances for algebraic structures. -/ import order.basic import algebra.module algebra.group import data.finset import tactic.pi_instances namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equiped with instances variables (x y : Π i, f i) (i : I) instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩ @[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩ @[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl attribute [to_additive pi.has_zero] pi.has_one attribute [to_additive pi.zero_apply] pi.one_apply instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩ @[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩ @[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl attribute [to_additive pi.has_add] pi.has_mul attribute [to_additive pi.add_apply] pi.mul_apply instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩ @[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩ @[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl attribute [to_additive pi.has_neg] pi.has_inv attribute [to_additive pi.neg_apply] pi.inv_apply instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : mul_action α (Π i : I, f i) := { smul := λ c f i, c • f i, mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance distrib_mul_action (α) {m : monoid α} [∀ i, add_monoid $ f i] [∀ i, distrib_mul_action α $ f i] : distrib_mul_action α (Π i : I, f i) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } variables (I f) instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule I f α} instance vector_space (α) {r : discrete_field α} [∀ i, add_comm_group $ f i] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) := {..pi.module α} instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) := by pi_instance instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) := by pi_instance instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) := by pi_instance attribute [to_additive pi.add_semigroup] pi.semigroup attribute [to_additive pi.add_comm_semigroup] pi.comm_semigroup attribute [to_additive pi.add_monoid] pi.monoid attribute [to_additive pi.add_comm_monoid] pi.comm_monoid attribute [to_additive pi.add_group] pi.group attribute [to_additive pi.add_comm_group] pi.comm_group attribute [to_additive pi.add_left_cancel_semigroup] pi.left_cancel_semigroup attribute [to_additive pi.add_right_cancel_semigroup] pi.right_cancel_semigroup @[to_additive pi.list_sum_apply] lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) : ∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod | [] := rfl | (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l] @[to_additive pi.multiset_sum_apply] lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α) (s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod := quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end @[to_additive pi.finset_sum_apply] lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → Πa, β a) : s.prod g a = s.prod (λc, g c a) := show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod, by rw [multiset_prod_apply, multiset.map_map] def is_ring_hom_pi {α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)] {γ : Type w} [ring γ] (f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] : is_ring_hom (λ x b, f b x) := begin split, -- It's a pity that these can't be done using `simp` lemmas. { ext, rw [is_ring_hom.map_one (f x)], refl, }, { intros x y, ext1 z, rw [is_ring_hom.map_mul (f z)], refl, }, { intros x y, ext1 z, rw [is_ring_hom.map_add (f z)], refl, } end end pi namespace prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β} instance [has_add α] [has_add β] : has_add (α × β) := ⟨λp q, (p.1 + q.1, p.2 + q.2)⟩ @[to_additive prod.has_add] instance [has_mul α] [has_mul β] : has_mul (α × β) := ⟨λp q, (p.1 * q.1, p.2 * q.2)⟩ @[simp, to_additive prod.fst_add] lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive prod.snd_add] lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive prod.mk_add_mk] lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩ @[to_additive prod.has_zero] instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩ @[simp, to_additive prod.fst_zero] lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl @[simp, to_additive prod.snd_zero] lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl @[to_additive prod.zero_eq_mk] lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩ @[to_additive prod.has_neg] instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive prod.fst_neg] lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive prod.snd_neg] lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl @[to_additive prod.neg_mk] lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) := { add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩, .. prod.has_add } @[to_additive prod.add_semigroup] instance [semigroup α] [semigroup β] : semigroup (α × β) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } instance [add_monoid α] [add_monoid β] : add_monoid (α × β) := { zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩, add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩, .. prod.add_semigroup, .. prod.has_zero } @[to_additive prod.add_monoid] instance [monoid α] [monoid β] : monoid (α × β) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.semigroup, .. prod.has_one } instance [add_group α] [add_group β] : add_group (α × β) := { add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩, .. prod.add_monoid, .. prod.has_neg } @[to_additive prod.add_group] instance [group α] [group β] : group (α × β) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, .. prod.monoid, .. prod.has_inv } instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) := { add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩, .. prod.add_semigroup } @[to_additive prod.add_comm_semigroup] instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) := { .. prod.add_comm_semigroup, .. prod.add_monoid } @[to_additive prod.add_comm_monoid] instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) := { .. prod.comm_semigroup, .. prod.monoid } instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) := { .. prod.add_comm_semigroup, .. prod.add_group } @[to_additive prod.add_comm_group] instance [comm_group α] [comm_group β] : comm_group (α × β) := { .. prod.comm_semigroup, .. prod.group } @[to_additive fst.is_add_monoid_hom] lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive snd.is_add_monoid_hom] lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive fst.is_add_group_hom] lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) := by refine_struct {..}; simp @[to_additive snd.is_add_group_hom] lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) := by refine_struct {..}; simp attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom @[to_additive prod.fst_sum] lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).1 = t.prod (λc, (f c).1) := (finset.prod_hom prod.fst).symm @[to_additive prod.snd_sum] lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (t.prod f).2 = t.prod (λc, (f c).2) := (finset.prod_hom prod.snd).symm instance [semiring α] [semiring β] : semiring (α × β) := { zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩, right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩, ..prod.add_comm_monoid, ..prod.monoid } instance [ring α] [ring β] : ring (α × β) := { ..prod.add_comm_group, ..prod.semiring } instance [comm_ring α] [comm_ring β] : comm_ring (α × β) := { ..prod.ring, ..prod.comm_monoid } instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) := { zero_ne_one := mt (congr_arg prod.fst) zero_ne_one, ..prod.comm_ring } instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) := by refine_struct {..}; simp instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) := by refine_struct {..}; simp instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) := by refine_struct {..}; simp instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) := by refine_struct {..}; simp /-- Left injection function for the inner product From a vector space (and also group and module) perspective the product is the same as the sum of two vector spaces. `inl` and `inr` provide the corresponding injection functions. -/ def inl [has_zero β] (a : α) : α × β := (a, 0) /-- Right injection function for the inner product -/ def inr [has_zero α] (b : β) : α × β := (0, b) lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) := assume x y h, (prod.mk.inj_iff.mp h).1 lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) := assume x y h, (prod.mk.inj_iff.mp h).2 @[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ := iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl) @[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ := iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl) @[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} : inl a = inr b ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} : inr b = inl a ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl @[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl @[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl @[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl @[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl @[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ] (a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ] [semimodule α β] [semimodule α γ] : semimodule α (β × γ) := { smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩, zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩, .. prod.has_scalar } instance {r : ring α} [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] : module α (β × γ) := {} instance {r : discrete_field α} [add_comm_group β] [add_comm_group γ] [vector_space α β] [vector_space α γ] : vector_space α (β × γ) := {} end prod namespace finset @[to_additive finset.prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) end finset
76cb5ce2d95dcc2efab3716cf31d3fcbb576c899
fc086f79b20cf002d6f34b023749998408e94fbf
/src/tidy/backwards_reasoning.lean
2f1aeebc5270dd1f44943d003b97e03703211550
[]
no_license
semorrison/lean-tidy
f039460136b898fb282f75efedd92f2d5c5d90f8
6c1d46de6cff05e1c2c4c9692af812bca3e13b6c
refs/heads/master
1,624,461,332,392
1,559,655,744,000
1,559,655,744,000
96,569,994
9
4
null
1,538,287,895,000
1,499,455,306,000
Lean
UTF-8
Lean
false
false
2,479
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import tactic.basic import tactic.ext open tactic meta def back_attribute : user_attribute := { name := `back, descr := "A lemma that should be applied to a goal whenever possible; use `backwards_reasoning` to automatically `apply` all lemmas tagged `[back]`." } run_cmd attribute.register ``back_attribute /-- Try to apply the given lemma, solving new terminal goals by solve_by_elim if possible. -/ meta def apply_using_solve_by_elim (c : name) : tactic unit := focus1 $ do t ← mk_const c, r ← apply t, try (any_goals (terminal_goal >> solve_by_elim)) meta def elim_attribute : user_attribute := { name := `elim, descr := "A lemma that should be applied to a goal whenever possible, as long as all arguments to the lemma by be fulfilled from existing hypotheses; use `backwards_reasoning` to automatically apply all lemmas tagged `[elim]`." } run_cmd attribute.register ``elim_attribute /-- Try to apply the given lemma, fulfilling all new goals using existing hypotheses. -/ meta def apply_no_new_goals (c : name) : tactic unit := focus1 $ do t ← mk_const c, r ← apply t, all_goals solve_by_elim, a ← r.mmap (λ p, do e ← instantiate_mvars p.2, return e.list_meta_vars.length), guard (a.all (λ n, n = 0)) /-- Try to apply one of the given lemmas; it succeeds as soon as one of them succeeds. -/ meta def any_apply_with (f : name → tactic unit) : list name → tactic name | [] := failed | (c::cs) := (f c >> pure c) <|> any_apply_with cs /-- Try to apply any lemma marked with the attributes `@[back]` or `@[elim]`. -/ meta def backwards_reasoning : tactic string := (attribute.get_instances `elim >>= any_apply_with apply_no_new_goals >>= λ n, return ("apply " ++ n.to_string ++ " ; solve_by_elim")) <|> (attribute.get_instances `back >>= any_apply_with apply_using_solve_by_elim >>= λ n, return ("apply " ++ n.to_string)) <|> fail "no @[back] or @[back'] lemmas could be applied" attribute [extensionality] subtype.eq -- TODO should `apply_instance` be in tidy? If so, these shouldn't be needed. @[back] definition decidable_true : decidable true := is_true dec_trivial @[back] definition decidable_false : decidable false := is_false dec_trivial attribute [back] quotient.mk quotient.sound attribute [back] eqv_gen.rel attribute [elim] Exists.intro
d71c805180d46286de100d031b5f629b789bd034
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/mv_polynomial/variables.lean
9fd1ca013972effdc01b18f4ca4c8c79cf8932ca
[ "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
29,059
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, Johan Commelin, Mario Carneiro -/ import algebra.big_operators.order import data.mv_polynomial.rename /-! # Degrees and variables of polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file establishes many results about the degree and variable sets of a multivariate polynomial. The *variable set* of a polynomial $P \in R[X]$ is a `finset` containing each $x \in X$ that appears in a monomial in $P$. The *degree set* of a polynomial $P \in R[X]$ is a `multiset` containing, for each $x$ in the variable set, $n$ copies of $x$, where $n$ is the maximum number of copies of $x$ appearing in a monomial of $P$. ## Main declarations * `mv_polynomial.degrees p` : the multiset of variables representing the union of the multisets corresponding to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}` * `mv_polynomial.vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then `vars p = {x, y, z}` * `mv_polynomial.degree_of n p : ℕ` : the total degree of `p` with respect to the variable `n`. For example if `p = x⁴y+yz` then `degree_of y p = 1`. * `mv_polynomial.total_degree p : ℕ` : the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`. ## Notation As in other polynomial files, we typically use the notation: + `σ τ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `r : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` -/ noncomputable theory open set function finsupp add_monoid_algebra open_locale big_operators universes u v w variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ τ : Type*} {r : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} section degrees /-! ### `degrees` -/ /-- The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset. (For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.) -/ def degrees (p : mv_polynomial σ R) : multiset σ := by letI := classical.dec_eq σ; exact p.support.sup (λs:σ →₀ ℕ, s.to_multiset) lemma degrees_def [decidable_eq σ] (p : mv_polynomial σ R) : p.degrees = p.support.sup (λs:σ →₀ ℕ, s.to_multiset) := by convert rfl lemma degrees_monomial (s : σ →₀ ℕ) (a : R) : degrees (monomial s a) ≤ s.to_multiset := begin classical, refine (finset.sup_le $ assume t h, _), have := finsupp.support_single_subset h, rw [finset.mem_singleton] at this, rw this end lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : R) (ha : a ≠ 0) : degrees (monomial s a) = s.to_multiset := begin classical, refine (le_antisymm (degrees_monomial s a) $ finset.le_sup $ _), rw [support_monomial, if_neg ha, finset.mem_singleton] end lemma degrees_C (a : R) : degrees (C a : mv_polynomial σ R) = 0 := multiset.le_zero.1 $ degrees_monomial _ _ lemma degrees_X' (n : σ) : degrees (X n : mv_polynomial σ R) ≤ {n} := le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _ @[simp] lemma degrees_X [nontrivial R] (n : σ) : degrees (X n : mv_polynomial σ R) = {n} := (degrees_monomial_eq _ (1 : R) one_ne_zero).trans (to_multiset_single _ _) @[simp] lemma degrees_zero : degrees (0 : mv_polynomial σ R) = 0 := by { rw ← C_0, exact degrees_C 0 } @[simp] lemma degrees_one : degrees (1 : mv_polynomial σ R) = 0 := degrees_C 1 lemma degrees_add [decidable_eq σ] (p q : mv_polynomial σ R) : (p + q).degrees ≤ p.degrees ⊔ q.degrees := begin classical, simp_rw degrees_def, refine finset.sup_le (assume b hb, _), have := finsupp.support_add hb, rw finset.mem_union at this, cases this, { exact le_sup_of_le_left (finset.le_sup this) }, { exact le_sup_of_le_right (finset.le_sup this) }, end lemma degrees_sum {ι : Type*} [decidable_eq σ] (s : finset ι) (f : ι → mv_polynomial σ R) : (∑ i in s, f i).degrees ≤ s.sup (λi, (f i).degrees) := begin classical, refine s.induction _ _, { simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_rfl }, { assume i s his ih, rw [finset.sup_insert, finset.sum_insert his], exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) } end lemma degrees_mul (p q : mv_polynomial σ R) : (p * q).degrees ≤ p.degrees + q.degrees := begin classical, refine finset.sup_le (assume b hb, _), have := support_mul p q hb, simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.to_multiset_add], exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) end lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (∏ i in s, f i).degrees ≤ ∑ i in s, (f i).degrees := begin classical, refine s.induction _ _, { simp only [finset.prod_empty, finset.sum_empty, degrees_one] }, { assume i s his ih, rw [finset.prod_insert his, finset.sum_insert his], exact le_trans (degrees_mul _ _) (add_le_add_left ih _) } end lemma degrees_pow (p : mv_polynomial σ R) : ∀(n : ℕ), (p^n).degrees ≤ n • p.degrees | 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end | (n + 1) := by { rw [pow_succ, add_smul, add_comm, one_smul], exact le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _) } lemma mem_degrees {p : mv_polynomial σ R} {i : σ} : i ∈ p.degrees ↔ ∃ d, p.coeff d ≠ 0 ∧ i ∈ d.support := by simp only [degrees, multiset.mem_sup, ← mem_support_iff, finsupp.mem_to_multiset, exists_prop] lemma le_degrees_add {p q : mv_polynomial σ R} (h : p.degrees.disjoint q.degrees) : p.degrees ≤ (p + q).degrees := begin classical, apply finset.sup_le, intros d hd, rw multiset.disjoint_iff_ne at h, rw multiset.le_iff_count, intros i, rw [degrees, multiset.count_finset_sup], simp only [finsupp.count_to_multiset], by_cases h0 : d = 0, { simp only [h0, zero_le, finsupp.zero_apply], }, { refine @finset.le_sup _ _ _ _ (p + q).support _ d _, rw [mem_support_iff, coeff_add], suffices : q.coeff d = 0, { rwa [this, add_zero, coeff, ← finsupp.mem_support_iff], }, rw [← finsupp.support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty] at h0, obtain ⟨j, hj⟩ := h0, contrapose! h, rw mem_support_iff at hd, refine ⟨j, _, j, _, rfl⟩, all_goals { rw mem_degrees, refine ⟨d, _, hj⟩, assumption } } end lemma degrees_add_of_disjoint [decidable_eq σ] {p q : mv_polynomial σ R} (h : multiset.disjoint p.degrees q.degrees) : (p + q).degrees = p.degrees ∪ q.degrees := begin apply le_antisymm, { apply degrees_add }, { apply multiset.union_le, { apply le_degrees_add h }, { rw add_comm, apply le_degrees_add h.symm } } end lemma degrees_map [comm_semiring S] (p : mv_polynomial σ R) (f : R →+* S) : (map f p).degrees ⊆ p.degrees := begin dsimp only [degrees], apply multiset.subset_of_le, apply finset.sup_mono, apply mv_polynomial.support_map_subset end lemma degrees_rename (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).degrees ⊆ (φ.degrees.map f) := begin classical, intros i, rw [mem_degrees, multiset.mem_map], rintro ⟨d, hd, hi⟩, obtain ⟨x, rfl, hx⟩ := coeff_rename_ne_zero _ _ _ hd, simp only [map_domain, finsupp.mem_support_iff] at hi, rw [sum_apply, finsupp.sum] at hi, contrapose! hi, rw [finset.sum_eq_zero], intros j hj, simp only [exists_prop, mem_degrees] at hi, specialize hi j ⟨x, hx, hj⟩, rw [single_apply, if_neg hi], end lemma degrees_map_of_injective [comm_semiring S] (p : mv_polynomial σ R) {f : R →+* S} (hf : injective f) : (map f p).degrees = p.degrees := by simp only [degrees, mv_polynomial.support_map_of_injective _ hf] lemma degrees_rename_of_injective {p : mv_polynomial σ R} {f : σ → τ} (h : function.injective f) : degrees (rename f p) = (degrees p).map f := begin classical, simp only [degrees, multiset.map_finset_sup p.support finsupp.to_multiset f h, support_rename_of_injective h, finset.sup_image], refine finset.sup_congr rfl (λ x hx, _), exact (finsupp.to_multiset_map _ _).symm, end end degrees section vars /-! ### `vars` -/ /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars (p : mv_polynomial σ R) : finset σ := by letI := classical.dec_eq σ; exact p.degrees.to_finset lemma vars_def [decidable_eq σ] (p : mv_polynomial σ R) : p.vars = p.degrees.to_finset := by convert rfl @[simp] lemma vars_0 : (0 : mv_polynomial σ R).vars = ∅ := by classical; rw [vars_def, degrees_zero, multiset.to_finset_zero] @[simp] lemma vars_monomial (h : r ≠ 0) : (monomial s r).vars = s.support := by classical; rw [vars_def, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset] @[simp] lemma vars_C : (C r : mv_polynomial σ R).vars = ∅ := by classical; rw [vars_def, degrees_C, multiset.to_finset_zero] @[simp] lemma vars_X [nontrivial R] : (X n : mv_polynomial σ R).vars = {n} := by rw [X, vars_monomial (one_ne_zero' R), finsupp.support_single_ne_zero _ (one_ne_zero' ℕ)] lemma mem_vars (i : σ) : i ∈ p.vars ↔ ∃ (d : σ →₀ ℕ) (H : d ∈ p.support), i ∈ d.support := by simp only [vars, multiset.mem_to_finset, mem_degrees, mem_support_iff, exists_prop] lemma mem_support_not_mem_vars_zero {f : mv_polynomial σ R} {x : σ →₀ ℕ} (H : x ∈ f.support) {v : σ} (h : v ∉ vars f) : x v = 0 := begin letI := classical.dec_eq σ, rw [vars_def, multiset.mem_to_finset] at h, rw ← finsupp.not_mem_support_iff, contrapose! h, rw degrees_def, rw (show f.support = insert x f.support, from eq.symm $ finset.insert_eq_of_mem H), rw finset.sup_insert, simp only [multiset.mem_union, multiset.sup_eq_union], left, rwa [←to_finset_to_multiset, multiset.mem_to_finset] at h, end lemma vars_add_subset [decidable_eq σ] (p q : mv_polynomial σ R) : (p + q).vars ⊆ p.vars ∪ q.vars := begin intros x hx, simp only [vars, finset.mem_union, multiset.mem_to_finset] at hx ⊢, simpa using multiset.mem_of_le (degrees_add _ _) hx, end lemma vars_add_of_disjoint [decidable_eq σ] (h : disjoint p.vars q.vars) : (p + q).vars = p.vars ∪ q.vars := begin apply finset.subset.antisymm (vars_add_subset p q), intros x hx, simp only [vars_def, multiset.disjoint_to_finset] at h hx ⊢, rw [degrees_add_of_disjoint h, multiset.to_finset_union], exact hx end section mul lemma vars_mul [decidable_eq σ] (φ ψ : mv_polynomial σ R) : (φ * ψ).vars ⊆ φ.vars ∪ ψ.vars := begin intro i, simp only [mem_vars, finset.mem_union], rintro ⟨d, hd, hi⟩, rw [mem_support_iff, coeff_mul] at hd, contrapose! hd, cases hd, rw finset.sum_eq_zero, rintro ⟨d₁, d₂⟩ H, rw finsupp.mem_antidiagonal at H, subst H, obtain H|H : i ∈ d₁.support ∨ i ∈ d₂.support, { simpa only [finset.mem_union] using finsupp.support_add hi, }, { suffices : coeff d₁ φ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, { suffices : coeff d₂ ψ = 0, by simp [this], rw [coeff, ← finsupp.not_mem_support_iff], intro, solve_by_elim, }, end @[simp] lemma vars_one : (1 : mv_polynomial σ R).vars = ∅ := vars_C lemma vars_pow (φ : mv_polynomial σ R) (n : ℕ) : (φ ^ n).vars ⊆ φ.vars := begin classical, simp_rw vars_def, induction n with n ih, { simp }, { rw pow_succ, apply finset.subset.trans (vars_mul _ _), exact finset.union_subset (finset.subset.refl _) ih } end /-- The variables of the product of a family of polynomials are a subset of the union of the sets of variables of each polynomial. -/ lemma vars_prod {ι : Type*} [decidable_eq σ] {s : finset ι} (f : ι → mv_polynomial σ R) : (∏ i in s, f i).vars ⊆ s.bUnion (λ i, (f i).vars) := begin classical, apply s.induction_on, { simp }, { intros a s hs hsub, simp only [hs, finset.bUnion_insert, finset.prod_insert, not_false_iff], apply finset.subset.trans (vars_mul _ _), exact finset.union_subset_union (finset.subset.refl _) hsub } end section is_domain variables {A : Type*} [comm_ring A] [is_domain A] lemma vars_C_mul (a : A) (ha : a ≠ 0) (φ : mv_polynomial σ A) : (C a * φ).vars = φ.vars := begin ext1 i, simp only [mem_vars, exists_prop, mem_support_iff], apply exists_congr, intro d, apply and_congr _ iff.rfl, rw [coeff_C_mul, mul_ne_zero_iff, eq_true_intro ha, true_and], end end is_domain end mul section sum variables {ι : Type*} (t : finset ι) (φ : ι → mv_polynomial σ R) lemma vars_sum_subset [decidable_eq σ] : (∑ i in t, φ i).vars ⊆ finset.bUnion t (λ i, (φ i).vars) := begin classical, apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has], refine finset.subset.trans (vars_add_subset _ _) (finset.union_subset_union (finset.subset.refl _) _), assumption } end lemma vars_sum_of_disjoint [decidable_eq σ] (h : pairwise $ disjoint on (λ i, (φ i).vars)) : (∑ i in t, φ i).vars = finset.bUnion t (λ i, (φ i).vars) := begin classical, apply t.induction_on, { simp }, { intros a s has hsum, rw [finset.bUnion_insert, finset.sum_insert has, vars_add_of_disjoint, hsum], unfold pairwise on_fun at h, rw hsum, simp only [finset.disjoint_iff_ne] at h ⊢, intros v hv v2 hv2, rw finset.mem_bUnion at hv2, rcases hv2 with ⟨i, his, hi⟩, refine h _ _ hv _ hi, rintro rfl, contradiction } end end sum section map variables [comm_semiring S] (f : R →+* S) variable (p) lemma vars_map : (map f p).vars ⊆ p.vars := by simp [vars, degrees_map] variable {f} lemma vars_map_of_injective (hf : injective f) : (map f p).vars = p.vars := by simp [vars, degrees_map_of_injective _ hf] lemma vars_monomial_single (i : σ) {e : ℕ} {r : R} (he : e ≠ 0) (hr : r ≠ 0) : (monomial (finsupp.single i e) r).vars = {i} := by rw [vars_monomial hr, finsupp.support_single_ne_zero _ he] lemma vars_eq_support_bUnion_support [decidable_eq σ] : p.vars = p.support.bUnion finsupp.support := by { ext i, rw [mem_vars, finset.mem_bUnion] } end map end vars section degree_of /-! ### `degree_of` -/ /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of (n : σ) (p : mv_polynomial σ R) : ℕ := by letI := classical.dec_eq σ; exact p.degrees.count n lemma degree_of_def [decidable_eq σ] (n : σ) (p : mv_polynomial σ R) : p.degree_of n = p.degrees.count n := by convert rfl lemma degree_of_eq_sup (n : σ) (f : mv_polynomial σ R) : degree_of n f = f.support.sup (λ m, m n) := begin classical, rw [degree_of_def, degrees_def, multiset.count_finset_sup], congr, ext, simp, end lemma degree_of_lt_iff {n : σ} {f : mv_polynomial σ R} {d : ℕ} (h : 0 < d) : degree_of n f < d ↔ ∀ m : σ →₀ ℕ, m ∈ f.support → m n < d := by rwa [degree_of_eq_sup n f, finset.sup_lt_iff] @[simp] lemma degree_of_zero (n : σ) : degree_of n (0 : mv_polynomial σ R) = 0 := by simp only [degree_of, degrees_zero, multiset.count_zero] @[simp] lemma degree_of_C (a : R) (x : σ): degree_of x (C a : mv_polynomial σ R) = 0 := by simp [degree_of, degrees_C] lemma degree_of_X [decidable_eq σ] (i j : σ) [nontrivial R] : degree_of i (X j : mv_polynomial σ R) = if i = j then 1 else 0 := begin by_cases c : i = j, { simp only [c, if_true, eq_self_iff_true, degree_of, degrees_X, multiset.count_singleton] }, simp [c, if_false, degree_of, degrees_X], end lemma degree_of_add_le (n : σ) (f g : mv_polynomial σ R) : degree_of n (f + g) ≤ max (degree_of n f) (degree_of n g) := begin classical, repeat {rw degree_of_def}, apply (multiset.count_le_of_le n (degrees_add f g)).trans, dsimp, rw multiset.count_union, end lemma monomial_le_degree_of (i : σ) {f : mv_polynomial σ R} {m : σ →₀ ℕ} (h_m : m ∈ f.support) : m i ≤ degree_of i f := begin rw degree_of_eq_sup i, apply finset.le_sup h_m, end -- TODO we can prove equality here if R is a domain lemma degree_of_mul_le (i : σ) (f g: mv_polynomial σ R) : degree_of i (f * g) ≤ degree_of i f + degree_of i g := begin classical, repeat {rw degree_of_def}, convert multiset.count_le_of_le i (degrees_mul f g), rw multiset.count_add, end lemma degree_of_mul_X_ne {i j : σ} (f : mv_polynomial σ R) (h : i ≠ j) : degree_of i (f * X j) = degree_of i f := begin classical, repeat {rw degree_of_eq_sup i}, rw support_mul_X, simp only [finset.sup_map], congr, ext, simp only [single, nat.one_ne_zero, add_right_eq_self, add_right_embedding_apply, coe_mk, pi.add_apply, comp_app, ite_eq_right_iff, finsupp.coe_add, pi.single_eq_of_ne h], end /- TODO in the following we have equality iff f ≠ 0 -/ lemma degree_of_mul_X_eq (j : σ) (f : mv_polynomial σ R) : degree_of j (f * X j) ≤ degree_of j f + 1 := begin classical, repeat {rw degree_of_def}, apply (multiset.count_le_of_le j (degrees_mul f (X j))).trans, simp only [multiset.count_add, add_le_add_iff_left], convert multiset.count_le_of_le j (degrees_X' j), rw multiset.count_singleton_self, end lemma degree_of_rename_of_injective {p : mv_polynomial σ R} {f : σ → τ} (h : function.injective f) (i : σ) : degree_of (f i) (rename f p) = degree_of i p := by classical; simp only [degree_of_def, degrees_rename_of_injective h, multiset.count_map_eq_count' f (p.degrees) h] end degree_of section total_degree /-! ### `total_degree` -/ /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree (p : mv_polynomial σ R) : ℕ := p.support.sup (λs, s.sum $ λn e, e) lemma total_degree_eq (p : mv_polynomial σ R) : p.total_degree = p.support.sup (λm, m.to_multiset.card) := begin rw [total_degree], congr, funext m, exact (finsupp.card_to_multiset _).symm end lemma total_degree_le_degrees_card (p : mv_polynomial σ R) : p.total_degree ≤ p.degrees.card := begin classical, rw [total_degree_eq], exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs) end @[simp] lemma total_degree_C (a : R) : (C a : mv_polynomial σ R).total_degree = 0 := nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn, have _ := finsupp.support_single_subset hn, begin rw [finset.mem_singleton] at this, subst this, exact le_rfl end @[simp] lemma total_degree_zero : (0 : mv_polynomial σ R).total_degree = 0 := by rw [← C_0]; exact total_degree_C (0 : R) @[simp] lemma total_degree_one : (1 : mv_polynomial σ R).total_degree = 0 := total_degree_C (1 : R) @[simp] lemma total_degree_X {R} [comm_semiring R] [nontrivial R] (s : σ) : (X s : mv_polynomial σ R).total_degree = 1 := begin rw [total_degree, support_X], simp only [finset.sup, sum_single_index, finset.fold_singleton, sup_bot_eq], end lemma total_degree_add (a b : mv_polynomial σ R) : (a + b).total_degree ≤ max a.total_degree b.total_degree := finset.sup_le $ assume n hn, begin classical, have := finsupp.support_add hn, rw finset.mem_union at this, cases this, { exact le_max_of_le_left (finset.le_sup this) }, { exact le_max_of_le_right (finset.le_sup this) } end lemma total_degree_add_eq_left_of_total_degree_lt {p q : mv_polynomial σ R} (h : q.total_degree < p.total_degree) : (p + q).total_degree = p.total_degree := begin classical, apply le_antisymm, { rw ← max_eq_left_of_lt h, exact total_degree_add p q, }, by_cases hp : p = 0, { simp [hp], }, obtain ⟨b, hb₁, hb₂⟩ := p.support.exists_mem_eq_sup (finsupp.support_nonempty_iff.mpr hp) (λ (m : σ →₀ ℕ), m.to_multiset.card), have hb : ¬ b ∈ q.support, { contrapose! h, rw [total_degree_eq p, hb₂, total_degree_eq], apply finset.le_sup h, }, have hbb : b ∈ (p + q).support, { apply support_sdiff_support_subset_support_add, rw finset.mem_sdiff, exact ⟨hb₁, hb⟩, }, rw [total_degree_eq, hb₂, total_degree_eq], exact finset.le_sup hbb, end lemma total_degree_add_eq_right_of_total_degree_lt {p q : mv_polynomial σ R} (h : q.total_degree < p.total_degree) : (q + p).total_degree = p.total_degree := by rw [add_comm, total_degree_add_eq_left_of_total_degree_lt h] lemma total_degree_mul (a b : mv_polynomial σ R) : (a * b).total_degree ≤ a.total_degree + b.total_degree := finset.sup_le $ assume n hn, begin classical, have := add_monoid_algebra.support_mul a b hn, simp only [finset.mem_bUnion, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.sum_add_index'], { exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) }, { assume a, refl }, { assume a b₁ b₂, refl } end lemma total_degree_smul_le [comm_semiring S] [distrib_mul_action R S] (a : R) (f : mv_polynomial σ S) : (a • f).total_degree ≤ f.total_degree := finset.sup_mono support_smul lemma total_degree_pow (a : mv_polynomial σ R) (n : ℕ) : (a ^ n).total_degree ≤ n * a.total_degree := begin induction n with n ih, { simp only [nat.nat_zero_eq_zero, zero_mul, pow_zero, total_degree_one] }, rw pow_succ, calc total_degree (a * a ^ n) ≤ a.total_degree + (a^n).total_degree : total_degree_mul _ _ ... ≤ a.total_degree + n * a.total_degree : add_le_add_left ih _ ... = (n+1) * a.total_degree : by rw [add_mul, one_mul, add_comm] end @[simp] lemma total_degree_monomial (s : σ →₀ ℕ) {c : R} (hc : c ≠ 0) : (monomial s c : mv_polynomial σ R).total_degree = s.sum (λ _ e, e) := by classical; simp [total_degree, support_monomial, if_neg hc] @[simp] lemma total_degree_X_pow [nontrivial R] (s : σ) (n : ℕ) : (X s ^ n : mv_polynomial σ R).total_degree = n := by simp [X_pow_eq_monomial, one_ne_zero] lemma total_degree_list_prod : ∀(s : list (mv_polynomial σ R)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum | [] := by rw [@list.prod_nil (mv_polynomial σ R) _, total_degree_one]; refl | (p :: ps) := begin rw [@list.prod_cons (mv_polynomial σ R) _, list.map, list.sum_cons], exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _) end lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ R)) : s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum := begin refine quotient.induction_on s (assume l, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum], exact total_degree_list_prod l end lemma total_degree_finset_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.prod f).total_degree ≤ ∑ i in s, (f i).total_degree := begin refine le_trans (total_degree_multiset_prod _) _, rw [multiset.map_map], refl end lemma total_degree_finset_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) : (s.sum f).total_degree ≤ finset.sup s (λ i, (f i).total_degree) := begin induction s using finset.cons_induction with a s has hind, { exact zero_le _ }, { rw [finset.sum_cons, finset.sup_cons, sup_eq_max], exact (mv_polynomial.total_degree_add _ _).trans (max_le_max le_rfl hind), } end lemma exists_degree_lt [fintype σ] (f : mv_polynomial σ R) (n : ℕ) (h : f.total_degree < n * fintype.card σ) {d : σ →₀ ℕ} (hd : d ∈ f.support) : ∃ i, d i < n := begin contrapose! h, calc n * fintype.card σ = ∑ s:σ, n : by rw [finset.sum_const, nat.nsmul_eq_mul, mul_comm, finset.card_univ] ... ≤ ∑ s, d s : finset.sum_le_sum (λ s _, h s) ... ≤ d.sum (λ i e, e) : by { rw [finsupp.sum_fintype], intros, refl } ... ≤ f.total_degree : finset.le_sup hd, end lemma coeff_eq_zero_of_total_degree_lt {f : mv_polynomial σ R} {d : σ →₀ ℕ} (h : f.total_degree < ∑ i in d.support, d i) : coeff d f = 0 := begin classical, rw [total_degree, finset.sup_lt_iff] at h, { specialize h d, rw mem_support_iff at h, refine not_not.mp (mt h _), exact lt_irrefl _, }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma total_degree_rename_le (f : σ → τ) (p : mv_polynomial σ R) : (rename f p).total_degree ≤ p.total_degree := finset.sup_le $ assume b, begin assume h, rw rename_eq at h, classical, have h' := finsupp.map_domain_support h, rw finset.mem_image at h', rcases h' with ⟨s, hs, rfl⟩, rw finsupp.sum_map_domain_index, exact le_trans le_rfl (finset.le_sup hs), exact assume _, rfl, exact assume _ _ _, rfl end end total_degree section eval_vars /-! ### `vars` and `eval` -/ variables [comm_semiring S] lemma eval₂_hom_eq_constant_coeff_of_vars (f : R →+* S) {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : eval₂_hom f g p = f (constant_coeff p) := begin conv_lhs { rw p.as_sum }, simp only [ring_hom.map_sum, eval₂_hom_monomial], by_cases h0 : constant_coeff p = 0, work_on_goal 1 { rw [h0, f.map_zero, finset.sum_eq_zero], intros d hd }, work_on_goal 2 { rw [finset.sum_eq_single (0 : σ →₀ ℕ)], { rw [finsupp.prod_zero_index, mul_one], refl }, intros d hd hd0, }, repeat { obtain ⟨i, hi⟩ : d.support.nonempty, { rw [constant_coeff_eq, coeff, ← finsupp.not_mem_support_iff] at h0, rw [finset.nonempty_iff_ne_empty, ne.def, finsupp.support_eq_empty], rintro rfl, contradiction }, rw [finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hp, zero_pow (nat.pos_of_ne_zero $ finsupp.mem_support_iff.mp hi)], rw [mem_vars], exact ⟨d, hd, hi⟩ }, { rw [constant_coeff_eq, coeff, ← ne.def, ← finsupp.mem_support_iff] at h0, intro, contradiction } end lemma aeval_eq_constant_coeff_of_vars [algebra R S] {g : σ → S} {p : mv_polynomial σ R} (hp : ∀ i ∈ p.vars, g i = 0) : aeval g p = algebra_map _ _ (constant_coeff p) := eval₂_hom_eq_constant_coeff_of_vars _ hp lemma eval₂_hom_congr' {f₁ f₂ : R →+* S} {g₁ g₂ : σ → S} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → (∀ i, i ∈ p₁.vars → i ∈ p₂.vars → g₁ i = g₂ i) → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := begin rintro rfl h rfl, rename [p₁ p, f₁ f], rw p.as_sum, simp only [ring_hom.map_sum, eval₂_hom_monomial], apply finset.sum_congr rfl, intros d hd, congr' 1, simp only [finsupp.prod], apply finset.prod_congr rfl, intros i hi, have : i ∈ p.vars, { rw mem_vars, exact ⟨d, hd, hi⟩ }, rw h i this this, end /-- If `f₁` and `f₂` are ring homs out of the polynomial ring and `p₁` and `p₂` are polynomials, then `f₁ p₁ = f₂ p₂` if `p₁ = p₂` and `f₁` and `f₂` are equal on `R` and on the variables of `p₁`. -/ lemma hom_congr_vars {f₁ f₂ : mv_polynomial σ R →+* S} {p₁ p₂ : mv_polynomial σ R} (hC : f₁.comp C = f₂.comp C) (hv : ∀ i, i ∈ p₁.vars → i ∈ p₂.vars → f₁ (X i) = f₂ (X i)) (hp : p₁ = p₂) : f₁ p₁ = f₂ p₂ := calc f₁ p₁ = eval₂_hom (f₁.comp C) (f₁ ∘ X) p₁ : ring_hom.congr_fun (by ext; simp) _ ... = eval₂_hom (f₂.comp C) (f₂ ∘ X) p₂ : eval₂_hom_congr' hC hv hp ... = f₂ p₂ : ring_hom.congr_fun (by ext; simp) _ lemma exists_rename_eq_of_vars_subset_range (p : mv_polynomial σ R) (f : τ → σ) (hfi : injective f) (hf : ↑p.vars ⊆ set.range f) : ∃ q : mv_polynomial τ R, rename f q = p := ⟨aeval (λ i : σ, option.elim 0 X $ partial_inv f i) p, begin show (rename f).to_ring_hom.comp _ p = ring_hom.id _ p, refine hom_congr_vars _ _ _, { ext1, simp [algebra_map_eq] }, { intros i hip _, rcases hf hip with ⟨i, rfl⟩, simp [partial_inv_left hfi] }, { refl } end⟩ lemma vars_rename [decidable_eq τ] (f : σ → τ) (φ : mv_polynomial σ R) : (rename f φ).vars ⊆ (φ.vars.image f) := begin intros i hi, simp only [vars, exists_prop, multiset.mem_to_finset, finset.mem_image] at hi ⊢, simpa only [multiset.mem_map] using degrees_rename _ _ hi end lemma mem_vars_rename (f : σ → τ) (φ : mv_polynomial σ R) {j : τ} (h : j ∈ (rename f φ).vars) : ∃ (i : σ), i ∈ φ.vars ∧ f i = j := by classical; simpa only [exists_prop, finset.mem_image] using vars_rename f φ h end eval_vars end comm_semiring end mv_polynomial
9ccb7072b1b579f4eb193914c7671b5d1638c8ac
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/bases.lean
bc331efcf848a815f5672322a94916c83312a72f
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
18,432
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 Bases of topologies. Countability axioms. -/ import topology.constructions data.set.countable open set filter lattice classical open_locale topological_space namespace filter universes u v variables {α : Type u} {β : Type v} /-- A filter has a countable basis iff it is generated by a countable collection of subsets of α. (A filter is a generated by a collection of sets iff it is the infimum of the principal filters.) Note: we do not require the collection to be closed under finite intersections. -/ def has_countable_basis (f : filter α) : Prop := ∃ s : set (set α), countable s ∧ f = ⨅ t ∈ s, principal t lemma has_countable_basis_of_seq (f : filter α) (x : ℕ → set α) (h : f = ⨅ i, principal (x i)) : f.has_countable_basis := ⟨range x, countable_range _, by rwa infi_range⟩ lemma seq_of_has_countable_basis (f : filter α) (cblb : f.has_countable_basis) : ∃ x : ℕ → set α, f = ⨅ i, principal (x i) := begin rcases cblb with ⟨B, Bcbl, gen⟩, subst gen, cases B.eq_empty_or_nonempty with hB Bnonempty, { use λ n, set.univ, simp [principal_univ, *] }, rw countable_iff_exists_surjective_to_subtype Bnonempty at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw lattice.infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_refl _ }, { intros a, rcases gsurj a with i, apply infi_le_of_le i _, subst h, apply le_refl _ } end /-- Different characterization of countable basis. A filter has a countable basis iff it is generated by a sequence of sets. -/ lemma has_countable_basis_iff_seq (f : filter α) : f.has_countable_basis ↔ ∃ x : ℕ → set α, f = ⨅ i, principal (x i) := ⟨seq_of_has_countable_basis _, λ ⟨x, xgen⟩, has_countable_basis_of_seq _ x xgen⟩ lemma mono_seq_of_has_countable_basis (f : filter α) (cblb : f.has_countable_basis) : ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ f = ⨅ i, principal (x i) := begin rcases (seq_of_has_countable_basis f cblb) with ⟨x', hx'⟩, let x := λ n, ⋂ m ≤ n, x' m, use x, split, { intros i j hij a, simp [x], intros h i' hi'i, apply h, transitivity; assumption }, subst hx', apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, apply Inter_mem_sets (finite_le_nat _), intros j hji, rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp [x], intro h, apply h, refl }, end /-- Different characterization of countable basis. A filter has a countable basis iff it is generated by a monotonically decreasing sequence of sets. -/ lemma has_countable_basis_iff_mono_seq (f : filter α) : f.has_countable_basis ↔ ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ f = ⨅ i, principal (x i) := ⟨mono_seq_of_has_countable_basis _, λ ⟨x, _, xgen⟩, has_countable_basis_of_seq _ x xgen⟩ /-- Different characterization of countable basis. A filter has a countable basis iff there exists a monotonically decreasing sequence of sets `x i` such that `s ∈ f ↔ ∃ i, x i ⊆ s`. -/ lemma has_countable_basis_iff_mono_seq' (f : filter α) : f.has_countable_basis ↔ ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ (∀ {s}, s ∈ f ↔ ∃ i, x i ⊆ s) := begin refine (has_countable_basis_iff_mono_seq f).trans (exists_congr $ λ x, and_congr_right _), intro hmono, have : directed (≥) (λ i, principal (x i)), from directed_of_mono _ (λ i j hij, principal_mono.2 (hmono _ _ hij)), simp only [filter.ext_iff, mem_infi this ⟨0⟩, mem_Union, mem_principal_sets] end lemma has_countable_basis.comap {l : filter β} (h : has_countable_basis l) (f : α → β) : has_countable_basis (l.comap f) := begin rcases h with ⟨S, h₁, h₂⟩, refine ⟨preimage f '' S, countable_image _ h₁, _⟩, calc comap f l = ⨅ s ∈ S, principal (f ⁻¹' s) : by simp [h₂] ... = ⨅ s ∈ S, ⨅ (t : set α) (H : f ⁻¹' s = t), principal t : by simp ... = ⨅ (t : set α) (s ∈ S) (h₂ : f ⁻¹' s = t), principal t : by { rw [infi_comm], congr' 1, ext t, rw [infi_comm] } ... = _ : by simp [-infi_infi_eq_right, infi_and] end -- TODO : prove this for a encodable type lemma has_countable_basis_at_top_finset_nat : has_countable_basis (@at_top (finset ℕ) _) := begin refine has_countable_basis_of_seq _ (λN, Ici (finset.range N)) (eq_infi_of_mem_sets_iff_exists_mem _), assume s, rw mem_at_top_sets, refine ⟨_, λ ⟨N, hN⟩, ⟨finset.range N, hN⟩⟩, rintros ⟨t, ht⟩, rcases mem_at_top_sets.1 (tendsto_finset_range (mem_at_top t)) with ⟨N, hN⟩, simp only [preimage, mem_set_of_eq] at hN, exact ⟨N, mem_principal_sets.2 $ λ t' ht', ht t' $ le_trans (hN _ $ le_refl N) ht'⟩ end lemma has_countable_basis.tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.has_countable_basis) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rw filter.has_countable_basis_iff_mono_seq at hcb, rcases hcb with ⟨g, gmon, gbasis⟩, have gbasis : ∀ A, A ∈ k ↔ ∃ i, g i ⊆ A, { intro A, subst gbasis, rw mem_infi, { simp only [set.mem_Union, iff_self, filter.mem_principal_sets] }, { exact directed_of_mono _ (λ i j h, principal_mono.mpr $ gmon _ _ h) }, { apply_instance } }, classical, contrapose, simp only [not_forall, not_imp, not_exists, subset_def, @tendsto_def _ _ f, gbasis], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { simp only [tendsto_at_top', gbasis], rintros A ⟨i, hgiA⟩, use i, refine (λ j hj, hgiA $ gmon _ _ hj _), simp only [h] }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma has_countable_basis.tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.has_countable_basis) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 end filter namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b, ie.symm ▸ ⟨_, h⟩⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _, by rw sInter_empty; exact ⟨a, mem_univ a⟩⟩, sInter_empty⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (le_generate_from $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)) (le_generate_from $ assume s hs, s.eq_empty_or_nonempty.elim (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s.nonempty, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs, by rwa sInter_singleton⟩, sInter_singleton s⟩)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, _root_.is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in ⟨u, h₁, h₂⟩, le_antisymm (le_generate_from h_open) (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu))⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin change s ∈ (𝓝 a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s, rw [hb.2.2, nhds_generate_from, binfi_sets_eq], { simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au lemma sUnion_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩ lemma Union_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in ⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩ variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, (𝓝 a).has_countable_basis) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b}, countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, countable_image _ hb, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ (⋂₀ s).nonempty} in ⟨b', countable_image _ $ countable_subset (by simp only [(and_assoc _ _).symm]; exact inter_subset_left _ _) (countable_set_of_finite_subset hb₁), assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 hp), is_topological_basis_of_subbasis hb₂⟩ /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance {β : Type*} [topological_space β] [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in ⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v}, have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}), by apply set.ext; simp, by rw [this]; exact (countable_bUnion ha₁ $ assume u hu, countable_bUnion hb₁ $ by simp), by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩ instance second_countable_topology_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from assume a, @is_open_generated_countable_inter (π a) _ (sc a), let ⟨g, hg⟩ := classical.axiom_of_choice this in have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2, begin constructor, refine ⟨pi univ '' pi univ g, countable_image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] }, exact countable_pi (assume i, (hg i).1), }, rw [this, pi_generate_from_eq_fintype], { congr' 1, ext f, simp [pi, eq_comm] }, exact assume a, (hg a).2.2.2.1 end @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in have nhds_eq : ∀a, 𝓝 a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val), by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl, have ∀s∈b, set.nonempty s, from assume s hs, ne_empty_iff_nonempty.1 $ λ eq, absurd hs (eq.symm ▸ hb₂), have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simpa only [skolem, set.nonempty] using this, let ⟨f, hf⟩ := this in ⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}), countable_bUnion hb₁ (λ _ _, countable_Union_Prop $ λ _, countable_singleton _), set.ext $ assume a, have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial, let ⟨t, ht₁, ht₂⟩ := this in have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩, suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥, by simpa only [closure_eq_nhds, nhds_eq, infi_inf w, inf_principal, mem_set_of_eq, mem_univ, iff_true], infi_ne_bot_of_directed ⟨a⟩ (assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩, let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in ⟨⟨s₃, has₃, hs₃⟩, begin simp only [le_principal_iff, mem_principal_sets, (≥)], simp only [subset_inter_iff] at hs, split; apply inter_subset_inter_left; simp only [hs] end⟩) (assume ⟨s, has, hs⟩, have (s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h})).nonempty, from ⟨_, hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩, principal_ne_bot_iff.2 this) ⟩⟩ variables {α} lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, _root_.is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in begin let B' := {b ∈ B | ∃ i, b ⊆ s i}, choose f hf using λ b:B', b.2.2, haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable, refine ⟨_, countable_range f, subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, countable_image _ cT, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ end topological_space
ec59d761e4e7df8bfa73df9f3972605d8a92d803
367134ba5a65885e863bdc4507601606690974c1
/src/data/real/cau_seq.lean
1d1ef05bc843e5e78f60660f9e21d17875f7d3ae
[ "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
25,967
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 algebra.big_operators.order /-! # Cauchy sequences A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology. This is a concrete implementation that is useful for simplicity and computability reasons. ## Important definitions * `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val * `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy. * `cau_seq`: the type of Cauchy sequences valued in type `β` with respect to an absolute value function `abv`. ## Tags sequence, cauchy, abs val, absolute value -/ open_locale big_operators /-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and multiplicative. -/ class is_absolute_value {α} [linear_ordered_field α] {β} [ring β] (f : β → α) : Prop := (abv_nonneg [] : ∀ x, 0 ≤ f x) (abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0) (abv_add [] : ∀ x y, f (x + y) ≤ f x + f y) (abv_mul [] : ∀ x y, f (x * y) = f x * f y) namespace is_absolute_value variables {α : Type*} [linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl theorem abv_one [nontrivial β] : abv 1 = 1 := (mul_right_inj' $ mt (abv_eq_zero abv).1 one_ne_zero).1 $ by rw [← abv_mul abv, mul_one, mul_one] theorem abv_pos {a : β} : 0 < abv a ↔ a ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv] theorem abv_neg (a : β) : abv (-a) = abv a := by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _), ← abv_mul abv, ← abv_mul abv]; simp theorem abv_sub (a b : β) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv_neg abv] /-- `abv` as a `monoid_with_zero_hom`. -/ def abv_hom [nontrivial β] : monoid_with_zero_hom β α := ⟨abv, abv_zero abv, abv_one abv, abv_mul abv⟩ theorem abv_inv {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a : β) : abv a⁻¹ = (abv a)⁻¹ := (abv_hom abv).map_inv' a theorem abv_div {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a b : β) : abv (a / b) = abv a / abv b := (abv_hom abv).map_div a b lemma abv_sub_le (a b c : β) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : β) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b lemma abs_abv_sub_le_abv_sub (a b : β) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _, by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩ lemma abv_pow [nontrivial β] (abv : β → α) [is_absolute_value abv] (a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n := (abv_hom abv).to_monoid_hom.map_pow a n end is_absolute_value instance abs_is_absolute_value {α} [linear_ordered_field α] : is_absolute_value (abs : α → α) := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} : (∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) → ∃ i, ∀ j ≥ i, P j ∧ Q j | ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩ section variables {α : Type*} [linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem rat_add_continuous_lemma {ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε := ⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂, by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩ theorem rat_mul_continuous_lemma {ε K₁ K₂ : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ → abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε := begin have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _), have εK := div_pos (half_pos ε0) K0, refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)), replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK) (mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) this end theorem rat_inv_continuous_lemma {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] {ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) : ∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b → abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε := begin have KK := mul_pos K0 K0, have εK := mul_pos ε0 KK, refine ⟨_, εK, λ a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel ε (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos ε0 KK) KK end end /-- A sequence is Cauchy if the distance between its entries tends to zero. -/ def is_cau_seq {α : Type*} [linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) (f : ℕ → β) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε namespace is_cau_seq variables {α : Type*} [linear_ordered_field α] {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₂ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := begin refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _), rw ← add_halves ε, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end theorem cauchy₃ (hf : is_cau_seq abv f) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩ end is_cau_seq /-- `cau_seq β abv` is the type of `β`-valued Cauchy sequences, with respect to the absolute value function `abv`. -/ def cau_seq {α : Type*} [linear_ordered_field α] (β : Type*) [ring β] (abv : β → α) : Type* := {f : ℕ → β // is_cau_seq abv f} namespace cau_seq variables {α : Type*} [linear_ordered_field α] section ring variables {β : Type*} [ring β] {abv : β → α} instance : has_coe_to_fun (cau_seq β abv) := ⟨_, subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq β abv) _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2 theorem cauchy (f : cau_seq β abv) : ∀ {ε}, 0 < ε → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2 /-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with the same values as `f`. -/ def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv := ⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ variable [is_absolute_value abv] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₂ (f : cau_seq β abv) {ε} : 0 < ε → ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂ theorem cauchy₃ (f : cau_seq β abv) {ε} : 0 < ε → ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃ theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := ∑ j in finset.range (i+1), abv (f j), have : ∀ j ≤ i, abv (f j) ≤ R, { intros j ij, change (λ j, abv (f j)) j ≤ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, λ j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ instance : has_add (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl variable (abv) /-- The constant Cauchy sequence. -/ def const (x : β) : cau_seq β abv := ⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y := ⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩ instance : has_zero (cau_seq β abv) := ⟨const 0⟩ instance : has_one (cau_seq β abv) := ⟨const 1⟩ instance : inhabited (cau_seq β abv) := ⟨0⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl theorem const_add (x y : β) : const (x + y) = const x + const y := ext $ λ i, rfl instance : has_mul (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl theorem const_mul (x y : β) : const (x * y) = const x * const y := ext $ λ i, rfl instance : has_neg (cau_seq β abv) := ⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : β) : const (-x) = -const x := ext $ λ i, rfl instance : has_sub (cau_seq β abv) := ⟨λ f g, of_eq (f + -g) (λ x, f x - g x) (λ i, by simp [sub_eq_add_neg])⟩ @[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl theorem const_sub (x y : β) : const (x - y) = const x - const y := ext $ λ i, rfl instance : ring (cau_seq β abv) := by refine { neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, sub := has_sub.sub, sub_eq_add_neg := _, .. }; { intros, apply ext, simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm, sub_eq_add_neg] } instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] : comm_ring (cau_seq β abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } /-- `lim_zero f` holds when `f` approaches 0. -/ def lim_zero {abv : β → α} (f : cau_seq β abv) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε theorem add_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | ε ε0 := (exists_forall_ge_and (hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $ λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂) theorem mul_lim_zero_right (f : cau_seq β abv) {g} (hg : lim_zero g) : lim_zero (f * g) | ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos ε0 F0).imp $ λ i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem mul_lim_zero_left {f} (g : cau_seq β abv) (hg : lim_zero f) : lim_zero (f * g) | ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in (hg _ $ div_pos ε0 G0).imp $ λ i H j ij, by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _); rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero_right _ hf theorem sub_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := by simpa only [sub_eq_add_neg] using add_lim_zero hf (neg_lim_zero hg) theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) := by simpa using neg_lim_zero hfg theorem zero_lim_zero : lim_zero (0 : cau_seq β abv) | ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩ theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _), λ e, e.symm ▸ zero_lim_zero⟩ instance equiv : setoid (cau_seq β abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], λ f g h, by simpa using neg_lim_zero h, λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩ lemma add_equiv_add {f1 f2 g1 g2 : cau_seq β abv} (hf : f1 ≈ f2) (hg : g1 ≈ g2) : f1 + g1 ≈ f2 + g2 := begin change lim_zero ((f1 + g1) - _), convert add_lim_zero hf hg using 1, simp only [sub_eq_add_neg, add_assoc], rw add_comm (-f2), simp only [add_assoc], congr' 2, simp end lemma neg_equiv_neg {f g : cau_seq β abv} (hf : f ≈ g) : -f ≈ -g := begin have hf : lim_zero _ := neg_lim_zero hf, show lim_zero (-f - -g), convert hf using 1, simp end theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε := (exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $ λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, λ l, by simpa using add_lim_zero h l⟩ theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (λ ε ε0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos ε0) with i hi, rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩, refine ⟨j, λ k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : ℕ → β) (g : cau_seq β abv) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f | ε ε0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in ⟨i, λ j ij, begin cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f := assume : lim_zero f, have lim_zero (f - 0), by simpa, hf this lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 := have lim_zero (f - 0), from hf, have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa, show lim_zero (g*f - 0), by simpa lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 := assume : lim_zero (f*g - 0), have hlz : lim_zero (f*g), by simpa, have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf), have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg), begin rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩, rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩, have : 0 < a1 * a2, from mul_pos ha1 ha2, cases hlz _ this with N hN, let i := max N (max N1 N2), have hN' := hN i (le_max_left _ _), have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)), have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)), apply not_le_of_lt hN', change _ ≤ abv (_ * _), rw is_absolute_value.abv_mul abv, apply mul_le_mul; try { assumption }, { apply le_of_lt ha2 }, { apply is_absolute_value.abv_nonneg abv } end theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] end ring section comm_ring variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 := by rw mul_comm; apply mul_equiv_zero _ hf end comm_ring section integral_domain variables {β : Type*} [integral_domain β] (abv : β → α) [is_absolute_value abv] lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) := assume h, have ∀ ε > 0, ∃ i, ∀ k, i ≤ k → abv (1 - 0) < ε, from h, have h1 : abv 1 ≤ 0, from le_of_not_gt $ assume h2 : 0 < abv 1, exists.elim (this _ h2) $ λ i hi, lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _), have h2 : 0 ≤ abv 1, from is_absolute_value.abv_nonneg _ _, have abv 1 = 0, from le_antisymm h1 h2, have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this, absurd this one_ne_zero end integral_domain section field variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩ /-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to the inverses of the values of `f`. -/ def inv (f : cau_seq β abv) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 := λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, λ j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using ε0⟩ theorem const_inv {x : β} (hx : x ≠ 0) : const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := ext (assume n, by simp[inv_apply, const_apply]) end field section abs local notation `const` := const abs /-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/ def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, h₂⟩ := h _ (le_refl _) in not_lt_of_le h₁ (abs_lt.1 h₂).2 theorem const_pos {x : α} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)), λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩ theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩ theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, λ j ij, begin cases h j ij with h₁ h₂, have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (λ h, ⟨K, K0, i, λ j ij, _⟩); have := (hi _ ij).1; cases hi _ (le_refl _) with h₁ h₂, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ h₂ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ } end instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq α abs} (fg : f < g) (gh : g ≈ h) : f < h := show pos (h - f), by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq α abs} (fg : f ≈ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h := show pos (h - f), by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) lemma le_of_eq_of_le {f g h : cau_seq α abs} (hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h := hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg) (or.inr ∘ setoid.trans hfg) lemma le_of_le_of_eq {f g h : cau_seq α abs} (hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h := hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh)) (λ h, or.inr (setoid.trans h hgh)) instance : preorder (cau_seq α abs) := { lt := (<), le := λ f g, f < g ∨ f ≈ g, le_refl := λ f, or.inr (setoid.refl _), le_trans := λ f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := λ f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_right (mt (λ h, or.inr (setoid.symm h)) h₂)⟩ } theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f := (trichotomy (g - f)).imp_right (λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : α} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv lemma le_of_exists {f g : cau_seq α abs} (h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g := let ⟨i, hi⟩ := h in (or.assoc.2 (cau_seq.lt_total f g)).elim id (λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in not_lt_of_ge (hi (max i j) (le_max_left _ _)) (sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _)))))) theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, λ i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ end abs end cau_seq
2a622272cb9146b43ca8ffb96ce4a9a5281458fa
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/fintype.lean
3c80dc74192f08af4d87a2c21c2de9636b248c45
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
33,792
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas logic.unique import tactic.wlog universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = (finset.univ : finset α).sum (λ _, 1) := finset.card_eq_sum_ones _ end fintype lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1), list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩, λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := by rw [fin.fintype]; simp [fintype.card, card, univ] @[instance, priority 0] def unique.fintype {α : Type*} [unique α] : fintype α := ⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩ @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_card_gt_one [fintype α] (h : fintype.card α > 1) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [∀ a, fintype (β a)] [decidable α] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [fintype α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 0] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, not_le_of_gt (nat.lt_succ_self (s.sum id)) $ @finset.single_le_sum _ _ _ id _ _ (λ _ _, nat.zero_le _) _ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
3dbfe58bc7dc6f219c9fb9d9557ffe828ad17771
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/group/semiconj.lean
46deb1e303fb7847c7e85d88cde3b9290af33566
[ "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,024
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov Some proofs and docs came from `algebra/commute` (c) Neil Strickland -/ import algebra.group.units /-! # Semiconjugate elements of a semigroup ## Main definitions We say that `x` is semiconjugate to `y` by `a` (`semiconj_by a x y`), if `a * x = y * a`. In this file we provide operations on `semiconj_by _ _ _`. In the names of these operations, we treat `a` as the “left” argument, and both `x` and `y` as “right” arguments. This way most names in this file agree with the names of the corresponding lemmas for `commute a b = semiconj_by a b b`. As a side effect, some lemmas have only `_right` version. Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like `rw [(h.pow_right 5).eq]` rather than just `rw [h.pow_right 5]`. This file provides only basic operations (`mul_left`, `mul_right`, `inv_right` etc). Other operations (`pow_right`, field inverse etc) are in the files that define corresponding notions. -/ universes u v /-- `x` is semiconjugate to `y` by `a`, if `a * x = y * a`. -/ @[to_additive add_semiconj_by "`x` is additive semiconjugate to `y` by `a` if `a + x = y + a`"] def semiconj_by {M : Type u} [has_mul M] (a x y : M) : Prop := a * x = y * a namespace semiconj_by /-- Equality behind `semiconj_by a x y`; useful for rewriting. -/ @[to_additive] protected lemma eq {S : Type u} [has_mul S] {a x y : S} (h : semiconj_by a x y) : a * x = y * a := h section semigroup variables {S : Type u} [semigroup S] {a b x y z x' y' : S} /-- If `a` semiconjugates `x` to `y` and `x'` to `y'`, then it semiconjugates `x * x'` to `y * y'`. -/ @[simp, to_additive] lemma mul_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x * x') (y * y') := by unfold semiconj_by; assoc_rw [h.eq, h'.eq] /-- If both `a` and `b` semiconjugate `x` to `y`, then so does `a * b`. -/ @[to_additive] lemma mul_left (ha : semiconj_by a y z) (hb : semiconj_by b x y) : semiconj_by (a * b) x z := by unfold semiconj_by; assoc_rw [hb.eq, ha.eq, mul_assoc] /-- The relation “there exists an element that semiconjugates `a` to `b`” on a semigroup is transitive. -/ @[to_additive "The relation “there exists an element that semiconjugates `a` to `b`” on an additive semigroup is transitive."] protected lemma transitive : transitive (λ a b : S, ∃ c, semiconj_by c a b) := λ a b c ⟨x, hx⟩ ⟨y, hy⟩, ⟨y * x, hy.mul_left hx⟩ end semigroup section mul_one_class variables {M : Type u} [mul_one_class M] /-- Any element semiconjugates `1` to `1`. -/ @[simp, to_additive] lemma one_right (a : M) : semiconj_by a 1 1 := by rw [semiconj_by, mul_one, one_mul] /-- One semiconjugates any element to itself. -/ @[simp, to_additive] lemma one_left (x : M) : semiconj_by 1 x x := eq.symm $ one_right x /-- The relation “there exists an element that semiconjugates `a` to `b`” on a monoid (or, more generally, on ` mul_one_class` type) is reflexive. -/ @[to_additive "The relation “there exists an element that semiconjugates `a` to `b`” on an additive monoid (or, more generally, on a `add_zero_class` type) is reflexive."] protected lemma reflexive : reflexive (λ a b : M, ∃ c, semiconj_by c a b) := λ a, ⟨1, one_left a⟩ end mul_one_class section monoid variables {M : Type u} [monoid M] /-- If `a` semiconjugates a unit `x` to a unit `y`, then it semiconjugates `x⁻¹` to `y⁻¹`. -/ @[to_additive] lemma units_inv_right {a : M} {x y : units M} (h : semiconj_by a x y) : semiconj_by a ↑x⁻¹ ↑y⁻¹ := calc a * ↑x⁻¹ = ↑y⁻¹ * (y * a) * ↑x⁻¹ : by rw [units.inv_mul_cancel_left] ... = ↑y⁻¹ * a : by rw [← h.eq, mul_assoc, units.mul_inv_cancel_right] @[simp, to_additive] lemma units_inv_right_iff {a : M} {x y : units M} : semiconj_by a ↑x⁻¹ ↑y⁻¹ ↔ semiconj_by a x y := ⟨units_inv_right, units_inv_right⟩ /-- If a unit `a` semiconjugates `x` to `y`, then `a⁻¹` semiconjugates `y` to `x`. -/ @[to_additive] lemma units_inv_symm_left {a : units M} {x y : M} (h : semiconj_by ↑a x y) : semiconj_by ↑a⁻¹ y x := calc ↑a⁻¹ * y = ↑a⁻¹ * (y * a * ↑a⁻¹) : by rw [units.mul_inv_cancel_right] ... = x * ↑a⁻¹ : by rw [← h.eq, ← mul_assoc, units.inv_mul_cancel_left] @[simp, to_additive] lemma units_inv_symm_left_iff {a : units M} {x y : M} : semiconj_by ↑a⁻¹ y x ↔ semiconj_by ↑a x y := ⟨units_inv_symm_left, units_inv_symm_left⟩ @[to_additive] theorem units_coe {a x y : units M} (h : semiconj_by a x y) : semiconj_by (a : M) x y := congr_arg units.val h @[to_additive] theorem units_of_coe {a x y : units M} (h : semiconj_by (a : M) x y) : semiconj_by a x y := units.ext h @[simp, to_additive] theorem units_coe_iff {a x y : units M} : semiconj_by (a : M) x y ↔ semiconj_by a x y := ⟨units_of_coe, units_coe⟩ @[simp, to_additive] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) := begin induction n with n ih, { rw [pow_zero, pow_zero], exact semiconj_by.one_right _ }, { rw [pow_succ, pow_succ], exact h.mul_right ih } end end monoid section group variables {G : Type u} [group G] {a x y : G} @[simp, to_additive] lemma inv_right_iff : semiconj_by a x⁻¹ y⁻¹ ↔ semiconj_by a x y := @units_inv_right_iff G _ a ⟨x, x⁻¹, mul_inv_self x, inv_mul_self x⟩ ⟨y, y⁻¹, mul_inv_self y, inv_mul_self y⟩ @[to_additive] lemma inv_right : semiconj_by a x y → semiconj_by a x⁻¹ y⁻¹ := inv_right_iff.2 @[simp, to_additive] lemma inv_symm_left_iff : semiconj_by a⁻¹ y x ↔ semiconj_by a x y := @units_inv_symm_left_iff G _ ⟨a, a⁻¹, mul_inv_self a, inv_mul_self a⟩ _ _ @[to_additive] lemma inv_symm_left : semiconj_by a x y → semiconj_by a⁻¹ y x := inv_symm_left_iff.2 @[to_additive] lemma inv_inv_symm (h : semiconj_by a x y) : semiconj_by a⁻¹ y⁻¹ x⁻¹ := h.inv_right.inv_symm_left -- this is not a simp lemma because it can be deduced from other simp lemmas @[to_additive] lemma inv_inv_symm_iff : semiconj_by a⁻¹ y⁻¹ x⁻¹ ↔ semiconj_by a x y := inv_right_iff.trans inv_symm_left_iff /-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/ @[to_additive] lemma conj_mk (a x : G) : semiconj_by a x (a * x * a⁻¹) := by unfold semiconj_by; rw [mul_assoc, inv_mul_self, mul_one] end group end semiconj_by @[simp, to_additive add_semiconj_by_iff_eq] lemma semiconj_by_iff_eq {M : Type u} [cancel_comm_monoid M] {a x y : M} : semiconj_by a x y ↔ x = y := ⟨λ h, mul_left_cancel (h.trans (mul_comm _ _)), λ h, by rw [h, semiconj_by, mul_comm] ⟩ /-- `a` semiconjugates `x` to `a * x * a⁻¹`. -/ @[to_additive] lemma units.mk_semiconj_by {M : Type u} [monoid M] (u : units M) (x : M) : semiconj_by ↑u x (u * x * ↑u⁻¹) := by unfold semiconj_by; rw [units.inv_mul_cancel_right]
c977f10de9da46cb30a83b3a4217610b79aa5153
26ac254ecb57ffcb886ff709cf018390161a9225
/src/ring_theory/coprime.lean
8e290dcb8fe1fd4d9ccbd21194eba8487e7b0cf1
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
11,474
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Ken Lee, Chris Hughes -/ import tactic.ring import algebra.big_operators import data.fintype.basic import data.int.gcd import data.set.disjointed /-! # Coprime elements of a ring ## Main definitions * `is_coprime x y`: that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. -/ open_locale classical big_operators universes u v section comm_semiring variables {R : Type u} [comm_semiring R] (x y z : R) /-- The proposition that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. -/ @[simp] def is_coprime : Prop := ∃ a b, a * x + b * y = 1 theorem nat.is_coprime_iff_coprime {m n : ℕ} : is_coprime (m : ℤ) n ↔ nat.coprime m n := ⟨λ ⟨a, b, H⟩, nat.eq_one_of_dvd_one $ int.coe_nat_dvd.1 $ by { rw [int.coe_nat_one, ← H], exact dvd_add (dvd_mul_of_dvd_right (int.coe_nat_dvd.2 $ nat.gcd_dvd_left m n) _) (dvd_mul_of_dvd_right (int.coe_nat_dvd.2 $ nat.gcd_dvd_right m n) _) }, λ H, ⟨nat.gcd_a m n, nat.gcd_b m n, by rw [mul_comm _ (m : ℤ), mul_comm _ (n : ℤ), ← nat.gcd_eq_gcd_ab, show _ = _, from H, int.coe_nat_one]⟩⟩ variables {x y z} theorem is_coprime.symm (H : is_coprime x y) : is_coprime y x := let ⟨a, b, H⟩ := H in ⟨b, a, by rw [add_comm, H]⟩ theorem is_coprime_comm : is_coprime x y ↔ is_coprime y x := ⟨is_coprime.symm, is_coprime.symm⟩ theorem is_coprime_self : is_coprime x x ↔ is_unit x := ⟨λ ⟨a, b, h⟩, is_unit_of_mul_eq_one x (a + b) $ by rwa [mul_comm, add_mul], λ h, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 h in ⟨b, 0, by rwa [zero_mul, add_zero]⟩⟩ theorem is_coprime_zero_left : is_coprime 0 x ↔ is_unit x := ⟨λ ⟨a, b, H⟩, is_unit_of_mul_eq_one x b $ by rwa [mul_zero, zero_add, mul_comm] at H, λ H, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 H in ⟨1, b, by rwa [one_mul, zero_add]⟩⟩ theorem is_coprime_zero_right : is_coprime x 0 ↔ is_unit x := is_coprime_comm.trans is_coprime_zero_left theorem is_coprime_one_left : is_coprime 1 x := ⟨1, 0, by rw [one_mul, zero_mul, add_zero]⟩ theorem is_coprime_one_right : is_coprime x 1 := ⟨0, 1, by rw [one_mul, zero_mul, zero_add]⟩ theorem is_coprime.dvd_of_dvd_mul_right (H1 : is_coprime x z) (H2 : x ∣ y * z) : x ∣ y := let ⟨a, b, H⟩ := H1 in by { rw [← mul_one y, ← H, mul_add, ← mul_assoc, mul_left_comm], exact dvd_add (dvd_mul_left _ _) (dvd_mul_of_dvd_right H2 _) } theorem is_coprime.dvd_of_dvd_mul_left (H1 : is_coprime x y) (H2 : x ∣ y * z) : x ∣ z := let ⟨a, b, H⟩ := H1 in by { rw [← one_mul z, ← H, add_mul, mul_right_comm, mul_assoc b], exact dvd_add (dvd_mul_left _ _) (dvd_mul_of_dvd_right H2 _) } theorem is_coprime.mul_left (H1 : is_coprime x z) (H2 : is_coprime y z) : is_coprime (x * y) z := let ⟨a, b, h1⟩ := H1, ⟨c, d, h2⟩ := H2 in ⟨a * c, a * x * d + b * c * y + b * d * z, calc a * c * (x * y) + (a * x * d + b * c * y + b * d * z) * z = (a * x + b * z) * (c * y + d * z) : by ring ... = 1 : by rw [h1, h2, mul_one]⟩ theorem is_coprime.mul_right (H1 : is_coprime x y) (H2 : is_coprime x z) : is_coprime x (y * z) := by { rw is_coprime_comm at H1 H2 ⊢, exact H1.mul_left H2 } variables {I : Type v} {s : I → R} {t : finset I} theorem is_coprime.prod_left : (∀ i ∈ t, is_coprime (s i) x) → is_coprime (∏ i in t, s i) x := finset.induction_on t (λ _, is_coprime_one_left) $ λ b t hbt ih H, by { rw finset.prod_insert hbt, rw finset.forall_mem_insert at H, exact H.1.mul_left (ih H.2) } theorem is_coprime.prod_right : (∀ i ∈ t, is_coprime x (s i)) → is_coprime x (∏ i in t, s i) := by simpa only [is_coprime_comm] using is_coprime.prod_left theorem is_coprime.mul_dvd (H : is_coprime x y) (H1 : x ∣ z) (H2 : y ∣ z) : x * y ∣ z := begin obtain ⟨a, b, h⟩ := H, rw [← mul_one z, ← h, mul_add], apply dvd_add, { rw [mul_comm z, mul_assoc], exact dvd_mul_of_dvd_right (mul_dvd_mul_left _ H2) _ }, { rw [mul_comm b, ← mul_assoc], exact dvd_mul_of_dvd_left (mul_dvd_mul_right H1 _) _ } end theorem finset.prod_dvd_of_coprime (Hs : pairwise (is_coprime on s)) (Hs1 : ∀ i, s i ∣ z) : ∏ x in t, s x ∣ z := finset.induction_on t (one_dvd z) (λ a r har ih, by { rw finset.prod_insert har, exact (is_coprime.prod_right $ λ i hir, Hs a i $ λ hai, har $ hai.symm ▸ hir).mul_dvd (Hs1 a) ih }) theorem fintype.prod_dvd_of_coprime [fintype I] (Hs : pairwise (is_coprime on s)) (Hs1 : ∀ i, s i ∣ z) : ∏ x, s x ∣ z := finset.prod_dvd_of_coprime Hs Hs1 theorem is_coprime.of_mul_left_left (H : is_coprime (x * y) z) : is_coprime x z := let ⟨a, b, h⟩ := H in ⟨a * y, b, by rwa [mul_right_comm, mul_assoc]⟩ theorem is_coprime.of_mul_left_right (H : is_coprime (x * y) z) : is_coprime y z := by { rw mul_comm at H, exact H.of_mul_left_left } theorem is_coprime.of_mul_right_left (H : is_coprime x (y * z)) : is_coprime x y := by { rw is_coprime_comm at H ⊢, exact H.of_mul_left_left } theorem is_coprime.of_mul_right_right (H : is_coprime x (y * z)) : is_coprime x z := by { rw mul_comm at H, exact H.of_mul_right_left } theorem is_coprime.mul_left_iff : is_coprime (x * y) z ↔ is_coprime x z ∧ is_coprime y z := ⟨λ H, ⟨H.of_mul_left_left, H.of_mul_left_right⟩, λ ⟨H1, H2⟩, H1.mul_left H2⟩ theorem is_coprime.mul_right_iff : is_coprime x (y * z) ↔ is_coprime x y ∧ is_coprime x z := by rw [is_coprime_comm, is_coprime.mul_left_iff, is_coprime_comm, @is_coprime_comm _ _ z] theorem is_coprime.prod_left_iff : is_coprime (∏ i in t, s i) x ↔ ∀ i ∈ t, is_coprime (s i) x := finset.induction_on t (iff_of_true is_coprime_one_left $ λ _, false.elim) $ λ b t hbt ih, by rw [finset.prod_insert hbt, is_coprime.mul_left_iff, ih, finset.forall_mem_insert] theorem is_coprime.prod_right_iff : is_coprime x (∏ i in t, s i) ↔ ∀ i ∈ t, is_coprime x (s i) := by simpa only [is_coprime_comm] using is_coprime.prod_left_iff theorem is_coprime.of_prod_left (H1 : is_coprime (∏ i in t, s i) x) (i : I) (hit : i ∈ t) : is_coprime (s i) x := is_coprime.prod_left_iff.1 H1 i hit theorem is_coprime.of_prod_right (H1 : is_coprime x (∏ i in t, s i)) (i : I) (hit : i ∈ t) : is_coprime x (s i) := is_coprime.prod_right_iff.1 H1 i hit variables {m n : ℕ} theorem is_coprime.pow_left (H : is_coprime x y) : is_coprime (x ^ m) y := by { rw [← finset.card_range m, ← finset.prod_const], exact is_coprime.prod_left (λ _ _, H) } theorem is_coprime.pow_right (H : is_coprime x y) : is_coprime x (y ^ n) := by { rw [← finset.card_range n, ← finset.prod_const], exact is_coprime.prod_right (λ _ _, H) } theorem is_coprime.pow (H : is_coprime x y) : is_coprime (x ^ m) (y ^ n) := H.pow_left.pow_right theorem is_coprime.is_unit_of_dvd (H : is_coprime x y) (d : x ∣ y) : is_unit x := let ⟨k, hk⟩ := d in is_coprime_self.1 $ is_coprime.of_mul_right_left $ show is_coprime x (x * k), from hk ▸ H theorem is_coprime.map (H : is_coprime x y) {S : Type v} [comm_semiring S] (f : R →+* S) : is_coprime (f x) (f y) := let ⟨a, b, h⟩ := H in ⟨f a, f b, by rw [← f.map_mul, ← f.map_mul, ← f.map_add, h, f.map_one]⟩ variables {x y z} lemma is_coprime.of_add_mul_left_left (h : is_coprime (x + y * z) y) : is_coprime x y := let ⟨a, b, H⟩ := h in ⟨a, a * z + b, by simpa only [add_mul, mul_add, add_assoc, add_comm, add_left_comm, mul_assoc, mul_comm, mul_left_comm] using H⟩ lemma is_coprime.of_add_mul_right_left (h : is_coprime (x + z * y) y) : is_coprime x y := by { rw mul_comm at h, exact h.of_add_mul_left_left } lemma is_coprime.of_add_mul_left_right (h : is_coprime x (y + x * z)) : is_coprime x y := by { rw is_coprime_comm at h ⊢, exact h.of_add_mul_left_left } lemma is_coprime.of_add_mul_right_right (h : is_coprime x (y + z * x)) : is_coprime x y := by { rw mul_comm at h, exact h.of_add_mul_left_right } lemma is_coprime.of_mul_add_left_left (h : is_coprime (y * z + x) y) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_left_left } lemma is_coprime.of_mul_add_right_left (h : is_coprime (z * y + x) y) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_right_left } lemma is_coprime.of_mul_add_left_right (h : is_coprime x (x * z + y)) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_left_right } lemma is_coprime.of_mul_add_right_right (h : is_coprime x (z * x + y)) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_right_right } end comm_semiring namespace is_coprime section comm_ring variables {R : Type u} [comm_ring R] lemma add_mul_left_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (x + y * z) y := @of_add_mul_left_left R _ _ _ (-z) $ by simpa only [mul_neg_eq_neg_mul_symm, add_neg_cancel_right] using h lemma add_mul_right_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (x + z * y) y := by { rw mul_comm, exact h.add_mul_left_left z } lemma add_mul_left_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (y + x * z) := by { rw is_coprime_comm, exact h.symm.add_mul_left_left z } lemma add_mul_right_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (y + z * x) := by { rw is_coprime_comm, exact h.symm.add_mul_right_left z } lemma mul_add_left_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (y * z + x) y := by { rw add_comm, exact h.add_mul_left_left z } lemma mul_add_right_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (z * y + x) y := by { rw add_comm, exact h.add_mul_right_left z } lemma mul_add_left_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (x * z + y) := by { rw add_comm, exact h.add_mul_left_right z } lemma mul_add_right_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (z * x + y) := by { rw add_comm, exact h.add_mul_right_right z } lemma add_mul_left_left_iff {x y z : R} : is_coprime (x + y * z) y ↔ is_coprime x y := ⟨of_add_mul_left_left, λ h, h.add_mul_left_left z⟩ lemma add_mul_right_left_iff {x y z : R} : is_coprime (x + z * y) y ↔ is_coprime x y := ⟨of_add_mul_right_left, λ h, h.add_mul_right_left z⟩ lemma add_mul_left_right_iff {x y z : R} : is_coprime x (y + x * z) ↔ is_coprime x y := ⟨of_add_mul_left_right, λ h, h.add_mul_left_right z⟩ lemma add_mul_right_right_iff {x y z : R} : is_coprime x (y + z * x) ↔ is_coprime x y := ⟨of_add_mul_right_right, λ h, h.add_mul_right_right z⟩ lemma mul_add_left_left_iff {x y z : R} : is_coprime (y * z + x) y ↔ is_coprime x y := ⟨of_mul_add_left_left, λ h, h.mul_add_left_left z⟩ lemma mul_add_right_left_iff {x y z : R} : is_coprime (z * y + x) y ↔ is_coprime x y := ⟨of_mul_add_right_left, λ h, h.mul_add_right_left z⟩ lemma mul_add_left_right_iff {x y z : R} : is_coprime x (x * z + y) ↔ is_coprime x y := ⟨of_mul_add_left_right, λ h, h.mul_add_left_right z⟩ lemma mul_add_right_right_iff {x y z : R} : is_coprime x (z * x + y) ↔ is_coprime x y := ⟨of_mul_add_right_right, λ h, h.mul_add_right_right z⟩ end comm_ring end is_coprime
ce7d98d3400b58b67d4c25dd92bf1349af4ae49b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/deprecated/group.lean
c85156a5faca6831df3174eba3c3cbddd2f08dbb
[ "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
14,353
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import algebra.group.type_tags import algebra.hom.equiv.basic import algebra.hom.ring import algebra.hom.units /-! # Unbundled monoid and group homomorphisms This file is deprecated, and is no longer imported by anything in mathlib other than other deprecated files, and test files. You should not need to import it. This file defines predicates for unbundled monoid and group homomorphisms. Instead of using this file, please use `monoid_hom`, defined in `algebra.hom.group`, with notation `→*`, for morphisms between monoids or groups. For example use `φ : G →* H` to represent a group homomorphism between multiplicative groups, and `ψ : A →+ B` to represent a group homomorphism between additive groups. ## Main Definitions `is_monoid_hom` (deprecated), `is_group_hom` (deprecated) ## Tags is_group_hom, is_monoid_hom -/ universes u v variables {α : Type u} {β : Type v} /-- Predicate for maps which preserve an addition. -/ structure is_add_hom {α β : Type*} [has_add α] [has_add β] (f : α → β) : Prop := (map_add [] : ∀ x y, f (x + y) = f x + f y) /-- Predicate for maps which preserve a multiplication. -/ @[to_additive] structure is_mul_hom {α β : Type*} [has_mul α] [has_mul β] (f : α → β) : Prop := (map_mul [] : ∀ x y, f (x * y) = f x * f y) namespace is_mul_hom variables [has_mul α] [has_mul β] {γ : Type*} [has_mul γ] /-- The identity map preserves multiplication. -/ @[to_additive "The identity map preserves addition"] lemma id : is_mul_hom (id : α → α) := {map_mul := λ _ _, rfl} /-- The composition of maps which preserve multiplication, also preserves multiplication. -/ @[to_additive "The composition of addition preserving maps also preserves addition"] lemma comp {f : α → β} {g : β → γ} (hf : is_mul_hom f) (hg : is_mul_hom g) : is_mul_hom (g ∘ f) := { map_mul := λ x y, by simp only [function.comp, hf.map_mul, hg.map_mul] } /-- A product of maps which preserve multiplication, preserves multiplication when the target is commutative. -/ @[to_additive "A sum of maps which preserves addition, preserves addition when the target is commutative."] lemma mul {α β} [semigroup α] [comm_semigroup β] {f g : α → β} (hf : is_mul_hom f) (hg : is_mul_hom g) : is_mul_hom (λ a, f a * g a) := { map_mul := λ a b, by simp only [hf.map_mul, hg.map_mul, mul_comm, mul_assoc, mul_left_comm] } /-- The inverse of a map which preserves multiplication, preserves multiplication when the target is commutative. -/ @[to_additive "The negation of a map which preserves addition, preserves addition when the target is commutative."] lemma inv {α β} [has_mul α] [comm_group β] {f : α → β} (hf : is_mul_hom f) : is_mul_hom (λ a, (f a)⁻¹) := { map_mul := λ a b, (hf.map_mul a b).symm ▸ mul_inv _ _ } end is_mul_hom /-- Predicate for add_monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/ structure is_add_monoid_hom [add_zero_class α] [add_zero_class β] (f : α → β) extends is_add_hom f : Prop := (map_zero [] : f 0 = 0) /-- Predicate for monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/ @[to_additive] structure is_monoid_hom [mul_one_class α] [mul_one_class β] (f : α → β) extends is_mul_hom f : Prop := (map_one [] : f 1 = 1) namespace monoid_hom variables {M : Type*} {N : Type*} [mM : mul_one_class M] [mN : mul_one_class N] include mM mN /-- Interpret a map `f : M → N` as a homomorphism `M →* N`. -/ @[to_additive "Interpret a map `f : M → N` as a homomorphism `M →+ N`."] def of {f : M → N} (h : is_monoid_hom f) : M →* N := { to_fun := f, map_one' := h.2, map_mul' := h.1.1 } variables {mM mN} @[simp, to_additive] lemma coe_of {f : M → N} (hf : is_monoid_hom f) : ⇑ (monoid_hom.of hf) = f := rfl @[to_additive] lemma is_monoid_hom_coe (f : M →* N) : is_monoid_hom (f : M → N) := { map_mul := f.map_mul, map_one := f.map_one } end monoid_hom namespace mul_equiv variables {M : Type*} {N : Type*} [mul_one_class M] [mul_one_class N] /-- A multiplicative isomorphism preserves multiplication (deprecated). -/ @[to_additive "An additive isomorphism preserves addition (deprecated)."] theorem is_mul_hom (h : M ≃* N) : is_mul_hom h := ⟨h.map_mul⟩ /-- A multiplicative bijection between two monoids is a monoid hom (deprecated -- use `mul_equiv.to_monoid_hom`). -/ @[to_additive "An additive bijection between two additive monoids is an additive monoid hom (deprecated). "] lemma is_monoid_hom (h : M ≃* N) : is_monoid_hom h := { map_mul := h.map_mul, map_one := h.map_one } end mul_equiv namespace is_monoid_hom variables [mul_one_class α] [mul_one_class β] {f : α → β} (hf : is_monoid_hom f) /-- A monoid homomorphism preserves multiplication. -/ @[to_additive "An additive monoid homomorphism preserves addition."] lemma map_mul (x y) : f (x * y) = f x * f y := hf.map_mul x y /-- The inverse of a map which preserves multiplication, preserves multiplication when the target is commutative. -/ @[to_additive "The negation of a map which preserves addition, preserves addition when the target is commutative."] lemma inv {α β} [mul_one_class α] [comm_group β] {f : α → β} (hf : is_monoid_hom f) : is_monoid_hom (λ a, (f a)⁻¹) := { map_one := hf.map_one.symm ▸ inv_one, map_mul := λ a b, (hf.map_mul a b).symm ▸ mul_inv _ _ } end is_monoid_hom /-- A map to a group preserving multiplication is a monoid homomorphism. -/ @[to_additive "A map to an additive group preserving addition is an additive monoid homomorphism."] theorem is_mul_hom.to_is_monoid_hom [mul_one_class α] [group β] {f : α → β} (hf : is_mul_hom f) : is_monoid_hom f := { map_one := mul_right_eq_self.1 $ by rw [← hf.map_mul, one_mul], map_mul := hf.map_mul } namespace is_monoid_hom variables [mul_one_class α] [mul_one_class β] {f : α → β} /-- The identity map is a monoid homomorphism. -/ @[to_additive "The identity map is an additive monoid homomorphism."] lemma id : is_monoid_hom (@id α) := { map_one := rfl, map_mul := λ _ _, rfl } /-- The composite of two monoid homomorphisms is a monoid homomorphism. -/ @[to_additive "The composite of two additive monoid homomorphisms is an additive monoid homomorphism."] lemma comp (hf : is_monoid_hom f) {γ} [mul_one_class γ] {g : β → γ} (hg : is_monoid_hom g) : is_monoid_hom (g ∘ f) := { map_one := show g _ = 1, by rw [hf.map_one, hg.map_one], ..is_mul_hom.comp hf.to_is_mul_hom hg.to_is_mul_hom } end is_monoid_hom namespace is_add_monoid_hom /-- Left multiplication in a ring is an additive monoid morphism. -/ lemma is_add_monoid_hom_mul_left {γ : Type*} [non_unital_non_assoc_semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, x * y) := { map_zero := mul_zero x, map_add := λ y z, mul_add x y z } /-- Right multiplication in a ring is an additive monoid morphism. -/ lemma is_add_monoid_hom_mul_right {γ : Type*} [non_unital_non_assoc_semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, y * x) := { map_zero := zero_mul x, map_add := λ y z, add_mul y z x } end is_add_monoid_hom /-- Predicate for additive group homomorphism (deprecated -- use bundled `monoid_hom`). -/ structure is_add_group_hom [add_group α] [add_group β] (f : α → β) extends is_add_hom f : Prop /-- Predicate for group homomorphisms (deprecated -- use bundled `monoid_hom`). -/ @[to_additive] structure is_group_hom [group α] [group β] (f : α → β) extends is_mul_hom f : Prop @[to_additive] lemma monoid_hom.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (f : G →* H) : is_group_hom (f : G → H) := { map_mul := f.map_mul } @[to_additive] lemma mul_equiv.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (h : G ≃* H) : is_group_hom h := { map_mul := h.map_mul } /-- Construct `is_group_hom` from its only hypothesis. -/ @[to_additive "Construct `is_add_group_hom` from its only hypothesis."] lemma is_group_hom.mk' [group α] [group β] {f : α → β} (hf : ∀ x y, f (x * y) = f x * f y) : is_group_hom f := { map_mul := hf } namespace is_group_hom variables [group α] [group β] {f : α → β} (hf : is_group_hom f) open is_mul_hom (map_mul) lemma map_mul : ∀ (x y), f (x * y) = f x * f y := hf.to_is_mul_hom.map_mul /-- A group homomorphism is a monoid homomorphism. -/ @[to_additive "An additive group homomorphism is an additive monoid homomorphism."] lemma to_is_monoid_hom : is_monoid_hom f := hf.to_is_mul_hom.to_is_monoid_hom /-- A group homomorphism sends 1 to 1. -/ @[to_additive "An additive group homomorphism sends 0 to 0."] lemma map_one : f 1 = 1 := hf.to_is_monoid_hom.map_one /-- A group homomorphism sends inverses to inverses. -/ @[to_additive "An additive group homomorphism sends negations to negations."] theorem map_inv (hf : is_group_hom f) (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one_left $ by rw [← hf.map_mul, inv_mul_self, hf.map_one] @[to_additive] lemma map_div (hf : is_group_hom f) (a b : α) : f (a / b) = f a / f b := by simp_rw [div_eq_mul_inv, hf.map_mul, hf.map_inv] /-- The identity is a group homomorphism. -/ @[to_additive "The identity is an additive group homomorphism."] lemma id : is_group_hom (@id α) := { map_mul := λ _ _, rfl} /-- The composition of two group homomorphisms is a group homomorphism. -/ @[to_additive "The composition of two additive group homomorphisms is an additive group homomorphism."] lemma comp (hf : is_group_hom f) {γ} [group γ] {g : β → γ} (hg : is_group_hom g) : is_group_hom (g ∘ f) := { ..is_mul_hom.comp hf.to_is_mul_hom hg.to_is_mul_hom } /-- A group homomorphism is injective iff its kernel is trivial. -/ @[to_additive "An additive group homomorphism is injective if its kernel is trivial."] lemma injective_iff {f : α → β} (hf : is_group_hom f) : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h _, by rw ← hf.map_one; exact @h _ _, λ h x y hxy, eq_of_div_eq_one $ h _ $ by rwa [hf.map_div, div_eq_one]⟩ /-- The product of group homomorphisms is a group homomorphism if the target is commutative. -/ @[to_additive "The sum of two additive group homomorphisms is an additive group homomorphism if the target is commutative."] lemma mul {α β} [group α] [comm_group β] {f g : α → β} (hf : is_group_hom f) (hg : is_group_hom g) : is_group_hom (λa, f a * g a) := { map_mul := (hf.to_is_mul_hom.mul hg.to_is_mul_hom).map_mul } /-- The inverse of a group homomorphism is a group homomorphism if the target is commutative. -/ @[to_additive "The negation of an additive group homomorphism is an additive group homomorphism if the target is commutative."] lemma inv {α β} [group α] [comm_group β] {f : α → β} (hf : is_group_hom f) : is_group_hom (λa, (f a)⁻¹) := { map_mul := hf.to_is_mul_hom.inv.map_mul } end is_group_hom namespace ring_hom /-! These instances look redundant, because `deprecated.ring` provides `is_ring_hom` for a `→+*`. Nevertheless these are harmless, and helpful for stripping out dependencies on `deprecated.ring`. -/ variables {R : Type*} {S : Type*} section variables [non_assoc_semiring R] [non_assoc_semiring S] lemma to_is_monoid_hom (f : R →+* S) : is_monoid_hom f := { map_one := f.map_one, map_mul := f.map_mul } lemma to_is_add_monoid_hom (f : R →+* S) : is_add_monoid_hom f := { map_zero := f.map_zero, map_add := f.map_add } end section variables [ring R] [ring S] lemma to_is_add_group_hom (f : R →+* S) : is_add_group_hom f := { map_add := f.map_add } end end ring_hom /-- Inversion is a group homomorphism if the group is commutative. -/ @[to_additive neg.is_add_group_hom "Negation is an `add_group` homomorphism if the `add_group` is commutative."] lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) := { map_mul := mul_inv } /-- The difference of two additive group homomorphisms is an additive group homomorphism if the target is commutative. -/ lemma is_add_group_hom.sub {α β} [add_group α] [add_comm_group β] {f g : α → β} (hf : is_add_group_hom f) (hg : is_add_group_hom g) : is_add_group_hom (λa, f a - g a) := by simpa only [sub_eq_add_neg] using hf.add hg.neg namespace units variables {M : Type*} {N : Type*} [monoid M] [monoid N] /-- The group homomorphism on units induced by a multiplicative morphism. -/ @[reducible] def map' {f : M → N} (hf : is_monoid_hom f) : Mˣ →* Nˣ := map (monoid_hom.of hf) @[simp] lemma coe_map' {f : M → N} (hf : is_monoid_hom f) (x : Mˣ) : ↑((map' hf : Mˣ → Nˣ) x) = f x := rfl lemma coe_is_monoid_hom : is_monoid_hom (coe : Mˣ → M) := (coe_hom M).is_monoid_hom_coe end units namespace is_unit variables {M : Type*} {N : Type*} [monoid M] [monoid N] {x : M} lemma map' {f : M → N} (hf :is_monoid_hom f) {x : M} (h : is_unit x) : is_unit (f x) := h.map (monoid_hom.of hf) end is_unit lemma additive.is_add_hom [has_mul α] [has_mul β] {f : α → β} (hf : is_mul_hom f) : @is_add_hom (additive α) (additive β) _ _ f := { map_add := is_mul_hom.map_mul hf } lemma multiplicative.is_mul_hom [has_add α] [has_add β] {f : α → β} (hf : is_add_hom f) : @is_mul_hom (multiplicative α) (multiplicative β) _ _ f := { map_mul := is_add_hom.map_add hf } -- defeq abuse lemma additive.is_add_monoid_hom [mul_one_class α] [mul_one_class β] {f : α → β} (hf : is_monoid_hom f) : @is_add_monoid_hom (additive α) (additive β) _ _ f := { map_zero := hf.map_one, ..additive.is_add_hom hf.to_is_mul_hom } lemma multiplicative.is_monoid_hom [add_zero_class α] [add_zero_class β] {f : α → β} (hf : is_add_monoid_hom f) : @is_monoid_hom (multiplicative α) (multiplicative β) _ _ f := { map_one := is_add_monoid_hom.map_zero hf, ..multiplicative.is_mul_hom hf.to_is_add_hom } lemma additive.is_add_group_hom [group α] [group β] {f : α → β} (hf : is_group_hom f) : @is_add_group_hom (additive α) (additive β) _ _ f := { map_add := hf.to_is_mul_hom.map_mul } lemma multiplicative.is_group_hom [add_group α] [add_group β] {f : α → β} (hf : is_add_group_hom f) : @is_group_hom (multiplicative α) (multiplicative β) _ _ f := { map_mul := hf.to_is_add_hom.map_add }
6603f7e087b43520cb7b03c968e22d31c0ec99c5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/regularity/uniform.lean
226cc63112a9a6fa1b414344b082ec625f0fefa1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,509
lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.simple_graph.density import set_theory.ordinal.basic /-! # Graph uniformity and uniform partitions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define uniformity of a pair of vertices in a graph and uniformity of a partition of vertices of a graph. Both are also known as ε-regularity. Finsets of vertices `s` and `t` are `ε`-uniform in a graph `G` if their edge density is at most `ε`-far from the density of any big enough `s'` and `t'` where `s' ⊆ s`, `t' ⊆ t`. The definition is pretty technical, but it amounts to the edges between `s` and `t` being "random" The literature contains several definitions which are equivalent up to scaling `ε` by some constant when the partition is equitable. A partition `P` of the vertices is `ε`-uniform if the proportion of non `ε`-uniform pairs of parts is less than `ε`. ## Main declarations * `simple_graph.is_uniform`: Graph uniformity of a pair of finsets of vertices. * `simple_graph.nonuniform_witness`: `G.nonuniform_witness ε s t` and `G.nonuniform_witness ε t s` together witness the non-uniformity of `s` and `t`. * `finpartition.non_uniforms`: Non uniform pairs of parts of a partition. * `finpartition.is_uniform`: Uniformity of a partition. * `finpartition.nonuniform_witnesses`: For each non-uniform pair of parts of a partition, pick witnesses of non-uniformity and dump them all together. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open finset variables {α 𝕜 : Type*} [linear_ordered_field 𝕜] /-! ### Graph uniformity -/ namespace simple_graph variables (G : simple_graph α) [decidable_rel G.adj] (ε : 𝕜) {s t : finset α} {a b : α} /-- A pair of finsets of vertices is `ε`-uniform (aka `ε`-regular) iff their edge density is close to the density of any big enough pair of subsets. Intuitively, the edges between them are random-like. -/ def is_uniform (s t : finset α) : Prop := ∀ ⦃s'⦄, s' ⊆ s → ∀ ⦃t'⦄, t' ⊆ t → (s.card : 𝕜) * ε ≤ s'.card → (t.card : 𝕜) * ε ≤ t'.card → |(G.edge_density s' t' : 𝕜) - (G.edge_density s t : 𝕜)| < ε variables {G ε} lemma is_uniform.mono {ε' : 𝕜} (h : ε ≤ ε') (hε : is_uniform G ε s t) : is_uniform G ε' s t := λ s' hs' t' ht' hs ht, by refine (hε hs' ht' (le_trans _ hs) (le_trans _ ht)).trans_le h; exact mul_le_mul_of_nonneg_left h (nat.cast_nonneg _) lemma is_uniform.symm : symmetric (is_uniform G ε) := λ s t h t' ht' s' hs' ht hs, by { rw [edge_density_comm _ t', edge_density_comm _ t], exact h hs' ht' hs ht } variables (G) lemma is_uniform_comm : is_uniform G ε s t ↔ is_uniform G ε t s := ⟨λ h, h.symm, λ h, h.symm⟩ lemma is_uniform_singleton (hε : 0 < ε) : G.is_uniform ε {a} {b} := begin intros s' hs' t' ht' hs ht, rw [card_singleton, nat.cast_one, one_mul] at hs ht, obtain rfl | rfl := finset.subset_singleton_iff.1 hs', { replace hs : ε ≤ 0 := by simpa using hs, exact (hε.not_le hs).elim }, obtain rfl | rfl := finset.subset_singleton_iff.1 ht', { replace ht : ε ≤ 0 := by simpa using ht, exact (hε.not_le ht).elim }, { rwa [sub_self, abs_zero] } end lemma not_is_uniform_zero : ¬ G.is_uniform (0 : 𝕜) s t := λ h, (abs_nonneg _).not_lt $ h (empty_subset _) (empty_subset _) (by simp) (by simp) lemma is_uniform_one : G.is_uniform (1 : 𝕜) s t := begin intros s' hs' t' ht' hs ht, rw mul_one at hs ht, rw [eq_of_subset_of_card_le hs' (nat.cast_le.1 hs), eq_of_subset_of_card_le ht' (nat.cast_le.1 ht), sub_self, abs_zero], exact zero_lt_one, end variables {G} lemma not_is_uniform_iff : ¬ G.is_uniform ε s t ↔ ∃ s', s' ⊆ s ∧ ∃ t', t' ⊆ t ∧ ↑s.card * ε ≤ s'.card ∧ ↑t.card * ε ≤ t'.card ∧ ε ≤ |G.edge_density s' t' - G.edge_density s t| := by { unfold is_uniform, simp only [not_forall, not_lt, exists_prop] } open_locale classical variables (G) /-- An arbitrary pair of subsets witnessing the non-uniformity of `(s, t)`. If `(s, t)` is uniform, returns `(s, t)`. Witnesses for `(s, t)` and `(t, s)` don't necessarily match. See `simple_graph.nonuniform_witness`. -/ noncomputable def nonuniform_witnesses (ε : 𝕜) (s t : finset α) : finset α × finset α := if h : ¬ G.is_uniform ε s t then ((not_is_uniform_iff.1 h).some, (not_is_uniform_iff.1 h).some_spec.2.some) else (s, t) lemma left_nonuniform_witnesses_subset (h : ¬ G.is_uniform ε s t) : (G.nonuniform_witnesses ε s t).1 ⊆ s := by { rw [nonuniform_witnesses, dif_pos h], exact (not_is_uniform_iff.1 h).some_spec.1 } lemma left_nonuniform_witnesses_card (h : ¬ G.is_uniform ε s t) : (s.card : 𝕜) * ε ≤ (G.nonuniform_witnesses ε s t).1.card := by { rw [nonuniform_witnesses, dif_pos h], exact (not_is_uniform_iff.1 h).some_spec.2.some_spec.2.1 } lemma right_nonuniform_witnesses_subset (h : ¬ G.is_uniform ε s t) : (G.nonuniform_witnesses ε s t).2 ⊆ t := by { rw [nonuniform_witnesses, dif_pos h], exact (not_is_uniform_iff.1 h).some_spec.2.some_spec.1 } lemma right_nonuniform_witnesses_card (h : ¬ G.is_uniform ε s t) : (t.card : 𝕜) * ε ≤ (G.nonuniform_witnesses ε s t).2.card := by { rw [nonuniform_witnesses, dif_pos h], exact (not_is_uniform_iff.1 h).some_spec.2.some_spec.2.2.1 } lemma nonuniform_witnesses_spec (h : ¬ G.is_uniform ε s t) : ε ≤ |G.edge_density (G.nonuniform_witnesses ε s t).1 (G.nonuniform_witnesses ε s t).2 - G.edge_density s t| := by { rw [nonuniform_witnesses, dif_pos h], exact (not_is_uniform_iff.1 h).some_spec.2.some_spec.2.2.2 } /-- Arbitrary witness of non-uniformity. `G.nonuniform_witness ε s t` and `G.nonuniform_witness ε t s` form a pair of subsets witnessing the non-uniformity of `(s, t)`. If `(s, t)` is uniform, returns `s`. -/ noncomputable def nonuniform_witness (ε : 𝕜) (s t : finset α) : finset α := if well_ordering_rel s t then (G.nonuniform_witnesses ε s t).1 else (G.nonuniform_witnesses ε t s).2 lemma nonuniform_witness_subset (h : ¬ G.is_uniform ε s t) : G.nonuniform_witness ε s t ⊆ s := begin unfold nonuniform_witness, split_ifs, { exact G.left_nonuniform_witnesses_subset h }, { exact G.right_nonuniform_witnesses_subset (λ i, h i.symm) } end lemma le_card_nonuniform_witness (h : ¬ G.is_uniform ε s t) : (s.card : 𝕜) * ε ≤ (G.nonuniform_witness ε s t).card := begin unfold nonuniform_witness, split_ifs, { exact G.left_nonuniform_witnesses_card h }, { exact G.right_nonuniform_witnesses_card (λ i, h i.symm) } end lemma nonuniform_witness_spec (h₁ : s ≠ t) (h₂ : ¬ G.is_uniform ε s t) : ε ≤ |G.edge_density (G.nonuniform_witness ε s t) (G.nonuniform_witness ε t s) - G.edge_density s t| := begin unfold nonuniform_witness, rcases trichotomous_of well_ordering_rel s t with lt | rfl | gt, { rw [if_pos lt, if_neg (asymm lt)], exact G.nonuniform_witnesses_spec h₂ }, { cases h₁ rfl }, { rw [if_neg (asymm gt), if_pos gt, edge_density_comm, edge_density_comm _ s], apply G.nonuniform_witnesses_spec (λ i, h₂ i.symm) } end end simple_graph /-! ### Uniform partitions -/ variables [decidable_eq α] {A : finset α} (P : finpartition A) (G : simple_graph α) [decidable_rel G.adj] {ε : 𝕜} namespace finpartition open_locale classical /-- The pairs of parts of a partition `P` which are not `ε`-uniform in a graph `G`. Note that we dismiss the diagonal. We do not care whether `s` is `ε`-uniform with itself. -/ noncomputable def non_uniforms (ε : 𝕜) : finset (finset α × finset α) := P.parts.off_diag.filter $ λ uv, ¬G.is_uniform ε uv.1 uv.2 lemma mk_mem_non_uniforms_iff (u v : finset α) (ε : 𝕜) : (u, v) ∈ P.non_uniforms G ε ↔ u ∈ P.parts ∧ v ∈ P.parts ∧ u ≠ v ∧ ¬G.is_uniform ε u v := by rw [non_uniforms, mem_filter, mem_off_diag, and_assoc, and_assoc] lemma non_uniforms_mono {ε ε' : 𝕜} (h : ε ≤ ε') : P.non_uniforms G ε' ⊆ P.non_uniforms G ε := monotone_filter_right _ $ λ uv, mt $ simple_graph.is_uniform.mono h lemma non_uniforms_bot (hε : 0 < ε) : (⊥ : finpartition A).non_uniforms G ε = ∅ := begin rw eq_empty_iff_forall_not_mem, rintro ⟨u, v⟩, simp only [finpartition.mk_mem_non_uniforms_iff, finpartition.parts_bot, mem_map, not_and, not_not, exists_imp_distrib], rintro x hx rfl y hy rfl h, exact G.is_uniform_singleton hε, end /-- A finpartition of a graph's vertex set is `ε`-uniform (aka `ε`-regular) iff the proportion of its pairs of parts that are not `ε`-uniform is at most `ε`. -/ def is_uniform (ε : 𝕜) : Prop := ((P.non_uniforms G ε).card : 𝕜) ≤ (P.parts.card * (P.parts.card - 1) : ℕ) * ε lemma bot_is_uniform (hε : 0 < ε) : (⊥ : finpartition A).is_uniform G ε := begin rw [finpartition.is_uniform, finpartition.card_bot, non_uniforms_bot _ hε, finset.card_empty, nat.cast_zero], exact mul_nonneg (nat.cast_nonneg _) hε.le, end lemma is_uniform_one : P.is_uniform G (1 : 𝕜) := begin rw [is_uniform, mul_one, nat.cast_le], refine (card_filter_le _ _).trans _, rw [off_diag_card, nat.mul_sub_left_distrib, mul_one], end variables {P G} lemma is_uniform.mono {ε ε' : 𝕜} (hP : P.is_uniform G ε) (h : ε ≤ ε') : P.is_uniform G ε' := ((nat.cast_le.2 $ card_le_of_subset $ P.non_uniforms_mono G h).trans hP).trans $ mul_le_mul_of_nonneg_left h $ nat.cast_nonneg _ lemma is_uniform_of_empty (hP : P.parts = ∅) : P.is_uniform G ε := by simp [is_uniform, hP, non_uniforms] lemma nonempty_of_not_uniform (h : ¬ P.is_uniform G ε) : P.parts.nonempty := nonempty_of_ne_empty $ λ h₁, h $ is_uniform_of_empty h₁ variables (P G ε) (s : finset α) /-- A choice of witnesses of non-uniformity among the parts of a finpartition. -/ noncomputable def nonuniform_witnesses : finset (finset α) := (P.parts.filter $ λ t, s ≠ t ∧ ¬ G.is_uniform ε s t).image (G.nonuniform_witness ε s) variables {P G ε s} {t : finset α} lemma nonuniform_witness_mem_nonuniform_witnesses (h : ¬ G.is_uniform ε s t) (ht : t ∈ P.parts) (hst : s ≠ t) : G.nonuniform_witness ε s t ∈ P.nonuniform_witnesses G ε s := mem_image_of_mem _ $ mem_filter.2 ⟨ht, hst, h⟩ end finpartition
b37e44a765b87846f2121d1fa771b2c24f079e11
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Data/Trie.lean
0d89ac588196dd9cb77c19f6a9e4688baf2a532c
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,924
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura Trie for tokenizing the Lean language -/ import Lean.Data.Format namespace Lean namespace Parser open Std (RBNode RBNode.leaf RBNode.singleton RBNode.find RBNode.insert) inductive Trie (α : Type) | Node : Option α → RBNode Char (fun _ => Trie) → Trie namespace Trie variables {α : Type} def empty : Trie α := ⟨none, RBNode.leaf⟩ instance : HasEmptyc (Trie α) := ⟨empty⟩ instance : Inhabited (Trie α) := ⟨Node none RBNode.leaf⟩ private partial def insertEmptyAux (s : String) (val : α) : String.Pos → Trie α | i => match s.atEnd i with | true => Trie.Node (some val) RBNode.leaf | false => let c := s.get i; let t := insertEmptyAux (s.next i); Trie.Node none (RBNode.singleton c t) private partial def insertAux (s : String) (val : α) : Trie α → String.Pos → Trie α | Trie.Node v m, i => match s.atEnd i with | true => Trie.Node (some val) m -- overrides old value | false => let c := s.get i; let i := s.next i; let t := match RBNode.find Char.lt m c with | none => insertEmptyAux s val i | some t => insertAux t i; Trie.Node v (RBNode.insert Char.lt m c t) def insert (t : Trie α) (s : String) (val : α) : Trie α := insertAux s val t 0 private partial def findAux? (s : String) : Trie α → String.Pos → Option α | Trie.Node val m, i => match s.atEnd i with | true => val | false => let c := s.get i; let i := s.next i; match RBNode.find Char.lt m c with | none => none | some t => findAux? t i def find? (t : Trie α) (s : String) : Option α := findAux? s t 0 private def updtAcc (v : Option α) (i : String.Pos) (acc : String.Pos × Option α) : String.Pos × Option α := match v, acc with | some v, (j, w) => (i, some v) -- we pattern match on `acc` to enable memory reuse | none, acc => acc private partial def matchPrefixAux (s : String) : Trie α → String.Pos → (String.Pos × Option α) → String.Pos × Option α | Trie.Node v m, i, acc => match s.atEnd i with | true => updtAcc v i acc | false => let acc := updtAcc v i acc; let c := s.get i; let i := s.next i; match RBNode.find Char.lt m c with | some t => matchPrefixAux t i acc | none => acc def matchPrefix (s : String) (t : Trie α) (i : String.Pos) : String.Pos × Option α := matchPrefixAux s t i (i, none) private partial def toStringAux {α : Type} : Trie α → List Format | Trie.Node val map => map.fold (fun Fs c t => format (repr c) :: (Format.group $ Format.nest 2 $ flip Format.joinSep Format.line $ toStringAux t) :: Fs) [] instance {α : Type} : HasToString (Trie α) := ⟨fun t => (flip Format.joinSep Format.line $ toStringAux t).pretty⟩ end Trie end Parser end Lean
8e648a8baebad55792ce250a7d4d8312500d897a
da3a76c514d38801bae19e8a9e496dc31f8e5866
/library/tools/super/clause.lean
92341dda6500f55fbfb31cc113cda25d5a34d9d0
[ "Apache-2.0" ]
permissive
cipher1024/lean
270c1ac5781e6aee12f5c8d720d267563a164beb
f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a
refs/heads/master
1,611,223,459,029
1,487,566,573,000
1,487,566,573,000
83,356,543
0
0
null
1,488,229,336,000
1,488,229,336,000
null
UTF-8
Lean
false
false
8,743
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import init.meta.tactic .utils .trim open expr list tactic monad decidable namespace super meta def is_local_not (local_false : expr) (e : expr) : option expr := match e with | (pi _ _ a b) := if b = local_false then some a else none | _ := if local_false = false_ then is_not e else none end meta structure clause := (num_quants : ℕ) (num_lits : ℕ) (proof : expr) (type : expr) (local_false : expr) namespace clause meta def num_binders (c : clause) : ℕ := num_quants c + num_lits c meta def inst (c : clause) (e : expr) : clause := (if num_quants c > 0 then mk (num_quants c - 1) (num_lits c) else mk 0 (num_lits c - 1)) (app (proof c) e) (instantiate_var (binding_body (type c)) e) c^.local_false meta def instn (c : clause) (es : list expr) : clause := foldr (λe c', inst c' e) c es meta def open_const (c : clause) : tactic (clause × expr) := do n ← mk_fresh_name, b ← return $ local_const n (binding_name (type c)) (binding_info (type c)) (binding_domain (type c)), return (inst c b, b) meta def open_meta (c : clause) : tactic (clause × expr) := do b ← mk_meta_var (binding_domain (type c)), return (inst c b, b) meta def close_const (c : clause) (e : expr) : clause := match e with | local_const uniq pp info t := let abst_type' := abstract_local (type c) (local_uniq_name e) in let type' := pi pp binder_info.default t (abstract_local (type c) uniq) in let abs_prf := abstract_local (proof c) uniq in let proof' := lambdas [e] c^.proof in if num_quants c > 0 ∨ has_var abst_type' then { c with num_quants := c^.num_quants + 1, proof := proof', type := type' } else { c with num_lits := c^.num_lits + 1, proof := proof', type := type' } | _ := ⟨0, 0, default expr, default expr, default expr⟩ end meta def open_constn : clause → ℕ → tactic (clause × list expr) | c 0 := return (c, nil) | c (n+1) := do (c', b) ← open_const c, (c'', bs) ← open_constn c' n, return (c'', b::bs) meta def open_metan : clause → ℕ → tactic (clause × list expr) | c 0 := return (c, nil) | c (n+1) := do (c', b) ← open_meta c, (c'', bs) ← open_metan c' n, return (c'', b::bs) meta def close_constn : clause → list expr → clause | c [] := c | c (b::bs') := close_const (close_constn c bs') b set_option eqn_compiler.max_steps 500 private meta def parse_clause (local_false : expr) : expr → expr → tactic clause | proof (pi n bi d b) := do lc_n ← mk_fresh_name, lc ← return $ local_const lc_n n bi d, c ← parse_clause (app proof lc) (instantiate_var b lc), return $ c^.close_const $ local_const lc_n n binder_info.default d | proof (app (const ``not []) formula) := parse_clause proof (formula^.imp false_) | proof type := if type = local_false then do return { num_quants := 0, num_lits := 0, proof := proof, type := type, local_false := local_false } else do univ ← infer_univ type, not_type ← return $ imp type local_false, parse_clause (lam `H binder_info.default not_type $ app (mk_var 0) proof) (imp not_type local_false) meta def of_proof_and_type (local_false proof type : expr) : tactic clause := parse_clause local_false proof type meta def of_proof (local_false proof : expr) : tactic clause := do type ← infer_type proof, of_proof_and_type local_false proof type meta def of_classical_proof (proof : expr) : tactic clause := of_proof false_ proof meta def inst_mvars (c : clause) : tactic clause := do proof' ← instantiate_mvars (proof c), type' ← instantiate_mvars (type c), return { c with proof := proof', type := type' } meta inductive literal | left : expr → literal | right : expr → literal namespace literal meta instance : decidable_eq literal := by mk_dec_eq_instance meta def formula : literal → expr | (left f) := f | (right f) := f meta def is_neg : literal → bool | (left _) := tt | (right _) := ff meta def is_pos (l : literal) : bool := bnot l^.is_neg meta def to_formula (l : literal) : expr := if l^.is_neg then app (const ``not []) l^.formula else formula l meta def type_str : literal → string | (literal.left _) := "left" | (literal.right _) := "right" meta instance : has_to_tactic_format literal := ⟨λl, do pp_f ← pp l^.formula, return $ to_fmt l^.type_str ++ " (" ++ pp_f ++ ")"⟩ end literal private meta def get_binding_body : expr → ℕ → expr | e 0 := e | e (i+1) := get_binding_body e^.binding_body i meta def get_binder (e : expr) (i : nat) := binding_domain (get_binding_body e i) meta def validate (c : clause) : tactic unit := do concl ← return $ get_binding_body c^.type c^.num_binders, unify concl c^.local_false <|> (do pp_concl ← pp concl, pp_lf ← pp c^.local_false, fail $ to_fmt "wrong local false: " ++ pp_concl ++ " =!= " ++ pp_lf), type' ← infer_type c^.proof, unify c^.type type' <|> (do pp_ty ← pp c^.type, pp_ty' ← pp type', fail (to_fmt "wrong type: " ++ pp_ty ++ " =!= " ++ pp_ty')) meta def get_lit (c : clause) (i : nat) : literal := let bind := get_binder (type c) (num_quants c + i) in match is_local_not c^.local_false bind with | some formula := literal.right formula | none := literal.left bind end meta def lits_where (c : clause) (p : literal → bool) : list nat := list.filter (λl, p (get_lit c l)) (range (num_lits c)) meta def get_lits (c : clause) : list literal := list.map (get_lit c) (range c^.num_lits) private meta def tactic_format (c : clause) : tactic format := do c ← c^.open_metan c^.num_quants, pp (do l ← c.1^.get_lits, [l^.to_formula]) meta instance : has_to_tactic_format clause := ⟨tactic_format⟩ meta def is_maximal (gt : expr → expr → bool) (c : clause) (i : nat) : bool := list.empty (list.filter (λj, gt (get_lit c j)^.formula (get_lit c i)^.formula) (range c^.num_lits)) meta def normalize (c : clause) : tactic clause := do opened ← open_constn c (num_binders c), lconsts_in_types ← return $ contained_lconsts_list (list.map local_type opened.2), quants' ← return $ list.filter (λlc, rb_map.contains lconsts_in_types (local_uniq_name lc)) opened.2, lits' ← return $ list.filter (λlc, ¬rb_map.contains lconsts_in_types (local_uniq_name lc)) opened.2, return $ close_constn opened.1 (quants' ++ lits') meta def whnf_head_lit (c : clause) : tactic clause := do atom' ← whnf $ literal.formula $ get_lit c 0, return $ if literal.is_neg (get_lit c 0) then { c with type := imp atom' (binding_body c^.type) } else { c with type := imp (app (const ``not []) atom') c^.type^.binding_body } end clause meta def unify_lit (l1 l2 : clause.literal) : tactic unit := if clause.literal.is_pos l1 = clause.literal.is_pos l2 then unify (clause.literal.formula l1) (clause.literal.formula l2) transparency.none else fail "cannot unify literals" -- FIXME: this is most definitely broken with meta-variables that were already in the goal meta def sort_and_constify_metas : list expr → tactic (list expr) | exprs_with_metas := do inst_exprs ← mapm instantiate_mvars exprs_with_metas, metas ← return $ inst_exprs >>= get_metas, match list.filter (λm, ¬has_meta_var (get_meta_type m)) metas with | [] := if metas^.empty then return [] else do for' metas (λm, do trace (expr.to_string m), t ← infer_type m, trace (expr.to_string t)), fail "could not sort metas" | ((mvar n t) :: _) := do c ← infer_type (mvar n t) >>= mk_local_def `x, unify c (mvar n t), rest ← sort_and_constify_metas metas, c ← instantiate_mvars c, return ([c] ++ rest) | _ := failed end namespace clause meta def meta_closure (metas : list expr) (qf : clause) : tactic clause := do bs ← sort_and_constify_metas metas, qf' ← clause.inst_mvars qf, clause.inst_mvars $ clause.close_constn qf' bs private meta def distinct' (local_false : expr) : list expr → expr → clause | [] proof := ⟨ 0, 0, proof, local_false, local_false ⟩ | (h::hs) proof := let (dups, rest) := partition (λh' : expr, h^.local_type = h'^.local_type) hs, proof_wo_dups := foldl (λproof (h' : expr), instantiate_var (abstract_local proof h'^.local_uniq_name) h) proof dups in (distinct' rest proof_wo_dups)^.close_const h meta def distinct (c : clause) : tactic clause := do (qf, vs) ← c^.open_constn c^.num_quants, (fls, hs) ← qf^.open_constn qf^.num_lits, return $ (distinct' c^.local_false hs fls^.proof)^.close_constn vs end clause end super
80122559efdaf6b0da25013d376aac297ca34092
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_pattern_inference_bug.lean
af308c0ef14420e7d39350c793de6aaa1a8cd584
[ "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
202
lean
constant p : nat → Prop constant q : ∀ a, p a → Prop lemma ex [forward] : ∀ (a : nat) (h : p a), (:q a h:) := sorry set_option blast.strategy "ematch" lemma test (h : p 0) : q 0 h := by blast
ce7caa78313118e134e4560acb029beccb2680ee
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/free_module/finite/basic.lean
eb8a3f782eae81900a94783ccd21a2bc5d70bd38
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,978
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.free_module.basic import linear_algebra.matrix.to_lin import ring_theory.finiteness /-! # Finite and free modules We provide some instances for finite and free modules. ## Main results * `module.free.choose_basis_index.fintype` : If a free module is finite, then any basis is finite. * `module.free.linear_map.free ` : if `M` and `N` are finite and free, then `M →ₗ[R] N` is free. * `module.finite.of_basis` : A free module with a basis indexed by a `fintype` is finite. * `module.free.linear_map.module.finite` : if `M` and `N` are finite and free, then `M →ₗ[R] N` is finite. -/ universes u v w variables (R : Type u) (M : Type v) (N : Type w) namespace module.free section ring variables [ring R] [add_comm_group M] [module R M] [module.free R M] /-- If a free module is finite, then any basis is finite. -/ noncomputable instance [nontrivial R] [module.finite R M] : fintype (module.free.choose_basis_index R M) := begin obtain ⟨h⟩ := id ‹module.finite R M›, choose s hs using h, exact basis_fintype_of_finite_spans ↑s hs (choose_basis _ _), end end ring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] [module.free R M] variables [add_comm_group N] [module R N] [module.free R N] instance [nontrivial R] [module.finite R M] [module.finite R N] : module.free R (M →ₗ[R] N) := begin classical, exact of_equiv (linear_map.to_matrix (module.free.choose_basis R M) (module.free.choose_basis R N)).symm, end variables {R M} /-- A free module with a basis indexed by a `fintype` is finite. -/ lemma _root_.module.finite.of_basis {R : Type*} {M : Type*} {ι : Type*} [comm_ring R] [add_comm_group M] [module R M] [fintype ι] (b : basis ι R M) : module.finite R M := begin classical, refine ⟨⟨finset.univ.image b, _⟩⟩, simp only [set.image_univ, finset.coe_univ, finset.coe_image, basis.span_eq], end instance _root_.module.finite.matrix {ι₁ : Type*} [fintype ι₁] {ι₂ : Type*} [fintype ι₂] : module.finite R (matrix ι₁ ι₂ R) := module.finite.of_basis $ pi.basis $ λ i, pi.basis_fun R _ instance [nontrivial R] [module.finite R M] [module.finite R N] : module.finite R (M →ₗ[R] N) := begin classical, have f := (linear_map.to_matrix (choose_basis R M) (choose_basis R N)).symm, exact module.finite.of_surjective f.to_linear_map (linear_equiv.surjective f), end end comm_ring section integer variables [add_comm_group M] [module.finite ℤ M] [module.free ℤ M] variables [add_comm_group N] [module.finite ℤ N] [module.free ℤ N] instance : module.finite ℤ (M →+ N) := module.finite.equiv (add_monoid_hom_lequiv_int ℤ).symm instance : module.free ℤ (M →+ N) := module.free.of_equiv (add_monoid_hom_lequiv_int ℤ).symm end integer end module.free
d6b13fffef682d447dcc188ad496bec6381b3612
5c4a0908390c4938ae21bc616ff2a969ce62fd76
/library/theories/analysis/real_limit.lean
323e0c3279febfcf72ada683453553604810712c
[ "Apache-2.0" ]
permissive
Bpalkmim/lean
968be8a73a06fa6db19073cd463d2093464dc0f6
994815bc7793f5765beb693c82341cf01d20d807
refs/heads/master
1,610,964,748,106
1,455,564,675,000
1,455,564,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,511
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis Instantiates the reals as a Banach space. -/ import .metric_space data.real.complete data.set .normed_space open real classical analysis nat noncomputable theory /- sup and inf -/ -- Expresses completeness, sup, and inf in a manner that is less constructive, but more convenient, -- than the way it is done in data.real.complete. -- Issue: real.sup and real.inf conflict with sup and inf in lattice. -- Perhaps put algebra sup and inf into a namespace? namespace real open set private definition exists_is_sup {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) : ∃ y, is_sup X y := let x := some (and.left H), b := some (and.right H) in exists_is_sup_of_inh_of_bdd X x (some_spec (and.left H)) b (some_spec (and.right H)) private definition sup_aux {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) := some (exists_is_sup H) private definition sup_aux_spec {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) : is_sup X (sup_aux H) := some_spec (exists_is_sup H) definition sup (X : set ℝ) : ℝ := if H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b) then sup_aux H else 0 proposition le_sup {x : ℝ} {X : set ℝ} (Hx : x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : x ≤ sup X := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b), from and.intro (exists.intro x Hx) (exists.intro b Hb), by+ rewrite [↑sup, dif_pos H]; exact and.left (sup_aux_spec H) x Hx proposition sup_le {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : sup X ≤ b := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b), from and.intro HX (exists.intro b Hb), by+ rewrite [↑sup, dif_pos H]; exact and.right (sup_aux_spec H) b Hb proposition exists_mem_and_lt_of_lt_sup {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : b < sup X) : ∃ x, x ∈ X ∧ b < x := have ¬ ∀ x, x ∈ X → x ≤ b, from assume H, not_le_of_gt Hb (sup_le HX H), obtain x (Hx : ¬ (x ∈ X → x ≤ b)), from exists_not_of_not_forall this, exists.intro x (have x ∈ X ∧ ¬ x ≤ b, by rewrite [-not_implies_iff_and_not]; apply Hx, and.intro (and.left this) (lt_of_not_ge (and.right this))) private definition exists_is_inf {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) : ∃ y, is_inf X y := let x := some (and.left H), b := some (and.right H) in exists_is_inf_of_inh_of_bdd X x (some_spec (and.left H)) b (some_spec (and.right H)) private definition inf_aux {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) := some (exists_is_inf H) private definition inf_aux_spec {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) : is_inf X (inf_aux H) := some_spec (exists_is_inf H) definition inf (X : set ℝ) : ℝ := if H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x) then inf_aux H else 0 proposition inf_le {x : ℝ} {X : set ℝ} (Hx : x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : inf X ≤ x := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x), from and.intro (exists.intro x Hx) (exists.intro b Hb), by+ rewrite [↑inf, dif_pos H]; exact and.left (inf_aux_spec H) x Hx proposition le_inf {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : b ≤ inf X := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x), from and.intro HX (exists.intro b Hb), by+ rewrite [↑inf, dif_pos H]; exact and.right (inf_aux_spec H) b Hb proposition exists_mem_and_lt_of_inf_lt {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : inf X < b) : ∃ x, x ∈ X ∧ x < b := have ¬ ∀ x, x ∈ X → b ≤ x, from assume H, not_le_of_gt Hb (le_inf HX H), obtain x (Hx : ¬ (x ∈ X → b ≤ x)), from exists_not_of_not_forall this, exists.intro x (have x ∈ X ∧ ¬ b ≤ x, by rewrite [-not_implies_iff_and_not]; apply Hx, and.intro (and.left this) (lt_of_not_ge (and.right this))) section local attribute mem [quasireducible] -- TODO: is there a better place to put this? proposition image_neg_eq (X : set ℝ) : (λ x, -x) ' X = {x | -x ∈ X} := set.ext (take x, iff.intro (assume H, obtain y [(Hy₁ : y ∈ X) (Hy₂ : -y = x)], from H, show -x ∈ X, by rewrite [-Hy₂, neg_neg]; exact Hy₁) (assume H : -x ∈ X, exists.intro (-x) (and.intro H !neg_neg))) proposition sup_neg {X : set ℝ} (nonempty_X : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : sup {x | -x ∈ X} = - inf X := let negX := {x | -x ∈ X} in have nonempty_negX : ∃ x, x ∈ negX, from obtain x Hx, from nonempty_X, have -(-x) ∈ X, by rewrite neg_neg; apply Hx, exists.intro (-x) this, have H₁ : ∀ x, x ∈ negX → x ≤ - inf X, from take x, assume H, have inf X ≤ -x, from inf_le H Hb, show x ≤ - inf X, from le_neg_of_le_neg this, have H₂ : ∀ x, x ∈ X → -sup negX ≤ x, from take x, assume H, have -(-x) ∈ X, by rewrite neg_neg; apply H, have -x ≤ sup negX, from le_sup this H₁, show -sup negX ≤ x, from !neg_le_of_neg_le this, eq_of_le_of_ge (show sup negX ≤ - inf X, from sup_le nonempty_negX H₁) (show -inf X ≤ sup negX, from !neg_le_of_neg_le (le_inf nonempty_X H₂)) proposition inf_neg {X : set ℝ} (nonempty_X : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : inf {x | -x ∈ X} = - sup X := let negX := {x | -x ∈ X} in have nonempty_negX : ∃ x, x ∈ negX, from obtain x Hx, from nonempty_X, have -(-x) ∈ X, by rewrite neg_neg; apply Hx, exists.intro (-x) this, have Hb' : ∀ x, x ∈ negX → -b ≤ x, from take x, assume H, !neg_le_of_neg_le (Hb _ H), have HX : X = {x | -x ∈ negX}, from set.ext (take x, by rewrite [↑set_of, ↑mem, +neg_neg]), show inf {x | -x ∈ X} = - sup X, using HX Hb' nonempty_negX, by rewrite [HX at {2}, sup_neg nonempty_negX Hb', neg_neg] end end real /- the reals form a complete metric space -/ namespace analysis theorem dist_eq_abs (x y : real) : dist x y = abs (x - y) := rfl proposition converges_to_seq_real_intro {X : ℕ → ℝ} {y : ℝ} (H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) < ε) : (X ⟶ y in ℕ) := H proposition converges_to_seq_real_elim {X : ℕ → ℝ} {y : ℝ} (H : X ⟶ y in ℕ) : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) < ε := H proposition converges_to_seq_real_intro' {X : ℕ → ℝ} {y : ℝ} (H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) ≤ ε) : converges_to_seq X y := converges_to_seq.intro H open pnat subtype local postfix ⁻¹ := pnat.inv private definition pnat.succ (n : ℕ) : ℕ+ := tag (succ n) !succ_pos private definition r_seq_of (X : ℕ → ℝ) : r_seq := λ n, X (elt_of n) private lemma rate_of_cauchy_aux {X : ℕ → ℝ} (H : cauchy X) : ∀ k : ℕ+, ∃ N : ℕ+, ∀ m n : ℕ+, m ≥ N → n ≥ N → abs (X (elt_of m) - X (elt_of n)) ≤ of_rat k⁻¹ := take k : ℕ+, have H1 : (k⁻¹ >[rat] (rat.of_num 0)), from !pnat.inv_pos, have H2 : (of_rat k⁻¹ > of_rat (rat.of_num 0)), from !of_rat_lt_of_rat_of_lt H1, obtain (N : ℕ) (H : ∀ m n, m ≥ N → n ≥ N → abs (X m - X n) < of_rat k⁻¹), from H _ H2, exists.intro (pnat.succ N) (take m n : ℕ+, assume Hm : m ≥ (pnat.succ N), assume Hn : n ≥ (pnat.succ N), have Hm' : elt_of m ≥ N, begin apply le.trans, apply le_succ, apply Hm end, have Hn' : elt_of n ≥ N, begin apply le.trans, apply le_succ, apply Hn end, show abs (X (elt_of m) - X (elt_of n)) ≤ of_rat k⁻¹, from le_of_lt (H _ _ Hm' Hn')) private definition rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) (k : ℕ+) : ℕ+ := some (rate_of_cauchy_aux H k) private lemma cauchy_with_rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : cauchy_with_rate (r_seq_of X) (rate_of_cauchy H) := take k : ℕ+, some_spec (rate_of_cauchy_aux H k) private lemma converges_to_with_rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : ∃ l Nb, converges_to_with_rate (r_seq_of X) l Nb := begin apply exists.intro, apply exists.intro, apply converges_to_with_rate_of_cauchy_with_rate, exact cauchy_with_rate_of_cauchy H end theorem converges_seq_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : converges_seq X := obtain l Nb (conv : converges_to_with_rate (r_seq_of X) l Nb), from converges_to_with_rate_of_cauchy H, exists.intro l (take ε : ℝ, suppose ε > 0, obtain (k' : ℕ) (Hn : 1 / succ k' < ε), from archimedean_small `ε > 0`, let k : ℕ+ := tag (succ k') !succ_pos, N : ℕ+ := Nb k in have Hk : real.of_rat k⁻¹ < ε, by rewrite [↑pnat.inv, of_rat_divide]; exact Hn, exists.intro (elt_of N) (take n : ℕ, assume Hn : n ≥ elt_of N, let n' : ℕ+ := tag n (nat.lt_of_lt_of_le (has_property N) Hn) in have abs (X n - l) ≤ real.of_rat k⁻¹, by apply conv k n' Hn, show abs (X n - l) < ε, from lt_of_le_of_lt this Hk)) end analysis definition complete_metric_space_real [reducible] [trans_instance] : complete_metric_space ℝ := ⦃complete_metric_space, metric_space_real, complete := @analysis.converges_seq_of_cauchy ⦄ /- the real numbers can be viewed as a banach space -/ definition real_vector_space_real : real_vector_space ℝ := ⦃ real_vector_space, real.discrete_linear_ordered_field, smul := mul, smul_left_distrib := left_distrib, smul_right_distrib := right_distrib, mul_smul := mul.assoc, one_smul := one_mul ⦄ definition banach_space_real [trans_instance] [reducible] : banach_space ℝ := ⦃ banach_space, real_vector_space_real, norm := abs, norm_zero := abs_zero, eq_zero_of_norm_eq_zero := λ a H, eq_zero_of_abs_eq_zero H, norm_triangle := abs_add_le_abs_add_abs, norm_smul := abs_mul, complete := λ X H, analysis.complete ℝ H ⦄ /- limits under pointwise operations -/ section limit_operations variables {X Y : ℕ → ℝ} variables {x y : ℝ} proposition mul_left_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) : (λ n, c * X n) ⟶ c * x in ℕ := smul_converges_to_seq c HX proposition mul_right_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) : (λ n, X n * c) ⟶ x * c in ℕ := have (λ n, X n * c) = (λ n, c * X n), from funext (take x, !mul.comm), by+ rewrite [this, mul.comm]; apply mul_left_converges_to_seq c HX theorem converges_to_seq_squeeze (HX : X ⟶ x in ℕ) (HY : Y ⟶ x in ℕ) {Z : ℕ → ℝ} (HZX : ∀ n, X n ≤ Z n) (HZY : ∀ n, Z n ≤ Y n) : Z ⟶ x in ℕ := begin intros ε Hε, have Hε4 : ε / 4 > 0, from div_pos_of_pos_of_pos Hε four_pos, cases HX Hε4 with N1 HN1, cases HY Hε4 with N2 HN2, existsi max N1 N2, intro n Hn, have HXY : abs (Y n - X n) < ε / 2, begin apply lt_of_le_of_lt, apply abs_sub_le _ x, have Hε24 : ε / 2 = ε / 4 + ε / 4, from eq.symm !add_quarters, rewrite Hε24, apply add_lt_add, apply HN2, apply ge.trans Hn !le_max_right, rewrite abs_sub, apply HN1, apply ge.trans Hn !le_max_left end, have HZX : abs (Z n - X n) < ε / 2, begin have HZXnp : Z n - X n ≥ 0, from sub_nonneg_of_le !HZX, have HXYnp : Y n - X n ≥ 0, from sub_nonneg_of_le (le.trans !HZX !HZY), rewrite [abs_of_nonneg HZXnp, abs_of_nonneg HXYnp at HXY], note Hgt := lt_add_of_sub_lt_right HXY, have Hlt : Z n < ε / 2 + X n, from calc Z n ≤ Y n : HZY ... < ε / 2 + X n : Hgt, apply sub_lt_right_of_lt_add Hlt end, have H : abs (Z n - x) < ε, begin apply lt_of_le_of_lt, apply abs_sub_le _ (X n), apply lt.trans, apply add_lt_add, apply HZX, apply HN1, apply ge.trans Hn !le_max_left, apply div_two_add_div_four_lt Hε end, exact H end proposition converges_to_seq_of_abs_sub_converges_to_seq (Habs : (λ n, abs (X n - x)) ⟶ 0 in ℕ) : X ⟶ x in ℕ := begin intros ε Hε, cases Habs Hε with N HN, existsi N, intro n Hn, have Hn' : abs (abs (X n - x) - 0) < ε, from HN Hn, rewrite [sub_zero at Hn', abs_abs at Hn'], exact Hn' end proposition abs_sub_converges_to_seq_of_converges_to_seq (HX : X ⟶ x in ℕ) : (λ n, abs (X n - x)) ⟶ 0 in ℕ := begin intros ε Hε, cases HX Hε with N HN, existsi N, intro n Hn, have Hn' : abs (abs (X n - x) - 0) < ε, by rewrite [sub_zero, abs_abs]; apply HN Hn, exact Hn' end proposition mul_converges_to_seq (HX : X ⟶ x in ℕ) (HY : Y ⟶ y in ℕ) : (λ n, X n * Y n) ⟶ x * y in ℕ := have Hbd : ∃ K : ℝ, ∀ n : ℕ, abs (X n) ≤ K, begin cases bounded_of_converges_seq HX with K HK, existsi K + abs x, intro n, note Habs := le.trans (abs_abs_sub_abs_le_abs_sub (X n) x) !HK, apply le_add_of_sub_right_le, apply le.trans, apply le_abs_self, assumption end, obtain K HK, from Hbd, have Habsle [visible] : ∀ n, abs (X n * Y n - x * y) ≤ K * abs (Y n - y) + abs y * abs (X n - x), begin intro, have Heq : X n * Y n - x * y = (X n * Y n - X n * y) + (X n * y - x * y), by rewrite [-sub_add_cancel (X n * Y n) (X n * y) at {1}, sub_eq_add_neg, *add.assoc], apply le.trans, rewrite Heq, apply abs_add_le_abs_add_abs, apply add_le_add, rewrite [-mul_sub_left_distrib, abs_mul], apply mul_le_mul_of_nonneg_right, apply HK, apply abs_nonneg, rewrite [-mul_sub_right_distrib, abs_mul, mul.comm], apply le.refl end, have Hdifflim [visible] : (λ n, abs (X n * Y n - x * y)) ⟶ 0 in ℕ, begin apply converges_to_seq_squeeze, rotate 2, intro, apply abs_nonneg, apply Habsle, apply converges_to_seq_constant, rewrite -{0}zero_add, apply add_converges_to_seq, krewrite -(mul_zero K), apply mul_left_converges_to_seq, apply abs_sub_converges_to_seq_of_converges_to_seq, exact HY, krewrite -(mul_zero (abs y)), apply mul_left_converges_to_seq, apply abs_sub_converges_to_seq_of_converges_to_seq, exact HX end, converges_to_seq_of_abs_sub_converges_to_seq Hdifflim -- TODO: converges_to_seq_div, converges_to_seq_mul_left_iff, etc. proposition abs_converges_to_seq_zero (HX : X ⟶ 0 in ℕ) : (λ n, abs (X n)) ⟶ 0 in ℕ := norm_converges_to_seq_zero HX proposition converges_to_seq_zero_of_abs_converges_to_seq_zero (HX : (λ n, abs (X n)) ⟶ 0 in ℕ) : X ⟶ 0 in ℕ := converges_to_seq_zero_of_norm_converges_to_seq_zero HX proposition abs_converges_to_seq_zero_iff (X : ℕ → ℝ) : ((λ n, abs (X n)) ⟶ 0 in ℕ) ↔ (X ⟶ 0 in ℕ) := iff.intro converges_to_seq_zero_of_abs_converges_to_seq_zero abs_converges_to_seq_zero -- TODO: products of two sequences, converges_seq, limit_seq end limit_operations /- properties of converges_to_at -/ section limit_operations_continuous variables {f g : ℝ → ℝ} variables {a b x y : ℝ} theorem mul_converges_to_at (Hf : f ⟶ a at x) (Hg : g ⟶ b at x) : (λ z, f z * g z) ⟶ a * b at x := begin apply converges_to_at_of_all_conv_seqs, intro X HX, apply mul_converges_to_seq, note Hfc := all_conv_seqs_of_converges_to_at Hf, apply Hfc _ HX, note Hgb := all_conv_seqs_of_converges_to_at Hg, apply Hgb _ HX end end limit_operations_continuous /- monotone sequences -/ section monotone_sequences open real set variable {X : ℕ → ℝ} definition nondecreasing (X : ℕ → ℝ) : Prop := ∀ ⦃i j⦄, i ≤ j → X i ≤ X j proposition nondecreasing_of_forall_le_succ (H : ∀ i, X i ≤ X (succ i)) : nondecreasing X := take i j, suppose i ≤ j, have ∀ n, X i ≤ X (i + n), from take n, nat.induction_on n (by rewrite nat.add_zero; apply le.refl) (take n, assume ih, le.trans ih (H (i + n))), have X i ≤ X (i + (j - i)), from !this, by+ rewrite [add_sub_of_le `i ≤ j` at this]; exact this proposition converges_to_seq_sup_of_nondecreasing (nondecX : nondecreasing X) {b : ℝ} (Hb : ∀ i, X i ≤ b) : X ⟶ sup (X ' univ) in ℕ := let sX := sup (X ' univ) in have Xle : ∀ i, X i ≤ sX, from take i, have ∀ x, x ∈ X ' univ → x ≤ b, from (take x, assume H, obtain i [H' (Hi : X i = x)], from H, by rewrite -Hi; exact Hb i), show X i ≤ sX, from le_sup (mem_image_of_mem X !mem_univ) this, have exX : ∃ x, x ∈ X ' univ, from exists.intro (X 0) (mem_image_of_mem X !mem_univ), take ε, assume epos : ε > 0, have sX - ε < sX, from !sub_lt_of_pos epos, obtain x' [(H₁x' : x' ∈ X ' univ) (H₂x' : sX - ε < x')], from exists_mem_and_lt_of_lt_sup exX this, obtain i [H' (Hi : X i = x')], from H₁x', have Hi' : ∀ j, j ≥ i → sX - ε < X j, from take j, assume Hj, lt_of_lt_of_le (by rewrite Hi; apply H₂x') (nondecX Hj), exists.intro i (take j, assume Hj : j ≥ i, have X j - sX ≤ 0, from sub_nonpos_of_le (Xle j), have eq₁ : abs (X j - sX) = sX - X j, using this, by rewrite [abs_of_nonpos this, neg_sub], have sX - ε < X j, from lt_of_lt_of_le (by rewrite Hi; apply H₂x') (nondecX Hj), have sX < X j + ε, from lt_add_of_sub_lt_right this, have sX - X j < ε, from sub_lt_left_of_lt_add this, show (abs (X j - sX)) < ε, using eq₁ this, by rewrite eq₁; exact this) definition nonincreasing (X : ℕ → ℝ) : Prop := ∀ ⦃i j⦄, i ≤ j → X i ≥ X j proposition nodecreasing_of_nonincreasing_neg (nonincX : nonincreasing (λ n, - X n)) : nondecreasing (λ n, X n) := take i j, suppose i ≤ j, show X i ≤ X j, from le_of_neg_le_neg (nonincX this) proposition noincreasing_neg_of_nondecreasing (nondecX : nondecreasing X) : nonincreasing (λ n, - X n) := take i j, suppose i ≤ j, show - X i ≥ - X j, from neg_le_neg (nondecX this) proposition nonincreasing_neg_iff (X : ℕ → ℝ) : nonincreasing (λ n, - X n) ↔ nondecreasing X := iff.intro nodecreasing_of_nonincreasing_neg noincreasing_neg_of_nondecreasing proposition nonincreasing_of_nondecreasing_neg (nondecX : nondecreasing (λ n, - X n)) : nonincreasing (λ n, X n) := take i j, suppose i ≤ j, show X i ≥ X j, from le_of_neg_le_neg (nondecX this) proposition nodecreasing_neg_of_nonincreasing (nonincX : nonincreasing X) : nondecreasing (λ n, - X n) := take i j, suppose i ≤ j, show - X i ≤ - X j, from neg_le_neg (nonincX this) proposition nondecreasing_neg_iff (X : ℕ → ℝ) : nondecreasing (λ n, - X n) ↔ nonincreasing X := iff.intro nonincreasing_of_nondecreasing_neg nodecreasing_neg_of_nonincreasing proposition nonincreasing_of_forall_succ_le (H : ∀ i, X (succ i) ≤ X i) : nonincreasing X := begin rewrite -nondecreasing_neg_iff, show nondecreasing (λ n : ℕ, - X n), from nondecreasing_of_forall_le_succ (take i, neg_le_neg (H i)) end proposition converges_to_seq_inf_of_nonincreasing (nonincX : nonincreasing X) {b : ℝ} (Hb : ∀ i, b ≤ X i) : X ⟶ inf (X ' univ) in ℕ := have H₁ : ∃ x, x ∈ X ' univ, from exists.intro (X 0) (mem_image_of_mem X !mem_univ), have H₂ : ∀ x, x ∈ X ' univ → b ≤ x, from (take x, assume H, obtain i [Hi₁ (Hi₂ : X i = x)], from H, show b ≤ x, by rewrite -Hi₂; apply Hb i), have H₃ : {x : ℝ | -x ∈ X ' univ} = {x : ℝ | x ∈ (λ n, -X n) ' univ}, from calc {x : ℝ | -x ∈ X ' univ} = (λ y, -y) ' (X ' univ) : by rewrite image_neg_eq ... = {x : ℝ | x ∈ (λ n, -X n) ' univ} : image_compose, have H₄ : ∀ i, - X i ≤ - b, from take i, neg_le_neg (Hb i), begin+ -- need krewrite here krewrite [-neg_converges_to_seq_iff, -sup_neg H₁ H₂, H₃, -nondecreasing_neg_iff at nonincX], apply converges_to_seq_sup_of_nondecreasing nonincX H₄ end end monotone_sequences /- x^n converges to 0 if abs x < 1 -/ section xn open nat set theorem pow_converges_to_seq_zero {x : ℝ} (H : abs x < 1) : (λ n, x^n) ⟶ 0 in ℕ := suffices H' : (λ n, (abs x)^n) ⟶ 0 in ℕ, from have (λ n, (abs x)^n) = (λ n, abs (x^n)), from funext (take n, eq.symm !abs_pow), using this, by rewrite this at H'; exact converges_to_seq_zero_of_abs_converges_to_seq_zero H', let aX := (λ n, (abs x)^n), iaX := real.inf (aX ' univ), asX := (λ n, (abs x)^(succ n)) in have noninc_aX : nonincreasing aX, from nonincreasing_of_forall_succ_le (take i, assert (abs x) * (abs x)^i ≤ 1 * (abs x)^i, from mul_le_mul_of_nonneg_right (le_of_lt H) (!pow_nonneg_of_nonneg !abs_nonneg), assert (abs x) * (abs x)^i ≤ (abs x)^i, by krewrite one_mul at this; exact this, show (abs x) ^ (succ i) ≤ (abs x)^i, by rewrite pow_succ; apply this), have bdd_aX : ∀ i, 0 ≤ aX i, from take i, !pow_nonneg_of_nonneg !abs_nonneg, assert aXconv : aX ⟶ iaX in ℕ, proof converges_to_seq_inf_of_nonincreasing noninc_aX bdd_aX qed, have asXconv : asX ⟶ iaX in ℕ, from converges_to_seq_offset_succ aXconv, have asXconv' : asX ⟶ (abs x) * iaX in ℕ, from mul_left_converges_to_seq (abs x) aXconv, have iaX = (abs x) * iaX, from converges_to_seq_unique asXconv asXconv', assert iaX = 0, from eq_zero_of_mul_eq_self_left (ne_of_lt H) (eq.symm this), show aX ⟶ 0 in ℕ, begin rewrite -this, exact aXconv end --from this ▸ aXconv end xn /- continuity on the reals -/ section continuous theorem continuous_real_elim {f : ℝ → ℝ} (H : continuous f) : ∀ x : ℝ, ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ x' : ℝ, abs (x' - x) < δ → abs (f x' - f x) < ε := take x, continuous_at_elim (H x) theorem continuous_real_intro {f : ℝ → ℝ} (H : ∀ x : ℝ, ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ x' : ℝ, abs (x' - x) < δ → abs (f x' - f x) < ε) : continuous f := take x, continuous_at_intro (H x) theorem pos_on_nbhd_of_cts_of_pos {f : ℝ → ℝ} (Hf : continuous f) {b : ℝ} (Hb : f b > 0) : ∃ δ : ℝ, δ > 0 ∧ ∀ y, abs (y - b) < δ → f y > 0 := begin let Hcont := continuous_real_elim Hf b Hb, cases Hcont with δ Hδ, existsi δ, split, exact and.left Hδ, intro y Hy, let Hy' := and.right Hδ y Hy, note Hlt := sub_lt_of_abs_sub_lt_left Hy', rewrite sub_self at Hlt, assumption end theorem neg_on_nbhd_of_cts_of_neg {f : ℝ → ℝ} (Hf : continuous f) {b : ℝ} (Hb : f b < 0) : ∃ δ : ℝ, δ > 0 ∧ ∀ y, abs (y - b) < δ → f y < 0 := begin let Hcont := continuous_real_elim Hf b (neg_pos_of_neg Hb), cases Hcont with δ Hδ, existsi δ, split, exact and.left Hδ, intro y Hy, let Hy' := and.right Hδ y Hy, let Hlt := sub_lt_of_abs_sub_lt_right Hy', note Hlt' := lt_add_of_sub_lt_left Hlt, rewrite [add.comm at Hlt', -sub_eq_add_neg at Hlt', sub_self at Hlt'], assumption end theorem continuous_neg_of_continuous {f : ℝ → ℝ} (Hcon : continuous f) : continuous (λ x, - f x) := begin apply continuous_real_intro, intros x ε Hε, cases continuous_real_elim Hcon x Hε with δ Hδ, cases Hδ with Hδ₁ Hδ₂, existsi δ, split, assumption, intros x' Hx', let HD := Hδ₂ x' Hx', rewrite [-abs_neg, neg_neg_sub_neg], exact HD end theorem continuous_offset_of_continuous {f : ℝ → ℝ} (Hcon : continuous f) (a : ℝ) : continuous (λ x, (f x) + a) := begin apply continuous_real_intro, intros x ε Hε, cases continuous_real_elim Hcon x Hε with δ Hδ, cases Hδ with Hδ₁ Hδ₂, existsi δ, split, assumption, intros x' Hx', rewrite [add_sub_comm, sub_self, add_zero], apply Hδ₂, assumption end theorem continuous_mul_of_continuous {f g : ℝ → ℝ} (Hconf : continuous f) (Hcong : continuous g) : continuous (λ x, f x * g x) := begin intro x, apply continuous_at_of_converges_to_at, apply mul_converges_to_at, all_goals apply converges_to_at_of_continuous_at, apply Hconf, apply Hcong end end continuous
bc0522cc2d62ba27a15a9446dfedfd118ea9d307
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/pkg/user_attr/UserAttr/BlaAttr.lean
dd652db07b53ea85caeb11b9e5426de86b75a2c7
[ "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
702
lean
import Lean open Lean initialize blaAttr : TagAttribute ← registerTagAttribute `bla "simple user defined attribute" /-- My own new simp attribute. -/ register_simp_attr my_simp syntax (name := foo) "foo" num "important"? : attr initialize fooAttr : ParametricAttribute (Nat × Bool) ← registerParametricAttribute { name := `foo descr := "parametric attribute containing a priority and flag" getParam := fun _ stx => match stx with | `(attr| foo $prio:num $[important%$imp]?) => return (prio.getNat, imp.isSome) | _ => throwError "unexpected foo attribute" afterSet := fun declName _ => do IO.println s!"set attribute [foo] at {declName}" }
b39acbf44fe878ff89d9e238ce2d5dd344614a90
9dc8cecdf3c4634764a18254e94d43da07142918
/src/model_theory/language_map.lean
e0eb3c7b024827f42ff6112c6212e3dd1eb352d9
[ "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
17,727
lean
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import model_theory.basic /-! # Language Maps Maps between first-order languages in the style of the [Flypitch project](https://flypitch.github.io/), as well as several important maps between structures. ## Main Definitions * A `first_order.language.Lhom`, denoted `L →ᴸ L'`, is a map between languages, sending the symbols of one to symbols of the same kind and arity in the other. * A `first_order.language.Lequiv`, denoted `L ≃ᴸ L'`, is an invertible language homomorphism. * `first_order.language.with_constants` is defined so that if `M` is an `L.Structure` and `A : set M`, `L.with_constants A`, denoted `L[[A]]`, is a language which adds constant symbols for elements of `A` to `L`. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universes u v u' v' w w' namespace first_order namespace language open Structure cardinal open_locale cardinal variables (L : language.{u v}) (L' : language.{u' v'}) {M : Type w} [L.Structure M] /-- A language homomorphism maps the symbols of one language to symbols of another. -/ structure Lhom := (on_function : ∀ ⦃n⦄, L.functions n → L'.functions n) (on_relation : ∀ ⦃n⦄, L.relations n → L'.relations n) infix ` →ᴸ `:10 := Lhom -- \^L variables {L L'} namespace Lhom /-- Defines a map between languages defined with `language.mk₂`. -/ protected def mk₂ {c f₁ f₂ : Type u} {r₁ r₂ : Type v} (φ₀ : c → L'.constants) (φ₁ : f₁ → L'.functions 1) (φ₂ : f₂ → L'.functions 2) (φ₁' : r₁ → L'.relations 1) (φ₂' : r₂ → L'.relations 2) : language.mk₂ c f₁ f₂ r₁ r₂ →ᴸ L' := ⟨λ n, nat.cases_on n φ₀ (λ n, nat.cases_on n φ₁ (λ n, nat.cases_on n φ₂ (λ _, pempty.elim))), λ n, nat.cases_on n pempty.elim (λ n, nat.cases_on n φ₁' (λ n, nat.cases_on n φ₂' (λ _, pempty.elim)))⟩ variables (ϕ : L →ᴸ L') /-- Pulls a structure back along a language map. -/ def reduct (M : Type*) [L'.Structure M] : L.Structure M := { fun_map := λ n f xs, fun_map (ϕ.on_function f) xs, rel_map := λ n r xs, rel_map (ϕ.on_relation r) xs } /-- The identity language homomorphism. -/ @[simps] protected def id (L : language) : L →ᴸ L := ⟨λn, id, λ n, id⟩ instance : inhabited (L →ᴸ L) := ⟨Lhom.id L⟩ /-- The inclusion of the left factor into the sum of two languages. -/ @[simps] protected def sum_inl : L →ᴸ L.sum L' := ⟨λn, sum.inl, λ n, sum.inl⟩ /-- The inclusion of the right factor into the sum of two languages. -/ @[simps] protected def sum_inr : L' →ᴸ L.sum L' := ⟨λn, sum.inr, λ n, sum.inr⟩ variables (L L') /-- The inclusion of an empty language into any other language. -/ @[simps] protected def of_is_empty [L.is_algebraic] [L.is_relational] : L →ᴸ L' := ⟨λ n, (is_relational.empty_functions n).elim, λ n, (is_algebraic.empty_relations n).elim⟩ variables {L L'} {L'' : language} @[ext] protected lemma funext {F G : L →ᴸ L'} (h_fun : F.on_function = G.on_function ) (h_rel : F.on_relation = G.on_relation ) : F = G := by {cases F with Ff Fr, cases G with Gf Gr, simp only *, exact and.intro h_fun h_rel} instance [L.is_algebraic] [L.is_relational] : unique (L →ᴸ L') := ⟨⟨Lhom.of_is_empty L L'⟩, λ _, Lhom.funext (subsingleton.elim _ _) (subsingleton.elim _ _)⟩ lemma mk₂_funext {c f₁ f₂ : Type u} {r₁ r₂ : Type v} {F G : language.mk₂ c f₁ f₂ r₁ r₂ →ᴸ L'} (h0 : ∀ (c : (language.mk₂ c f₁ f₂ r₁ r₂).constants), F.on_function c = G.on_function c) (h1 : ∀ (f : (language.mk₂ c f₁ f₂ r₁ r₂).functions 1), F.on_function f = G.on_function f) (h2 : ∀ (f : (language.mk₂ c f₁ f₂ r₁ r₂).functions 2), F.on_function f = G.on_function f) (h1' : ∀ (r : (language.mk₂ c f₁ f₂ r₁ r₂).relations 1), F.on_relation r = G.on_relation r) (h2' : ∀ (r : (language.mk₂ c f₁ f₂ r₁ r₂).relations 2), F.on_relation r = G.on_relation r) : F = G := Lhom.funext (funext (λ n, nat.cases_on n (funext h0) (λ n, nat.cases_on n (funext h1) (λ n, nat.cases_on n (funext h2) (λ n, funext (λ f, pempty.elim f)))))) (funext (λ n, nat.cases_on n (funext (λ r, pempty.elim r)) (λ n, nat.cases_on n (funext h1') (λ n, nat.cases_on n (funext h2') (λ n, funext (λ r, pempty.elim r)))))) /-- The composition of two language homomorphisms. -/ @[simps] def comp (g : L' →ᴸ L'') (f : L →ᴸ L') : L →ᴸ L'' := ⟨λ n F, g.1 (f.1 F), λ _ R, g.2 (f.2 R)⟩ local infix (name := Lhom.comp) ` ∘ `:60 := Lhom.comp @[simp] lemma id_comp (F : L →ᴸ L') : (Lhom.id L') ∘ F = F := by {cases F, refl} @[simp] lemma comp_id (F : L →ᴸ L') : F ∘ (Lhom.id L) = F := by {cases F, refl} lemma comp_assoc {L3 : language} (F: L'' →ᴸ L3) (G : L' →ᴸ L'') (H : L →ᴸ L') : (F ∘ G) ∘ H = F ∘ (G ∘ H) := rfl section sum_elim variables (ψ : L'' →ᴸ L') /-- A language map defined on two factors of a sum. -/ @[simps] protected def sum_elim : L.sum L'' →ᴸ L' := { on_function := λ n, sum.elim (λ f, ϕ.on_function f) (λ f, ψ.on_function f), on_relation := λ n, sum.elim (λ f, ϕ.on_relation f) (λ f, ψ.on_relation f) } lemma sum_elim_comp_inl (ψ : L'' →ᴸ L') : (ϕ.sum_elim ψ) ∘ Lhom.sum_inl = ϕ := Lhom.funext (funext (λ _, rfl)) (funext (λ _, rfl)) lemma sum_elim_comp_inr (ψ : L'' →ᴸ L') : (ϕ.sum_elim ψ) ∘ Lhom.sum_inr = ψ := Lhom.funext (funext (λ _, rfl)) (funext (λ _, rfl)) theorem sum_elim_inl_inr : (Lhom.sum_inl).sum_elim (Lhom.sum_inr) = Lhom.id (L.sum L') := Lhom.funext (funext (λ _, sum.elim_inl_inr)) (funext (λ _, sum.elim_inl_inr)) theorem comp_sum_elim {L3 : language} (θ : L' →ᴸ L3) : θ ∘ (ϕ.sum_elim ψ) = (θ ∘ ϕ).sum_elim (θ ∘ ψ) := Lhom.funext (funext (λ n, sum.comp_elim _ _ _)) (funext (λ n, sum.comp_elim _ _ _)) end sum_elim section sum_map variables {L₁ L₂ : language} (ψ : L₁ →ᴸ L₂) /-- The map between two sum-languages induced by maps on the two factors. -/ @[simps] def sum_map : L.sum L₁ →ᴸ L'.sum L₂ := { on_function := λ n, sum.map (λ f, ϕ.on_function f) (λ f, ψ.on_function f), on_relation := λ n, sum.map (λ f, ϕ.on_relation f) (λ f, ψ.on_relation f) } @[simp] lemma sum_map_comp_inl : (ϕ.sum_map ψ) ∘ Lhom.sum_inl = Lhom.sum_inl ∘ ϕ := Lhom.funext (funext (λ _, rfl)) (funext (λ _, rfl)) @[simp] lemma sum_map_comp_inr : (ϕ.sum_map ψ) ∘ Lhom.sum_inr = Lhom.sum_inr ∘ ψ := Lhom.funext (funext (λ _, rfl)) (funext (λ _, rfl)) end sum_map /-- A language homomorphism is injective when all the maps between symbol types are. -/ protected structure injective : Prop := (on_function {n} : function.injective (λ f : L.functions n, on_function ϕ f)) (on_relation {n} : function.injective (λ R : L.relations n, on_relation ϕ R)) /-- A language homomorphism is an expansion on a structure if it commutes with the interpretation of all symbols on that structure. -/ class is_expansion_on (M : Type*) [L.Structure M] [L'.Structure M] : Prop := (map_on_function : ∀ {n} (f : L.functions n) (x : fin n → M), fun_map (ϕ.on_function f) x = fun_map f x) (map_on_relation : ∀ {n} (R : L.relations n) (x : fin n → M), rel_map (ϕ.on_relation R) x = rel_map R x) @[simp] lemma map_on_function {M : Type*} [L.Structure M] [L'.Structure M] [ϕ.is_expansion_on M] {n} (f : L.functions n) (x : fin n → M) : fun_map (ϕ.on_function f) x = fun_map f x := is_expansion_on.map_on_function f x @[simp] lemma map_on_relation {M : Type*} [L.Structure M] [L'.Structure M] [ϕ.is_expansion_on M] {n} (R : L.relations n) (x : fin n → M) : rel_map (ϕ.on_relation R) x = rel_map R x := is_expansion_on.map_on_relation R x instance id_is_expansion_on (M : Type*) [L.Structure M] : is_expansion_on (Lhom.id L) M := ⟨λ _ _ _, rfl, λ _ _ _, rfl⟩ instance of_is_empty_is_expansion_on (M : Type*) [L.Structure M] [L'.Structure M] [L.is_algebraic] [L.is_relational] : is_expansion_on (Lhom.of_is_empty L L') M := ⟨λ n, (is_relational.empty_functions n).elim, λ n, (is_algebraic.empty_relations n).elim⟩ instance sum_elim_is_expansion_on {L'' : language} (ψ : L'' →ᴸ L') (M : Type*) [L.Structure M] [L'.Structure M] [L''.Structure M] [ϕ.is_expansion_on M] [ψ.is_expansion_on M] : (ϕ.sum_elim ψ).is_expansion_on M := ⟨λ _ f _, sum.cases_on f (by simp) (by simp), λ _ R _, sum.cases_on R (by simp) (by simp)⟩ instance sum_map_is_expansion_on {L₁ L₂ : language} (ψ : L₁ →ᴸ L₂) (M : Type*) [L.Structure M] [L'.Structure M] [L₁.Structure M] [L₂.Structure M] [ϕ.is_expansion_on M] [ψ.is_expansion_on M] : (ϕ.sum_map ψ).is_expansion_on M := ⟨λ _ f _, sum.cases_on f (by simp) (by simp), λ _ R _, sum.cases_on R (by simp) (by simp)⟩ instance sum_inl_is_expansion_on (M : Type*) [L.Structure M] [L'.Structure M] : (Lhom.sum_inl : L →ᴸ L.sum L').is_expansion_on M := ⟨λ _ f _, rfl, λ _ R _, rfl⟩ instance sum_inr_is_expansion_on (M : Type*) [L.Structure M] [L'.Structure M] : (Lhom.sum_inr : L' →ᴸ L.sum L').is_expansion_on M := ⟨λ _ f _, rfl, λ _ R _, rfl⟩ @[simp] lemma fun_map_sum_inl [(L.sum L').Structure M] [(Lhom.sum_inl : L →ᴸ L.sum L').is_expansion_on M] {n} {f : L.functions n} {x : fin n → M} : @fun_map (L.sum L') M _ n (sum.inl f) x = fun_map f x := (Lhom.sum_inl : L →ᴸ L.sum L').map_on_function f x @[simp] lemma fun_map_sum_inr [(L'.sum L).Structure M] [(Lhom.sum_inr : L →ᴸ L'.sum L).is_expansion_on M] {n} {f : L.functions n} {x : fin n → M} : @fun_map (L'.sum L) M _ n (sum.inr f) x = fun_map f x := (Lhom.sum_inr : L →ᴸ L'.sum L).map_on_function f x @[priority 100] instance is_expansion_on_reduct (ϕ : L →ᴸ L') (M : Type*) [L'.Structure M] : @is_expansion_on L L' ϕ M (ϕ.reduct M) _ := begin letI := ϕ.reduct M, exact ⟨λ _ f _, rfl, λ _ R _, rfl⟩, end end Lhom /-- A language equivalence maps the symbols of one language to symbols of another bijectively. -/ structure Lequiv (L L' : language) := (to_Lhom : L →ᴸ L') (inv_Lhom : L' →ᴸ L) (left_inv : inv_Lhom.comp to_Lhom = Lhom.id L) (right_inv : to_Lhom.comp inv_Lhom = Lhom.id L') infix ` ≃ᴸ `:10 := Lequiv -- \^L namespace Lequiv variable (L) /-- The identity equivalence from a first-order language to itself. -/ @[simps] protected def refl : L ≃ᴸ L := ⟨Lhom.id L, Lhom.id L, Lhom.id_comp _, Lhom.id_comp _⟩ variable {L} instance : inhabited (L ≃ᴸ L) := ⟨Lequiv.refl L⟩ variables {L'' : language} (e' : L' ≃ᴸ L'') (e : L ≃ᴸ L') /-- The inverse of an equivalence of first-order languages. -/ @[simps] protected def symm : L' ≃ᴸ L := ⟨e.inv_Lhom, e.to_Lhom, e.right_inv, e.left_inv⟩ /-- The composition of equivalences of first-order languages. -/ @[simps, trans] protected def trans (e : L ≃ᴸ L') (e' : L' ≃ᴸ L'') : L ≃ᴸ L'' := ⟨e'.to_Lhom.comp e.to_Lhom, e.inv_Lhom.comp e'.inv_Lhom, by rw [Lhom.comp_assoc, ← Lhom.comp_assoc e'.inv_Lhom, e'.left_inv, Lhom.id_comp, e.left_inv], by rw [Lhom.comp_assoc, ← Lhom.comp_assoc e.to_Lhom, e.right_inv, Lhom.id_comp, e'.right_inv]⟩ end Lequiv section constants_on variables (α : Type u') /-- A language with constants indexed by a type. -/ @[simp] def constants_on : language.{u' 0} := language.mk₂ α pempty pempty pempty pempty variables {α} lemma constants_on_constants : (constants_on α).constants = α := rfl instance is_algebraic_constants_on : is_algebraic (constants_on α) := language.is_algebraic_mk₂ instance is_relational_constants_on [ie : is_empty α] : is_relational (constants_on α) := language.is_relational_mk₂ instance is_empty_functions_constants_on_succ {n : ℕ} : is_empty ((constants_on α).functions (n + 1)) := nat.cases_on n pempty.is_empty (λ n, nat.cases_on n pempty.is_empty (λ _, pempty.is_empty)) lemma card_constants_on : (constants_on α).card = # α := by simp /-- Gives a `constants_on α` structure to a type by assigning each constant a value. -/ def constants_on.Structure (f : α → M) : (constants_on α).Structure M := Structure.mk₂ f pempty.elim pempty.elim pempty.elim pempty.elim variables {β : Type v'} /-- A map between index types induces a map between constant languages. -/ def Lhom.constants_on_map (f : α → β) : (constants_on α) →ᴸ (constants_on β) := Lhom.mk₂ f pempty.elim pempty.elim pempty.elim pempty.elim lemma constants_on_map_is_expansion_on {f : α → β} {fα : α → M} {fβ : β → M} (h : fβ ∘ f = fα) : @Lhom.is_expansion_on _ _ (Lhom.constants_on_map f) M (constants_on.Structure fα) (constants_on.Structure fβ) := begin letI := constants_on.Structure fα, letI := constants_on.Structure fβ, exact ⟨λ n, nat.cases_on n (λ F x, (congr_fun h F : _)) (λ n F, is_empty_elim F), λ _ R, is_empty_elim R⟩ end end constants_on section with_constants variable (L) section variables (α : Type w') /-- Extends a language with a constant for each element of a parameter set in `M`. -/ def with_constants : language.{(max u w') v} := L.sum (constants_on α) localized "notation (name := language.with_constants) L`[[`:95 α`]]`:90 := L.with_constants α" in first_order @[simp] lemma card_with_constants : (L[[α]]).card = cardinal.lift.{w'} L.card + cardinal.lift.{max u v} (# α) := by rw [with_constants, card_sum, card_constants_on] /-- The language map adding constants. -/ @[simps] def Lhom_with_constants : L →ᴸ L[[α]] := Lhom.sum_inl variables {α} /-- The constant symbol indexed by a particular element. -/ protected def con (a : α) : L[[α]].constants := sum.inr a variables {L} (α) /-- Adds constants to a language map. -/ def Lhom.add_constants {L' : language} (φ : L →ᴸ L') : L[[α]] →ᴸ L'[[α]] := φ.sum_map (Lhom.id _) instance params_Structure (A : set α) : (constants_on A).Structure α := constants_on.Structure coe variables (L) (α) /-- The language map removing an empty constant set. -/ @[simps] def Lequiv.add_empty_constants [ie : is_empty α] : L ≃ᴸ L[[α]] := { to_Lhom := Lhom_with_constants L α, inv_Lhom := Lhom.sum_elim (Lhom.id L) (Lhom.of_is_empty (constants_on α) L), left_inv := by rw [Lhom_with_constants, Lhom.sum_elim_comp_inl], right_inv := by { simp only [Lhom.comp_sum_elim, Lhom_with_constants, Lhom.comp_id], exact trans (congr rfl (subsingleton.elim _ _)) Lhom.sum_elim_inl_inr } } variables {α} {β : Type*} @[simp] lemma with_constants_fun_map_sum_inl [L[[α]].Structure M] [(Lhom_with_constants L α).is_expansion_on M] {n} {f : L.functions n} {x : fin n → M} : @fun_map (L[[α]]) M _ n (sum.inl f) x = fun_map f x := (Lhom_with_constants L α).map_on_function f x @[simp] lemma with_constants_rel_map_sum_inl [L[[α]].Structure M] [(Lhom_with_constants L α).is_expansion_on M] {n} {R : L.relations n} {x : fin n → M} : @rel_map (L[[α]]) M _ n (sum.inl R) x = rel_map R x := (Lhom_with_constants L α).map_on_relation R x /-- The language map extending the constant set. -/ def Lhom_with_constants_map (f : α → β) : L[[α]] →ᴸ L[[β]] := Lhom.sum_map (Lhom.id L) (Lhom.constants_on_map f) @[simp] lemma Lhom.map_constants_comp_sum_inl {f : α → β} : (L.Lhom_with_constants_map f).comp (Lhom.sum_inl) = L.Lhom_with_constants β := by ext n f R; refl end open_locale first_order instance constants_on_self_Structure : (constants_on M).Structure M := constants_on.Structure id instance with_constants_self_Structure : L[[M]].Structure M := language.sum_Structure _ _ M instance with_constants_self_expansion : (Lhom_with_constants L M).is_expansion_on M := ⟨λ _ _ _, rfl, λ _ _ _, rfl⟩ variables (α : Type*) [(constants_on α).Structure M] instance with_constants_Structure : L[[α]].Structure M := language.sum_Structure _ _ _ instance with_constants_expansion : (L.Lhom_with_constants α).is_expansion_on M := ⟨λ _ _ _, rfl, λ _ _ _, rfl⟩ instance add_empty_constants_is_expansion_on' : (Lequiv.add_empty_constants L (∅ : set M)).to_Lhom.is_expansion_on M := L.with_constants_expansion _ instance add_empty_constants_symm_is_expansion_on : (Lequiv.add_empty_constants L (∅ : set M)).symm.to_Lhom.is_expansion_on M := Lhom.sum_elim_is_expansion_on _ _ _ instance add_constants_expansion {L' : language} [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M] : (φ.add_constants α).is_expansion_on M := Lhom.sum_map_is_expansion_on _ _ M @[simp] lemma with_constants_fun_map_sum_inr {a : α} {x : fin 0 → M} : @fun_map (L[[α]]) M _ 0 (sum.inr a : L[[α]].functions 0) x = L.con a := begin rw unique.eq_default x, exact (Lhom.sum_inr : (constants_on α) →ᴸ L.sum _).map_on_function _ _, end variables {α} (A : set M) @[simp] lemma coe_con {a : A} : ((L.con a) : M) = a := rfl variables {A} {B : set M} (h : A ⊆ B) instance constants_on_map_inclusion_is_expansion_on : (Lhom.constants_on_map (set.inclusion h)).is_expansion_on M := constants_on_map_is_expansion_on rfl instance map_constants_inclusion_is_expansion_on : (L.Lhom_with_constants_map (set.inclusion h)).is_expansion_on M := Lhom.sum_map_is_expansion_on _ _ _ end with_constants end language end first_order
84fe709d446965ffcf8a402418fd63aaf7111568
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/complete_field.lean
1b886cb7392cb06fb9991abd682c1506aa271adb
[ "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
13,084
lean
/- Copyright (c) 2022 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Yaël Dillies -/ import algebra.order.hom.ring import algebra.order.pointwise import analysis.special_functions.pow /-! # Conditionally complete linear ordered fields This file shows that the reals are unique, or, more formally, given a type satisfying the common axioms of the reals (field, conditionally complete, linearly ordered) that there is an isomorphism preserving these properties to the reals. This is `rat.induced_order_ring_iso`. Moreover this isomorphism is unique. We introduce definitions of conditionally complete linear ordered fields, and show all such are archimedean. We also construct the natural map from a `linear_ordered_field` to such a field. ## Main definitions * `conditionally_complete_linear_ordered_field`: A field satisfying the standard axiomatization of the real numbers, being a Dedekind complete and linear ordered field. * `linear_ordered_field.induced_map`: A (unique) map from any archimedean linear ordered field to a conditionally complete linear ordered field. Various bundlings are available. ## Main results * `unique.order_ring_hom` : Uniqueness of `order_ring_hom`s from an archimedean linear ordered field to a conditionally complete linear ordered field. * `unique.order_ring_iso` : Uniqueness of `order_ring_iso`s between two conditionally complete linearly ordered fields. ## References * https://mathoverflow.net/questions/362991/ who-first-characterized-the-real-numbers-as-the-unique-complete-ordered-field ## Tags reals, conditionally complete, ordered field, uniqueness -/ variables {F α β γ : Type*} noncomputable theory open function rat real set open_locale classical pointwise set_option old_structure_cmd true /-- A field which is both linearly ordered and conditionally complete with respect to the order. This axiomatizes the reals. -/ @[protect_proj, ancestor linear_ordered_field conditionally_complete_linear_order] class conditionally_complete_linear_ordered_field (α : Type*) extends linear_ordered_field α renaming max → sup min → inf, conditionally_complete_linear_order α /-- Any conditionally complete linearly ordered field is archimedean. -/ @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_ordered_field.to_archimedean [conditionally_complete_linear_ordered_field α] : archimedean α := archimedean_iff_nat_lt.2 begin by_contra' h, obtain ⟨x, h⟩ := h, have := cSup_le (range_nonempty (coe : ℕ → α)) (forall_range_iff.2 $ λ n, le_sub_iff_add_le.2 $ le_cSup ⟨x, forall_range_iff.2 h⟩ ⟨n + 1, nat.cast_succ n⟩), linarith, end /-- The reals are a conditionally complete linearly ordered field. -/ instance : conditionally_complete_linear_ordered_field ℝ := { ..real.linear_ordered_field, ..real.conditionally_complete_linear_order } namespace linear_ordered_field /-! ### Rational cut map The idea is that a conditionally complete linear ordered field is fully characterized by its copy of the rationals. Hence we define `rat.cut_map β : α → set β` which sends `a : α` to the "rationals in `β`" that are less than `a`. -/ section cut_map variables [linear_ordered_field α] section division_ring variables (β) [division_ring β] {a a₁ a₂ : α} {b : β} {q : ℚ} /-- The lower cut of rationals inside a linear ordered field that are less than a given element of another linear ordered field. -/ def cut_map (a : α) : set β := (coe : ℚ → β) '' {t | ↑t < a} lemma cut_map_mono (h : a₁ ≤ a₂) : cut_map β a₁ ⊆ cut_map β a₂ := image_subset _ $ λ _, h.trans_lt' variables {β} @[simp] lemma mem_cut_map_iff : b ∈ cut_map β a ↔ ∃ q : ℚ, (q : α) < a ∧ (q : β) = b := iff.rfl @[simp] lemma coe_mem_cut_map_iff [char_zero β] : (q : β) ∈ cut_map β a ↔ (q : α) < a := rat.cast_injective.mem_set_image lemma cut_map_self (a : α) : cut_map α a = Iio a ∩ range (coe : ℚ → α) := begin ext, split, { rintro ⟨q, h, rfl⟩, exact ⟨h, q, rfl⟩ }, { rintro ⟨h, q, rfl⟩, exact ⟨q, h, rfl⟩ } end end division_ring variables (β) [linear_ordered_field β] {a a₁ a₂ : α} {b : β} {q : ℚ} lemma cut_map_coe (q : ℚ) : cut_map β (q : α) = coe '' {r : ℚ | (r : β) < q} := by simp_rw [cut_map, rat.cast_lt] variables [archimedean α] lemma cut_map_nonempty (a : α) : (cut_map β a).nonempty := nonempty.image _ $ exists_rat_lt a lemma cut_map_bdd_above (a : α) : bdd_above (cut_map β a) := begin obtain ⟨q, hq⟩ := exists_rat_gt a, exact ⟨q, ball_image_iff.2 $ λ r hr, by exact_mod_cast (hq.trans' hr).le⟩, end lemma cut_map_add (a b : α) : cut_map β (a + b) = cut_map β a + cut_map β b := begin refine (image_subset_iff.2 $ λ q hq, _).antisymm _, { rw [mem_set_of_eq, ←sub_lt_iff_lt_add] at hq, obtain ⟨q₁, hq₁q, hq₁ab⟩ := exists_rat_btwn hq, refine ⟨q₁, q - q₁, _, _, add_sub_cancel'_right _ _⟩; try {norm_cast}; rwa coe_mem_cut_map_iff, exact_mod_cast sub_lt_comm.mp hq₁q }, { rintro _ ⟨_, _, ⟨qa, ha, rfl⟩, ⟨qb, hb, rfl⟩, rfl⟩, refine ⟨qa + qb, _, by norm_cast⟩, rw [mem_set_of_eq, cast_add], exact add_lt_add ha hb } end end cut_map /-! ### Induced map `rat.cut_map` spits out a `set β`. To get something in `β`, we now take the supremum. -/ section induced_map variables (α β γ) [linear_ordered_field α] [conditionally_complete_linear_ordered_field β] [conditionally_complete_linear_ordered_field γ] /-- The induced order preserving function from a linear ordered field to a conditionally complete linear ordered field, defined by taking the Sup in the codomain of all the rationals less than the input. -/ def induced_map (x : α) : β := Sup $ cut_map β x variables [archimedean α] lemma induced_map_mono : monotone (induced_map α β) := λ a b h, cSup_le_cSup (cut_map_bdd_above β _) (cut_map_nonempty β _) (cut_map_mono β h) lemma induced_map_rat (q : ℚ) : induced_map α β (q : α) = q := begin refine cSup_eq_of_forall_le_of_forall_lt_exists_gt (cut_map_nonempty β q) (λ x h, _) (λ w h, _), { rw cut_map_coe at h, obtain ⟨r, h, rfl⟩ := h, exact le_of_lt h }, { obtain ⟨q', hwq, hq⟩ := exists_rat_btwn h, rw cut_map_coe, exact ⟨q', ⟨_, hq, rfl⟩, hwq⟩ } end @[simp] lemma induced_map_zero : induced_map α β 0 = 0 := by exact_mod_cast induced_map_rat α β 0 @[simp] lemma induced_map_one : induced_map α β 1 = 1 := by exact_mod_cast induced_map_rat α β 1 variables {α β} {a : α} {b : β} {q : ℚ} lemma induced_map_nonneg (ha : 0 ≤ a) : 0 ≤ induced_map α β a := (induced_map_zero α _).ge.trans $ induced_map_mono _ _ ha lemma coe_lt_induced_map_iff : (q : β) < induced_map α β a ↔ (q : α) < a := begin refine ⟨λ h, _, λ hq, _⟩, { rw ←induced_map_rat α at h, exact (induced_map_mono α β).reflect_lt h }, { obtain ⟨q', hq, hqa⟩ := exists_rat_btwn hq, apply lt_cSup_of_lt (cut_map_bdd_above β a) (coe_mem_cut_map_iff.mpr hqa), exact_mod_cast hq } end lemma lt_induced_map_iff : b < induced_map α β a ↔ ∃ q : ℚ, b < q ∧ (q : α) < a := ⟨λ h, (exists_rat_btwn h).imp $ λ q, and.imp_right coe_lt_induced_map_iff.1, λ ⟨q, hbq, hqa⟩, hbq.trans $ by rwa coe_lt_induced_map_iff⟩ @[simp] lemma induced_map_self (b : β) : induced_map β β b = b := eq_of_forall_rat_lt_iff_lt $ λ q, coe_lt_induced_map_iff variables (α β) @[simp] lemma induced_map_induced_map (a : α) : induced_map β γ (induced_map α β a) = induced_map α γ a := eq_of_forall_rat_lt_iff_lt $ λ q, by rw [coe_lt_induced_map_iff, coe_lt_induced_map_iff, iff.comm, coe_lt_induced_map_iff] @[simp] lemma induced_map_inv_self (b : β) : induced_map γ β (induced_map β γ b) = b := by rw [induced_map_induced_map, induced_map_self] lemma induced_map_add (x y : α) : induced_map α β (x + y) = induced_map α β x + induced_map α β y := begin rw [induced_map, cut_map_add], exact cSup_add (cut_map_nonempty β x) (cut_map_bdd_above β x) (cut_map_nonempty β y) (cut_map_bdd_above β y), end variables {α β} /-- Preparatory lemma for `induced_ring_hom`. -/ lemma le_induced_map_mul_self_of_mem_cut_map (ha : 0 < a) (b : β) (hb : b ∈ cut_map β (a * a)) : b ≤ induced_map α β a * induced_map α β a := begin obtain ⟨q, hb, rfl⟩ := hb, obtain ⟨q', hq', hqq', hqa⟩ := exists_rat_pow_btwn two_ne_zero hb (mul_self_pos.2 ha.ne'), transitivity (q' : β)^2, exact_mod_cast hqq'.le, rw pow_two at ⊢ hqa, exact mul_self_le_mul_self (by exact_mod_cast hq'.le) (le_cSup (cut_map_bdd_above β a) $ coe_mem_cut_map_iff.2 $ lt_of_mul_self_lt_mul_self ha.le hqa), end /-- Preparatory lemma for `induced_ring_hom`. -/ lemma exists_mem_cut_map_mul_self_of_lt_induced_map_mul_self (ha : 0 < a) (b : β) (hba : b < induced_map α β a * induced_map α β a) : ∃ c ∈ cut_map β (a * a), b < c := begin obtain hb | hb := lt_or_le b 0, { refine ⟨0, _, hb⟩, rw [←rat.cast_zero, coe_mem_cut_map_iff, rat.cast_zero], exact mul_self_pos.2 ha.ne' }, obtain ⟨q, hq, hbq, hqa⟩ := exists_rat_pow_btwn two_ne_zero hba (hb.trans_lt hba), rw ←cast_pow at hbq, refine ⟨(q^2 : ℚ), coe_mem_cut_map_iff.2 _, hbq⟩, rw pow_two at ⊢ hqa, push_cast, obtain ⟨q', hq', hqa'⟩ := lt_induced_map_iff.1 (lt_of_mul_self_lt_mul_self _ hqa), exact mul_self_lt_mul_self (by exact_mod_cast hq.le) (hqa'.trans' $ by assumption_mod_cast), exact induced_map_nonneg ha.le, end variables (α β) /-- `induced_map` as an additive homomorphism. -/ def induced_add_hom : α →+ β := ⟨induced_map α β, induced_map_zero α β, induced_map_add α β⟩ /-- `induced_map` as an `order_ring_hom`. -/ @[simps] def induced_order_ring_hom : α →+*o β := { monotone' := induced_map_mono _ _, ..(induced_add_hom α β).mk_ring_hom_of_mul_self_of_two_ne_zero -- reduce to the case of x = y begin -- reduce to the case of 0 < x suffices : ∀ x, 0 < x → induced_add_hom α β (x * x) = induced_add_hom α β x * induced_add_hom α β x, { rintro x, obtain h | rfl | h := lt_trichotomy x 0, { convert this (-x) (neg_pos.2 h) using 1, { rw [neg_mul, mul_neg, neg_neg] }, { simp_rw [add_monoid_hom.map_neg, neg_mul, mul_neg, neg_neg] } }, { simp only [mul_zero, add_monoid_hom.map_zero] }, { exact this x h } }, -- prove that the (Sup of rationals less than x) ^ 2 is the Sup of the set of rationals less -- than (x ^ 2) by showing it is an upper bound and any smaller number is not an upper bound refine λ x hx, cSup_eq_of_forall_le_of_forall_lt_exists_gt (cut_map_nonempty β _) _ _, exact le_induced_map_mul_self_of_mem_cut_map hx, exact exists_mem_cut_map_mul_self_of_lt_induced_map_mul_self hx, end two_ne_zero (induced_map_one _ _) } /-- The isomorphism of ordered rings between two conditionally complete linearly ordered fields. -/ def induced_order_ring_iso : β ≃+*o γ := { inv_fun := induced_map γ β, left_inv := induced_map_inv_self _ _, right_inv := induced_map_inv_self _ _, map_le_map_iff' := λ x y, begin refine ⟨λ h, _, λ h, induced_map_mono _ _ h⟩, simpa [induced_order_ring_hom, add_monoid_hom.mk_ring_hom_of_mul_self_of_two_ne_zero, induced_add_hom] using induced_map_mono γ β h, end, ..induced_order_ring_hom β γ } @[simp] lemma coe_induced_order_ring_iso : ⇑(induced_order_ring_iso β γ) = induced_map β γ := rfl @[simp] lemma induced_order_ring_iso_symm : (induced_order_ring_iso β γ).symm = induced_order_ring_iso γ β := rfl @[simp] lemma induced_order_ring_iso_self : induced_order_ring_iso β β = order_ring_iso.refl β := order_ring_iso.ext induced_map_self open order_ring_iso /-- There is a unique ordered ring homomorphism from an archimedean linear ordered field to a conditionally complete linear ordered field. -/ instance : unique (α →+*o β) := unique_of_subsingleton $ induced_order_ring_hom α β /-- There is a unique ordered ring isomorphism between two conditionally complete linear ordered fields. -/ instance : unique (β ≃+*o γ) := unique_of_subsingleton $ induced_order_ring_iso β γ end induced_map end linear_ordered_field section real variables {R S : Type*} [ordered_ring R] [linear_ordered_ring S] lemma ring_hom_monotone (hR : ∀ r : R, 0 ≤ r → ∃ s : R, s^2 = r) (f : R →+* S) : monotone f := (monotone_iff_map_nonneg f).2 $ λ r h, by { obtain ⟨s, rfl⟩ := hR r h, rw map_pow, apply sq_nonneg } /-- There exists no nontrivial ring homomorphism `ℝ →+* ℝ`. -/ instance real.ring_hom.unique : unique (ℝ →+* ℝ) := { default := ring_hom.id ℝ, uniq := λ f, congr_arg order_ring_hom.to_ring_hom (subsingleton.elim ⟨f, ring_hom_monotone (λ r hr, ⟨real.sqrt r, sq_sqrt hr⟩) f⟩ default), } end real
9c4708f710777fe8cb3ae906ec75f036f3d07fca
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/finiteness.lean
210138bd91f5d9fe942300fb930511589c8b8aca
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,041
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.noetherian import ring_theory.ideal.operations import ring_theory.algebra_tower import group_theory.finiteness /-! # Finiteness conditions in commutative algebra In this file we define several notions of finiteness that are common in commutative algebra. ## Main declarations - `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite` all of these express that some object is finitely generated *as module* over some base ring. - `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type` all of these express that some object is finitely generated *as algebra* over some base ring. - `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation` all of these express that some object is finitely presented *as algebra* over some base ring. -/ open function (surjective) open_locale big_operators section module_and_algebra variables (R A B M N : Type*) [comm_ring R] variables [comm_ring A] [algebra R A] [comm_ring B] [algebra R B] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] /-- A module over a commutative ring is `finite` if it is finitely generated as a module. -/ class module.finite (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M] : Prop := (out : (⊤ : submodule R M).fg) /-- An algebra over a commutative ring is of `finite_type` if it is finitely generated over the base ring as algebra. -/ class algebra.finite_type : Prop := (out : (⊤ : subalgebra R A).fg) /-- An algebra over a commutative ring is `finite_presentation` if it is the quotient of a polynomial ring in `n` variables by a finitely generated ideal. -/ def algebra.finite_presentation : Prop := ∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg namespace module lemma finite_def {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : finite R M ↔ (⊤ : submodule R M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ @[priority 100] -- see Note [lower instance priority] instance is_noetherian.finite [is_noetherian R M] : finite R M := ⟨is_noetherian.noetherian ⊤⟩ namespace finite open submodule set lemma iff_add_monoid_fg {M : Type*} [add_comm_monoid M] : module.finite ℕ M ↔ add_monoid.fg M := ⟨λ h, add_monoid.fg_def.2 $ (fg_iff_add_submonoid_fg ⊤).1 (finite_def.1 h), λ h, finite_def.2 $ (fg_iff_add_submonoid_fg ⊤).2 (add_monoid.fg_def.1 h)⟩ lemma iff_add_group_fg {G : Type*} [add_comm_group G] : module.finite ℤ G ↔ add_group.fg G := ⟨λ h, add_group.fg_def.2 $ (fg_iff_add_subgroup_fg ⊤).1 (finite_def.1 h), λ h, finite_def.2 $ (fg_iff_add_subgroup_fg ⊤).2 (add_group.fg_def.1 h)⟩ variables {R M N} lemma exists_fin [finite R M] : ∃ (n : ℕ) (s : fin n → M), span R (range s) = ⊤ := submodule.fg_iff_exists_fin_generating_family.mp out lemma of_surjective [hM : finite R M] (f : M →ₗ[R] N) (hf : surjective f) : finite R N := ⟨begin rw [← linear_map.range_eq_top.2 hf, ← submodule.map_top], exact submodule.fg_map hM.1 end⟩ lemma of_injective [is_noetherian R N] (f : M →ₗ[R] N) (hf : function.injective f) : finite R M := ⟨fg_of_injective f $ linear_map.ker_eq_bot.2 hf⟩ variables (R) instance self : finite R R := ⟨⟨{1}, by simpa only [finset.coe_singleton] using ideal.span_singleton_one⟩⟩ variable (M) lemma of_restrict_scalars_finite [module A M] [is_scalar_tower R A M] [hM : finite R M] : finite A M := begin rw [finite_def, fg_def] at hM ⊢, obtain ⟨S, hSfin, hSgen⟩ := hM, refine ⟨S, hSfin, eq_top_iff.2 _⟩, have := submodule.span_le_restrict_scalars R A M S, rw hSgen at this, exact this end variables {R M} instance prod [hM : finite R M] [hN : finite R N] : finite R (M × N) := ⟨begin rw ← submodule.prod_top, exact submodule.fg_prod hM.1 hN.1 end⟩ lemma equiv [hM : finite R M] (e : M ≃ₗ[R] N) : finite R N := of_surjective (e : M →ₗ[R] N) e.surjective section algebra lemma trans [algebra A B] [is_scalar_tower R A B] : ∀ [finite R A] [finite A B], finite R B | ⟨⟨s, hs⟩⟩ ⟨⟨t, ht⟩⟩ := ⟨submodule.fg_def.2 ⟨set.image2 (•) (↑s : set A) (↑t : set B), set.finite.image2 _ s.finite_to_set t.finite_to_set, by rw [set.image2_smul, submodule.span_smul hs (↑t : set B), ht, submodule.restrict_scalars_top]⟩⟩ @[priority 100] -- see Note [lower instance priority] instance finite_type [hRA : finite R A] : algebra.finite_type R A := ⟨subalgebra.fg_of_submodule_fg hRA.1⟩ end algebra end finite end module namespace algebra namespace finite_type lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩ section open_locale classical protected lemma mv_polynomial (ι : Type*) [fintype ι] : finite_type R (mv_polynomial ι R) := ⟨⟨finset.univ.image mv_polynomial.X, begin rw eq_top_iff, refine λ p, mv_polynomial.induction_on' p (λ u x, finsupp.induction u (subalgebra.algebra_map_mem _ x) (λ i n f hif hn ih, _)) (λ p q ihp ihq, subalgebra.add_mem _ ihp ihq), rw [add_comm, mv_polynomial.monomial_add_single], exact subalgebra.mul_mem _ ih (subalgebra.pow_mem _ (subset_adjoin $ finset.mem_image_of_mem _ $ finset.mem_univ _) _) end⟩⟩ end lemma of_restrict_scalars_finite_type [algebra A B] [is_scalar_tower R A B] [hB : finite_type R B] : finite_type A B := begin obtain ⟨S, hS⟩ := hB.out, refine ⟨⟨S, eq_top_iff.2 (λ b, _)⟩⟩, have le : adjoin R (S : set B) ≤ subalgebra.restrict_scalars R (adjoin A S), { apply (algebra.adjoin_le _ : _ ≤ (subalgebra.restrict_scalars R (adjoin A ↑S))), simp only [subalgebra.coe_restrict_scalars], exact algebra.subset_adjoin, }, exact le (eq_top_iff.1 hS b), end variables {R A B} lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) : finite_type R B := ⟨begin convert subalgebra.fg_map _ f hRA.1, simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf end⟩ lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B := hRA.of_surjective e e.surjective lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) : finite_type R B := ⟨fg_trans' hRA.1 hAB.1⟩ /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a finset. -/ lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A) (f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) := begin split, { rintro ⟨s, hs⟩, use [s, mv_polynomial.aeval coe], intro x, have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl, rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs], exact set.mem_univ x }, { rintro ⟨s, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype. -/ lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) (_ : fintype ι) (f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial, rintro ⟨s, ⟨f, hsur⟩⟩, use [{x // x ∈ s}, by apply_instance, f, hsur] }, { rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩, letI : fintype ι := hfintype, exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n` variables. -/ lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ) (f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial', rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩, letI := hfintype, obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) hfintype, replace equiv := mv_polynomial.rename_equiv R equiv, exact ⟨fintype.card ι, alg_hom.comp f equiv.symm, function.surjective.comp hsur (alg_equiv.symm equiv).surjective⟩ }, { rintro ⟨n, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur } end /-- A finitely presented algebra is of finite type. -/ lemma of_finite_presentation : finite_presentation R A → finite_type R A := begin rintro ⟨n, f, hf⟩, apply (finite_type.iff_quotient_mv_polynomial'').2, exact ⟨n, f, hf.1⟩ end instance prod [hA : finite_type R A] [hB : finite_type R B] : finite_type R (A × B) := ⟨begin rw ← subalgebra.prod_top, exact subalgebra.fg_prod hA.1 hB.1 end⟩ end finite_type namespace finite_presentation variables {R A B} /-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely presented. -/ lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A := begin refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩, obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h, refine ⟨n, f, hf, _⟩, have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance, replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian, exact hnoet f.to_ring_hom.ker, end /-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/ lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B := begin obtain ⟨n, f, hf⟩ := hfp, use [n, alg_hom.comp ↑e f], split, { exact function.surjective.comp e.surjective hf.1 }, suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker, { rw hker, exact hf.2 }, { have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom, { have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl, have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl, rw [h, h1] }, rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot, ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] } end variable (R) /-- The ring of polynomials in finitely many variables is finitely presented. -/ lemma mv_polynomial (ι : Type u_2) [fintype ι] : finite_presentation R (mv_polynomial ι R) := begin obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) _, replace equiv := mv_polynomial.rename_equiv R equiv, refine ⟨_, alg_equiv.to_alg_hom equiv.symm, _⟩, split, { exact (alg_equiv.symm equiv).surjective }, suffices hinj : function.injective equiv.symm.to_alg_hom.to_ring_hom, { rw [(ring_hom.injective_iff_ker_eq_bot _).1 hinj], exact submodule.fg_bot }, exact (alg_equiv.symm equiv).injective end /-- `R` is finitely presented as `R`-algebra. -/ lemma self : finite_presentation R R := equiv (mv_polynomial R pempty) (mv_polynomial.is_empty_alg_equiv R pempty) variable {R} /-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely presented. -/ lemma quotient {I : ideal A} (h : submodule.fg I) (hfp : finite_presentation R A) : finite_presentation R I.quotient := begin obtain ⟨n, f, hf⟩ := hfp, refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩, { exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 }, { refine submodule.fg_ker_ring_hom_comp _ _ hf.2 _ hf.1, simp [h] } end /-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented, then so is `B`. -/ lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg) (hfp : finite_presentation R A) : finite_presentation R B := equiv (quotient hker hfp) (ideal.quotient_ker_alg_equiv_of_surjective hf) lemma iff : finite_presentation R A ↔ ∃ n (I : ideal (_root_.mv_polynomial (fin n) R)) (e : I.quotient ≃ₐ[R] A), I.fg := begin refine ⟨λ h,_, λ h, _⟩, { obtain ⟨n, f, hf⟩ := h, use [n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2] }, { obtain ⟨n, I, e, hfg⟩ := h, exact equiv (quotient hfg (mv_polynomial R _)) e } end /-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype by a finitely generated ideal. -/ lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) (_ : fintype ι) (f : (_root_.mv_polynomial ι R) →ₐ[R] A), (surjective f) ∧ f.to_ring_hom.ker.fg := begin split, { rintro ⟨n, f, hfs, hfk⟩, set ulift_var := mv_polynomial.rename_equiv R equiv.ulift, refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom, hfs.comp ulift_var.surjective, submodule.fg_ker_ring_hom_comp _ _ _ hfk ulift_var.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, }, { rintro ⟨ι, hfintype, f, hf⟩, haveI : fintype ι := hfintype, obtain ⟨equiv⟩ := @fintype.trunc_equiv_fin ι (classical.dec_eq ι) _, replace equiv := mv_polynomial.rename_equiv R equiv, refine ⟨fintype.card ι, f.comp equiv.symm, hf.1.comp (alg_equiv.symm equiv).surjective, submodule.fg_ker_ring_hom_comp _ f _ hf.2 equiv.symm.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), } end /-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented as `R`-algebra. -/ lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*) [fintype ι] : finite_presentation R (_root_.mv_polynomial ι A) := begin classical, let n := fintype.card ι, obtain ⟨e⟩ := fintype.trunc_equiv_fin ι, replace e := (mv_polynomial.rename_equiv A e).restrict_scalars R, refine equiv _ e.symm, obtain ⟨m, I, e, hfg⟩ := iff.1 hfp, refine equiv _ (mv_polynomial.map_alg_equiv (fin n) e), -- typeclass inference seems to struggle to find this path letI : is_scalar_tower R (_root_.mv_polynomial (fin m) R) (_root_.mv_polynomial (fin m) R) := is_scalar_tower.right, letI : is_scalar_tower R (_root_.mv_polynomial (fin m) R) (_root_.mv_polynomial (fin n) (_root_.mv_polynomial (fin m) R)) := mv_polynomial.is_scalar_tower, refine equiv _ ((@mv_polynomial.quotient_equiv_quotient_mv_polynomial _ (fin n) _ I).restrict_scalars R).symm, refine quotient (submodule.map_fg_of_fg I hfg _) _, let := mv_polynomial.sum_alg_equiv R (fin n) (fin m), refine equiv _ this, exact equiv (mv_polynomial R (fin (n + m))) (mv_polynomial.rename_equiv R fin_sum_fin_equiv).symm end /-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is finitely presented as `R`-algebra. -/ lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A) (hfpB : finite_presentation A B) : finite_presentation R B := begin obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB, exact equiv (quotient hfg (mv_polynomial_of_finite_presentation hfpA _)) (e.restrict_scalars R) end end finite_presentation end algebra end module_and_algebra namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] /-- A ring morphism `A →+* B` is `finite` if `B` is finitely generated as `A`-module. -/ def finite (f : A →+* B) : Prop := by letI : algebra A B := f.to_algebra; exact module.finite A B /-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra /-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra namespace finite variables (A) lemma id : finite (ring_hom.id A) := module.finite.self A variables {A} lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite := begin letI := f.to_algebra, exact module.finite.of_surjective (algebra.of_id A B).to_linear_map hf end lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := @module.finite.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f := @module.finite.finite_type _ _ _ _ f.to_algebra hf lemma of_comp_finite {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite) : g.finite := begin letI := f.to_algebra, letI := g.to_algebra, letI := (g.comp f).to_algebra, letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C, letI : module.finite A C := h, exact module.finite.of_restrict_scalars_finite A B C end end finite namespace finite_type variables (A) lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := @algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf { to_fun := g, commutes' := λ a, rfl, .. g } hg lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type := by { rw ← f.comp_id, exact (id A).comp_surjective hf } lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := @algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type := @algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf lemma of_comp_finite_type {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite_type) : g.finite_type := begin letI := f.to_algebra, letI := g.to_algebra, letI := (g.comp f).to_algebra, letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C, letI : algebra.finite_type A C := h, exact algebra.finite_type.of_restrict_scalars_finite_type A B C end end finite_type namespace finite_presentation variables (A) lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.ker.fg) : (g.comp f).finite_presentation := @algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra { to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation := by { rw ← f.comp_id, exact (id A).comp_surjective hf hker} lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation := @algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _ lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := @algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra { smul_assoc := λ a b c, begin simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end } hf hg end finite_presentation end ring_hom namespace alg_hom variables {R A B C : Type*} [comm_ring R] variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra R A] [algebra R B] [algebra R C] /-- An algebra morphism `A →ₐ[R] B` is finite if it is finite as ring morphism. In other words, if `B` is finitely generated as `A`-module. -/ def finite (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite /-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism. In other words, if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type /-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation namespace finite variables (R A) lemma id : finite (alg_hom.id R A) := ring_hom.finite.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := ring_hom.finite.comp hg hf lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite := ring_hom.finite.of_surjective f hf lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f := ring_hom.finite.finite_type hf lemma of_comp_finite {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite) : g.finite := ring_hom.finite.of_comp_finite h end finite namespace finite_type variables (R A) lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := ring_hom.finite_type.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := ring_hom.finite_type.comp_surjective hf hg lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type := ring_hom.finite_type.of_surjective f hf lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type := ring_hom.finite_type.of_finite_presentation hf lemma of_comp_finite_type {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite_type) : g.finite_type := ring_hom.finite_type.of_comp_finite_type h end finite_type namespace finite_presentation variables (R A) lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp_surjective hf hg hker lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) : f.finite_presentation := ring_hom.finite_presentation.of_surjective f hf hker lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} : f.finite_type ↔ f.finite_presentation := ring_hom.finite_presentation.of_finite_type end finite_presentation end alg_hom section monoid_algebra variables {R : Type*} {M : Type*} namespace add_monoid_algebra open algebra add_submonoid submodule section span section semiring variables [comm_semiring R] [add_monoid M] /-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_adjoin_support (f : add_monoid_algebra R M) : f ∈ adjoin R (of' R M '' f.support) := begin suffices : span R (of' R M '' f.support) ≤ (adjoin R (of' R M '' f.support)).to_submodule, { exact this (mem_span_support f) }, rw submodule.span_le, exact subset_adjoin end /-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the set of supports of elements of `S` generates `add_monoid_algebra R M`. -/ lemma support_gen_of_gen {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (⋃ f ∈ S, (of' R M '' (f.support : set M))) = ⊤ := begin refine le_antisymm le_top _, rw [← hS, adjoin_le_iff], intros f hf, have hincl : of' R M '' f.support ⊆ ⋃ (g : add_monoid_algebra R M) (H : g ∈ S), of' R M '' g.support, { intros s hs, exact set.mem_bUnion_iff.2 ⟨f, ⟨hf, hs⟩⟩ }, exact adjoin_mono hincl (mem_adjoin_support f) end /-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the image of the union of the supports of elements of `S` generates `add_monoid_algebra R M`. -/ lemma support_gen_of_gen' {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (of' R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ := begin suffices : of' R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of' R M '' (f.support : set M)), { rw this, exact support_gen_of_gen hS }, simp only [set.image_Union] end end semiring section ring variables [comm_ring R] [add_comm_monoid M] /-- If `add_monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image generates, as algera, `add_monoid_algebra R M`. -/ lemma exists_finset_adjoin_eq_top [h : finite_type R (add_monoid_algebra R M)] : ∃ G : finset M, algebra.adjoin R (of' R M '' G) = ⊤ := begin unfreezingI { obtain ⟨S, hS⟩ := h }, letI : decidable_eq M := classical.dec_eq M, use finset.bUnion S (λ f, f.support), have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M), { simp only [finset.set_bUnion_coe, finset.coe_bUnion] }, rw [this], exact support_gen_of_gen' hS end /-- The image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by `S : set M` if and only if `m ∈ S`. -/ lemma of'_mem_span [nontrivial R] {m : M} {S : set M} : of' R M m ∈ span R (of' R M '' S) ↔ m ∈ S := begin refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩, rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported, finsupp.support_single_ne_zero (@one_ne_zero R _ (by apply_instance))] at h, simpa using h end /--If the image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by the closure of some `S : set M` then `m ∈ closure S`. -/ lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M} (h : of' R M m ∈ span R (submonoid.closure (of' R M '' S) : set (add_monoid_algebra R M))) : m ∈ closure S := begin suffices : multiplicative.of_add m ∈ submonoid.closure (multiplicative.to_add ⁻¹' S), { simpa [← to_submonoid_closure] }, rw [set.image_congr' (show ∀ x, of' R M x = of R M x, from λ x, of'_eq_of x), ← monoid_hom.map_mclosure] at h, simpa using of'_mem_span.1 h end end ring end span variables [add_comm_monoid M] /-- If a set `S` generates an additive monoid `M`, then the image of `M` generates, as algebra, `add_monoid_algebra R M`. -/ lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M} (hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval (λ (s : S), of' R M ↑s) : mv_polynomial S R → add_monoid_algebra R M) := begin refine λ f, induction_on f (λ m, _) _ _, { have : m ∈ closure S := hS.symm ▸ mem_top _, refine closure_induction this (λ m hm, _) _ _, { exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ }, { exact ⟨1, alg_hom.map_one _⟩ }, { rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩, exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply, single_mul_single, one_mul]; refl⟩ } }, { rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩, exact ⟨P + Q, alg_hom.map_add _ _ _⟩ }, { rintro r f ⟨P, rfl⟩, exact ⟨r • P, alg_hom.map_smul _ _ _⟩ } end /-- If an additive monoid `M` is finitely generated then `add_monoid_algebra R M` is of finite type. -/ instance finite_type_of_fg [comm_ring R] [h : add_monoid.fg M] : finite_type R (add_monoid_algebra R M) := begin obtain ⟨S, hS⟩ := h.out, exact (finite_type.mv_polynomial R (S : set M)).of_surjective (mv_polynomial.aeval (λ (s : (S : set M)), of' R M ↑s)) (mv_polynomial_aeval_of_surjective_of_closure hS) end /-- An additive monoid `M` is finitely generated if and only if `add_monoid_algebra R M` is of finite type. -/ lemma finite_type_iff_fg [comm_ring R] [nontrivial R] : finite_type R (add_monoid_algebra R M) ↔ add_monoid.fg M := begin refine ⟨λ h, _, λ h, @add_monoid_algebra.finite_type_of_fg _ _ _ _ h⟩, obtain ⟨S, hS⟩ := @exists_finset_adjoin_eq_top R M _ _ h, refine add_monoid.fg_def.2 ⟨S, (eq_top_iff' _).2 (λ m, _)⟩, have hm : of' R M m ∈ (adjoin R (of' R M '' ↑S)).to_submodule, { simp only [hS, top_to_submodule, submodule.mem_top], }, rw [adjoin_eq_span] at hm, exact mem_closure_of_mem_span_closure hm end /-- If `add_monoid_algebra R M` is of finite type then `M` is finitely generated. -/ lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (add_monoid_algebra R M)] : add_monoid.fg M := finite_type_iff_fg.1 h /-- An additive group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/ lemma finite_type_iff_group_fg {G : Type*} [add_comm_group G] [comm_ring R] [nontrivial R] : finite_type R (add_monoid_algebra R G) ↔ add_group.fg G := by simpa [add_group.fg_iff_add_monoid.fg] using finite_type_iff_fg end add_monoid_algebra namespace monoid_algebra open algebra submonoid submodule section span section semiring variables [comm_semiring R] [monoid M] /-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_adjoint_support (f : monoid_algebra R M) : f ∈ adjoin R (of R M '' f.support) := begin suffices : span R (of R M '' f.support) ≤ (adjoin R (of R M '' f.support)).to_submodule, { exact this (mem_span_support f) }, rw submodule.span_le, exact subset_adjoin end /-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the set of supports of elements of `S` generates `monoid_algebra R M`. -/ lemma support_gen_of_gen {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (⋃ f ∈ S, (of R M '' (f.support : set M))) = ⊤ := begin refine le_antisymm le_top _, rw [← hS, adjoin_le_iff], intros f hf, have hincl : (of R M) '' f.support ⊆ ⋃ (g : monoid_algebra R M) (H : g ∈ S), of R M '' g.support, { intros s hs, exact set.mem_bUnion_iff.2 ⟨f, ⟨hf, hs⟩⟩ }, exact adjoin_mono hincl (mem_adjoint_support f) end /-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the image of the union of the supports of elements of `S` generates `monoid_algebra R M`. -/ lemma support_gen_of_gen' {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (of R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ := begin suffices : of R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of R M '' (f.support : set M)), { rw this, exact support_gen_of_gen hS }, simp only [set.image_Union] end end semiring section ring variables [comm_ring R] [comm_monoid M] /-- If `monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image generates, as algera, `monoid_algebra R M`. -/ lemma exists_finset_adjoin_eq_top [h :finite_type R (monoid_algebra R M)] : ∃ G : finset M, algebra.adjoin R (of R M '' G) = ⊤ := begin unfreezingI { obtain ⟨S, hS⟩ := h }, letI : decidable_eq M := classical.dec_eq M, use finset.bUnion S (λ f, f.support), have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M), { simp only [finset.set_bUnion_coe, finset.coe_bUnion] }, rw [this], exact support_gen_of_gen' hS end /-- The image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by `S : set M` if and only if `m ∈ S`. -/ lemma of_mem_span_of_iff [nontrivial R] {m : M} {S : set M} : of R M m ∈ span R (of R M '' S) ↔ m ∈ S := begin refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩, rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported, finsupp.support_single_ne_zero (@one_ne_zero R _ (by apply_instance))] at h, simpa using h end /--If the image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by the closure of some `S : set M` then `m ∈ closure S`. -/ lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M} (h : of R M m ∈ span R (submonoid.closure (of R M '' S) : set (monoid_algebra R M))) : m ∈ closure S := begin rw ← monoid_hom.map_mclosure at h, simpa using of_mem_span_of_iff.1 h end end ring end span variables [comm_monoid M] /-- If a set `S` generates a monoid `M`, then the image of `M` generates, as algebra, `monoid_algebra R M`. -/ lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M} (hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval (λ (s : S), of R M ↑s) : mv_polynomial S R → monoid_algebra R M) := begin refine λ f, induction_on f (λ m, _) _ _, { have : m ∈ closure S := hS.symm ▸ mem_top _, refine closure_induction this (λ m hm, _) _ _, { exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ }, { exact ⟨1, alg_hom.map_one _⟩ }, { rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩, exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply, single_mul_single, one_mul]⟩ } }, { rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩, exact ⟨P + Q, alg_hom.map_add _ _ _⟩ }, { rintro r f ⟨P, rfl⟩, exact ⟨r • P, alg_hom.map_smul _ _ _⟩ } end /-- If a monoid `M` is finitely generated then `monoid_algebra R M` is of finite type. -/ instance finite_type_of_fg [comm_ring R] [monoid.fg M] : finite_type R (monoid_algebra R M) := add_monoid_algebra.finite_type_of_fg.equiv (to_additive_alg_equiv R M).symm /-- A monoid `M` is finitely generated if and only if `monoid_algebra R M` is of finite type. -/ lemma finite_type_iff_fg [comm_ring R] [nontrivial R] : finite_type R (monoid_algebra R M) ↔ monoid.fg M := ⟨λ h, monoid.fg_iff_add_fg.2 $ add_monoid_algebra.finite_type_iff_fg.1 $ h.equiv $ to_additive_alg_equiv R M, λ h, @monoid_algebra.finite_type_of_fg _ _ _ _ h⟩ /-- If `monoid_algebra R M` is of finite type then `M` is finitely generated. -/ lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (monoid_algebra R M)] : monoid.fg M := finite_type_iff_fg.1 h /-- A group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/ lemma finite_type_iff_group_fg {G : Type*} [comm_group G] [comm_ring R] [nontrivial R] : finite_type R (monoid_algebra R G) ↔ group.fg G := by simpa [group.fg_iff_monoid.fg] using finite_type_iff_fg end monoid_algebra end monoid_algebra
ac234eac88cbb00432198c2463d66a7ee59a796b
076f5040b63237c6dd928c6401329ed5adcb0e44
/answers/exam_1_key.lean
d1f25c5461f8fb571234888a1aa7cbdc7f51c8de
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
7,861
lean
/- THe exam is graded out of 100 points. The regular questions provide opportunity earn 105. There is an extra credit worth 5 points [all or none]. So the maximum possible grade is 110/100. -/ /- #1 [10 points] [Grading: 2 free points + 1 for each correct answer] Complete the following definitions to give examples of literal values of specified types. Use lambda expressions to complete the questions involving function types. Make functions (lambda expressions) simple: we don't care what the functions, do, just that they are of the right types. -/ def n : ℕ := 0 def s : string := "" def b : bool := tt def f1 : ℕ → bool := λ n, tt def f2 : (ℕ → ℕ) → bool := λ f, tt def f3 : (ℕ → ℕ) → (ℕ → ℕ) := λ f, f def t1 : Type := nat def t2 : Type → Type := λ t, t /- #2 [10 points] [Grading: 3 for zero case; 7 for succ case] Complete the following recursive function definition so that the function computes the sum of the natural numbers from 0 to (and including) a given value, n. -/ def sumto : ℕ → ℕ | 0 := 0 | (nat.succ n') := (nat.succ n') + sumto n' /- #3. [5 points] [Grading 3 points for spec, 2 points for the impl; -1 for an answer that is confused but contains the right idea] We have seen that we can write function *specifications* in the language of predicate logic, and specifically in the language of pure functional programming. We also know we can, and generally do, write *implementations* in the language of imperative programming (e.g., in Python or in Java). Complete the following sentence by filling in the blanks to explain the esssential tradeoff between function specifications, in the langugae of predicate logic, and function implementations written in imperative programming languages, respectively. Specifications are generally _______ [clear, understandable, abstract] but less ________ [efficient] while implementations are generally the opposite: less [clear, understandable, abstract] ________ but more _________ [efficient]. -/ /- # 4. [10 points] [Grading: 5 then 3 then 2 for each correct answer] Natural languages, such as English and Mandarin, are very powerful, but they have some fundamental weaknesses when it comes to writing and verifying precise specifications and claims about properties of algorithms and programs. It is for this reason that computer scientists often prefer to express such things using mathematical logic instead of natural language. Name three fundamental weaknesses of natural language when it comes to carrying out such tasks. You may given one-word answers if you wish. A. __________ [ambiguity] B. __________ [inconsistency] C. __________ [uncheckability] -/ /- #5. [10 points] [5 for correct equality, 5 for the ∀] What logical proposition expresses the claim that a given implementation, I, of a function of type ℕ → ℕ, is correct with respect to a specification, S, of the same function? Answer: [∀ (n : ℕ), I n = S n. Answer can be given in English but must include concept that I n = S n *for all* values of n.] -/ /- #6. [10 points] [Grading: 5 points for each correct answer] What Boolean functions do the following definitions define? -/ def mystery1 : bool → bool → bool | tt tt := ff | ff ff := ff | _ _ := tt /- Answer: [xor, exclusive or] -/ def mystery2 : bool → bool → bool | tt ff := ff | _ _ := tt /- Answer: [implies] -/ /- #7. [10 points] [Grading: 10 points for right answer, no partial credit] Define a function that takes a string, s, and a natural number, n, and that returns value of type (list string) in which s is repeated n times. -/ def repeat : string → ℕ → list string | s 0 := list.nil | s (nat.succ n') := list.cons s (repeat s n') /- #8. [10 points] [Grading: 3 point zero case, 7 points for succ case] Definea a polymorphic function that takes a type, α, a value, s : α, and a natural number, n, and that returns a list in which the value, a, is repeated n times. Make the type argument to this function implicit. -/ def poly_repeat {α : Type} : α → ℕ → list α | a 0 := list.nil | a (nat.succ n') := list.cons a (poly_repeat a n') /- #9. [10 points] [6 for data type, 4 for the function definition] Define a data type, an enumerated type, friend_or_foe, with just two terms, one called friend, one called foe. Then define a function called eval that takes two terms, F1 and F2, of this type and returns a term of this type, where the function implements the following table: F1 F2 result friend friend friend friend foe foe foe friend foe foe foe friend -/ inductive friend_or_foe : Type | friend | foe open friend_or_foe def eval : friend_or_foe → friend_or_foe → friend_or_foe | friend friend := friend | friend foe := foe | foe friend := foe | foe foe := friend /- #10. [10 points] We studied the higher-order function, map. In particular, we implemented a version of it, which we called mmap, for functions of type ℕ → ℕ, and for lists of type (list ℕ). The function is reproduced next for your reference. Read and recall how the function works, then continue on to the questions that follow. -/ def mmap : (ℕ → ℕ) → list ℕ → list ℕ | f [] := [] | f (list.cons h t) := list.cons (f h) (mmap f t) -- An example application of this function #eval mmap (λ n, n + 1) [1, 2, 3, 4, 5] /- [Grading: 5 points, 1 for base case, 4 for recursive] A. Write a polymorphic version of this function, called pmap, that takes (1) two type arguments, α and β, (2) a function of type α → β, and (3) a list of values of type α, and that returns the list of values obtained by applying the given function to each value in the given list. Make α and β implicit arguments. -/ def pmap {α β : Type} : (α → β) → list α → list β | f [] := [] | f (list.cons h t) := list.cons (f h) (pmap f t) /- B. [Grading: 5 points, all or nothing] Use #eval to evaluate an application of pmap to a function of type ℕ to bool and a non-empty list of natural numbers. Use a lambda abstraction to give the function argument. It does not matter to us what value the function returns. -/ #eval pmap (λ n : ℕ, tt) [0,1,2,3] /- #11. [10 points] [ Grading: 5 for data type, 5 for 3 correct functions] Define a data type, prod3_nat, with one constructor, triple, that takes three natural numbers as arguments, yielding a term of type prod3_nat. Then write three "projection functions", prod3_nat_fst, prod3_nat_snd, and prod3_nat_thd, each of which takes a prod3_nat value and returns its corresponding component element. Hint: look to see how we defined the prod type, its pair constructor, and its two projection functions. -/ inductive prod3_nat : Type | triple : ℕ → ℕ → ℕ → prod3_nat def prod3_nat_fst : prod3_nat → ℕ | (prod3_nat.triple f s t) := f def prod3_nat_snd : prod3_nat → ℕ | (prod3_nat.triple f s t) := s def prod3_nat_thd : prod3_nat → ℕ | (prod3_nat.triple f s t) := t /- Extra credit. Define prod3 as a version of prod3_nat that is polymorphic in each of its three components; define polymorphic projection functions; and then use them to define a function, rotate_right, that takes a triple, (a, b, c), and returns the triple (c, a, b). (Call your type arguments α, β, and γ - alpha, beta, and gamma). -/ -- Answer here inductive prod3 (α β γ : Type) : Type | triple : α → β → γ → prod3 def prod3_fst {α β γ : Type}: prod3 α β γ → α | (prod3.triple f s t) := f def prod3_snd {α β γ : Type} : prod3 α β γ → β | (prod3.triple f s t) := s def prod3_thd {α β γ : Type} : prod3 α β γ → γ | (prod3.triple f s t) := t def rotate_right {α β γ : Type} : prod3 α β γ → prod3 γ α β | (prod3.triple a b c) := prod3.triple c a b
65d1cc39d020ec9ae071f16ab29e409132c1369f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/lean_core_docs.lean
47284b752a4b5602fa81accf34f34cef8da91d04
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,526
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Bryan Gin-ge Chen, Robert Y. Lewis, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.doc_commands import Mathlib.PostPort namespace Mathlib /-! # Core tactic documentation This file adds the majority of the interactive tactics from core Lean (i.e. pre-mathlib) to the API documentation. ## TODO * Make a PR to core changing core docstrings to the docstrings below, and also changing the docstrings of `cc`, `simp` and `conv` to the ones already in the API docs. * SMT tactics are currently not documented. * `rsimp` and `constructor_matching` are currently not documented. * `dsimp` deserves better documentation. -/ /-- Proves a goal of the form `s = t` when `s` and `t` are expressions built up out of a binary operation, and equality can be proved using associativity and commutativity of that operation. -/ /-- `by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax `by_cases h : p`. If `p` is not already decidable, `by_cases` will use the instance `classical.prop_decidable p`. -/ /-- If the target of the main goal is a proposition `p`, `by_contra h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `open_locale classical` (or `local attribute [instance, priority 10] classical.prop_decidable` if you are not using mathlib). -/ /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` is a more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. `casesm` is shorthand for `cases_matching`. Example: The following tactic destructs all conjunctions and disjunctions in the current context. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ /-- * `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` * `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` * `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` * `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current context. ``` cases_type* or and ``` -/ /-- Close goals of the form `n ≠ m` when `n` and `m` have type `nat`, `char`, `string`, `int` or `fin sz`, and they are literals. It also closes goals of the form `n < m`, `n > m`, `n ≤ m` and `n ≥ m` for `nat`. If the goal is of the form `n = m`, then it tries to close it using reflexivity. In mathlib, consider using `norm_num` instead for numeric types. -/ /-- The `congr` tactic attempts to identify both sides of an equality goal `A = B`, leaving as new goals the subterms of `A` and `B` which are not definitionally equal. Example: suppose the goal is `x * f y = g w * f z`. Then `congr` will produce two goals: `x = g w` and `y = z`. If `x y : t`, and an instance `subsingleton t` is in scope, then any goals of the form `x = y` are solved automatically. Note that `congr` can be over-aggressive at times; the `congr'` tactic in mathlib provides a more refined approach, by taking a parameter that limits the recursion depth. -/ /-- A variant of `rw` that uses the unifier more aggressively, unfolding semireducible definitions. -/ /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. Note: in mathlib, the `use` tactic is an equivalent tactic which sometimes is smarter with unification. -/ /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. Note also the mathlib tactic `ext`, which applies as many extensionality lemmas as possible. -/ /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. The variant `intro z` uses the identifier `z` to name the new hypothesis. The variant `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ /-- `left` applies the first constructor when the type of the target is an inductive data type with two constructors. Similarly, `right` applies the second constructor. -/ /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. Note the related mathlib tactic `set a := t with h`, which adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. -/ /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ /-- `rw e` applies an equation or iff `e` as a rewrite rule to the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rw [e₁, ..., eₙ]` applies the given rules sequentially. `rw e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. `rewrite` is synonymous with `rw`. -/ /- conv mode tactics -/ /-- Navigate to the left-hand-side of a relation. A goal of `| a = b` will turn into the the goal `| a`. -/ /-- Navigate to the right-hand-side of a relation. A goal of `| a = b` will turn into the the goal `| b`. -/ /-- Navigate into every argument of the current head function. A target of `| (a * b) * c` will turn into the two targets `| a * b` and `| c`. -/ /-- Navigate into the contents of top-level `λ` binders. A target of `| λ a, a + b` will turn into the target `| a + b` and introduce `a` into the local context. If there are multiple binders, all of them will be entered, and if there are none, this tactic is a no-op. -/ /-- Navigate into the first scope matching the expression. For a target of `| ∀ c, a + (b + c) = 1`, `find (b + _) { ... }` will run the tactics within the `{}` with a target of `| b + c`. -/ /-- Navigate into the numbered scopes matching the expression. For a target of `| λ c, 10 * c + 20 * c + 30 * c`, `for (_ * _) [1, 3] { ... }` will run the tactics within the `{}` with first a target of `| 10 * c`, then a target of `| 30 * c`. -/ /-- End conversion of the current goal. This is often what is needed when muscle memory would type `sorry`.
af8e0c7d32d757ffefd3037ba9ae3ff98446ed9a
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/run/tacticExtOverlap.lean
c3608f2d9942c30c2d8cac86de78f64bcdc9c426
[ "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
549
lean
open Lean syntax (name := myintro) "intros" sepBy(ident, ",") : tactic macro_rules [myintro] | `(tactic| intros $x,*) => pure $ Syntax.node `Lean.Parser.Tactic.intros #[Syntax.atom {} "intros", mkNullNode x] theorem tst1 {p q : Prop} : p → q → p := by { intros h1, h2; assumption } theorem tst2 {p q : Prop} : p → q → p := by { intros h1; -- the builtin and myintro overlap here. intros h2; -- the builtin and myintro overlap here. assumption } theorem tst3 {p q : Prop} : p → q → p := by { intros h1 h2; assumption }
6350082a6cfe824f27affd50b8f29cd54f42edba
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/test/where.lean
56f6501ab73cb8d11947049318f234371946ea47
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
8,399
lean
import data.multiset import tactic.where -- First set up the testing framework... section framework -- Note that we cannot have any explicit `open`s, we are currently working around this bug: -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/What's.20the.20deal.20with.20.60open.60 @[user_command] meta def run_parser_from_command_cmd (_ : interactive.parse $ lean.parser.tk "run_parser_from_command") : lean.parser unit := do ns ← lean.parser.ident, let ns := if ns = `NONE then name.anonymous else ns, n ← lean.parser.ident, prog ← lean.parser.of_tactic $ tactic.mk_const (ns ++ n) >>= tactic.eval_expr (lean.parser unit), if ns = name.anonymous then tactic.skip else lean.parser.emit_code_here $ "namespace " ++ ns.to_string, prog, if ns = name.anonymous then tactic.skip else lean.parser.emit_code_here $ "end " ++ ns.to_string meta def remove_dot_aux : list char → list char | [] := [] | (c :: rest) := (if c = '.' then '_' else c) :: remove_dot_aux rest meta def remove_dot (s : string) : string := (remove_dot_aux s.data).as_string -- NOTE We must emit fully qualified names below in order to not influence the real tests! @[user_command] meta def run_parser_from_tactic_cmd (_ : interactive.parse $ lean.parser.tk "run_parser_from_tactic") : lean.parser unit := do ns ← lean.parser.ident, let ns := if ns = `NONE then name.anonymous else ns, n ← lean.parser.ident, let tac_name := "try_test_" ++ (remove_dot (ns ++ n).to_string), lean.parser.emit_code_here $ "meta def tactic.interactive." ++ tac_name ++ " (_ : interactive.parse " ++ (ns ++ n).to_string ++ ")" ++ ": tactic unit := tactic.triv", if ns = name.anonymous then tactic.skip else lean.parser.emit_code_here $ "namespace " ++ ns.to_string, lean.parser.emit_code_here $ "example : true := by " ++ (name.mk_string tac_name name.anonymous).to_string, if ns = name.anonymous then tactic.skip else lean.parser.emit_code_here $ "end " ++ ns.to_string meta def assert_name_eq (n₁ n₂ : name) : lean.parser unit := if n₁ = n₂ then return () else tactic.fail sformat!"violation: '{n₁}' ≠ '{n₂}'!" meta def assert_list_noorder_eq {α : Type} [decidable_eq α] [has_to_string α] (l₁ l₂ : list α) : lean.parser unit := if (l₁ : multiset α) = (l₂ : multiset α) then return () else tactic.fail sformat!"violation: '{l₁}' ≠ '{l₂}'!" meta def assert_where_msg_eq (s : string) : lean.parser unit := do tw ← where.build_msg, if s = tw then return () else tactic.fail sformat!"violation:\n'\n{tw}\n'\n\n ≠\n\n'\n{s}\n'!" -- Test the test framework... meta def dummy : lean.parser unit := return () run_parser_from_command NONE dummy run_parser_from_tactic NONE dummy end framework -- TESTS START -- TEST: `#where` output -- NOTE: This section must come first because of the `open_namespaces` bug referenced above. -- NOTE: All other sections have correct answers, but the order of variables (say) may be safely -- reordered here: changes to `#where` which break this set of tests are possible, without an -- error. meta def test_output_1 : lean.parser unit := assert_where_msg_eq "namespace [root namespace]\n\n\n\n\nend [root namespace]\n" meta def test_output_2 : lean.parser unit := assert_where_msg_eq "namespace [root namespace]\n\nopen list nat\n\n\n\nend [root namespace]\n" meta def test_output_3 : lean.parser unit := assert_where_msg_eq "namespace [root namespace]\n\nopen list nat\nvariables {c : ℕ → list ℕ} (b a : ℕ) [decidable_eq : ℕ]\n\n\n\nend [root namespace]\n" meta def test_output_4 : lean.parser unit := assert_where_msg_eq "namespace [root namespace]\n\nopen list nat\nvariables {c : ℕ → list ℕ} (b a : ℕ) [decidable_eq : ℕ]\ninclude c a\n\n\n\nend [root namespace]\n" meta def test_output_5 : lean.parser unit := assert_where_msg_eq "namespace a\n\nopen list nat\nvariables {c : ℕ → list ℕ} (b a : ℕ) [decidable_eq : ℕ]\ninclude c a\n\n\n\nend a\n" meta def test_output_6 : lean.parser unit := assert_where_msg_eq "namespace a.b\n\nopen a list nat\nvariables {c : ℕ → list ℕ} (b a : ℕ) [decidable_eq : ℕ]\ninclude c a\n\n\n\nend a.b\n" section b1 -- #where run_parser_from_command NONE test_output_1 open nat list -- #where run_parser_from_command NONE test_output_2 variables (a b : ℕ) [decidable_eq : ℕ] {c : ℕ → list ℕ} -- #where run_parser_from_command NONE test_output_3 include a c -- #where run_parser_from_command NONE test_output_4 end b1 namespace a variables (a b : ℕ) [decidable_eq : ℕ] {c : ℕ → list ℕ} include a c open nat list -- #where run_parser_from_command NONE test_output_5 namespace b -- #where run_parser_from_command NONE test_output_6 end b end a -- TEST: `lean.parser.get_current_namespace` -- Check no namespace meta def test_no_namespace : lean.parser unit := do ns ← lean.parser.get_current_namespace, assert_name_eq ns name.anonymous, return () run_parser_from_command NONE test_no_namespace run_parser_from_tactic NONE test_no_namespace section a1 open nat list -- Check no namespace with opens meta def test_no_namespace_w_opens : lean.parser unit := do ns ← lean.parser.get_current_namespace, assert_name_eq ns name.anonymous, return () run_parser_from_command NONE test_no_namespace_w_opens run_parser_from_tactic NONE test_no_namespace_w_opens end a1 namespace test1 -- Check a namespace meta def test_1 : lean.parser unit := do ns ← lean.parser.get_current_namespace, assert_name_eq ns `test1, return () open nat list -- Check a 2 namespaces with opens meta def test_2 : lean.parser unit := do ns ← lean.parser.get_current_namespace, assert_name_eq ns `test1, return () end test1 run_parser_from_command test1 test_1 run_parser_from_command test1 test_2 run_parser_from_tactic test1 test_1 run_parser_from_tactic test1 test_2 namespace test1.test2 -- Check a 2 namespaces meta def test_1 : lean.parser unit := do ns ← lean.parser.get_current_namespace, assert_name_eq ns `test1.test2, return () open nat list -- Check a 2 namespaces with opens meta def test_2 : lean.parser unit := do ns ← lean.parser.get_current_namespace, assert_name_eq ns `test1.test2, return () end test1.test2 run_parser_from_command test1.test2 test_1 run_parser_from_command test1.test2 test_2 run_parser_from_tactic test1.test2 test_1 run_parser_from_tactic test1.test2 test_2 -- TEST: `lean.parser.get_variables` and `lean.parser.get_included_variables` -- Check no variables meta def test_no_variables : lean.parser unit := do ns ← lean.parser.get_variables, assert_list_noorder_eq (ns.map prod.fst) [], return () run_parser_from_command NONE test_no_variables run_parser_from_tactic NONE test_no_variables section a1 variables (a : ℕ) -- Check 1 variable from command meta def test_1_variable_from_command : lean.parser unit := do ns ← lean.parser.get_variables, assert_list_noorder_eq (ns.map prod.fst) [`a], return () run_parser_from_command NONE test_1_variable_from_command -- Check 1 variable from tactic meta def test_1_variable_from_tactic : lean.parser unit := do ns ← lean.parser.get_variables, assert_list_noorder_eq (ns.map prod.fst) [], return () run_parser_from_tactic NONE test_1_variable_from_tactic end a1 namespace a2 variables (a : ℕ) -- Check 1 variable from command inside namespace meta def test_1_variable_from_command : lean.parser unit := do ns ← lean.parser.get_variables, assert_list_noorder_eq (ns.map prod.fst) [`a], return () run_parser_from_command NONE test_1_variable_from_command -- Check 1 variable from tactic inside namespace meta def test_1_variable_from_tactic : lean.parser unit := do ns ← lean.parser.get_variables, assert_list_noorder_eq (ns.map prod.fst) [], return () run_parser_from_tactic NONE test_1_variable_from_tactic end a2 section a3 -- Check 3 variables with 1 include meta def test_2_variable_from_command : lean.parser unit := do ns ← lean.parser.get_variables, assert_list_noorder_eq (ns.map prod.fst) [`a, `b, `c], ns ← lean.parser.get_included_variables, assert_list_noorder_eq (ns.map prod.fst) [`b], return () variables (a b c : ℕ) include b run_parser_from_command NONE test_2_variable_from_command end a3
dc587d823595014a8da0eda6b1c7c889e0b665b6
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/measure/hausdorff.lean
eacda09aa45054a91ffcb7658120df8fd92fd230
[ "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
44,799
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.metric_space.metric_separated import measure_theory.constructions.borel_space import measure_theory.measure.lebesgue import analysis.special_functions.pow import topology.metric_space.holder import data.equiv.list /-! # Hausdorff measure and metric (outer) measures In this file we define the `d`-dimensional Hausdorff measure on an (extended) metric space `X` and the Hausdorff dimension of a set in an (extended) metric space. Let `μ d δ` be the maximal outer measure such that `μ d δ s ≤ (emetric.diam s) ^ d` for every set of diameter less than `δ`. Then the Hausdorff measure `μH[d] s` of `s` is defined as `⨆ δ > 0, μ d δ s`. By Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, this is a Borel measure on `X`. The value of `μH[d]`, `d > 0`, on a set `s` (measurable or not) is given by ``` μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, emetric.diam (t n) ^ d ``` For every set `s` for any `d < d'` we have either `μH[d] s = ∞` or `μH[d'] s = 0`, see `measure_theory.measure.hausdorff_measure_zero_or_top`. In `topology.metric_space.hausdorff_dimension` we use this fact to define the Hausdorff dimension `dimH` of a set in an (extended) metric space. We also define two generalizations of the Hausdorff measure. In one generalization (see `measure_theory.measure.mk_metric`) we take any function `m (diam s)` instead of `(diam s) ^ d`. In an even more general definition (see `measure_theory.measure.mk_metric'`) we use any function of `m : set X → ℝ≥0∞`. Some authors start with a partial function `m` defined only on some sets `s : set X` (e.g., only on balls or only on measurable sets). This is equivalent to our definition applied to `measure_theory.extend m`. We also define a predicate `measure_theory.outer_measure.is_metric` which says that an outer measure is additive on metric separated pairs of sets: `μ (s ∪ t) = μ s + μ t` provided that `⨅ (x ∈ s) (y ∈ t), edist x y ≠ 0`. This is the property required for the Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, so we prove this theorem for any metric outer measure, then prove that outer measures constructed using `mk_metric'` are metric outer measures. ## Main definitions * `measure_theory.outer_measure.is_metric`: an outer measure `μ` is called *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s` and `t`. A metric outer measure in a Borel extended metric space is guaranteed to satisfy the Caratheodory condition, see `measure_theory.outer_measure.is_metric.borel_le_caratheodory`. * `measure_theory.outer_measure.mk_metric'` and its particular case `measure_theory.outer_measure.mk_metric`: a construction of an outer measure that is guaranteed to be metric. Both constructions are generalizations of the Hausdorff measure. The same measures interpreted as Borel measures are called `measure_theory.measure.mk_metric'` and `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure` a.k.a. `μH[d]`: the `d`-dimensional Hausdorff measure. There are many definitions of the Hausdorff measure that differ from each other by a multiplicative constant. We put `μH[d] s = ⨆ r > 0, ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬set.subsingleton (t n)), (emetric.diam (t n)) ^ d`, see `measure_theory.measure.hausdorff_measure_apply'`. In the most interesting case `0 < d` one can omit the `⨆ (ht : ¬set.subsingleton (t n))` part. ## Main statements ### Basic properties * `measure_theory.outer_measure.is_metric.borel_le_caratheodory`: if `μ` is a metric outer measure on an extended metric space `X` (that is, it is additive on pairs of metric separated sets), then every Borel set is Caratheodory measurable (hence, `μ` defines an actual `measure_theory.measure`). See also `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure_mono`: `μH[d] s` is an antitone function of `d`. * `measure_theory.measure.hausdorff_measure_zero_or_top`: if `d₁ < d₂`, then for any `s`, either `μH[d₂] s = 0` or `μH[d₁] s = ∞`. Together with the previous lemma, this means that `μH[d] s` is equal to infinity on some ray `(-∞, D)` and is equal to zero on `(D, +∞)`, where `D` is a possibly infinite number called the *Hausdorff dimension* of `s`; `μH[D] s` can be zero, infinity, or anything in between. * `measure_theory.measure.no_atoms_hausdorff`: Hausdorff measure has no atoms. ### Hausdorff measure in `ℝⁿ` * `measure_theory.hausdorff_measure_pi_real`: for a nonempty `ι`, `μH[card ι]` on `ι → ℝ` equals Lebesgue measure. ## Notations We use the following notation localized in `measure_theory`. - `μH[d]` : `measure_theory.measure.hausdorff_measure d` ## Implementation notes There are a few similar constructions called the `d`-dimensional Hausdorff measure. E.g., some sources only allow coverings by balls and use `r ^ d` instead of `(diam s) ^ d`. While these construction lead to different Hausdorff measures, they lead to the same notion of the Hausdorff dimension. ## TODO * prove that `1`-dimensional Hausdorff measure on `ℝ` equals `volume`; * prove a similar statement for `ℝ × ℝ`. ## References * [Herbert Federer, Geometric Measure Theory, Chapter 2.10][Federer1996] ## Tags Hausdorff measure, measure, metric measure -/ open_locale nnreal ennreal topological_space big_operators open emetric set function filter encodable finite_dimensional topological_space noncomputable theory variables {ι X Y : Type*} [emetric_space X] [emetric_space Y] namespace measure_theory namespace outer_measure /-! ### Metric outer measures In this section we define metric outer measures and prove Caratheodory theorem: a metric outer measure has the Caratheodory property. -/ /-- We say that an outer measure `μ` in an (e)metric space is *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s`, `t`. -/ def is_metric (μ : outer_measure X) : Prop := ∀ (s t : set X), is_metric_separated s t → μ (s ∪ t) = μ s + μ t namespace is_metric variables {μ : outer_measure X} /-- A metric outer measure is additive on a finite set of pairwise metric separated sets. -/ lemma finset_Union_of_pairwise_separated (hm : is_metric μ) {I : finset ι} {s : ι → set X} (hI : ∀ (i ∈ I) (j ∈ I), i ≠ j → is_metric_separated (s i) (s j)) : μ (⋃ i ∈ I, s i) = ∑ i in I, μ (s i) := begin classical, induction I using finset.induction_on with i I hiI ihI hI, { simp }, simp only [finset.mem_insert] at hI, rw [finset.set_bUnion_insert, hm, ihI, finset.sum_insert hiI], exacts [λ i hi j hj hij, (hI i (or.inr hi) j (or.inr hj) hij), is_metric_separated.finset_Union_right (λ j hj, hI i (or.inl rfl) j (or.inr hj) (ne_of_mem_of_not_mem hj hiI).symm)] end /-- Caratheodory theorem. If `m` is a metric outer measure, then every Borel measurable set `t` is Caratheodory measurable: for any (not necessarily measurable) set `s` we have `μ (s ∩ t) + μ (s \ t) = μ s`. -/ lemma borel_le_caratheodory (hm : is_metric μ) : borel X ≤ μ.caratheodory := begin rw [borel_eq_generate_from_is_closed], refine measurable_space.generate_from_le (λ t ht, μ.is_caratheodory_iff_le.2 $ λ s, _), set S : ℕ → set X := λ n, {x ∈ s | (↑n)⁻¹ ≤ inf_edist x t}, have n0 : ∀ {n : ℕ}, (n⁻¹ : ℝ≥0∞) ≠ 0, from λ n, ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top, have Ssep : ∀ n, is_metric_separated (S n) t, from λ n, ⟨n⁻¹, n0, λ x hx y hy, hx.2.trans $ inf_edist_le_edist_of_mem hy⟩, have Ssep' : ∀ n, is_metric_separated (S n) (s ∩ t), from λ n, (Ssep n).mono subset.rfl (inter_subset_right _ _), have S_sub : ∀ n, S n ⊆ s \ t, from λ n, subset_inter (inter_subset_left _ _) (Ssep n).subset_compl_right, have hSs : ∀ n, μ (s ∩ t) + μ (S n) ≤ μ s, from λ n, calc μ (s ∩ t) + μ (S n) = μ (s ∩ t ∪ S n) : eq.symm $ hm _ _ $ (Ssep' n).symm ... ≤ μ (s ∩ t ∪ s \ t) : by { mono*, exact le_rfl } ... = μ s : by rw [inter_union_diff], have Union_S : (⋃ n, S n) = s \ t, { refine subset.antisymm (Union_subset S_sub) _, rintro x ⟨hxs, hxt⟩, rw mem_iff_inf_edist_zero_of_closed ht at hxt, rcases ennreal.exists_inv_nat_lt hxt with ⟨n, hn⟩, exact mem_Union.2 ⟨n, hxs, hn.le⟩ }, /- Now we have `∀ n, μ (s ∩ t) + μ (S n) ≤ μ s` and we need to prove `μ (s ∩ t) + μ (⋃ n, S n) ≤ μ s`. We can't pass to the limit because `μ` is only an outer measure. -/ by_cases htop : μ (s \ t) = ∞, { rw [htop, ennreal.add_top, ← htop], exact μ.mono (diff_subset _ _) }, suffices : μ (⋃ n, S n) ≤ ⨆ n, μ (S n), calc μ (s ∩ t) + μ (s \ t) = μ (s ∩ t) + μ (⋃ n, S n) : by rw Union_S ... ≤ μ (s ∩ t) + ⨆ n, μ (S n) : add_le_add le_rfl this ... = ⨆ n, μ (s ∩ t) + μ (S n) : ennreal.add_supr ... ≤ μ s : supr_le hSs, /- It suffices to show that `∑' k, μ (S (k + 1) \ S k) ≠ ∞`. Indeed, if we have this, then for all `N` we have `μ (⋃ n, S n) ≤ μ (S N) + ∑' k, m (S (N + k + 1) \ S (N + k))` and the second term tends to zero, see `outer_measure.Union_nat_of_monotone_of_tsum_ne_top` for details. -/ have : ∀ n, S n ⊆ S (n + 1), from λ n x hx, ⟨hx.1, le_trans (ennreal.inv_le_inv.2 $ ennreal.coe_nat_le_coe_nat.2 n.le_succ) hx.2⟩, refine (μ.Union_nat_of_monotone_of_tsum_ne_top this _).le, clear this, /- While the sets `S (k + 1) \ S k` are not pairwise metric separated, the sets in each subsequence `S (2 * k + 1) \ S (2 * k)` and `S (2 * k + 2) \ S (2 * k)` are metric separated, so `m` is additive on each of those sequences. -/ rw [← tsum_even_add_odd ennreal.summable ennreal.summable, ennreal.add_ne_top], suffices : ∀ a, (∑' (k : ℕ), μ (S (2 * k + 1 + a) \ S (2 * k + a))) ≠ ∞, from ⟨by simpa using this 0, by simpa using this 1⟩, refine λ r, ne_top_of_le_ne_top htop _, rw [← Union_S, ennreal.tsum_eq_supr_nat, supr_le_iff], intro n, rw [← hm.finset_Union_of_pairwise_separated], { exact μ.mono (Union_subset $ λ i, Union_subset $ λ hi x hx, mem_Union.2 ⟨_, hx.1⟩) }, suffices : ∀ i j, i < j → is_metric_separated (S (2 * i + 1 + r)) (s \ S (2 * j + r)), from λ i _ j _ hij, hij.lt_or_lt.elim (λ h, (this i j h).mono (inter_subset_left _ _) (λ x hx, ⟨hx.1.1, hx.2⟩)) (λ h, (this j i h).symm.mono (λ x hx, ⟨hx.1.1, hx.2⟩) (inter_subset_left _ _)), intros i j hj, have A : ((↑(2 * j + r))⁻¹ : ℝ≥0∞) < (↑(2 * i + 1 + r))⁻¹, by { rw [ennreal.inv_lt_inv, ennreal.coe_nat_lt_coe_nat], linarith }, refine ⟨(↑(2 * i + 1 + r))⁻¹ - (↑(2 * j + r))⁻¹, by simpa using A, λ x hx y hy, _⟩, have : inf_edist y t < (↑(2 * j + r))⁻¹, from not_le.1 (λ hle, hy.2 ⟨hy.1, hle⟩), rcases inf_edist_lt_iff.mp this with ⟨z, hzt, hyz⟩, have hxz : (↑(2 * i + 1 + r))⁻¹ ≤ edist x z, from le_inf_edist.1 hx.2 _ hzt, apply ennreal.le_of_add_le_add_right hyz.ne_top, refine le_trans _ (edist_triangle _ _ _), refine (add_le_add le_rfl hyz.le).trans (eq.trans_le _ hxz), rw [tsub_add_cancel_of_le A.le] end lemma le_caratheodory [measurable_space X] [borel_space X] (hm : is_metric μ) : ‹measurable_space X› ≤ μ.caratheodory := by { rw @borel_space.measurable_eq X _ _, exact hm.borel_le_caratheodory } end is_metric /-! ### Constructors of metric outer measures In this section we provide constructors `measure_theory.outer_measure.mk_metric'` and `measure_theory.outer_measure.mk_metric` and prove that these outer measures are metric outer measures. We also prove basic lemmas about `map`/`comap` of these measures. -/ /-- Auxiliary definition for `outer_measure.mk_metric'`: given a function on sets `m : set X → ℝ≥0∞`, returns the maximal outer measure `μ` such that `μ s ≤ m s` for any set `s` of diameter at most `r`.-/ def mk_metric'.pre (m : set X → ℝ≥0∞) (r : ℝ≥0∞) : outer_measure X := bounded_by $ extend (λ s (hs : diam s ≤ r), m s) /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `mk_metric'.pre m r` over `r > 0`. Equivalently, it is the limit of `mk_metric'.pre m r` as `r` tends to zero from the right. -/ def mk_metric' (m : set X → ℝ≥0∞) : outer_measure X := ⨆ r > 0, mk_metric'.pre m r /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞` and `r > 0`, let `μ r` be the maximal outer measure such that `μ s ≤ m (emetric.diam s)` whenever `emetric.diam s < r`. Then `mk_metric m = ⨆ r > 0, μ r`. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : outer_measure X := mk_metric' (λ s, m (diam s)) namespace mk_metric' variables {m : set X → ℝ≥0∞} {r : ℝ≥0∞} {μ : outer_measure X} {s : set X} lemma le_pre : μ ≤ pre m r ↔ ∀ s : set X, diam s ≤ r → μ s ≤ m s := by simp only [pre, le_bounded_by, extend, le_infi_iff] lemma pre_le (hs : diam s ≤ r) : pre m r s ≤ m s := (bounded_by_le _).trans $ infi_le _ hs lemma mono_pre (m : set X → ℝ≥0∞) {r r' : ℝ≥0∞} (h : r ≤ r') : pre m r' ≤ pre m r := le_pre.2 $ λ s hs, pre_le (hs.trans h) lemma mono_pre_nat (m : set X → ℝ≥0∞) : monotone (λ k : ℕ, pre m k⁻¹) := λ k l h, le_pre.2 $ λ s hs, pre_le (hs.trans $ by simpa) lemma tendsto_pre (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ r, pre m r s) (𝓝[>] 0) (𝓝 $ mk_metric' m s) := begin rw [← map_coe_Ioi_at_bot, tendsto_map'_iff], simp only [mk_metric', outer_measure.supr_apply, supr_subtype'], exact tendsto_at_bot_supr (λ r r' hr, mono_pre _ hr _) end lemma tendsto_pre_nat (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ n : ℕ, pre m n⁻¹ s) at_top (𝓝 $ mk_metric' m s) := begin refine (tendsto_pre m s).comp (tendsto_inf.2 ⟨ennreal.tendsto_inv_nat_nhds_zero, _⟩), refine tendsto_principal.2 (eventually_of_forall $ λ n, _), simp end lemma eq_supr_nat (m : set X → ℝ≥0∞) : mk_metric' m = ⨆ n : ℕ, mk_metric'.pre m n⁻¹ := begin ext1 s, rw supr_apply, refine tendsto_nhds_unique (mk_metric'.tendsto_pre_nat m s) (tendsto_at_top_supr $ λ k l hkl, mk_metric'.mono_pre_nat m hkl s) end /-- `measure_theory.outer_measure.mk_metric'.pre m r` is a trimmed measure provided that `m (closure s) = m s` for any set `s`. -/ lemma trim_pre [measurable_space X] [opens_measurable_space X] (m : set X → ℝ≥0∞) (hcl : ∀ s, m (closure s) = m s) (r : ℝ≥0∞) : (pre m r).trim = pre m r := begin refine le_antisymm (le_pre.2 $ λ s hs, _) (le_trim _), rw trim_eq_infi, refine (infi_le_of_le (closure s) $ infi_le_of_le subset_closure $ infi_le_of_le measurable_set_closure ((pre_le _).trans_eq (hcl _))), rwa diam_closure end end mk_metric' /-- An outer measure constructed using `outer_measure.mk_metric'` is a metric outer measure. -/ lemma mk_metric'_is_metric (m : set X → ℝ≥0∞) : (mk_metric' m).is_metric := begin rintros s t ⟨r, r0, hr⟩, refine tendsto_nhds_unique_of_eventually_eq (mk_metric'.tendsto_pre _ _) ((mk_metric'.tendsto_pre _ _).add (mk_metric'.tendsto_pre _ _)) _, rw [← pos_iff_ne_zero] at r0, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, r0⟩], rintro ε ⟨ε0, εr⟩, refine bounded_by_union_of_top_of_nonempty_inter _, rintro u ⟨x, hxs, hxu⟩ ⟨y, hyt, hyu⟩, have : ε < diam u, from εr.trans_le ((hr x hxs y hyt).trans $ edist_le_diam_of_mem hxu hyu), exact infi_eq_top.2 (λ h, (this.not_le h).elim) end /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[≥] 0] c • m₂) : (mk_metric m₁ : outer_measure X) ≤ c • mk_metric m₂ := begin classical, rcases (mem_nhds_within_Ici_iff_exists_Ico_subset' ennreal.zero_lt_one).1 hle with ⟨r, hr0, hr⟩, refine λ s, le_of_tendsto_of_tendsto (mk_metric'.tendsto_pre _ s) (ennreal.tendsto.const_mul (mk_metric'.tendsto_pre _ s) (or.inr hc)) (mem_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_rfl, hr0⟩) (λ r' hr', _)), simp only [mem_set_of_eq, mk_metric'.pre], rw [← smul_apply, smul_bounded_by hc], refine le_bounded_by.2 (λ t, (bounded_by_le _).trans _) _, simp only [smul_eq_mul, pi.smul_apply, extend, infi_eq_if], split_ifs with ht ht, { apply hr, exact ⟨zero_le _, ht.trans_lt hr'.2⟩ }, { simp [h0] } end /-- If `m₁ d ≤ m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[≥] 0] m₂) : (mk_metric m₁ : outer_measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top ennreal.zero_lt_one.ne' _; simp * } lemma isometry_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone m ∨ surjective f) : comap f (mk_metric m) = mk_metric m := begin simp only [mk_metric, mk_metric', mk_metric'.pre, induced_outer_measure, comap_supr], refine supr_congr id surjective_id (λ ε, supr_congr id surjective_id $ λ hε, _), rw comap_bounded_by _ (H.imp (λ h_mono, _) id), { congr' with s : 1, apply extend_congr, { simp [hf.ediam_image] }, { intros, simp [hf.injective.subsingleton_image_iff, hf.ediam_image] } }, { assume s t hst, simp only [extend, le_infi_iff], assume ht, apply le_trans _ (h_mono (diam_mono hst)), simp only [(diam_mono hst).trans ht, le_refl, cinfi_pos] } end lemma isometry_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone m ∨ surjective f) : map f (mk_metric m) = restrict (range f) (mk_metric m) := by rw [← isometry_comap_mk_metric _ hf H, map_comap] lemma isometric_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : comap f (mk_metric m) = mk_metric m := isometry_comap_mk_metric _ f.isometry (or.inr f.surjective) lemma isometric_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : map f (mk_metric m) = mk_metric m := by rw [← isometric_comap_mk_metric _ f, map_comap_of_surjective f.surjective] lemma trim_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : outer_measure X).trim = mk_metric m := begin simp only [mk_metric, mk_metric'.eq_supr_nat, trim_supr], congr' 1 with n : 1, refine mk_metric'.trim_pre _ (λ s, _) _, simp end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : outer_measure X) (r : ℝ≥0∞) (h0 : 0 < r) (hr : ∀ s, diam s ≤ r → μ s ≤ m (diam s)) : μ ≤ mk_metric m := le_bsupr_of_le r h0 $ mk_metric'.le_pre.2 $ λ s hs, hr _ hs end outer_measure /-! ### Metric measures In this section we use `measure_theory.outer_measure.to_measure` and theorems about `measure_theory.outer_measure.mk_metric'`/`measure_theory.outer_measure.mk_metric` to define `measure_theory.measure.mk_metric'`/`measure_theory.measure.mk_metric`. We also restate some lemmas about metric outer measures for metric measures. -/ namespace measure variables [measurable_space X] [borel_space X] /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all `s`. While each `μ r` is an *outer* measure, the supremum is a measure. -/ def mk_metric' (m : set X → ℝ≥0∞) : measure X := (outer_measure.mk_metric' m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞`, `mk_metric m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all sets `s` that contain at least two points. While each `mk_metric'.pre` is an *outer* measure, the supremum is a measure. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : measure X := (outer_measure.mk_metric m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory @[simp] lemma mk_metric'_to_outer_measure (m : set X → ℝ≥0∞) : (mk_metric' m).to_outer_measure = (outer_measure.mk_metric' m).trim := rfl @[simp] lemma mk_metric_to_outer_measure (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : measure X).to_outer_measure = outer_measure.mk_metric m := outer_measure.trim_mk_metric m end measure lemma outer_measure.coe_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : ⇑(outer_measure.mk_metric m : outer_measure X) = measure.mk_metric m := by rw [← measure.mk_metric_to_outer_measure, coe_to_outer_measure] namespace measure variables [measurable_space X] [borel_space X] /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[≥] 0] c • m₂) : (mk_metric m₁ : measure X) ≤ c • mk_metric m₂ := begin intros s hs, rw [← outer_measure.coe_mk_metric, coe_smul, ← outer_measure.coe_mk_metric], exact outer_measure.mk_metric_mono_smul hc h0 hle s end /-- If `m₁ d ≤ m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[≥] 0] m₂) : (mk_metric m₁ : measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top ennreal.zero_lt_one.ne' _; simp * } /-- A formula for `measure_theory.measure.mk_metric`. -/ lemma mk_metric_apply (m : ℝ≥0∞ → ℝ≥0∞) (s : set X) : mk_metric m s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (h : s ⊆ Union t) (h' : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (h : (t n).nonempty), m (diam (t n)) := begin -- We mostly unfold the definitions but we need to switch the order of `∑'` and `⨅` classical, simp only [← outer_measure.coe_mk_metric, outer_measure.mk_metric, outer_measure.mk_metric', outer_measure.supr_apply, outer_measure.mk_metric'.pre, outer_measure.bounded_by_apply, extend], refine supr_congr (λ r, r) surjective_id (λ r, supr_congr_Prop iff.rfl $ λ hr, infi_congr _ surjective_id $ λ t, infi_congr_Prop iff.rfl $ λ ht, _), by_cases htr : ∀ n, diam (t n) ≤ r, { rw [infi_eq_if, if_pos htr], congr' 1 with n : 1, simp only [infi_eq_if, htr n, id, if_true, supr_and'] }, { rw [infi_eq_if, if_neg htr], push_neg at htr, rcases htr with ⟨n, hn⟩, refine ennreal.tsum_eq_top_of_eq_top ⟨n, _⟩, rw [supr_eq_if, if_pos, infi_eq_if, if_neg], exact hn.not_le, rcases diam_pos_iff.1 ((zero_le r).trans_lt hn) with ⟨x, hx, -⟩, exact ⟨x, hx⟩ } end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : measure X) (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → μ s ≤ m (diam s)) : μ ≤ mk_metric m := begin rw [← to_outer_measure_le, mk_metric_to_outer_measure], exact outer_measure.le_mk_metric m μ.to_outer_measure ε h₀ h end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of encodable types. -/ lemma mk_metric_le_liminf_tsum {β : Type*} {ι : β → Type*} [∀ n, encodable (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf l (λ n, ∑' i, m (diam (t n i))) := begin simp only [mk_metric_apply], refine bsupr_le (λ ε hε, _), refine le_of_forall_le_of_dense (λ c hc, _), rcases ((frequently_lt_of_liminf_lt (by apply_auto_param) hc).and_eventually ((hr.eventually (gt_mem_nhds hε)).and (ht.and hst))).exists with ⟨n, hn, hrn, htn, hstn⟩, set u : ℕ → set X := λ j, ⋃ b ∈ decode₂ (ι n) j, t n b, refine binfi_le_of_le u (by rwa Union_decode₂) _, refine infi_le_of_le (λ j, _) _, { rw emetric.diam_Union_mem_option, exact bsupr_le (λ _ _, (htn _).trans hrn.le) }, { calc (∑' (j : ℕ), ⨆ (h : (u j).nonempty), m (diam (u j))) = _ : tsum_Union_decode₂ (λ t : set X, ⨆ (h : t.nonempty), m (diam t)) (by simp) _ ... ≤ ∑' (i : ι n), m (diam (t n i)) : ennreal.tsum_le_tsum (λ b, supr_le $ λ htb, le_rfl) ... ≤ c : hn.le } end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma mk_metric_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf l (λ n, ∑ i, m (diam (t n i))) := begin haveI : ∀ n, encodable (ι n), from λ n, fintype.encodable _, simpa only [tsum_fintype] using mk_metric_le_liminf_tsum s r hr t ht hst m, end /-! ### Hausdorff measure and Hausdorff dimension -/ /-- Hausdorff measure on an (e)metric space. -/ def hausdorff_measure (d : ℝ) : measure X := mk_metric (λ r, r ^ d) localized "notation `μH[` d `]` := measure_theory.measure.hausdorff_measure d" in measure_theory lemma le_hausdorff_measure (d : ℝ) (μ : measure X) (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → μ s ≤ diam s ^ d) : μ ≤ μH[d] := le_mk_metric _ μ ε h₀ h /-- A formula for `μH[d] s`. -/ lemma hausdorff_measure_apply (d : ℝ) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (h : (t n).nonempty), (diam (t n)) ^ d := mk_metric_apply _ _ /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of encodable types. -/ lemma hausdorff_measure_le_liminf_tsum {β : Type*} {ι : β → Type*} [hι : ∀ n, encodable (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf l (λ n, ∑' i, diam (t n i) ^ d) := mk_metric_le_liminf_tsum s r hr t ht hst _ /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma hausdorff_measure_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf l (λ n, ∑ i, diam (t n i) ^ d) := mk_metric_le_liminf_sum s r hr t ht hst _ /-- If `d₁ < d₂`, then for any set `s` we have either `μH[d₂] s = 0`, or `μH[d₁] s = ∞`. -/ lemma hausdorff_measure_zero_or_top {d₁ d₂ : ℝ} (h : d₁ < d₂) (s : set X) : μH[d₂] s = 0 ∨ μH[d₁] s = ∞ := begin by_contra' H, suffices : ∀ (c : ℝ≥0), c ≠ 0 → μH[d₂] s ≤ c * μH[d₁] s, { rcases ennreal.exists_nnreal_pos_mul_lt H.2 H.1 with ⟨c, hc0, hc⟩, exact hc.not_le (this c (pos_iff_ne_zero.1 hc0)) }, intros c hc, refine le_iff'.1 (mk_metric_mono_smul ennreal.coe_ne_top (by exact_mod_cast hc) _) s, have : 0 < (c ^ (d₂ - d₁)⁻¹ : ℝ≥0∞), { rw [ennreal.coe_rpow_of_ne_zero hc, pos_iff_ne_zero, ne.def, ennreal.coe_eq_zero, nnreal.rpow_eq_zero_iff], exact mt and.left hc }, filter_upwards [Ico_mem_nhds_within_Ici ⟨le_rfl, this⟩], rintro r ⟨hr₀, hrc⟩, lift r to ℝ≥0 using ne_top_of_lt hrc, rw [pi.smul_apply, smul_eq_mul, ← ennreal.div_le_iff_le_mul (or.inr ennreal.coe_ne_top) (or.inr $ mt ennreal.coe_eq_zero.1 hc)], rcases eq_or_ne r 0 with rfl|hr₀, { rcases lt_or_le 0 d₂ with h₂|h₂, { simp only [h₂, ennreal.zero_rpow_of_pos, zero_le', ennreal.coe_nonneg, ennreal.zero_div, ennreal.coe_zero] }, { simp only [h.trans_le h₂, ennreal.div_top, zero_le', ennreal.coe_nonneg, ennreal.zero_rpow_of_neg, ennreal.coe_zero] } }, { have : (r : ℝ≥0∞) ≠ 0, by simpa only [ennreal.coe_eq_zero, ne.def] using hr₀, rw [← ennreal.rpow_sub _ _ this ennreal.coe_ne_top], refine (ennreal.rpow_lt_rpow hrc (sub_pos.2 h)).le.trans _, rw [← ennreal.rpow_mul, inv_mul_cancel (sub_pos.2 h).ne', ennreal.rpow_one], exact le_rfl } end /-- Hausdorff measure `μH[d] s` is monotone in `d`. -/ lemma hausdorff_measure_mono {d₁ d₂ : ℝ} (h : d₁ ≤ d₂) (s : set X) : μH[d₂] s ≤ μH[d₁] s := begin rcases h.eq_or_lt with rfl|h, { exact le_rfl }, cases hausdorff_measure_zero_or_top h s with hs hs, { rw hs, exact zero_le _ }, { rw hs, exact le_top } end variables (X) lemma no_atoms_hausdorff {d : ℝ} (hd : 0 < d) : has_no_atoms (hausdorff_measure d : measure X) := begin refine ⟨λ x, _⟩, rw [← nonpos_iff_eq_zero, hausdorff_measure_apply], refine bsupr_le (λ ε ε0, binfi_le_of_le (λ n, {x}) _ (infi_le_of_le (λ n, _) _)), { exact subset_Union (λ n, {x} : ℕ → set X) 0 }, { simp only [emetric.diam_singleton, zero_le] }, { simp [hd] } end variables {X} @[simp] lemma hausdorff_measure_zero_singleton (x : X) : μH[0] ({x} : set X) = 1 := begin apply le_antisymm, { let r : ℕ → ℝ≥0∞ := λ _, 0, let t : ℕ → unit → set X := λ n _, {x}, have ht : ∀ᶠ n in at_top, ∀ i, diam (t n i) ≤ r n, by simp only [implies_true_iff, eq_self_iff_true, diam_singleton, eventually_at_top, nonpos_iff_eq_zero, exists_const], simpa [liminf_const] using hausdorff_measure_le_liminf_sum 0 {x} r tendsto_const_nhds t ht }, { rw hausdorff_measure_apply, suffices : (1 : ℝ≥0∞) ≤ ⨅ (t : ℕ → set X) (hts : {x} ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ 1), ∑' n, ⨆ (h : (t n).nonempty), (diam (t n)) ^ (0 : ℝ), { apply le_trans this _, convert le_bsupr (1 : ℝ≥0∞) (ennreal.zero_lt_one), refl }, simp only [ennreal.rpow_zero, le_infi_iff], assume t hst h't, rcases mem_Union.1 (hst (mem_singleton x)) with ⟨m, hm⟩, have A : (t m).nonempty := ⟨x, hm⟩, calc (1 : ℝ≥0∞) = ⨆ (h : (t m).nonempty), 1 : by simp only [A, csupr_pos] ... ≤ ∑' n, ⨆ (h : (t n).nonempty), 1 : ennreal.le_tsum _ } end lemma one_le_hausdorff_measure_zero_of_nonempty {s : set X} (h : s.nonempty) : 1 ≤ μH[0] s := begin rcases h with ⟨x, hx⟩, calc (1 : ℝ≥0∞) = μH[0] ({x} : set X) : (hausdorff_measure_zero_singleton x).symm ... ≤ μH[0] s : measure_mono (singleton_subset_iff.2 hx) end lemma hausdorff_measure_le_one_of_subsingleton {s : set X} (hs : s.subsingleton) {d : ℝ} (hd : 0 ≤ d) : μH[d] s ≤ 1 := begin rcases eq_empty_or_nonempty s with rfl|⟨x, hx⟩, { simp only [measure_empty, zero_le] }, { rw (subsingleton_iff_singleton hx).1 hs, rcases eq_or_lt_of_le hd with rfl|dpos, { simp only [le_refl, hausdorff_measure_zero_singleton] }, { haveI := no_atoms_hausdorff X dpos, simp only [zero_le, measure_singleton] } } end end measure open_locale measure_theory open measure /-! ### Hausdorff measure and Lebesgue measure -/ /-- In the space `ι → ℝ`, Hausdorff measure coincides exactly with Lebesgue measure. -/ @[simp] theorem hausdorff_measure_pi_real {ι : Type*} [fintype ι] : (μH[fintype.card ι] : measure (ι → ℝ)) = volume := begin classical, -- it suffices to check that the two measures coincide on products of rational intervals refine (pi_eq_generate_from (λ i, real.borel_eq_generate_from_Ioo_rat.symm) (λ i, real.is_pi_system_Ioo_rat) (λ i, real.finite_spanning_sets_in_Ioo_rat _) _).symm, simp only [mem_Union, mem_singleton_iff], -- fix such a product `s` of rational intervals, of the form `Π (a i, b i)`. intros s hs, choose a b H using hs, obtain rfl : s = λ i, Ioo (a i) (b i), from funext (λ i, (H i).2), replace H := λ i, (H i).1, apply le_antisymm _, -- first check that `volume s ≤ μH s` { have Hle : volume ≤ (μH[fintype.card ι] : measure (ι → ℝ)), { refine le_hausdorff_measure _ _ ∞ ennreal.coe_lt_top (λ s _, _), rw [ennreal.rpow_nat_cast], exact real.volume_pi_le_diam_pow s }, rw [← volume_pi_pi (λ i, Ioo (a i : ℝ) (b i))], exact measure.le_iff'.1 Hle _ }, /- For the other inequality `μH s ≤ volume s`, we use a covering of `s` by sets of small diameter `1/n`, namely cubes with left-most point of the form `a i + f i / n` with `f i` ranging between `0` and `⌈(b i - a i) * n⌉`. Their number is asymptotic to `n^d * Π (b i - a i)`. -/ have I : ∀ i, 0 ≤ (b i : ℝ) - a i := λ i, by simpa only [sub_nonneg, rat.cast_le] using (H i).le, let γ := λ (n : ℕ), (Π (i : ι), fin ⌈((b i : ℝ) - a i) * n⌉₊), let t : Π (n : ℕ), γ n → set (ι → ℝ) := λ n f, set.pi univ (λ i, Icc (a i + f i / n) (a i + (f i + 1) / n)), have A : tendsto (λ (n : ℕ), 1/(n : ℝ≥0∞)) at_top (𝓝 0), by simp only [one_div, ennreal.tendsto_inv_nat_nhds_zero], have B : ∀ᶠ n in at_top, ∀ (i : γ n), diam (t n i) ≤ 1 / n, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, assume f, apply diam_pi_le_of_le (λ b, _), simp only [real.ediam_Icc, add_div, ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), le_refl, add_sub_add_left_eq_sub, add_sub_cancel', ennreal.of_real_one, ennreal.of_real_coe_nat] }, have C : ∀ᶠ n in at_top, set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i)) ⊆ ⋃ (i : γ n), t n i, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, have npos : (0 : ℝ) < n := nat.cast_pos.2 hn, assume x hx, simp only [mem_Ioo, mem_univ_pi] at hx, simp only [mem_Union, mem_Ioo, mem_univ_pi, coe_coe], let f : γ n := λ i, ⟨⌊(x i - a i) * n⌋₊, begin apply nat.floor_lt_ceil_of_lt_of_pos, { refine (mul_lt_mul_right npos).2 _, simp only [(hx i).right, sub_lt_sub_iff_right] }, { refine mul_pos _ npos, simpa only [rat.cast_lt, sub_pos] using H i } end⟩, refine ⟨f, λ i, ⟨_, _⟩⟩, { calc (a i : ℝ) + ⌊(x i - a i) * n⌋₊ / n ≤ (a i : ℝ) + ((x i - a i) * n) / n : begin refine add_le_add le_rfl ((div_le_div_right npos).2 _), exact nat.floor_le (mul_nonneg (sub_nonneg.2 (hx i).1.le) npos.le), end ... = x i : by field_simp [npos.ne'] }, { calc x i = (a i : ℝ) + ((x i - a i) * n) / n : by field_simp [npos.ne'] ... ≤ (a i : ℝ) + (⌊(x i - a i) * n⌋₊ + 1) / n : add_le_add le_rfl ((div_le_div_right npos).2 (nat.lt_floor_add_one _).le) } }, calc μH[fintype.card ι] (set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i))) ≤ liminf at_top (λ (n : ℕ), ∑ (i : γ n), diam (t n i) ^ ↑(fintype.card ι)) : hausdorff_measure_le_liminf_sum _ (set.pi univ (λ i, Ioo (a i : ℝ) (b i))) (λ (n : ℕ), 1/(n : ℝ≥0∞)) A t B C ... ≤ liminf at_top (λ (n : ℕ), ∑ (i : γ n), (1/n) ^ (fintype.card ι)) : begin refine liminf_le_liminf _ (by is_bounded_default), filter_upwards [B] with _ hn, apply finset.sum_le_sum (λ i _, _), rw ennreal.rpow_nat_cast, exact pow_le_pow_of_le_left' (hn i) _, end ... = liminf at_top (λ (n : ℕ), ∏ (i : ι), (⌈((b i : ℝ) - a i) * n⌉₊ : ℝ≥0∞) / n) : begin simp only [finset.card_univ, nat.cast_prod, one_mul, fintype.card_fin, finset.sum_const, nsmul_eq_mul, fintype.card_pi, div_eq_mul_inv, finset.prod_mul_distrib, finset.prod_const] end ... = ∏ (i : ι), volume (Ioo (a i : ℝ) (b i)) : begin simp only [real.volume_Ioo], apply tendsto.liminf_eq, refine ennreal.tendsto_finset_prod_of_ne_top _ (λ i hi, _) (λ i hi, _), { apply tendsto.congr' _ ((ennreal.continuous_of_real.tendsto _).comp ((tendsto_nat_ceil_mul_div_at_top (I i)).comp tendsto_coe_nat_at_top_at_top)), apply eventually_at_top.2 ⟨1, λ n hn, _⟩, simp only [ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), comp_app, ennreal.of_real_coe_nat] }, { simp only [ennreal.of_real_ne_top, ne.def, not_false_iff] } end end end measure_theory /-! ### Hausdorff measure, Hausdorff dimension, and Hölder or Lipschitz continuous maps -/ open_locale measure_theory open measure_theory measure_theory.measure variables [measurable_space X] [borel_space X] [measurable_space Y] [borel_space Y] namespace holder_on_with variables {C r : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is Hölder continuous on `s` with a positive exponent `r`, then `μH[d] (f '' s) ≤ C ^ d * μH[r * d] s`. -/ lemma hausdorff_measure_image_le (h : holder_on_with C r f s) (hr : 0 < r) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ C ^ d * μH[r * d] s := begin -- We start with the trivial case `C = 0` rcases (zero_le C).eq_or_lt with rfl|hC0, { rcases eq_empty_or_nonempty s with rfl|⟨x, hx⟩, { simp only [measure_empty, nonpos_iff_eq_zero, mul_zero, image_empty] }, have : f '' s = {f x}, { have : (f '' s).subsingleton, by simpa [diam_eq_zero_iff] using h.ediam_image_le, exact (subsingleton_iff_singleton (mem_image_of_mem f hx)).1 this }, rw this, rcases eq_or_lt_of_le hd with rfl|h'd, { simp only [ennreal.rpow_zero, one_mul, mul_zero], rw hausdorff_measure_zero_singleton, exact one_le_hausdorff_measure_zero_of_nonempty ⟨x, hx⟩ }, { haveI := no_atoms_hausdorff Y h'd, simp only [zero_le, measure_singleton] } }, -- Now assume `C ≠ 0` { have hCd0 : (C : ℝ≥0∞) ^ d ≠ 0, by simp [hC0.ne'], have hCd : (C : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply, ennreal.mul_supr, ennreal.mul_infi_of_ne hCd0 hCd, ← ennreal.tsum_mul_left], refine supr_le (λ R, supr_le $ λ hR, _), have : tendsto (λ d : ℝ≥0∞, (C : ℝ≥0∞) * d ^ (r : ℝ)) (𝓝 0) (𝓝 0), from ennreal.tendsto_const_mul_rpow_nhds_zero_of_pos ennreal.coe_ne_top hr, rcases ennreal.nhds_zero_basis_Iic.eventually_iff.1 (this.eventually (gt_mem_nhds hR)) with ⟨δ, δ0, H⟩, refine le_supr_of_le δ (le_supr_of_le δ0 $ le_binfi $ λ t hst, le_infi $ λ htδ, _), refine binfi_le_of_le (λ n, f '' (t n ∩ s)) _ (infi_le_of_le (λ n, _) _), { rw [← image_Union, ← Union_inter], exact image_subset _ (subset_inter hst subset.rfl) }, { exact (h.ediam_image_inter_le (t n)).trans (H (htδ n)).le }, { apply ennreal.tsum_le_tsum (λ n, _), simp only [supr_le_iff, nonempty_image_iff], assume hft, simp only [nonempty.mono ((t n).inter_subset_left s) hft, csupr_pos], rw [ennreal.rpow_mul, ← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (h.ediam_image_inter_le _) hd } } end end holder_on_with namespace lipschitz_on_with variables {K : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is `K`-Lipschitz on `s`, then `μH[d] (f '' s) ≤ K ^ d * μH[d] s`. -/ lemma hausdorff_measure_image_le (h : lipschitz_on_with K f s) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := by simpa only [nnreal.coe_one, one_mul] using h.holder_on_with.hausdorff_measure_image_le zero_lt_one hd end lipschitz_on_with namespace lipschitz_with variables {K : ℝ≥0} {f : X → Y} /-- If `f` is a `K`-Lipschitz map, then it increases the Hausdorff `d`-measures of sets at most by the factor of `K ^ d`.-/ lemma hausdorff_measure_image_le (h : lipschitz_with K f) {d : ℝ} (hd : 0 ≤ d) (s : set X) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := (h.lipschitz_on_with s).hausdorff_measure_image_le hd end lipschitz_with /-! ### Antilipschitz maps do not decrease Hausdorff measures and dimension -/ namespace antilipschitz_with variables {f : X → Y} {K : ℝ≥0} {d : ℝ} lemma hausdorff_measure_preimage_le (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set Y) : μH[d] (f ⁻¹' s) ≤ K ^ d * μH[d] s := begin rcases eq_or_ne K 0 with rfl|h0, { rcases eq_empty_or_nonempty (f ⁻¹' s) with hs|⟨x, hx⟩, { simp only [hs, measure_empty, zero_le], }, have : f ⁻¹' s = {x}, { haveI : subsingleton X := hf.subsingleton, have : (f ⁻¹' s).subsingleton, from subsingleton_univ.mono (subset_univ _), exact (subsingleton_iff_singleton hx).1 this }, rw this, rcases eq_or_lt_of_le hd with rfl|h'd, { simp only [ennreal.rpow_zero, one_mul, mul_zero], rw hausdorff_measure_zero_singleton, exact one_le_hausdorff_measure_zero_of_nonempty ⟨f x, hx⟩ }, { haveI := no_atoms_hausdorff X h'd, simp only [zero_le, measure_singleton] } }, have hKd0 : (K : ℝ≥0∞) ^ d ≠ 0, by simp [h0], have hKd : (K : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply, ennreal.mul_supr, ennreal.mul_infi_of_ne hKd0 hKd, ← ennreal.tsum_mul_left], refine bsupr_le (λ ε ε0, _), refine le_bsupr_of_le (ε / K) (by simp [ε0.ne']) _, refine le_binfi (λ t hst, le_infi $ λ htε, _), replace hst : f ⁻¹' s ⊆ _ := preimage_mono hst, rw preimage_Union at hst, refine binfi_le_of_le _ hst (infi_le_of_le (λ n, _) _), { exact (hf.ediam_preimage_le _).trans (ennreal.mul_le_of_le_div' $ htε n) }, { refine ennreal.tsum_le_tsum (λ n, supr_le_iff.2 (λ hft, _)), simp only [nonempty_of_nonempty_preimage hft, csupr_pos], rw [← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (hf.ediam_preimage_le _) hd } end lemma le_hausdorff_measure_image (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set X) : μH[d] s ≤ K ^ d * μH[d] (f '' s) := calc μH[d] s ≤ μH[d] (f ⁻¹' (f '' s)) : measure_mono (subset_preimage_image _ _) ... ≤ K ^ d * μH[d] (f '' s) : hf.hausdorff_measure_preimage_le hd (f '' s) end antilipschitz_with /-! ### Isometries preserve the Hausdorff measure and Hausdorff dimension -/ namespace isometry variables {f : X → Y} {d : ℝ} lemma hausdorff_measure_image (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set X) : μH[d] (f '' s) = μH[d] s := begin simp only [hausdorff_measure, ← outer_measure.coe_mk_metric, ← outer_measure.comap_apply], rw [outer_measure.isometry_comap_mk_metric _ hf (hd.imp_left _)], exact λ hd x y hxy, ennreal.rpow_le_rpow hxy hd end lemma hausdorff_measure_preimage (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set Y) : μH[d] (f ⁻¹' s) = μH[d] (s ∩ range f) := by rw [← hf.hausdorff_measure_image hd, image_preimage_eq_inter_range] lemma map_hausdorff_measure (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) : measure.map f μH[d] = (μH[d]).restrict (range f) := begin ext1 s hs, rw [map_apply hf.continuous.measurable hs, restrict_apply hs, hf.hausdorff_measure_preimage hd] end end isometry namespace isometric @[simp] lemma hausdorff_measure_image (e : X ≃ᵢ Y) (d : ℝ) (s : set X) : μH[d] (e '' s) = μH[d] s := e.isometry.hausdorff_measure_image (or.inr e.surjective) s @[simp] lemma hausdorff_measure_preimage (e : X ≃ᵢ Y) (d : ℝ) (s : set Y) : μH[d] (e ⁻¹' s) = μH[d] s := by rw [← e.image_symm, e.symm.hausdorff_measure_image] end isometric
abbda0983e11f7acc3cf1e5b0eca4abdf92a8b63
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/limits/limits.lean
5cbf73f80ad340e9112c472991dac17054aeab80
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
71,810
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.adjunction.basic import category_theory.limits.cones import category_theory.reflects_isomorphisms /-! # Limits and colimits We set up the general theory of limits and colimits in a category. In this introduction we only describe the setup for limits; it is repeated, with slightly different names, for colimits. The three main structures involved are * `is_limit c`, for `c : cone F`, `F : J ⥤ C`, expressing that `c` is a limit cone, * `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `has_limit F`, asserting the mere existence of some limit cone for `F`. `has_limit` is a propositional typeclass (it's important that it is a proposition merely asserting the existence of a limit, as otherwise we would have non-defeq problems from incompatible instances). Typically there are two different ways one can use the limits library: 1. working with particular cones, and terms of type `is_limit` 2. working solely with `has_limit`. While `has_limit` only asserts the existence of a limit cone, we happily use the axiom of choice in mathlib, so there are convenience functions all depending on `has_limit F`: * `limit F : C`, producing some limit object (of course all such are isomorphic) * `limit.π F j : limit F ⟶ F.obj j`, the morphisms out of the limit, * `limit.lift F c : c.X ⟶ limit F`, the universal morphism from any other `c : cone F`, etc. Key to using the `has_limit` interface is that there is an `@[ext]` lemma stating that to check `f = g`, for `f g : Z ⟶ limit F`, it suffices to check `f ≫ limit.π F j = g ≫ limit.π F j` for every `j`. This, combined with `@[simp]` lemmas, makes it possible to prove many easy facts about limits using automation (e.g. `tidy`). There are abbreviations `has_limits_of_shape J C` and `has_limits C` asserting the existence of classes of limits. Later more are introduced, for finite limits, special shapes of limits, etc. Ideally, many results about limits should be stated first in terms of `is_limit`, and then a result in terms of `has_limit` derived from this. At this point, however, this is far from uniformly achieved in mathlib --- often statements are only written in terms of `has_limit`. ## Implementation At present we simply say everything twice, in order to handle both limits and colimits. It would be highly desirable to have some automation support, e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`. ## References * [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D) -/ noncomputable theory open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits universes v u u' u'' w -- declare the `v`'s first; see `category_theory.category` for an explanation variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. See https://stacks.math.columbia.edu/tag/002E. -/ @[nolint has_inhabited_instance] structure is_limit (t : cone F) := (lift : Π (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp, reassoc] is_limit.fac restate_axiom is_limit.uniq' namespace is_limit instance subsingleton {t : cone F} : subsingleton (is_limit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cone point of any cone over `F` to the cone point of a limit cone over `G`. -/ def map {F G : J ⥤ C} (s : cone F) {t : cone G} (P : is_limit t) (α : F ⟶ G) : s.X ⟶ t.X := P.lift ((cones.postcompose α).obj s) @[simp, reassoc] lemma map_π {F G : J ⥤ C} (c : cone F) {d : cone G} (hd : is_limit d) (α : F ⟶ G) (j : J) : hd.map c α ≫ d.π.app j = c.π.app j ≫ α.app j := fac _ _ _ lemma lift_self {c : cone F} (t : is_limit c) : t.lift c = 𝟙 c.X := (t.uniq _ _ (λ j, id_comp _)).symm /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from any other cone to a limit cone. -/ @[simps] def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t := { hom := h.lift s } lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} : f = f' := have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_limit`, providing a morphism of cones rather than a morphism between the cone points and separately the factorisation condition. -/ @[simps] def mk_cone_morphism {t : cone F} (lift : Π (s : cone F), s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := { lift := λ s, (lift s).hom, uniq' := λ s m w, have cone_morphism.mk m w = lift s, by apply uniq', congr_arg cone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ @[simps] def unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := { hom := Q.lift_cone_morphism s, inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism } /-- Any cone morphism between limit cones is an isomorphism. -/ lemma hom_is_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) (f : s ⟶ t) : is_iso f := ⟨P.lift_cone_morphism t, ⟨P.uniq_cone_morphism, Q.uniq_cone_morphism⟩⟩ /-- Limits of `F` are unique up to isomorphism. -/ def cone_point_unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s.X ≅ t.X := (cones.forget F).map_iso (unique_up_to_iso P Q) @[simp, reassoc] lemma cone_point_unique_up_to_iso_hom_comp {s t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : (cone_point_unique_up_to_iso P Q).hom ≫ t.π.app j = s.π.app j := (unique_up_to_iso P Q).hom.w _ @[simp, reassoc] lemma cone_point_unique_up_to_iso_inv_comp {s t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : (cone_point_unique_up_to_iso P Q).inv ≫ s.π.app j = t.π.app j := (unique_up_to_iso P Q).inv.w _ @[simp, reassoc] lemma lift_comp_cone_point_unique_up_to_iso_hom {r s t : cone F} (P : is_limit s) (Q : is_limit t) : P.lift r ≫ (cone_point_unique_up_to_iso P Q).hom = Q.lift r := Q.uniq _ _ (by simp) @[simp, reassoc] lemma lift_comp_cone_point_unique_up_to_iso_inv {r s t : cone F} (P : is_limit s) (Q : is_limit t) : Q.lift r ≫ (cone_point_unique_up_to_iso P Q).inv = P.lift r := P.uniq _ _ (by simp) /-- Transport evidence that a cone is a limit cone across an isomorphism of cones. -/ def of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := is_limit.mk_cone_morphism (λ s, P.lift_cone_morphism s ≫ i.hom) (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism) @[simp] lemma of_iso_limit_lift {r t : cone F} (P : is_limit r) (i : r ≅ t) (s) : (P.of_iso_limit i).lift s = P.lift s ≫ i.hom.hom := rfl /-- Isomorphism of cones preserves whether or not they are limiting cones. -/ def equiv_iso_limit {r t : cone F} (i : r ≅ t) : is_limit r ≃ is_limit t := { to_fun := λ h, h.of_iso_limit i, inv_fun := λ h, h.of_iso_limit i.symm, left_inv := by tidy, right_inv := by tidy } @[simp] lemma equiv_iso_limit_apply {r t : cone F} (i : r ≅ t) (P : is_limit r) : equiv_iso_limit i P = P.of_iso_limit i := rfl @[simp] lemma equiv_iso_limit_symm_apply {r t : cone F} (i : r ≅ t) (P : is_limit t) : (equiv_iso_limit i).symm P = P.of_iso_limit i.symm := rfl /-- If the canonical morphism from a cone point to a limiting cone point is an iso, then the first cone was limiting also. -/ def of_point_iso {r t : cone F} (P : is_limit r) [i : is_iso (P.lift t)] : is_limit t := of_iso_limit P begin haveI : is_iso (P.lift_cone_morphism t).hom := i, haveI : is_iso (P.lift_cone_morphism t) := cones.cone_iso_of_hom_iso _, symmetry, apply as_iso (P.lift_cone_morphism t), end variables {t : cone F} lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) : m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } := h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl) /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X} (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' := by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w /-- Given a right adjoint functor between categories of cones, the image of a limit cone is a limit cone. -/ def of_right_adjoint {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ⥤ cone F) [is_right_adjoint h] {c : cone G} (t : is_limit c) : is_limit (h.obj c) := mk_cone_morphism (λ s, (adjunction.of_right_adjoint h).hom_equiv s c (t.lift_cone_morphism _)) (λ s m, (adjunction.eq_hom_equiv_apply _ _ _).2 t.uniq_cone_morphism) /-- Given two functors which have equivalent categories of cones, we can transport a limiting cone across the equivalence. -/ def of_cone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} : is_limit (h.functor.obj c) ≃ is_limit c := { to_fun := λ P, of_iso_limit (of_right_adjoint h.inverse P) (h.unit_iso.symm.app c), inv_fun := of_right_adjoint h.functor, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma of_cone_equiv_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} (P : is_limit (h.functor.obj c)) (s) : (of_cone_equiv h P).lift s = ((h.unit_iso.hom.app s).hom ≫ (h.functor.inv.map (P.lift_cone_morphism (h.functor.obj s))).hom) ≫ (h.unit_iso.inv.app c).hom := rfl @[simp] lemma of_cone_equiv_symm_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} (P : is_limit c) (s) : ((of_cone_equiv h).symm P).lift s = (h.counit_iso.inv.app s).hom ≫ (h.functor.map (P.lift_cone_morphism (h.inverse.obj s))).hom := rfl /-- A cone postcomposed with a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_hom_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cone F) : is_limit ((cones.postcompose α.hom).obj c) ≃ is_limit c := of_cone_equiv (cones.postcompose_equivalence α) /-- A cone postcomposed with the inverse of a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_inv_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cone G) : is_limit ((cones.postcompose α.inv).obj c) ≃ is_limit c := postcompose_hom_equiv α.symm c /-- The cone points of two limit cones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def cone_points_iso_of_nat_iso {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) : s.X ≅ t.X := { hom := Q.map s w.hom, inv := P.map t w.inv, hom_inv_id' := P.hom_ext (by tidy), inv_hom_id' := Q.hom_ext (by tidy), } @[reassoc] lemma cone_points_iso_of_nat_iso_hom_comp {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) (j : J) : (cone_points_iso_of_nat_iso P Q w).hom ≫ t.π.app j = s.π.app j ≫ w.hom.app j := by simp @[reassoc] lemma cone_points_iso_of_nat_iso_inv_comp {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) (j : J) : (cone_points_iso_of_nat_iso P Q w).inv ≫ s.π.app j = t.π.app j ≫ w.inv.app j := by simp @[reassoc] lemma lift_comp_cone_points_iso_of_nat_iso_hom {F G : J ⥤ C} {r s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) : P.lift r ≫ (cone_points_iso_of_nat_iso P Q w).hom = Q.map r w.hom := Q.hom_ext (by simp) section equivalence open category_theory.equivalence /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {s : cone F} (P : is_limit s) (e : K ≌ J) : is_limit (s.whisker e.functor) := of_right_adjoint (cones.whiskering_equivalence e).functor P /-- We can prove two cone points `(s : cone F).X` and `(t.cone F).X` are isomorphic if * both cones are limit cones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simps] def cone_points_iso_of_equivalence {F : J ⥤ C} {s : cone F} {G : K ⥤ C} {t : cone G} (P : is_limit s) (Q : is_limit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.X ≅ t.X := let w' : e.inverse ⋙ F ≅ G := (iso_whisker_left e.inverse w).symm ≪≫ inv_fun_id_assoc e G in { hom := Q.lift ((cones.equivalence_of_reindexing e.symm w').functor.obj s), inv := P.lift ((cones.equivalence_of_reindexing e w).functor.obj t), hom_inv_id' := begin apply hom_ext P, intros j, dsimp, simp only [limits.cone.whisker_π, limits.cones.postcompose_obj_π, fac, whisker_left_app, assoc, id_comp, inv_fun_id_assoc_hom_app, fac_assoc, nat_trans.comp_app], rw [counit_app_functor, ←functor.comp_map, w.hom.naturality], simp, end, inv_hom_id' := by { apply hom_ext Q, tidy, }, } end equivalence /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟶ F) := { hom := λ f, (t.extend f).π, inv := λ π, h.lift { X := W, π := π }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) : (is_limit.hom_iso h W).hom f = (t.extend f).π := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with vertex `W`. -/ def nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones := nat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy). /-- Another, more explicit, formulation of the universal property of a limit cone. See also `hom_iso`. -/ def hom_iso' (h : is_limit t) (W : C) : ((W ⟶ t.X) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.hom_iso W ≪≫ { hom := λ π, ⟨λ j, π.app j, λ j j' f, by convert ←(π.naturality f).symm; apply id_comp⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } } /-- If G : C → D is a faithful functor which sends t to a limit cone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X) (h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t := { lift := lift, fac' := λ s j, by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.map_injective, rw h, refine ht.uniq (G.map_cone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a limit implies `G.map_cone c` is also a limit. -/ def map_cone_equiv {D : Type u'} [category.{v} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : cone K} (t : is_limit (F.map_cone c)) : is_limit (G.map_cone c) := begin apply postcompose_inv_equiv (iso_whisker_left K h : _) (G.map_cone c) _, apply t.of_iso_limit (postcompose_whisker_left_map_cone h.symm c).symm, end /-- A cone is a limit cone exactly if there is a unique cone morphism from any other cone. -/ def iso_unique_cone_morphism {t : cone F} : is_limit t ≅ Π s, unique (s ⟶ t) := { hom := λ h s, { default := h.lift_cone_morphism s, uniq := λ _, h.uniq_cone_morphism }, inv := λ h, { lift := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : yoneda.obj X ≅ F.cones) /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def cone_of_hom {Y : C} (f : Y ⟶ X) : cone F := { X := Y, π := h.hom.app (op Y) f } /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.X ⟶ X`. -/ def hom_of_cone (s : cone F) : s.X ⟶ X := h.inv.app (op s.X) s.π @[simp] lemma cone_of_hom_of_cone (s : cone F) : cone_of_hom h (hom_of_cone h s) = s := begin dsimp [cone_of_hom, hom_of_cone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) (op s_X)) s_π, end @[simp] lemma hom_of_cone_of_hom {Y : C} (f : Y ⟶ X) : hom_of_cone h (cone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) (op Y)) f /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limit_cone : cone F := cone_of_hom h (𝟙 X) /-- If `F.cones` is represented by `X`, the cone corresponding to a morphism `f : Y ⟶ X` is the limit cone extended by `f`. -/ lemma cone_of_hom_fac {Y : C} (f : Y ⟶ X) : cone_of_hom h f = (limit_cone h).extend f := begin dsimp [cone_of_hom, limit_cone, cone.extend], congr' with j, have t := congr_fun (h.hom.naturality f.op) (𝟙 X), dsimp at t, simp only [comp_id] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ lemma cone_fac (s : cone F) : (limit_cone h).extend (hom_of_cone h s) = s := begin rw ←cone_of_hom_of_cone h s, conv_lhs { simp only [hom_of_cone_of_hom] }, apply (cone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def of_nat_iso {X : C} (h : yoneda.obj X ≅ F.cones) : is_limit (limit_cone h) := { lift := λ s, hom_of_cone h s, fac' := λ s j, begin have h := cone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cone_of_hom h m, congr, rw cone_of_hom_fac, dsimp, cases s, congr' with j, exact w j, end } end end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. See https://stacks.math.columbia.edu/tag/002F. -/ @[nolint has_inhabited_instance] structure is_colimit (t : cocone F) := (desc : Π (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp,reassoc] is_colimit.fac restate_axiom is_colimit.uniq' namespace is_colimit instance subsingleton {t : cocone F} : subsingleton (is_colimit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cocone point of a colimit cocone over `F` to the cocone point of any cocone over `G`. -/ def map {F G : J ⥤ C} {s : cocone F} (P : is_colimit s) (t : cocone G) (α : F ⟶ G) : s.X ⟶ t.X := P.desc ((cocones.precompose α).obj t) @[simp, reassoc] lemma ι_map {F G : J ⥤ C} {c : cocone F} (hc : is_colimit c) (d : cocone G) (α : F ⟶ G) (j : J) : c.ι.app j ≫ is_colimit.map hc d α = α.app j ≫ d.ι.app j := fac _ _ _ @[simp] lemma desc_self {t : cocone F} (h : is_colimit t) : h.desc t = 𝟙 t.X := (h.uniq _ _ (λ j, comp_id _)).symm /- Repackaging the definition in terms of cocone morphisms. -/ /-- The universal morphism from a colimit cocone to any other cocone. -/ @[simps] def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := { hom := h.desc s } lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} : f = f' := have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_colimit`, providing a morphism of cocones rather than a morphism between the cocone points and separately the factorisation condition. -/ @[simps] def mk_cocone_morphism {t : cocone F} (desc : Π (s : cocone F), t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := { desc := λ s, (desc s).hom, uniq' := λ s m w, have cocone_morphism.mk m w = desc s, by apply uniq', congr_arg cocone_morphism.hom this } /-- Colimit cocones on `F` are unique up to isomorphism. -/ @[simps] def unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t := { hom := P.desc_cocone_morphism t, inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism } /-- Any cocone morphism between colimit cocones is an isomorphism. -/ lemma hom_is_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (f : s ⟶ t) : is_iso f := ⟨Q.desc_cocone_morphism s, ⟨P.uniq_cocone_morphism, Q.uniq_cocone_morphism⟩⟩ /-- Colimits of `F` are unique up to isomorphism. -/ def cocone_point_unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s.X ≅ t.X := (cocones.forget F).map_iso (unique_up_to_iso P Q) @[simp, reassoc] lemma comp_cocone_point_unique_up_to_iso_hom {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : s.ι.app j ≫ (cocone_point_unique_up_to_iso P Q).hom = t.ι.app j := (unique_up_to_iso P Q).hom.w _ @[simp, reassoc] lemma comp_cocone_point_unique_up_to_iso_inv {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : t.ι.app j ≫ (cocone_point_unique_up_to_iso P Q).inv = s.ι.app j := (unique_up_to_iso P Q).inv.w _ @[simp, reassoc] lemma cocone_point_unique_up_to_iso_hom_desc {r s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : (cocone_point_unique_up_to_iso P Q).hom ≫ Q.desc r = P.desc r := P.uniq _ _ (by simp) @[simp, reassoc] lemma cocone_point_unique_up_to_iso_inv_desc {r s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : (cocone_point_unique_up_to_iso P Q).inv ≫ P.desc r = Q.desc r := Q.uniq _ _ (by simp) /-- Transport evidence that a cocone is a colimit cocone across an isomorphism of cocones. -/ def of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := is_colimit.mk_cocone_morphism (λ s, i.inv ≫ P.desc_cocone_morphism s) (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism) @[simp] lemma of_iso_colimit_desc {r t : cocone F} (P : is_colimit r) (i : r ≅ t) (s) : (P.of_iso_colimit i).desc s = i.inv.hom ≫ P.desc s := rfl /-- Isomorphism of cocones preserves whether or not they are colimiting cocones. -/ def equiv_iso_colimit {r t : cocone F} (i : r ≅ t) : is_colimit r ≃ is_colimit t := { to_fun := λ h, h.of_iso_colimit i, inv_fun := λ h, h.of_iso_colimit i.symm, left_inv := by tidy, right_inv := by tidy } @[simp] lemma equiv_iso_colimit_apply {r t : cocone F} (i : r ≅ t) (P : is_colimit r) : equiv_iso_colimit i P = P.of_iso_colimit i := rfl @[simp] lemma equiv_iso_colimit_symm_apply {r t : cocone F} (i : r ≅ t) (P : is_colimit t) : (equiv_iso_colimit i).symm P = P.of_iso_colimit i.symm := rfl /-- If the canonical morphism to a cocone point from a colimiting cocone point is an iso, then the first cocone was colimiting also. -/ def of_point_iso {r t : cocone F} (P : is_colimit r) [i : is_iso (P.desc t)] : is_colimit t := of_iso_colimit P begin haveI : is_iso (P.desc_cocone_morphism t).hom := i, haveI : is_iso (P.desc_cocone_morphism t) := cocones.cocone_iso_of_hom_iso _, apply as_iso (P.desc_cocone_morphism t), end variables {t : cocone F} lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) : m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } := h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl) /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W} (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' := by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w /-- Given a left adjoint functor between categories of cocones, the image of a colimit cocone is a colimit cocone. -/ def of_left_adjoint {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ⥤ cocone F) [is_left_adjoint h] {c : cocone G} (t : is_colimit c) : is_colimit (h.obj c) := mk_cocone_morphism (λ s, ((adjunction.of_left_adjoint h).hom_equiv c s).symm (t.desc_cocone_morphism _)) (λ s m, (adjunction.hom_equiv_apply_eq _ _ _).1 t.uniq_cocone_morphism) /-- Given two functors which have equivalent categories of cocones, we can transport a colimiting cocone across the equivalence. -/ def of_cocone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} : is_colimit (h.functor.obj c) ≃ is_colimit c := { to_fun := λ P, of_iso_colimit (of_left_adjoint h.inverse P) (h.unit_iso.symm.app c), inv_fun := of_left_adjoint h.functor, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma of_cocone_equiv_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit (h.functor.obj c)) (s) : (of_cocone_equiv h P).desc s = (h.unit.app c).hom ≫ (h.inverse.map (P.desc_cocone_morphism (h.functor.obj s))).hom ≫ (h.unit_inv.app s).hom := rfl @[simp] lemma of_cocone_equiv_symm_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit c) (s) : ((of_cocone_equiv h).symm P).desc s = (h.functor.map (P.desc_cocone_morphism (h.inverse.obj s))).hom ≫ (h.counit.app s).hom := rfl /-- A cocone precomposed with a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_hom_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cocone G) : is_colimit ((cocones.precompose α.hom).obj c) ≃ is_colimit c := of_cocone_equiv (cocones.precompose_equivalence α) /-- A cocone precomposed with the inverse of a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_inv_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cocone F) : is_colimit ((cocones.precompose α.inv).obj c) ≃ is_colimit c := precompose_hom_equiv α.symm c /-- The cocone points of two colimit cocones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def cocone_points_iso_of_nat_iso {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : s.X ≅ t.X := { hom := P.map t w.hom, inv := Q.map s w.inv, hom_inv_id' := P.hom_ext (by tidy), inv_hom_id' := Q.hom_ext (by tidy) } @[reassoc] lemma comp_cocone_points_iso_of_nat_iso_hom {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) (j : J) : s.ι.app j ≫ (cocone_points_iso_of_nat_iso P Q w).hom = w.hom.app j ≫ t.ι.app j := by simp @[reassoc] lemma comp_cocone_points_iso_of_nat_iso_inv {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) (j : J) : t.ι.app j ≫ (cocone_points_iso_of_nat_iso P Q w).inv = w.inv.app j ≫ s.ι.app j := by simp @[reassoc] lemma cocone_points_iso_of_nat_iso_hom_desc {F G : J ⥤ C} {s : cocone F} {r t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : (cocone_points_iso_of_nat_iso P Q w).hom ≫ Q.desc r = P.map _ w.hom := P.hom_ext (by simp) section equivalence open category_theory.equivalence /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {s : cocone F} (P : is_colimit s) (e : K ≌ J) : is_colimit (s.whisker e.functor) := of_left_adjoint (cocones.whiskering_equivalence e).functor P /-- We can prove two cocone points `(s : cocone F).X` and `(t.cocone F).X` are isomorphic if * both cocones are colimit ccoones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cocone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simps] def cocone_points_iso_of_equivalence {F : J ⥤ C} {s : cocone F} {G : K ⥤ C} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.X ≅ t.X := let w' : e.inverse ⋙ F ≅ G := (iso_whisker_left e.inverse w).symm ≪≫ inv_fun_id_assoc e G in { hom := P.desc ((cocones.equivalence_of_reindexing e w).functor.obj t), inv := Q.desc ((cocones.equivalence_of_reindexing e.symm w').functor.obj s), hom_inv_id' := begin apply hom_ext P, intros j, dsimp, simp only [limits.cocone.whisker_ι, fac, inv_fun_id_assoc_inv_app, whisker_left_app, assoc, comp_id, limits.cocones.precompose_obj_ι, fac_assoc, nat_trans.comp_app], rw [counit_inv_app_functor, ←functor.comp_map, ←w.inv.naturality_assoc], dsimp, simp, end, inv_hom_id' := by { apply hom_ext Q, tidy, }, } end equivalence /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟶ (const J).obj W) := { hom := λ f, (t.extend f).ι, inv := λ ι, h.desc { X := W, ι := ι }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) : (is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with vertex `W`. -/ def nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ≅ F.cocones := nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl) /-- Another, more explicit, formulation of the universal property of a colimit cocone. See also `hom_iso`. -/ def hom_iso' (h : is_colimit t) (W : C) : ((t.X ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.hom_iso W ≪≫ { hom := λ ι, ⟨λ j, ι.app j, λ j j' f, by convert ←(ι.naturality f); apply comp_id⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } } /-- If G : C → D is a faithful functor which sends t to a colimit cocone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cocone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X) (h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t := { desc := desc, fac' := λ s j, by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.map_injective, rw h, refine ht.uniq (G.map_cocone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a colimit implies `G.map_cone c` is also a colimit. -/ def map_cocone_equiv {D : Type u'} [category.{v} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : cocone K} (t : is_colimit (F.map_cocone c)) : is_colimit (G.map_cocone c) := begin apply is_colimit.of_iso_colimit _ (precompose_whisker_left_map_cocone h c), apply (precompose_inv_equiv (iso_whisker_left K h : _) _).symm t, end /-- A cocone is a colimit cocone exactly if there is a unique cocone morphism from any other cocone. -/ def iso_unique_cocone_morphism {t : cocone F} : is_colimit t ≅ Π s, unique (t ⟶ s) := { hom := λ h s, { default := h.desc_cocone_morphism s, uniq := λ _, h.uniq_cocone_morphism }, inv := λ h, { desc := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def cocone_of_hom {Y : C} (f : X ⟶ Y) : cocone F := { X := Y, ι := h.hom.app Y f } /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.X`. -/ def hom_of_cocone (s : cocone F) : X ⟶ s.X := h.inv.app s.X s.ι @[simp] lemma cocone_of_hom_of_cocone (s : cocone F) : cocone_of_hom h (hom_of_cocone h s) = s := begin dsimp [cocone_of_hom, hom_of_cocone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) s_X) s_ι, end @[simp] lemma hom_of_cocone_of_hom {Y : C} (f : X ⟶ Y) : hom_of_cocone h (cocone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) Y) f /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimit_cocone : cocone F := cocone_of_hom h (𝟙 X) /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to a morphism `f : Y ⟶ X` is the colimit cocone extended by `f`. -/ lemma cocone_of_hom_fac {Y : C} (f : X ⟶ Y) : cocone_of_hom h f = (colimit_cocone h).extend f := begin dsimp [cocone_of_hom, colimit_cocone, cocone.extend], congr' with j, have t := congr_fun (h.hom.naturality f) (𝟙 X), dsimp at t, simp only [id_comp] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ lemma cocone_fac (s : cocone F) : (colimit_cocone h).extend (hom_of_cocone h s) = s := begin rw ←cocone_of_hom_of_cocone h s, conv_lhs { simp only [hom_of_cocone_of_hom] }, apply (cocone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def of_nat_iso {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) : is_colimit (colimit_cocone h) := { desc := λ s, hom_of_cocone h s, fac' := λ s j, begin have h := cocone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cocone_of_hom h m, congr, rw cocone_of_hom_fac, dsimp, cases s, congr' with j, exact w j, end } end end is_colimit section limit /-- `limit_cone F` contains a cone over `F` together with the information that it is a limit. -/ @[nolint has_inhabited_instance] structure limit_cone (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) /-- `has_limit F` represents the mere existence of a limit for `F`. -/ class has_limit (F : J ⥤ C) : Prop := mk' :: (exists_limit : nonempty (limit_cone F)) lemma has_limit.mk {F : J ⥤ C} (d : limit_cone F) : has_limit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `limit_cone F` from `has_limit F`. -/ def get_limit_cone (F : J ⥤ C) [has_limit F] : limit_cone F := classical.choice $ has_limit.exists_limit variables (J C) /-- `C` has limits of shape `J` if there exists a limit for every functor `F : J ⥤ C`. -/ class has_limits_of_shape : Prop := (has_limit : Π F : J ⥤ C, has_limit F . tactic.apply_instance) /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits : Prop := (has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C . tactic.apply_instance) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F @[priority 100] -- see Note [lower instance priority] instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits C] : has_limits_of_shape J C := has_limits.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- An arbitrary choice of limit cone for a functor. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := (get_limit_cone F).cone /-- An arbitrary choice of limit object of a functor. -/ def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X /-- The projection from the limit object to a value of the functor. -/ def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_X {F : J ⥤ C} [has_limit F] : (limit.cone F).X = limit F := rfl @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] : (limit.cone F).π.app = limit.π _ := rfl @[simp, reassoc] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f /-- Evidence that the arbitrary choice of cone provied by `limit.cone F` is a limit cone. -/ def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := (get_limit_cone F).is_limit /-- The morphism from the cone point of any other cone to the limit object. -/ def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j /-- Functoriality of limits. Usually this morphism should be accessed through `lim.map`, but may be needed separately when you have specified limits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def lim_map {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) : limit F ⟶ limit G := is_limit.map _ (limit.is_limit G) α @[simp, reassoc] lemma lim_map_π {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) (j : J) : lim_map α ≫ limit.π G j = limit.π F j ≫ α.app j := limit.lift_π _ j /-- The cone morphism from any cone to the arbitrary choice of limit cone. -/ def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ limit.cone F := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by simp @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_hom_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso hc (limit.is_limit _)).hom ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ _ @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_inv_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) hc).inv ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _ /-- Given any other limit cone for `F`, the chosen `limit F` is isomorphic to the cone point. -/ def limit.iso_limit_cone {F : J ⥤ C} [has_limit F] (t : limit_cone F) : limit F ≅ t.cone.X := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) t.is_limit @[simp, reassoc] lemma limit.iso_limit_cone_hom_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).hom ≫ t.cone.π.app j = limit.π F j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma limit.iso_limit_cone_inv_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).inv ≫ limit.π F j = t.cone.π.app j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w @[simp] lemma limit.lift_map {F G : J ⥤ C} [has_limit F] [has_limit G] (c : cone F) (α : F ⟶ G) : limit.lift F c ≫ lim_map α = limit.lift G ((cones.postcompose α).obj c) := by { ext, rw [assoc, lim_map_π, limit.lift_π_assoc, limit.lift_π], refl } @[simp] lemma limit.lift_cone {F : J ⥤ C} [has_limit F] : limit.lift F (limit.cone F) = 𝟙 (limit F) := (limit.is_limit _).lift_self /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously /-- If a functor `F` has a limit, so does any naturally isomorphic functor. -/ lemma has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := has_limit.mk { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. lemma has_limit.of_cones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := has_limit.mk ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ /-- The limits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_limit.iso_of_nat_iso {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) : limit F ≅ limit G := is_limit.cone_points_iso_of_nat_iso (limit.is_limit F) (limit.is_limit G) w @[simp, reassoc] lemma has_limit.iso_of_nat_iso_hom_π {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) (j : J) : (has_limit.iso_of_nat_iso w).hom ≫ limit.π G j = limit.π F j ≫ w.hom.app j := is_limit.cone_points_iso_of_nat_iso_hom_comp _ _ _ _ @[simp, reassoc] lemma has_limit.lift_iso_of_nat_iso_hom {F G : J ⥤ C} [has_limit F] [has_limit G] (t : cone F) (w : F ≅ G) : limit.lift F t ≫ (has_limit.iso_of_nat_iso w).hom = limit.lift G ((cones.postcompose w.hom).obj _) := is_limit.lift_comp_cone_points_iso_of_nat_iso_hom _ _ _ /-- The limits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_limit.iso_of_equivalence {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : limit F ≅ limit G := is_limit.cone_points_iso_of_equivalence (limit.is_limit F) (limit.is_limit G) e w @[simp] lemma has_limit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : (has_limit.iso_of_equivalence e w).hom ≫ limit.π G k = limit.π F (e.inverse.obj k) ≫ w.inv.app (e.inverse.obj k) ≫ G.map (e.counit.app k) := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end @[simp] lemma has_limit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : (has_limit.iso_of_equivalence e w).inv ≫ limit.π F j = limit.π G (e.functor.obj j) ≫ w.hom.app j := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] /-- The canonical morphism from the limit of `F` to the limit of `E ⋙ F`. -/ def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) ((limit.cone F).whisker E) @[simp, reassoc] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl variables {E F} /--- If we have particular limit cones available for `E ⋙ F` and for `F`, we obtain a formula for `limit.pre F E`. -/ lemma limit.pre_eq (s : limit_cone (E ⋙ F)) (t : limit_cone F) : limit.pre F E = (limit.iso_limit_cone t).hom ≫ s.is_limit.lift ((t.cone).whisker E) ≫ (limit.iso_limit_cone s).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] /-- The canonical morphism from `G` applied to the limit of `F` to the limit of `F ⋙ G`. -/ def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) (G.map_cone (limit.cone F)) @[simp, reassoc] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by { ext, rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π], refl } @[simp] lemma limit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := has_limit.mk { cone := cone.whisker e.functor (limit.cone F), is_limit := is_limit.whisker_equivalence (limit.is_limit F) e, } local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed /-- If a `E ⋙ F` has a limit, and `E` is an equivalence, we can construct a limit of `F`. -/ lemma has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor variables [has_limits_of_shape J C] section /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ @[simps obj] def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, lim_map α, map_id' := λ F, by { ext, erw [lim_map_π, category.id_comp, category.comp_id] }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } end variables {F} {G : J ⥤ C} (α : F ⟶ G) -- We generate this manually since `simps` gives it a weird name. @[simp] lemma lim_map_eq_lim_map : lim.map α = lim_map α := rfl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by { ext, simp } lemma limit.map_pre' [has_limits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [← category.assoc] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim_map α) ≫ limit.post G H = limit.post F H ≫ lim_map (whisker_right α H) := begin ext, simp only [whisker_right_app, lim_map_π, assoc, limit.post_π_assoc, limit.post_π, ← H.map_comp], end /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor /-- We can transport limits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_limits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } end limit section colimit /-- `colimit_cocone F` contains a cocone over `F` together with the information that it is a colimit. -/ @[nolint has_inhabited_instance] structure colimit_cocone (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) /-- `has_colimit F` represents the mere existence of a colimit for `F`. -/ class has_colimit (F : J ⥤ C) : Prop := mk' :: (exists_colimit : nonempty (colimit_cocone F)) lemma has_colimit.mk {F : J ⥤ C} (d : colimit_cocone F) : has_colimit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `colimit_cocone F` from `has_colimit F`. -/ def get_colimit_cocone (F : J ⥤ C) [has_colimit F] : colimit_cocone F := classical.choice $ has_colimit.exists_colimit variables (J C) /-- `C` has colimits of shape `J` if there exists a colimit for every functor `F : J ⥤ C`. -/ class has_colimits_of_shape : Prop := (has_colimit : Π F : J ⥤ C, has_colimit F . tactic.apply_instance) /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits : Prop := (has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C . tactic.apply_instance) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- An arbitrary choice of colimit cocone of a functor. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := (get_colimit_cocone F).cocone /-- An arbitrary choice of colimit object of a functor. -/ def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X /-- The coprojection from a value of the functor to the colimit object. -/ def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.cocone_X {F : J ⥤ C} [has_colimit F] : (colimit.cocone F).X = colimit F := rfl @[simp, reassoc] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f /-- Evidence that the arbitrary choice of cocone is a colimit cocone. -/ def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := (get_colimit_cocone F).is_colimit /-- The morphism from the colimit object to the cone point of any other cocone. -/ def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j /-- Functoriality of colimits. Usually this morphism should be accessed through `colim.map`, but may be needed separately when you have specified colimits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) : colimit F ⟶ colimit G := is_colimit.map (colimit.is_colimit F) _ α @[simp, reassoc] lemma ι_colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) (j : J) : colimit.ι F j ≫ colim_map α = α.app j ≫ colimit.ι G j := colimit.ι_desc _ j /-- The cocone morphism from the arbitrary choice of colimit cocone to any cocone. -/ def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone F) ⟶ c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by simp @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_hom {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hc).hom = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _ @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_inv {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso hc (colimit.is_colimit _)).inv = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_inv _ _ _ /-- Given any other colimit cocone for `F`, the chosen `colimit F` is isomorphic to the cocone point. -/ def colimit.iso_colimit_cocone {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) : colimit F ≅ t.cocone.X := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) t.is_colimit @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_hom {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : colimit.ι F j ≫ (colimit.iso_colimit_cocone t).hom = t.cocone.ι.app j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_inv {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : t.cocone.ι.app j ≫ (colimit.iso_colimit_cocone t).inv = colimit.ι F j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w @[simp] lemma colimit.desc_cocone {F : J ⥤ C} [has_colimit F] : colimit.desc F (colimit.cocone F) = 𝟙 (colimit F) := (colimit.is_colimit _).desc_self /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end /-- If `F` has a colimit, so does any naturally isomorphic functor. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. lemma has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := has_colimit.mk { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ lemma has_colimit.of_cocones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := has_colimit.mk ⟨_, is_colimit.of_nat_iso ((is_colimit.nat_iso (colimit.is_colimit F)) ≪≫ h)⟩ /-- The colimits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_colimit.iso_of_nat_iso {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_nat_iso (colimit.is_colimit F) (colimit.is_colimit G) w @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_ι_hom {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_nat_iso w).hom = w.hom.app j ≫ colimit.ι G j := is_colimit.comp_cocone_points_iso_of_nat_iso_hom _ _ _ _ @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_hom_desc {F G : J ⥤ C} [has_colimit F] [has_colimit G] (t : cocone G) (w : F ≅ G) : (has_colimit.iso_of_nat_iso w).hom ≫ colimit.desc G t = colimit.desc F ((cocones.precompose w.hom).obj _) := is_colimit.cocone_points_iso_of_nat_iso_hom_desc _ _ _ /-- The colimits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_colimit.iso_of_equivalence {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_equivalence (colimit.is_colimit F) (colimit.is_colimit G) e w @[simp] lemma has_colimit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_equivalence e w).hom = F.map (e.unit.app j) ≫ w.inv.app _ ≫ colimit.ι G _ := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end @[simp] lemma has_colimit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : colimit.ι G k ≫ (has_colimit.iso_of_equivalence e w).inv = G.map (e.counit_inv.app k) ≫ w.hom.app (e.inverse.obj k) ≫ colimit.ι F (e.inverse.obj k) := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] /-- The canonical morphism from the colimit of `E ⋙ F` to the colimit of `F`. -/ def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) ((colimit.cocone F).whisker E) @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end variables {E F} /--- If we have particular colimit cocones available for `E ⋙ F` and for `F`, we obtain a formula for `colimit.pre F E`. -/ lemma colimit.pre_eq (s : colimit_cocone (E ⋙ F)) (t : colimit_cocone F) : colimit.pre F E = (colimit.iso_colimit_cocone s).hom ≫ s.is_colimit.desc ((t.cocone).whisker E) ≫ (colimit.iso_colimit_cocone t).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] /-- The canonical morphism from `G` applied to the colimit of `F ⋙ G` to `G` applied to the colimit of `F`. -/ def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) (G.map_cocone (colimit.cocone F)) @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by { ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc], refl } @[simp] lemma colimit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := has_colimit.mk { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := is_colimit.whisker_equivalence (colimit.is_colimit F) e, } /-- If a `E ⋙ F` has a colimit, and `E` is an equivalence, we can construct a colimit of `F`. -/ lemma has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor variables [has_colimits_of_shape J C] section local attribute [simp] colim_map /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ @[simps obj] def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colim_map α, map_id' := λ F, by { ext, erw [ι_colim_map, id_comp, comp_id] }, map_comp' := λ F G H α β, by { ext, erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc], refl } } end variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colimit.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [← category.assoc] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp], rw [←assoc, colimit.ι_map, assoc, colimit.ι_post], refl end /-- The isomorphism between morphisms from the cone point of the colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor /-- We can transport colimits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } end colimit section opposite /-- If `t : cone F` is a limit cone, then `t.op : cocone F.op` is a colimit cocone. -/ def is_limit.op {t : cone F} (P : is_limit t) : is_colimit t.op := { desc := λ s, (P.lift s.unop).op, fac' := λ s j, congr_arg has_hom.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F` is a colimit cocone, then `t.op : cone F.op` is a limit cone. -/ def is_colimit.op {t : cocone F} (P : is_colimit t) : is_limit t.op := { lift := λ s, (P.desc s.unop).op, fac' := λ s j, congr_arg has_hom.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cone F.op` is a limit cone, then `t.unop : cocone F` is a colimit cocone. -/ def is_limit.unop {t : cone F.op} (P : is_limit t) : is_colimit t.unop := { desc := λ s, (P.lift s.op).unop, fac' := λ s j, congr_arg has_hom.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F.op` is a colimit cocone, then `t.unop : cone F.` is a limit cone. -/ def is_colimit.unop {t : cocone F.op} (P : is_colimit t) : is_limit t.unop := { lift := λ s, (P.desc s.op).unop, fac' := λ s j, congr_arg has_hom.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- `t : cone F` is a limit cone if and only is `t.op : cocone F.op` is a colimit cocone. -/ def is_limit_equiv_is_colimit_op {t : cone F} : is_limit t ≃ is_colimit t.op := equiv_of_subsingleton_of_subsingleton is_limit.op (λ P, P.unop.of_iso_limit (cones.ext (iso.refl _) (by tidy))) /-- `t : cocone F` is a colimit cocone if and only is `t.op : cone F.op` is a limit cone. -/ def is_colimit_equiv_is_limit_op {t : cocone F} : is_colimit t ≃ is_limit t.op := equiv_of_subsingleton_of_subsingleton is_colimit.op (λ P, P.unop.of_iso_colimit (cocones.ext (iso.refl _) (by tidy))) end opposite end category_theory.limits
ad577b29e4d8e710a84a259fe1462ec9c39ce00e
c777c32c8e484e195053731103c5e52af26a25d1
/src/probability/kernel/with_density.lean
5ab8e74f45cfb8cabaa1b33a004c9b37cd764b85
[ "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
10,702
lean
/- Copyright (c) 2023 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import probability.kernel.measurable_integral /-! # With Density For an s-finite kernel `κ : kernel α β` and a function `f : α → β → ℝ≥0∞` which is finite everywhere, we define `with_density κ f` as the kernel `a ↦ (κ a).with_density (f a)`. This is an s-finite kernel. ## Main definitions * `probability_theory.kernel.with_density κ (f : α → β → ℝ≥0∞)`: kernel `a ↦ (κ a).with_density (f a)`. It is defined if `κ` is s-finite. If `f` is finite everywhere, then this is also an s-finite kernel. The class of s-finite kernels is the smallest class of kernels that contains finite kernels and which is stable by `with_density`. Integral: `∫⁻ b, g b ∂(with_density κ f a) = ∫⁻ b, f a b * g b ∂(κ a)` ## Main statements * `probability_theory.kernel.lintegral_with_density`: `∫⁻ b, g b ∂(with_density κ f a) = ∫⁻ b, f a b * g b ∂(κ a)` -/ open measure_theory probability_theory open_locale measure_theory ennreal nnreal big_operators namespace probability_theory.kernel variables {α β ι : Type*} {mα : measurable_space α} {mβ : measurable_space β} include mα mβ variables {κ : kernel α β} {f : α → β → ℝ≥0∞} /-- Kernel with image `(κ a).with_density (f a)` if `function.uncurry f` is measurable, and with image 0 otherwise. If `function.uncurry f` is measurable, it satisfies `∫⁻ b, g b ∂(with_density κ f hf a) = ∫⁻ b, f a b * g b ∂(κ a)`. -/ noncomputable def with_density (κ : kernel α β) [is_s_finite_kernel κ] (f : α → β → ℝ≥0∞) : kernel α β := @dite _ (measurable (function.uncurry f)) (classical.dec _) (λ hf, ({ val := λ a, (κ a).with_density (f a), property := begin refine measure.measurable_of_measurable_coe _ (λ s hs, _), simp_rw with_density_apply _ hs, exact hf.set_lintegral_kernel_prod_right hs, end, } : kernel α β)) (λ hf, 0) lemma with_density_of_not_measurable (κ : kernel α β) [is_s_finite_kernel κ] (hf : ¬ measurable (function.uncurry f)) : with_density κ f = 0 := by { classical, exact dif_neg hf, } protected lemma with_density_apply (κ : kernel α β) [is_s_finite_kernel κ] (hf : measurable (function.uncurry f)) (a : α) : with_density κ f a = (κ a).with_density (f a) := by { classical, rw [with_density, dif_pos hf], refl, } lemma with_density_apply' (κ : kernel α β) [is_s_finite_kernel κ] (hf : measurable (function.uncurry f)) (a : α) {s : set β} (hs : measurable_set s) : with_density κ f a s = ∫⁻ b in s, f a b ∂(κ a) := by rw [kernel.with_density_apply κ hf, with_density_apply _ hs] lemma lintegral_with_density (κ : kernel α β) [is_s_finite_kernel κ] (hf : measurable (function.uncurry f)) (a : α) {g : β → ℝ≥0∞} (hg : measurable g) : ∫⁻ b, g b ∂(with_density κ f a) = ∫⁻ b, f a b * g b ∂(κ a) := begin rw [kernel.with_density_apply _ hf, lintegral_with_density_eq_lintegral_mul _ (measurable.of_uncurry_left hf) hg], simp_rw pi.mul_apply, end lemma with_density_add_left (κ η : kernel α β) [is_s_finite_kernel κ] [is_s_finite_kernel η] (f : α → β → ℝ≥0∞) : with_density (κ + η) f = with_density κ f + with_density η f := begin by_cases hf : measurable (function.uncurry f), { ext a s hs : 2, simp only [kernel.with_density_apply _ hf, coe_fn_add, pi.add_apply, with_density_add_measure, measure.add_apply], }, { simp_rw [with_density_of_not_measurable _ hf], rw zero_add, }, end lemma with_density_kernel_sum [countable ι] (κ : ι → kernel α β) (hκ : ∀ i, is_s_finite_kernel (κ i)) (f : α → β → ℝ≥0∞) : @with_density _ _ _ _ (kernel.sum κ) (is_s_finite_kernel_sum hκ) f = kernel.sum (λ i, with_density (κ i) f) := begin by_cases hf : measurable (function.uncurry f), { ext1 a, simp_rw [sum_apply, kernel.with_density_apply _ hf, sum_apply, with_density_sum (λ n, κ n a) (f a)], }, { simp_rw [with_density_of_not_measurable _ hf], exact sum_zero.symm, }, end lemma with_density_tsum [countable ι] (κ : kernel α β) [is_s_finite_kernel κ] {f : ι → α → β → ℝ≥0∞} (hf : ∀ i, measurable (function.uncurry (f i))) : with_density κ (∑' n, f n) = kernel.sum (λ n, with_density κ (f n)) := begin have h_sum_a : ∀ a, summable (λ n, f n a) := λ a, pi.summable.mpr (λ b, ennreal.summable), have h_sum : summable (λ n, f n) := pi.summable.mpr h_sum_a, ext a s hs : 2, rw [sum_apply' _ a hs, with_density_apply' κ _ a hs], swap, { have : function.uncurry (∑' n, f n) = ∑' n, function.uncurry (f n), { ext1 p, simp only [function.uncurry_def], rw [tsum_apply h_sum, tsum_apply (h_sum_a _), tsum_apply], exact pi.summable.mpr (λ p, ennreal.summable), }, rw this, exact measurable.ennreal_tsum' hf, }, have : ∫⁻ b in s, (∑' n, f n) a b ∂(κ a) = ∫⁻ b in s, (∑' n, (λ b, f n a b) b) ∂(κ a), { congr' with b, rw [tsum_apply h_sum, tsum_apply (h_sum_a a)], }, rw [this, lintegral_tsum (λ n, (measurable.of_uncurry_left (hf n)).ae_measurable)], congr' with n, rw with_density_apply' _ (hf n) a hs, end /-- If a kernel `κ` is finite and a function `f : α → β → ℝ≥0∞` is bounded, then `with_density κ f` is finite. -/ lemma is_finite_kernel_with_density_of_bounded (κ : kernel α β) [is_finite_kernel κ] {B : ℝ≥0∞} (hB_top : B ≠ ∞) (hf_B : ∀ a b, f a b ≤ B) : is_finite_kernel (with_density κ f) := begin by_cases hf : measurable (function.uncurry f), { exact ⟨⟨B * is_finite_kernel.bound κ, ennreal.mul_lt_top hB_top (is_finite_kernel.bound_ne_top κ), λ a, begin rw with_density_apply' κ hf a measurable_set.univ, calc ∫⁻ b in set.univ, f a b ∂(κ a) ≤ ∫⁻ b in set.univ, B ∂(κ a) : lintegral_mono (hf_B a) ... = B * κ a set.univ : by simp only [measure.restrict_univ, measure_theory.lintegral_const] ... ≤ B * is_finite_kernel.bound κ : mul_le_mul_left' (measure_le_bound κ a set.univ) _, end⟩⟩, }, { rw with_density_of_not_measurable _ hf, apply_instance, }, end /-- Auxiliary lemma for `is_s_finite_kernel_with_density`. If a kernel `κ` is finite, then `with_density κ f` is s-finite. -/ lemma is_s_finite_kernel_with_density_of_is_finite_kernel (κ : kernel α β) [is_finite_kernel κ] (hf_ne_top : ∀ a b, f a b ≠ ∞) : is_s_finite_kernel (with_density κ f) := begin -- We already have that for `f` bounded from above and a `κ` a finite kernel, -- `with_density κ f` is finite. We write any function as a countable sum of bounded -- functions, and decompose an s-finite kernel as a sum of finite kernels. We then use that -- `with_density` commutes with sums for both arguments and get a sum of finite kernels. by_cases hf : measurable (function.uncurry f), swap, { rw with_density_of_not_measurable _ hf, apply_instance, }, let fs : ℕ → α → β → ℝ≥0∞ := λ n a b, min (f a b) (n + 1) - min (f a b) n, have h_le : ∀ a b n, ⌈(f a b).to_real⌉₊ ≤ n → f a b ≤ n, { intros a b n hn, have : (f a b).to_real ≤ n := nat.le_of_ceil_le hn, rw ← ennreal.le_of_real_iff_to_real_le (hf_ne_top a b) _ at this, { refine this.trans (le_of_eq _), rw ennreal.of_real_coe_nat, }, { norm_cast, exact zero_le _, }, }, have h_zero : ∀ a b n, ⌈(f a b).to_real⌉₊ ≤ n → fs n a b = 0, { intros a b n hn, suffices : min (f a b) (n + 1) = f a b ∧ min (f a b) n = f a b, { simp_rw [fs, this.1, this.2, tsub_self (f a b)], }, exact ⟨min_eq_left ((h_le a b n hn).trans (le_add_of_nonneg_right zero_le_one)), min_eq_left (h_le a b n hn)⟩, }, have hf_eq_tsum : f = ∑' n, fs n, { have h_sum_a : ∀ a, summable (λ n, fs n a), { refine λ a, pi.summable.mpr (λ b, _), suffices : ∀ n, n ∉ finset.range ⌈(f a b).to_real⌉₊ → fs n a b = 0, from summable_of_ne_finset_zero this, intros n hn_not_mem, rw [finset.mem_range, not_lt] at hn_not_mem, exact h_zero a b n hn_not_mem, }, ext a b : 2, rw [tsum_apply (pi.summable.mpr h_sum_a), tsum_apply (h_sum_a a), ennreal.tsum_eq_liminf_sum_nat], have h_finset_sum : ∀ n, ∑ i in finset.range n, fs i a b = min (f a b) n, { intros n, induction n with n hn, { simp only [finset.range_zero, finset.sum_empty, algebra_map.coe_zero, min_zero], }, rw [finset.sum_range_succ, hn], simp_rw [fs], norm_cast, rw add_tsub_cancel_iff_le, refine min_le_min le_rfl _, norm_cast, exact nat.le_succ n, }, simp_rw h_finset_sum, refine (filter.tendsto.liminf_eq _).symm, refine filter.tendsto.congr' _ tendsto_const_nhds, rw [filter.eventually_eq, filter.eventually_at_top], exact ⟨⌈(f a b).to_real⌉₊, λ n hn, (min_eq_left (h_le a b n hn)).symm⟩, }, rw [hf_eq_tsum, with_density_tsum _ (λ (n : ℕ), _)], swap, { exact (hf.min measurable_const).sub (hf.min measurable_const), }, refine is_s_finite_kernel_sum (λ n, _), suffices : is_finite_kernel (with_density κ (fs n)), by { haveI := this, apply_instance, }, refine is_finite_kernel_with_density_of_bounded _ (ennreal.coe_ne_top : (↑n + 1) ≠ ∞) (λ a b, _), norm_cast, calc fs n a b ≤ min (f a b) (n + 1) : tsub_le_self ... ≤ (n + 1) : min_le_right _ _ ... = ↑(n + 1) : by norm_cast, end /-- For a s-finite kernel `κ` and a function `f : α → β → ℝ≥0∞` which is everywhere finite, `with_density κ f` is s-finite. -/ theorem is_s_finite_kernel.with_density (κ : kernel α β) [is_s_finite_kernel κ] (hf_ne_top : ∀ a b, f a b ≠ ∞) : is_s_finite_kernel (with_density κ f) := begin have h_eq_sum : with_density κ f = kernel.sum (λ i, with_density (seq κ i) f), { rw ← with_density_kernel_sum _ _, congr, exact (kernel_sum_seq κ).symm, }, rw h_eq_sum, exact is_s_finite_kernel_sum (λ n, is_s_finite_kernel_with_density_of_is_finite_kernel (seq κ n) hf_ne_top), end /-- For a s-finite kernel `κ` and a function `f : α → β → ℝ≥0`, `with_density κ f` is s-finite. -/ instance (κ : kernel α β) [is_s_finite_kernel κ] (f : α → β → ℝ≥0) : is_s_finite_kernel (with_density κ (λ a b, f a b)) := is_s_finite_kernel.with_density κ (λ _ _, ennreal.coe_ne_top) end probability_theory.kernel
79295fc2c016341982e0a7070e8b1a27437621b3
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/group_theory/perm/concrete_cycle.lean
dbb86e70c50fdde93ae777205cd3d49baaa08b41
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,936
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import group_theory.perm.list import data.list.cycle import group_theory.perm.cycle_type /-! # Properties of cyclic permutations constructed from lists In the following, `{α : Type*} [fintype α] [decidable_eq α]`. ## Main definitions * `cycle.form_perm`: the cyclic permutation created by looping over a `cycle α` ## Main results * `list.is_cycle_form_perm`: a nontrivial list without duplicates, when interpreted as a permutation, is cyclic -/ open equiv equiv.perm list namespace list variables {α : Type*} [decidable_eq α] {l l' : list α} lemma form_perm_disjoint_iff (hl : nodup l) (hl' : nodup l') (hn : 2 ≤ l.length) (hn' : 2 ≤ l'.length) : perm.disjoint (form_perm l) (form_perm l') ↔ l.disjoint l' := begin rw [disjoint_iff_eq_or_eq, list.disjoint], split, { rintro h x hx hx', specialize h x, rw [form_perm_apply_mem_eq_self_iff _ hl _ hx, form_perm_apply_mem_eq_self_iff _ hl' _ hx'] at h, rcases h with hl | hl'; linarith }, { intros h x, by_cases hx : x ∈ l; by_cases hx' : x ∈ l', { exact (h hx hx').elim }, all_goals { have := form_perm_eq_self_of_not_mem _ _ ‹_›, tauto } } end lemma is_cycle_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : is_cycle (form_perm l) := begin cases l with x l, { norm_num at hn }, induction l with y l IH generalizing x, { norm_num at hn }, { use x, split, { rwa form_perm_apply_mem_ne_self_iff _ hl _ (mem_cons_self _ _) }, { intros w hw, have : w ∈ (x :: y :: l) := mem_of_form_perm_ne_self _ _ hw, obtain ⟨k, hk, rfl⟩ := nth_le_of_mem this, use k, simp only [gpow_coe_nat, form_perm_pow_apply_head _ _ hl k, nat.mod_eq_of_lt hk] } } end lemma pairwise_same_cycle_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : pairwise (l.form_perm.same_cycle) l := pairwise.imp_mem.mpr (pairwise_of_forall (λ x y hx hy, (is_cycle_form_perm hl hn).same_cycle ((form_perm_apply_mem_ne_self_iff _ hl _ hx).mpr hn) ((form_perm_apply_mem_ne_self_iff _ hl _ hy).mpr hn))) lemma cycle_of_form_perm (hl : nodup l) (hn : 2 ≤ l.length) (x) : cycle_of l.attach.form_perm x = l.attach.form_perm := have hn : 2 ≤ l.attach.length := by rwa ← length_attach at hn, have hl : l.attach.nodup := by rwa ← nodup_attach at hl, (is_cycle_form_perm hl hn).cycle_of_eq ((form_perm_apply_mem_ne_self_iff _ hl _ (mem_attach _ _)).mpr hn) lemma cycle_type_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : cycle_type l.attach.form_perm = {l.length} := begin rw ←length_attach at hn, rw ←nodup_attach at hl, rw cycle_type_eq [l.attach.form_perm], { simp only [map, function.comp_app], rw [support_form_perm_of_nodup _ hl, card_to_finset, erase_dup_eq_self.mpr hl], { simpa }, { intros x h, simpa [h, nat.succ_le_succ_iff] using hn } }, { simp }, { simpa using is_cycle_form_perm hl hn }, { simp } end lemma form_perm_apply_mem_eq_next (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = next l x hx := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [next_nth_le _ hl, form_perm_apply_nth_le _ hl] end end list namespace cycle variables {α : Type*} [decidable_eq α] (s s' : cycle α) /-- A cycle `s : cycle α` , given `nodup s` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. -/ def form_perm : Π (s : cycle α) (h : nodup s), equiv.perm α := λ s, quot.hrec_on s (λ l h, form_perm l) (λ l₁ l₂ (h : l₁ ~r l₂), begin ext, { exact h.nodup_iff }, { intros h₁ h₂ _, exact heq_of_eq (form_perm_eq_of_is_rotated h₁ h) } end) @[simp] lemma form_perm_coe (l : list α) (hl : l.nodup) : form_perm (l : cycle α) hl = l.form_perm := rfl lemma form_perm_subsingleton (s : cycle α) (h : subsingleton s) : form_perm s h.nodup = 1 := begin induction s using quot.induction_on, simp only [form_perm_coe, mk_eq_coe], simp only [length_subsingleton_iff, length_coe, mk_eq_coe] at h, cases s with hd tl, { simp }, { simp only [length_eq_zero, add_le_iff_nonpos_left, list.length, nonpos_iff_eq_zero] at h, simp [h] } end lemma is_cycle_form_perm (s : cycle α) (h : nodup s) (hn : nontrivial s) : is_cycle (form_perm s h) := begin induction s using quot.induction_on, exact list.is_cycle_form_perm h (length_nontrivial hn) end lemma support_form_perm [fintype α] (s : cycle α) (h : nodup s) (hn : nontrivial s) : support (form_perm s h) = s.to_finset := begin induction s using quot.induction_on, refine support_form_perm_of_nodup s h _, rintro _ rfl, simpa [nat.succ_le_succ_iff] using length_nontrivial hn end lemma form_perm_eq_self_of_not_mem (s : cycle α) (h : nodup s) (x : α) (hx : x ∉ s) : form_perm s h x = x := begin induction s using quot.induction_on, simpa using list.form_perm_eq_self_of_not_mem _ _ hx end lemma form_perm_apply_mem_eq_next (s : cycle α) (h : nodup s) (x : α) (hx : x ∈ s) : form_perm s h x = next s h x hx := begin induction s using quot.induction_on, simpa using list.form_perm_apply_mem_eq_next h _ _ end lemma form_perm_reverse (s : cycle α) (h : nodup s) : form_perm s.reverse (nodup_reverse_iff.mpr h) = (form_perm s h)⁻¹ := begin induction s using quot.induction_on, simpa using form_perm_reverse _ h end lemma form_perm_eq_form_perm_iff {α : Type*} [decidable_eq α] {s s' : cycle α} {hs : s.nodup} {hs' : s'.nodup} : s.form_perm hs = s'.form_perm hs' ↔ s = s' ∨ s.subsingleton ∧ s'.subsingleton := begin rw [cycle.length_subsingleton_iff, cycle.length_subsingleton_iff], revert s s', intros s s', apply quotient.induction_on₂' s s', intros l l', simpa using form_perm_eq_form_perm_iff end end cycle
34b92765b6fad1e08bca062305f5588c8c7bb915
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/universal/comparisons/products.lean
33570650ff38fc5aa91e4bd9e6543d2cf97494de
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
1,433
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 ...isomorphism import ...natural_transformation import ...equivalence import ..comma_categories import ..universal open categories open categories.functor open categories.natural_transformation open categories.isomorphism open categories.equivalence open categories.universal namespace categories.universal -- definition comma_Product_to_Product { C : Category } { I : Type } ( F : I → C.Obj ) ( product : comma.Product F ) : Product F := { -- product := product.object.1, -- projection := product.object.2.2.components, -- -- Grah, "tactic failed, result contains meta-variables" -- map := λ Z f, (product.morphisms ⟨ Z, _, { components := f, naturality := begin intros, unfold_projections, unfold_projections_hypotheses, simp, induction f_1, induction down, induction down_1, simp, end } ⟩).val.1, -- factorisation := sorry, -- uniqueness := sorry -- } -- definition Product_to_comma_Product { C : Category } { I : Type } ( F : I → C.Obj ) ( product : Product F ) : comma.Product F := sorry -- definition Products_agree { C : Category } { I : Type } ( F : I → C.Obj ) : Isomorphism CategoryOfTypes (comma.Product f g) (Product f g) := sorry -- PROJECT prove products are unique end categories.universal
e0e3ee3a65622839ab68d73a06cd14f64cc79c42
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/category/Mon/limits.lean
358510c9fa89954883bed007d2d118f50d9956bb
[ "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
6,603
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.group.pi import algebra.category.Mon.basic import category_theory.limits.types import category_theory.limits.creates /-! # The category of (commutative) (additive) monoids has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ noncomputable theory open category_theory open category_theory.limits universe u namespace Mon variables {J : Type u} [small_category J] @[to_additive] instance monoid_obj (F : J ⥤ Mon) (j) : monoid ((F ⋙ forget Mon).obj j) := by { change monoid (F.obj j), apply_instance } /-- The flat sections of a functor into `Mon` form a submonoid of all sections. -/ @[to_additive "The flat sections of a functor into `AddMon` form an additive submonoid of all sections."] def sections_submonoid (F : J ⥤ Mon) : submonoid (Π j, F.obj j) := { carrier := (F ⋙ forget Mon).sections, one_mem' := λ j j' f, by simp, mul_mem' := λ a b ah bh j j' f, begin simp only [forget_map_eq_coe, functor.comp_map, monoid_hom.map_mul, pi.mul_apply], dsimp [functor.sections] at ah bh, rw [ah f, bh f], end } @[to_additive] instance limit_monoid (F : J ⥤ Mon) : monoid (types.limit_cone (F ⋙ forget Mon.{u})).X := (sections_submonoid F).to_monoid /-- `limit.π (F ⋙ forget Mon) j` as a `monoid_hom`. -/ @[to_additive "`limit.π (F ⋙ forget AddMon) j` as an `add_monoid_hom`."] def limit_π_monoid_hom (F : J ⥤ Mon.{u}) (j) : (types.limit_cone (F ⋙ forget Mon)).X →* (F ⋙ forget Mon).obj j := { to_fun := (types.limit_cone (F ⋙ forget Mon)).π.app j, map_one' := rfl, map_mul' := λ x y, rfl } namespace has_limits -- The next two definitions are used in the construction of `has_limits Mon`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `Mon`. (Internal use only; use the limits API.) -/ @[to_additive "(Internal use only; use the limits API.)"] def limit_cone (F : J ⥤ Mon) : cone F := { X := Mon.of (types.limit_cone (F ⋙ forget _)).X, π := { app := limit_π_monoid_hom F, naturality' := λ j j' f, monoid_hom.coe_inj ((types.limit_cone (F ⋙ forget _)).π.naturality f) } } /-- Witness that the limit cone in `Mon` is a limit cone. (Internal use only; use the limits API.) -/ @[to_additive "(Internal use only; use the limits API.)"] def limit_cone_is_limit (F : J ⥤ Mon) : is_limit (limit_cone F) := begin refine is_limit.of_faithful (forget Mon) (types.limit_cone_is_limit _) (λ s, ⟨_, _, _⟩) (λ s, rfl); tidy, end end has_limits open has_limits /-- The category of monoids has all limits. -/ @[to_additive] instance has_limits : has_limits Mon := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } /-- The forgetful functor from monoids to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ @[to_additive] instance forget_preserves_limits : preserves_limits (forget Mon) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (types.limit_cone_is_limit (F ⋙ forget _)) } } end Mon namespace CommMon variables {J : Type u} [small_category J] @[to_additive] instance comm_monoid_obj (F : J ⥤ CommMon) (j) : comm_monoid ((F ⋙ forget CommMon).obj j) := by { change comm_monoid (F.obj j), apply_instance } @[to_additive] instance limit_comm_monoid (F : J ⥤ CommMon) : comm_monoid (types.limit_cone (F ⋙ forget CommMon.{u})).X := @submonoid.to_comm_monoid (Π j, F.obj j) _ (Mon.sections_submonoid (F ⋙ forget₂ CommMon Mon.{u})) /-- We show that the forgetful functor `CommMon ⥤ Mon` creates limits. All we need to do is notice that the limit point has a `comm_monoid` instance available, and then reuse the existing limit. -/ @[to_additive] instance (F : J ⥤ CommMon) : creates_limit F (forget₂ CommMon Mon.{u}) := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := { X := CommMon.of (types.limit_cone (F ⋙ forget CommMon)).X, π := { app := Mon.limit_π_monoid_hom (F ⋙ forget₂ CommMon Mon), naturality' := (Mon.has_limits.limit_cone (F ⋙ forget₂ _ _)).π.naturality, } }, valid_lift := is_limit.unique_up_to_iso (Mon.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forget₂ CommMon Mon.{u}) (Mon.has_limits.limit_cone_is_limit _) (λ s, _) (λ s, rfl) }) /-- A choice of limit cone for a functor into `CommMon`. (Generally, you'll just want to use `limit F`.) -/ @[to_additive "A choice of limit cone for a functor into `CommMon`. (Generally, you'll just want to use `limit F`.)"] def limit_cone (F : J ⥤ CommMon) : cone F := lift_limit (limit.is_limit (F ⋙ (forget₂ CommMon Mon.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ @[to_additive "The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.)"] def limit_cone_is_limit (F : J ⥤ CommMon) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of commutative monoids has all limits. -/ @[to_additive] instance has_limits : has_limits CommMon := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit_of_created F (forget₂ CommMon Mon) } } /-- The forgetful functor from commutative monoids to monoids preserves all limits. (That is, the underlying monoid could have been computed instead as limits in the category of monoids.) -/ @[to_additive AddCommMon.forget₂_AddMon_preserves_limits] instance forget₂_Mon_preserves_limits : preserves_limits (forget₂ CommMon Mon) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by apply_instance } } /-- The forgetful functor from commutative monoids to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ @[to_additive] instance forget_preserves_limits : preserves_limits (forget CommMon) := { preserves_limits_of_shape := λ J 𝒥, by exactI { preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommMon Mon) (forget Mon) } } end CommMon
8df7f96daa07ca6a9b43dc9087dfa26b36a2bc7e
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/category/combinators.lean
dcf686a009776567d0eb59a637a0f702bef291a4
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
3,740
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Monad combinators, as in Haskell's Control.Monad. -/ prelude import init.category.monad init.data.list.basic universes u v w def list.mmap {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m β) : list α → m (list β) | [] := return [] | (h :: t) := do h' ← f h, t' ← list.mmap t, return (h' :: t') def list.mmap' {m : Type → Type v} [monad m] {α : Type u} {β : Type} (f : α → m β) : list α → m unit | [] := return () | (h :: t) := f h >> list.mmap' t def list.mfor {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (l : list α) (f : α → m β) : m (list β) := list.mmap f l def list.mfor' {m : Type → Type v} [monad m] {α : Type u} {β : Type} (l : list α) (f : α → m β) : m unit := list.mmap' f l infix ` =<< `:2 := λ u v, v >>= u infix ` >=> `:2 := λ s t a, s a >>= t infix ` <=< `:2 := λ t s a, s a >>= t def mjoin {m : Type u → Type u} [monad m] {α : Type u} (a : m (m α)) : m α := bind a id def list.mfilter {m : Type → Type v} [monad m] {α : Type} (f : α → m bool) : list α → m (list α) | [] := return [] | (h :: t) := do b ← f h, t' ← list.mfilter t, cond b (return (h :: t')) (return t') def list.mfoldl {m : Type u → Type v} [monad m] {s : Type u} {α : Type w} : (s → α → m s) → s → list α → m s | f s [] := return s | f s (h :: r) := do s' ← f s h, list.mfoldl f s' r def when {m : Type → Type} [monad m] (c : Prop) [h : decidable c] (t : m unit) : m unit := ite c t (pure ()) def mcond {m : Type → Type} [monad m] {α : Type} (mbool : m bool) (tm fm : m α) : m α := do b ← mbool, cond b tm fm def mwhen {m : Type → Type} [monad m] (c : m bool) (t : m unit) : m unit := mcond c t (return ()) export list (mmap mmap' mfor mfor' mfilter mfoldl) namespace monad def mapm := @mmap def mapm' := @mmap' def for := @mfor def for' := @mfor' def join := @mjoin def filter := @mfilter def foldl := @mfoldl def cond := @mcond def sequence {m : Type u → Type v} [monad m] {α : Type u} : list (m α) → m (list α) | [] := return [] | (h :: t) := do h' ← h, t' ← sequence t, return (h' :: t') def sequence' {m : Type → Type u} [monad m] {α : Type} : list (m α) → m unit | [] := return () | (h :: t) := h >> sequence' t def whenb {m : Type → Type} [monad m] (b : bool) (t : m unit) : m unit := _root_.cond b t (return ()) def unlessb {m : Type → Type} [monad m] (b : bool) (t : m unit) : m unit := _root_.cond b (return ()) t def lift {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → φ) (ma : m α) : m φ := do a ← ma, return (f a) def lift₂ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → φ) (ma₁ ma₂: m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, return (f a₁ a₂) def lift₃ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → φ) (ma₁ ma₂ ma₃ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, return (f a₁ a₂ a₃) def lift₄ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → α → φ) (ma₁ ma₂ ma₃ ma₄ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, a₄ ← ma₄, return (f a₁ a₂ a₃ a₄) def lift₅ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → α → α → φ) (ma₁ ma₂ ma₃ ma₄ ma₅ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, a₄ ← ma₄, a₅ ← ma₅, return (f a₁ a₂ a₃ a₄ a₅) end monad
63add9524823c20cccb792b81f4994ac9bb64509
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/646.lean
54389567056f90826080dae16cca1a8820b86f13
[ "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
389
lean
def build (n : Nat) : Array Unit := Id.run <| do let mut out := #[] for _ in [0:n] do out := out.push () out @[noinline] def size : IO Nat := pure 50000 def bench (f : ∀ {α : Type}, α → IO Unit := fun _ => pure ()) : IO Unit := do let n ← size let arr := build n timeit "time" $ for _ in [:1000] do f $ #[1, 2, 3, 4].map fun ty => arr[ty]! #eval bench
3398fe3cb0870f88c618f5cdb3708cc40a6c6cb2
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/advanced_addition/06.lean
affc686b6c22b962dd32db6f963c5923cb869de7
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
168
lean
theorem add_left_cancel (t a b : mynat) : t + a = t + b → a = b := begin rw [add_comm t a, add_comm t b], exact add_right_cancel a t b, -- I can't count to 3 end
050185a0144d5e2423701874f971e223f418a75b
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/init/quot.lean
e69eded61dfcdac800d873cfd26c505eb361e402
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,990
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.quot Author: Leonardo de Moura Quotient types. -/ prelude import init.sigma init.setoid init.logic open sigma.ops setoid constant quot.{l} : Π {A : Type.{l}}, setoid A → Type.{l} -- Remark: if we do not use propext here, then we would need a quot.lift for propositions. constant propext {a b : Prop} : (a ↔ b) → a = b namespace quot constant mk : Π {A : Type} [s : setoid A], A → quot s notation `⟦`:max a `⟧`:0 := mk a constant sound : Π {A : Type} [s : setoid A] {a b : A}, a ≈ b → ⟦a⟧ = ⟦b⟧ constant exact : Π {A : Type} [s : setoid A] {a b : A}, ⟦a⟧ = ⟦b⟧ → a ≈ b constant lift : Π {A B : Type} [s : setoid A] (f : A → B), (∀ a b, a ≈ b → f a = f b) → quot s → B constant ind : ∀ {A : Type} [s : setoid A] {B : quot s → Prop}, (∀ a, B ⟦a⟧) → ∀ q, B q init_quotient protected theorem lift_beta {A B : Type} [s : setoid A] (f : A → B) (c : ∀ a b, a ≈ b → f a = f b) (a : A) : lift f c ⟦a⟧ = f a := rfl protected theorem ind_beta {A : Type} [s : setoid A] {B : quot s → Prop} (p : ∀ a, B ⟦a⟧) (a : A) : ind p ⟦a⟧ = p a := rfl protected definition lift_on [reducible] {A B : Type} [s : setoid A] (q : quot s) (f : A → B) (c : ∀ a b, a ≈ b → f a = f b) : B := lift f c q protected theorem induction_on {A : Type} [s : setoid A] {B : quot s → Prop} (q : quot s) (H : ∀ a, B ⟦a⟧) : B q := ind H q section variable {A : Type} variable [s : setoid A] variable {B : quot s → Type} include s protected definition indep [reducible] (f : Π a, B ⟦a⟧) (a : A) : Σ q, B q := ⟨⟦a⟧, f a⟩ protected lemma indep_coherent (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) : ∀ a b, a ≈ b → indep f a = indep f b := λa b e, sigma.equal (sound e) (H a b e) protected lemma lift_indep_pr1 (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) (q : quot s) : (lift (indep f) (indep_coherent f H) q).1 = q := ind (λ a, by esimp) q protected definition rec [reducible] (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) (q : quot s) : B q := let p := lift (indep f) (indep_coherent f H) q in eq.rec_on (lift_indep_pr1 f H q) (p.2) protected definition rec_on [reducible] (q : quot s) (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) : B q := rec f H q protected definition rec_on_subsingleton [reducible] [H : ∀ a, subsingleton (B ⟦a⟧)] (q : quot s) (f : Π a, B ⟦a⟧) : B q := rec f (λ a b h, !subsingleton.elim) q end section variables {A B C : Type} variables [s₁ : setoid A] [s₂ : setoid B] include s₁ s₂ protected definition lift₂ [reducible] (f : A → B → C)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (q₁ : quot s₁) (q₂ : quot s₂) : C := lift (λ a₁, lift (λ a₂, f a₁ a₂) (λ a b H, c a₁ a a₁ b (setoid.refl a₁) H) q₂) (λ a b H, ind (λ a', proof c a a' b a' H (setoid.refl a') qed) q₂) q₁ protected definition lift_on₂ [reducible] (q₁ : quot s₁) (q₂ : quot s₂) (f : A → B → C) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : C := lift₂ f c q₁ q₂ protected theorem ind₂ {C : quot s₁ → quot s₂ → Prop} (H : ∀ a b, C ⟦a⟧ ⟦b⟧) (q₁ : quot s₁) (q₂ : quot s₂) : C q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, H a₁ a₂) q₂) q₁ protected theorem induction_on₂ {C : quot s₁ → quot s₂ → Prop} (q₁ : quot s₁) (q₂ : quot s₂) (H : ∀ a b, C ⟦a⟧ ⟦b⟧) : C q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, H a₁ a₂) q₂) q₁ protected theorem induction_on₃ [s₃ : setoid C] {D : quot s₁ → quot s₂ → quot s₃ → Prop} (q₁ : quot s₁) (q₂ : quot s₂) (q₃ : quot s₃) (H : ∀ a b c, D ⟦a⟧ ⟦b⟧ ⟦c⟧) : D q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, H a₁ a₂ a₃) q₃) q₂) q₁ end section variables {A B : Type} variables [s₁ : setoid A] [s₂ : setoid B] include s₁ s₂ variable {C : quot s₁ → quot s₂ → Type} protected definition rec_on_subsingleton₂ [reducible] {C : quot s₁ → quot s₂ → Type₁} [H : ∀ a b, subsingleton (C ⟦a⟧ ⟦b⟧)] (q₁ : quot s₁) (q₂ : quot s₂) (f : Π a b, C ⟦a⟧ ⟦b⟧) : C q₁ q₂:= @quot.rec_on_subsingleton _ _ _ (λ a, quot.ind _ _) q₁ (λ a, quot.rec_on_subsingleton q₂ (λ b, f a b)) end end quot
67446ebbdd96acbcec7936e0a35cb830bcc33c43
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/omin/tactic.lean
b29959ec4728c1d58650bd3b624ea323e56deb3f
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
13,102
lean
import data.list.alist import .presheaf2 namespace o_minimal variables {R : Type*} {S : struc R} structure sect (Γ : Def S) (X : Type*) [definable_psh S X] := (to_fun : Γ → X) (definable : definable_psh.definable to_fun) infixr ` ⊢ `:10 := sect def sect.precomp {Γ' Γ : Def S} {X : Type*} [definable_psh S X] (σ : Γ ⊢ X) (φ : Hom Γ' Γ) : Γ' ⊢ X := { to_fun := σ.to_fun ∘ φ.to_fun, definable := definable_psh.definable_precomp φ σ.definable } lemma begin_lem {X : Type*} [definable_psh S X] {x : X} : definable S x ↔ ∀ (Γ : Def S), definable_psh.definable (λ (γ : Γ), x) := begin unfold definable, split; intro H, { intro Γ, let u : Hom Γ pt := ⟨λ _, default _, by exact pt.definable⟩, exact definable_psh.definable_precomp u H }, { apply H } end lemma intro_lem₁ {X Y : Type*} [definable_psh S X] [definable_psh S Y] (f : X → Y) : (∀ (Γ : Def S), definable S (λ (γ : Γ), f)) ↔ (∀ (Γ : Def S) (x : Γ → X), definable S x → definable S (λ (γ : Γ), f (x γ))) := sorry lemma definable_fun' {Γ : Def S} {X Y : Type*} [definable_psh S X] [definable_psh S Y] {f : Γ → X → Y} : definable_psh.definable f ↔ (∀ (Γ' : Def S) (π : Hom Γ' Γ) (g : Γ' ⊢ X), definable_psh.definable (λ γ_1, f (π.to_fun γ_1) (g.to_fun γ_1))) := begin split; intro H, { intros Γ' π g, have : definable_psh.definable (λ γ', (π.to_fun γ', g.to_fun γ')) := ⟨π.is_definable, g.definable⟩, exact H Γ' this }, { intros M g hg, exact H M ⟨_, hg.1⟩ ⟨_, hg.2⟩ } end lemma definable.app_ctx' {Γ : Def S} {X Y : Type*} [definable_psh S X] [definable_psh S Y] (f : Γ → X → Y) {hf : definable_psh.definable f} (x : Γ → X) {hx : definable_psh.definable x} : definable_psh.definable (λ γ, f γ (x γ)) := begin have : definable_psh.definable (λ γ, (γ, x γ)) := ⟨(Def.id _).is_definable, hx⟩, exact hf Γ this end lemma definable_const {Γ : Def S} {X : Type*} [definable_psh S X] {x : X} : definable S x → definable_psh.definable (λ (_ : Γ), x) := λ H, begin_lem.mp H Γ end o_minimal namespace tactic.interactive open tactic open interactive interactive.types meta def defin_start : tactic unit := `[rw o_minimal.begin_lem, intro Γ] /-- Return the variable representing the definable context. -/ meta def guess_ctx_var : tactic expr := do `(o_minimal.definable_psh.definable (λ (_ : ↥%%var), _)) ← target, -- trace var, return var /-- Return a list of "definable" variables along with their processed types. -/ meta def guess_defin_vars (ctx_var : expr) : tactic (list (expr × expr)) := do l ← local_context, -- some kind of moption_map? l ← l.mmap (λ var, (do `(o_minimal.sect %%ctx_var %%ty) ← infer_type var, return $ some (var, ty)) <|> return none), let l' := l.filter_map id, -- trace l', return l' meta def guess_defin_vars' : tactic (list (expr × expr)) := guess_ctx_var >>= guess_defin_vars /-- Goal should look like ⊢ definable_psh.definable (λ γ, λ x, e) We want to "intro" `x` as a definable variable, and leave ⊢ definable_psh.definable (λ γ, e) as the new goal. Strategy: By `definable_fun'` it's enough to check the new goal for an arbitrary context extension π : Γ' → Γ and section x : Γ' ⊢ α. However, we also have to move any existing definable variables from Γ to Γ'. So, we proceed as follows: * Identify the variables `γ` (`i_var`) and `Γ` (`ctx_var`) in the goal `definable_psh.definable (λ (γ : Γ), body)`. Here `body` is expected to be a function whose argument `x` we want to intro. * Use `definable_fun'` but then intro only `Γ'` and `π`. * For each existing definable variable `p`, we add a let binding `p' := p.precomp π`. * Now intro the new variable `x` (`new_var`) as well, and build a new function (λ (γ' : Γ'), body' (x.to_fun γ')), by making the following replacements: - each old `p` becomes `p'`; - `i` becomes `i'`; - `Γ` becomes `Γ'`. The claim is that the new expression is well-typed and definitionally equal (in the context of the let-bound variables `p'`, ...) to the current goal. Moreover, it only mentions the new `Γ'` and `p'`. * Now we cover our tracks: - clear the bodies of the let bindings `p'`, so that we can: - clear the old definable variables, `π`, and the old `Γ`. The tactic reuses the same user-visible names for the new `Γ` and `γ`. This is nice for interactive use, but not so nice for debugging the tactic. In the latter case, add `name.append_after _ 1` when generating names. -/ meta def defin_intro (var : parse ident_) : tactic unit := let trace : Π {α : Type} [has_to_tactic_format α] (a : α), tactic unit := λ _ _ _, tactic.skip in -- comment this for debugging do `(o_minimal.definable_psh.definable %%f) ← target, ([i_var], body) ← open_n_lambdas f 1, ctx_var ← guess_ctx_var, trace i_var, trace body, `[rw definable_fun'], new_ctx_var ← tactic.intro ctx_var.local_pp_name, proj_var ← tactic.intro `π, defin_vars ← guess_defin_vars ctx_var, -- do something to them: -- * for each old variable `p`, create a new variable `p'` -- which is let-bound to `p.precomp π` defin_var_list ← defin_vars.mmap (λ ⟨dvar, dvar_ty⟩, do -- "let p' := p.precomp π," new_body ← to_expr ``((%%dvar).precomp %%proj_var), new_dvar ← tactic.pose dvar.local_pp_name none new_body, return (sigma.mk dvar new_dvar)), new_i_type ← to_expr ``(↥%%new_ctx_var), new_i_var ← mk_local' i_var.local_pp_name f.binding_info new_i_type, -- * replace variables `p` → `p'` in `body`, and also the γ and Γ vars let var_map := (defin_var_list.to_alist.insert i_var new_i_var).insert ctx_var new_ctx_var, let body' := body.replace (λ e _, do -- for "efficiency", first check whether we have a variable at all guard (e.is_local_constant), -- then, look up the whole expression in our map var_map.lookup e), -- do the actual intro new_var ← tactic.intro var, new_var' ← to_expr ``((%%new_var).to_fun %%new_i_var), new_f ← tactic.lambdas [new_i_var] (body'.subst new_var'), trace new_f, new_target ← to_expr ``(o_minimal.definable_psh.definable %%new_f), tactic.change new_target, -- for each defin var: -- * forget its let binding (so that we can do the `clear`s below) -- (using `clear_value` from mathlib's `tactic.core`) -- * clear the original variable tactic.clear_value (defin_var_list.map sigma.snd), defin_var_list.mmap (λ ⟨dvar, new_dvar⟩, do tactic.clear dvar), tactic.clear proj_var, tactic.clear ctx_var, return () /-- Goal should look like ⊢ definable_psh.definable (λ γ, f x) and we want to produce ⊢ definable_psh.definable (λ γ, f) ⊢ definable_psh.definable (λ γ, x) This is just `apply definable.app_ctx'`, but Lean needs help with the unification problem. -/ meta def defin_app : tactic unit := do `(o_minimal.definable_psh.definable %%e) ← target, ([i_var], body) ← open_n_lambdas e 1, (expr.app f x) ← pure body, f' ← tactic.lambdas [i_var] f, x' ← tactic.lambdas [i_var] x, `[apply o_minimal.definable.app_ctx' %%f' %%x'], return () /-- Goal should look like ⊢ definable_psh.definable (λ γ, p.to_fun γ) where p : Γ ⊢ α. Just apply `sect.definable`. -/ meta def defin_var : tactic unit := `[refine o_minimal.sect.definable _] end tactic.interactive -- Now dress it up meta def defin := tactic meta instance : monad defin := show monad tactic, by apply_instance meta instance : interactive.executor defin := { config_type := unit, inhabited := by apply_instance, execute_with := λ _ tac, tactic.interactive.defin_start >> tac } namespace defin meta def execute (tac : defin unit) : tactic unit := tactic.interactive.defin_start >> tac meta def step := @tactic.step -- what does this even do meta def istep := @tactic.istep -- ditto meta def solve1 : defin unit → defin unit := tactic.solve1 open tactic -- Tactic state display borrows liberally from -- https://github.com/unitb/temporal-logic -- file temporal_logic.tactic /-- Replace any occurrences of `p.to_fun γ` with simply `p`. This is rather crude, but these aren't expected to appear outside the execution of a defin tactic. (More sophisticated would be to process only those variables which are sections over the context variable that appears in the goal.) The resulting expression is intended to be used for display purposes. -/ meta def shorten (E : expr) : expr := E.replace $ λ e _, match e with | `(o_minimal.sect.to_fun %%p _) := some p | _ := none end meta structure hyp_data : Type := (crisp : bool) (var : expr) (ty : expr) (val : option expr) /-- Return information about a local hypothesis `l`. -/ meta def get_hyp_data (l : expr) : defin hyp_data := do ty ← infer_type l, val ← try_core (shorten <$> local_def_value l), match ty with | `(o_minimal.sect %%Γ %%ty') := return ⟨ff, l, shorten ty', val⟩ | _ := return ⟨tt, l, shorten ty, val⟩ end meta def decl_to_fmt (s : tactic_state) (crisp : bool) (vs : list expr) (ty : expr) (val : option expr) : format := let vs' := format.join $ (vs.map s.format_expr).intersperse " ", t := s.format_expr ty, sep := if crisp then "::" else ":" in match val with | (some val) := format! "{vs'} {sep} {t} := {s.format_expr val}" | none := format! "{vs'} {sep} {t}" end meta def goal_to_fmt (g : expr) : defin (thunk format) := do set_goals [g], s ← read, `(o_minimal.definable_psh.definable (λ (_ : ↥%%Γ), %%body)) ← target | pure (λ _, to_fmt s), lc ← local_context, ctx_var ← tactic.interactive.guess_ctx_var, dat ← (lc.filter (λ l, l ≠ ctx_var)).mmap get_hyp_data, return $ λ _, format.intercalate format.line [format.intercalate ("," ++ format.line) $ dat.map $ λ d, decl_to_fmt s d.crisp [d.var] d.ty d.val, format! "⊢ {s.format_expr (shorten body)} def"] meta def save_info (p : pos) : defin unit := do gs ← get_goals, fmt ← gs.mmap goal_to_fmt, set_goals gs, tactic.save_info_thunk p (λ _, let header := if fmt.length > 1 then format! "{fmt.length} goals\n" else "", eval : thunk format → format := λ f, f () in if fmt.empty then "no goals" else format.join ((fmt.map eval).intersperse (format.line ++ format.line))) namespace interactive meta def swap := tactic.interactive.swap meta def exact := tactic.interactive.exact meta def solve1 : defin unit → defin unit := tactic.interactive.solve1 meta def intro := tactic.interactive.defin_intro meta def app := tactic.interactive.defin_app meta def var := tactic.interactive.defin_var meta def trace_state : defin unit := do s ← read, trace s.to_format end interactive end defin namespace o_minimal variables {R : Type*} {S : struc R} local infixr ` ⊢ `:10 := sect example : definable S (λ p q, (q ∧ p) ∧ q) := begin defin_start, defin_intro p, defin_intro q, defin_app, swap, { defin_var }, defin_app, { exact definable_const definable_and }, defin_app, { defin_app, { exact definable_const definable_and }, defin_var }, { defin_var }, end example : definable S (λ p q, (q ∧ p) ∧ q) := begin [defin] intro p, intro q, app, swap, { var }, app, { exact definable_const definable_and }, app, { app, { exact definable_const definable_and }, var }, { var }, end example : definable S and := begin [defin] intro p, intro q, exact struc.def_coords.inter p.definable q.definable end example {X Y Z : Type*} [definable_psh S X] [definable_psh S Y] [definable_psh S Z] : definable S (@function.curry X Y Z) := begin unfold function.curry, begin [defin] intro f, intro x, intro y, app, { var }, exact ⟨x.definable, y.definable⟩ /- app, app, exact definable_const definable_prod_mk, var, var, -/ end end #exit -- stuff after this uses pi type instances, which we don't need yet variables {Y : Type*} [definable_psh S Y] (y : Y) --set_option trace.class_instances true example : definable S (λ (X : set Y) (h : nonempty X), true) := begin defin_start, rw ←definable_yoneda, -- TODO: combine these -- "intro X", rw definable_fun', intros Γ' π p, -- now we need to pull back any variables mentioning Γ -- to use Γ' -- there aren't any yet ✓ -- since that's done, we can dispose of the old context clear π Γ, rename Γ' → Γ, -- "intro x", rw definable_fun', intros Γ' π, -- don't intro q just yet -- this time we need to deal with p have : ∀ d, p.to_fun (π.to_fun d) = (p.precomp π).to_fun d := λ d, rfl, simp only [this], generalize H : (p.precomp π) = p', clear this H p, rename p' → p, -- okay, now it's safe to intro q intro q, -- dispose of old context again clear π Γ, rename Γ' → Γ, -- we're done with intros! end end o_minimal
e95ebccc9aed17e9bcb1fe4e55bc1c7f136c2e10
4fa161becb8ce7378a709f5992a594764699e268
/src/data/monoid_algebra.lean
7dd87873a381dc96d63224e30cffd00772823940
[ "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
25,585
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury G. Kudryashov, Scott Morrison -/ import data.finsupp import ring_theory.algebra /-! # Monoid algebras When the domain of a `finsupp` has a multiplicative or additive structure, we can define a convolution product. To mathematicians this structure is known as the "monoid algebra", i.e. the finite formal linear combinations over a given semiring of elements of the monoid. The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses. In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G` in the same way, and then define the convolution product on these. When the domain is additive, this is used to define polynomials: ``` polynomial α := add_monoid_algebra ℕ α mv_polynominal σ α := add_monoid_algebra (σ →₀ ℕ) α ``` When the domain is multiplicative, e.g. a group, this will be used to define the group ring. ## Implementation note Unfortunately because additive and multiplicative structures both appear in both cases, it doesn't appear to be possible to make much use of `to_additive`, and we just settle for saying everything twice. Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale classical big_operators open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def monoid_algebra : Type (max u₁ u₂) := G →₀ k end namespace monoid_algebra variables {k G} local attribute [reducible] monoid_algebra section variables [semiring k] [monoid G] /-- The product of `f g : monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x * y = a`. (Think of the group ring of a group.) -/ instance : has_mul (monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl lemma mul_apply (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma mul_apply_antidiagonal (f g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) : mul_apply f g x ... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm ... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 : (finset.sum_filter _ _).symm ... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 : sum_congr (by { ext, simp [hs, and_comm] }) (λ _ _, rfl) ... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _) $ λ p hps hp, begin simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢, by_cases h1 : f p.1 = 0, { rw [h1, zero_mul] }, { rw [hp hps h1, mul_zero] } end end section variables [semiring k] [monoid G] lemma support_mul (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `1` and zero elsewhere. -/ instance : has_one (monoid_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_algebra k G) = single 1 1 := rfl -- TODO: the simplifier unfolds 0 in the instance proof! protected lemma zero_mul (f : monoid_algebra k G) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] protected lemma mul_zero (f : monoid_algebra k G) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : monoid_algebra k G) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : monoid_algebra k G) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] instance : semiring (monoid_algebra k G) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := monoid_algebra.zero_mul, mul_zero := monoid_algebra.mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } @[simp] lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) @[simp] lemma single_pow {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n) | 0 := rfl | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : G →* monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by rw [single_mul_single, one_mul] } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma mul_single_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) = ite (a₁ * x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_one_apply (f : monoid_algebra k G) (r : k) (x : G) : (f * single 1 r) x = f x * r := f.mul_single_apply_aux $ λ a, by rw [mul_one] lemma single_mul_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr, ext; split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_one_mul_apply (f : monoid_algebra k G) (r : k) (x : G) : (single 1 r * f) x = r * f x := f.single_mul_apply_aux $ λ a, by rw [one_mul] end instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [mul_comm] end, .. monoid_algebra.semiring } instance [ring k] : has_neg (monoid_algebra k G) := by apply_instance instance [ring k] [monoid G] : ring (monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. monoid_algebra.semiring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) := { mul_comm := mul_comm, .. monoid_algebra.ring} instance [semiring k] : has_scalar k (monoid_algebra k G) := finsupp.has_scalar instance [semiring k] : semimodule k (monoid_algebra k G) := finsupp.semimodule G k lemma single_one_comm [comm_semiring k] [monoid G] (r : k) (f : monoid_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } instance [comm_semiring k] [monoid G] : algebra k (monoid_algebra k G) := { to_fun := single 1, map_one' := rfl, map_mul' := λ x y, by rw [single_mul_single, one_mul], map_zero' := single_zero, map_add' := λ x y, single_add, smul_def' := λ r a, ext (λ _, smul_apply.trans (single_one_mul_apply _ _ _).symm), commutes' := λ r f, ext $ λ _, by rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } @[simp] lemma coe_algebra_map [comm_semiring k] [monoid G] : (algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) = single 1 := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = (algebra_map k (monoid_algebra k G) : k → monoid_algebra k G) b * of k G a := by simp instance [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) := finsupp.comap_distrib_mul_action_self section lift variables (k G) [comm_semiring k] [monoid G] (R : Type u₃) [semiring R] [algebra k R] /-- Any monoid homomorphism `G →* R` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] R`. -/ def lift : (G →* R) ≃ (monoid_algebra k G →ₐ[k] R) := { inv_fun := λ f, (f : monoid_algebra k G →* R).comp (of k G), to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a), map_one' := by { rw [one_def, sum_single_index, one_smul, F.map_one], apply zero_smul }, map_mul' := begin intros f g, rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a ha, _), simp only [], rw [finsupp.mul_sum, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a' ha', _), simp only [], rw [sum_single_index, F.map_mul, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm], apply zero_smul end, map_zero' := sum_zero_index, map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul], commutes' := λ r, by rw [coe_algebra_map, sum_single_index, F.map_one, algebra.smul_def, mul_one]; apply zero_smul }, left_inv := λ f, begin ext x, simp [sum_single_index] end, right_inv := λ F, begin ext f, conv_rhs { rw ← f.sum_single }, simp [← F.map_smul, finsupp.sum, ← F.map_sum] end } variables {k G R} lemma lift_apply (F : G →* R) (f : monoid_algebra k G) : lift k G R F f = f.sum (λ a b, b • F a) := rfl @[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] R) (x : G) : (lift k G R).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* R) (x) : lift k G R F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* R) (a b) : lift k G R F (single a b) = b • F a := by rw [single_eq_algebra_map_mul_of, ← algebra.smul_def, alg_hom.map_smul, lift_of] lemma lift_unique' (F : monoid_algebra k G →ₐ[k] R) : F = lift k G R ((F : monoid_algebra k G →* R).comp (of k G)) := ((lift k G R).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_algebra k G →ₐ[k] R) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] R⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := (lift k G R).symm.injective $ monoid_hom.ext h end lift section variables (k) /-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/ def group_smul.linear_map [group G] [comm_ring k] (V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) : (module.restrict_scalars k (monoid_algebra k G) V) →ₗ[k] (module.restrict_scalars k (monoid_algebra k G) V) := { to_fun := λ v, (single g (1 : k) • v : V), map_add' := λ x y, smul_add (single g (1 : k)) x y, map_smul' := λ c x, by simp only [module.restrict_scalars_smul_def, coe_algebra_map, ←mul_smul, single_one_comm], }. @[simp] lemma group_smul.linear_map_apply [group G] [comm_ring k] (V : Type u₃) [add_comm_group V] [module (monoid_algebra k G) V] (g : G) (v : V) : (group_smul.linear_map k V g) v = (single g (1 : k) • v : V) := rfl section variables {k} variables [group G] [comm_ring k] {V : Type u₃} {gV : add_comm_group V} {mV : module (monoid_algebra k G) V} {W : Type u₃} {gW : add_comm_group W} {mW : module (monoid_algebra k G) W} (f : (module.restrict_scalars k (monoid_algebra k G) V) →ₗ[k] (module.restrict_scalars k (monoid_algebra k G) W)) (h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W)) include h /-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/ def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W := { to_fun := f, map_add' := λ v v', by simp, map_smul' := λ c v, begin apply finsupp.induction c, { simp, }, { intros g r c' nm nz w, rw [add_smul, linear_map.map_add, w, add_smul, add_left_inj, single_eq_algebra_map_mul_of, ←smul_smul, ←smul_smul], erw [f.map_smul, h g v], refl, } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, prod_insert has, prod_insert has] section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] @[simp] lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y * x⁻¹) * r := f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm @[simp] lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) : (single x r * f) y = r * f (x⁻¹ * y) := f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm lemma mul_apply_left (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) := calc (f * g) x = sum f (λ a b, (single a (f a) * g) x) : by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single] ... = _ : by simp only [single_mul_apply, finsupp.sum] -- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`. lemma mul_apply_right (f g : monoid_algebra k G) (x : G) : (f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) := calc (f * g) x = sum g (λ a b, (f * single a (g a)) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end end monoid_algebra section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the additive monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def add_monoid_algebra := G →₀ k end namespace add_monoid_algebra variables {k G} local attribute [reducible] add_monoid_algebra section variables [semiring k] [add_monoid G] /-- The product of `f g : add_monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the additive monoid of monomial exponents.) -/ instance : has_mul (add_monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def {f g : add_monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl lemma mul_apply (f g : add_monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma support_mul (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `0` and zero elsewhere. -/ instance : has_one (add_monoid_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 := rfl -- TODO: the simplifier unfolds 0 in the instance proof! protected lemma zero_mul (f : add_monoid_algebra k G) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] protected lemma mul_zero (f : add_monoid_algebra k G) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : add_monoid_algebra k G) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : add_monoid_algebra k G) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] instance : semiring (add_monoid_algebra k G) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := add_monoid_algebra.zero_mul, mul_zero := add_monoid_algebra.mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : add_monoid_algebra k G) * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by { rw [single_mul_single, one_mul], refl } } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma mul_single_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ + a₂ = z) (b₁ * b₂) 0) = ite (a₁ + x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_zero_apply (f : add_monoid_algebra k G) (r : k) (x : G) : (f * single 0 r) x = f x * r := f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero] lemma single_mul_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x + a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x + a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr, ext; split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_zero_mul_apply (f : add_monoid_algebra k G) (r : k) (x : G) : (single 0 r * f) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] end instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. add_monoid_algebra.semiring } instance [ring k] : has_neg (add_monoid_algebra k G) := by apply_instance instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. add_monoid_algebra.semiring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) := { mul_comm := mul_comm, .. add_monoid_algebra.ring} instance [semiring k] : has_scalar k (add_monoid_algebra k G) := finsupp.has_scalar instance [semiring k] : semimodule k (add_monoid_algebra k G) := finsupp.semimodule G k instance [comm_semiring k] [add_monoid G] : algebra k (add_monoid_algebra k G) := { to_fun := single 0, map_one' := rfl, map_mul' := λ x y, by rw [single_mul_single, zero_add], map_zero' := single_zero, map_add' := λ x y, single_add, smul_def' := λ r a, by { ext x, exact smul_apply.trans (single_zero_mul_apply _ _ _).symm }, commutes' := λ r f, show single 0 r * f = f * single 0 r, by ext; rw [single_zero_mul_apply, mul_single_zero_apply, mul_comm] } @[simp] lemma coe_algebra_map [comm_semiring k] [add_monoid G] : (algebra_map k (add_monoid_algebra k G) : k → add_monoid_algebra k G) = single 0 := rfl /-- Any monoid homomorphism `multiplicative G →* R` can be lifted to an algebra homomorphism `add_monoid_algebra k G →ₐ[k] R`. -/ def lift [comm_semiring k] [add_monoid G] {R : Type u₃} [semiring R] [algebra k R] : (multiplicative G →* R) ≃ (add_monoid_algebra k G →ₐ[k] R) := { inv_fun := λ f, ((f : add_monoid_algebra k G →+* R) : add_monoid_algebra k G →* R).comp (of k G), to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a), map_one' := by { rw [one_def, sum_single_index, one_smul], erw [F.map_one], apply zero_smul }, map_mul' := begin intros f g, rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a ha, _), simp only [], rw [finsupp.mul_sum, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a' ha', _), simp only [], rw [sum_single_index], erw [F.map_mul], rw [algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm], apply zero_smul end, map_zero' := sum_zero_index, map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul], commutes' := λ r, begin rw [coe_algebra_map, sum_single_index], erw [F.map_one], rw [algebra.smul_def, mul_one], apply zero_smul end, }, left_inv := λ f, begin ext x, simp [sum_single_index] end, right_inv := λ F, begin ext f, conv_rhs { rw ← f.sum_single }, simp [← F.map_smul, finsupp.sum, ← F.map_sum] end } -- It is hard to state the equivalent of `distrib_mul_action G (monoid_algebra k G)` -- because we've never discussed actions of additive groups. universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] end add_monoid_algebra
9083a44008f37b108b749f1c4df50363ec30de6f
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/fin/tuple/sort.lean
9b3dced457ac5f1f313e3d1f8af3cae4e1475ace
[ "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,694
lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.fin.basic import data.finset.sort import data.prod.lex /-! # Sorting tuples by their values Given an `n`-tuple `f : fin n → α` where `α` is ordered, we may want to turn it into a sorted `n`-tuple. This file provides an API for doing so, with the sorted `n`-tuple given by `f ∘ tuple.sort f`. ## Main declarations * `tuple.sort`: given `f : fin n → α`, produces a permutation on `fin n` * `tuple.monotone_sort`: `f ∘ tuple.sort f` is `monotone` -/ namespace tuple variables {n : ℕ} variables {α : Type*} [linear_order α] /-- `graph f` produces the finset of pairs `(f i, i)` equipped with the lexicographic order. -/ def graph (f : fin n → α) : finset (α ×ₗ (fin n)) := finset.univ.image (λ i, (f i, i)) /-- Given `p : α ×ₗ (fin n) := (f i, i)` with `p ∈ graph f`, `graph.proj p` is defined to be `f i`. -/ def graph.proj {f : fin n → α} : graph f → α := λ p, p.1.1 @[simp] lemma graph.card (f : fin n → α) : (graph f).card = n := begin rw [graph, finset.card_image_of_injective], { exact finset.card_fin _ }, { intros _ _, simp } end /-- `graph_equiv₁ f` is the natural equivalence between `fin n` and `graph f`, mapping `i` to `(f i, i)`. -/ def graph_equiv₁ (f : fin n → α) : fin n ≃ graph f := { to_fun := λ i, ⟨(f i, i), by simp [graph]⟩, inv_fun := λ p, p.1.2, left_inv := λ i, by simp, right_inv := λ ⟨⟨x, i⟩, h⟩, by simpa [graph] using h } @[simp] lemma proj_equiv₁' (f : fin n → α) : graph.proj ∘ graph_equiv₁ f = f := rfl /-- `graph_equiv₂ f` is an equivalence between `fin n` and `graph f` that respects the order. -/ def graph_equiv₂ (f : fin n → α) : fin n ≃o graph f := finset.order_iso_of_fin _ (by simp) /-- `sort f` is the permutation that orders `fin n` according to the order of the outputs of `f`. -/ def sort (f : fin n → α) : equiv.perm (fin n) := (graph_equiv₂ f).to_equiv.trans (graph_equiv₁ f).symm lemma self_comp_sort (f : fin n → α) : f ∘ sort f = graph.proj ∘ graph_equiv₂ f := show graph.proj ∘ ((graph_equiv₁ f) ∘ (graph_equiv₁ f).symm) ∘ (graph_equiv₂ f).to_equiv = _, by simp lemma monotone_proj (f : fin n → α) : monotone (graph.proj : graph f → α) := begin rintro ⟨⟨x, i⟩, hx⟩ ⟨⟨y, j⟩, hy⟩ (h|h), { exact le_of_lt ‹_› }, { simp [graph.proj] }, end lemma monotone_sort (f : fin n → α) : monotone (f ∘ sort f) := begin rw [self_comp_sort], exact (monotone_proj f).comp (graph_equiv₂ f).monotone, end end tuple
f2c177649e782468f26926375f379a738f3ebc79
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/linear_algebra/basis.lean
bf8b902e2002054c785985a4012190acde7f3b9a
[ "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
60,605
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp -/ import linear_algebra.finsupp import linear_algebra.projection import order.zorn import data.fintype.card import data.finset.order /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function set submodule open_locale classical big_operators universe u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, s.sum (λ i, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, not_forall], end lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma linear_independent.ne_zero [nontrivial R] {i : ι} (hv : linear_independent R v) : v i ≠ 0 := λ h, @zero_ne_one R _ _ $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective [nontrivial R] (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end theorem linear_independent_equiv (e : ι ≃ ι') {f : ι' → M} : linear_independent R (f ∘ e) ↔ linear_independent R f := ⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, λ h, h.comp _ e.injective⟩ theorem linear_independent_equiv' (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ e = g) : linear_independent R g ↔ linear_independent R f := h ▸ linear_independent_equiv e theorem linear_independent_image {ι} {s : set ι} {f : ι → M} (hf : set.inj_on f s) : linear_independent R (λ x : s, f x) ↔ linear_independent R (λ x : f '' s, (x : M)) := linear_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl theorem linear_independent.image' {ι} {s : set ι} {f : ι → M} (hs : linear_independent R (λ x : s, f x)) : linear_independent R (λ x : f '' s, (x : M)) := or.cases_on (subsingleton_or_nontrivial R) (λ hr, linear_independent_of_zero_eq_one $ by exactI subsingleton.elim _ _) (λ hr, by exactI (linear_independent_image $ set.inj_on_iff_injective.2 hs.injective).1 hs) lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end lemma linear_independent_of_comp (f : M →ₗ[R] M') (hfv : linear_independent R (f ∘ v)) : linear_independent R v := linear_independent_iff'.2 $ λ s g hg i his, have ∑ (i : ι) in s, g i • f (v i) = 0, by simp_rw [← f.map_smul, ← f.map_sum, hg, f.map_zero], linear_independent_iff'.1 hfv s g this i his section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on coe (coe ⁻¹' ↑l.support : set s) ↑l.support, { apply bij_on.mk, { apply maps_to_preimage }, { apply subtype.coe_injective.inj_on }, intros i hi, rw [image_preimage_eq_inter_range, subtype.range_coe], exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (coe : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], exact subtype.coe_injective, rw subtype.range_coe, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨coe, subtype.coe_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨coe, subtype.coe_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, haveI : nontrivial R := ⟨⟨0, 1, zero_eq_one⟩⟩, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' ↑l.support) ↑l.support, { apply bij_on.mk, { apply maps_to_preimage }, { apply (linear_independent.injective hv).inj_on }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l h_bij, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage_of_bij v l.support h_bij (λ (x : M), l x • x)], rwa [finsupp.total_apply, finsupp.sum] at hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.map_domain_injective hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := begin have h_restrict : restrict v s = v ∘ coe := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain coe = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R coe l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.coe_image_subset _ _ this }, apply @finsupp.map_domain_injective _ (subtype s) ι, { apply subtype.coe_injective }, { simpa }, end variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { resetI, refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros i s his ih, rw [finset.sup_insert], refine (hl _).union ih _, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros i, exact ⟨i, le_refl _⟩ }, { exact s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, haveI : nontrivial R := ⟨⟨0, 1, zero_eq_one⟩⟩, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) : surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype [nontrivial R] {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, haveI : nontrivial R := ⟨⟨0, 1, zero_eq_one⟩⟩, have inj_v : injective v := (linear_independent.injective hv), have inj_v' : injective v' := (linear_independent.injective hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact inl_injective.comp inj_v }, { exact inr_injective.comp inj_v' }, { intros, simp [hv.ne_zero] } }, { rw sum.elim_range, refine (hv.image _).to_subtype_range.union (hv'.image _).to_subtype_range _; [simp, simp, skip], apply disjoint_inl_inr.mono _ _; simp only [set.range_comp, span_image, linear_map.map_le_range] } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : finset.sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [finset.sum_apply, finset.sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective [nontrivial R] (hv : is_basis R v) : injective v := λ x y h, linear_independent.injective hv.1 h lemma is_basis.range (hv : is_basis R v) : is_basis R (λ x, x : range v → M) := ⟨hv.1.to_subtype_range, by { convert hv.2, ext i, exact ⟨λ ⟨p, hp⟩, hp ▸ p.2, λ hi, ⟨⟨i, hi⟩, rfl⟩⟩ }⟩ /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := linear_map.ext_on hv.2 h lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ left_inverse.injective hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp @[simp] lemma is_basis.repr_self_apply (i j : ι) : hv.repr (v i) j = if i = j then 1 else 0 := by rw [hv.repr_eq_single, finsupp.single_apply] lemma is_basis.repr_eq_iff {f : M →ₗ[R] (ι →₀ R)} : hv.repr = f ↔ ∀ i, f (v i) = finsupp.single i 1 := begin split, { rintros rfl i, exact hv.repr_eq_single }, intro h, refine hv.ext (λ _, _), rw [h, hv.repr_eq_single] end lemma is_basis.repr_apply_eq {f : M → ι → R} (hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x) (f_eq : ∀ i, f (v i) = finsupp.single i 1) (x : M) (i : ι) : hv.repr x i = f x i := begin let f_i : M →ₗ[R] R := { to_fun := λ x, f x i, map_add' := λ _ _, by rw [hadd, pi.add_apply], map_smul' := λ _ _, by rw [hsmul, pi.smul_apply] }, show (finsupp.leval i).comp hv.repr x = f_i x, congr' 1, refine hv.ext (λ j, _), show hv.repr (v j) i = f (v j) i, rw [hv.repr_eq_single, f_eq] end /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr] ; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] @[simp] lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ λ b, by simp lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ λ b, by simp lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm @[simp] theorem module_equiv_finsupp_apply_basis (hv : is_basis R v) (i : ι) : module_equiv_finsupp hv (v i) = finsupp.single i 1 := (linear_equiv.symm_apply_eq _).2 $ by simp [linear_independent.total_equiv] /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the indexing sets of the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') (e : ι ≃ ι') : M ≃ₗ[R] M' := { inv_fun := hv'.constr (v ∘ e.symm), left_inv := have (hv'.constr (v ∘ e.symm)).comp (hv.constr (v' ∘ e)) = linear_map.id, from hv.ext $ by simp, λ x, congr_arg (λ h : M →ₗ[R] M, h x) this, right_inv := have (hv.constr (v' ∘ e)).comp (hv'.constr (v ∘ e.symm)) = linear_map.id, from hv'.ext $ by simp, λ y, congr_arg (λ h : M' →ₗ[R] M', h y) this, ..hv.constr (v' ∘ e) } /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def equiv_of_is_basis' {v : ι → M} {v' : ι' → M'} (f : M → M') (g : M' → M) (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } @[simp] lemma equiv_of_is_basis_comp {ι'' : Type*} {v : ι → M} {v' : ι' → M'} {v'' : ι'' → M''} (hv : is_basis R v) (hv' : is_basis R v') (hv'' : is_basis R v'') (e : ι ≃ ι') (f : ι' ≃ ι'' ) : (equiv_of_is_basis hv hv' e).trans (equiv_of_is_basis hv' hv'' f) = equiv_of_is_basis hv hv'' (e.trans f) := begin apply linear_equiv.eq_of_linear_map_eq, apply hv.ext, intros i, simp [equiv_of_is_basis] end @[simp] lemma equiv_of_is_basis_refl : equiv_of_is_basis hv hv (equiv.refl ι) = linear_equiv.refl R M := begin apply linear_equiv.eq_of_linear_map_eq, apply hv.ext, intros i, simp [equiv_of_is_basis] end lemma equiv_of_is_basis_trans_symm (e : ι ≃ ι') {v' : ι' → M'} (hv' : is_basis R v') : (equiv_of_is_basis hv hv' e).trans (equiv_of_is_basis hv' hv e.symm) = linear_equiv.refl R M := by simp lemma equiv_of_is_basis_symm_trans (e : ι ≃ ι') {v' : ι' → M'} (hv' : is_basis R v') : (equiv_of_is_basis hv' hv e.symm).trans (equiv_of_is_basis hv hv' e) = linear_equiv.refl R M' := by simp lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp only [mem_span_singleton, range_const, mul_one, exists_eq, smul_eq_mul] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.ext_iff, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext_iff_val.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def is_basis.equiv_fun : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, map_add' := λ x y, by ext; exact finsupp.add_apply, map_smul' := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ h.equiv_fun.to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr h.equiv_fun.to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma is_basis.equiv_fun_symm_apply (x : ι → R) : h.equiv_fun.symm x = ∑ i, x i • v i := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = ∑ i, x i • v i, dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0, { simp [H] }, { simp [H], refl } end lemma is_basis.equiv_fun_apply (u : M) : h.equiv_fun u = h.repr u := rfl lemma is_basis.equiv_fun_total (u : M) : ∑ i, h.equiv_fun u i • v i = u:= begin conv_rhs { rw ← h.total_repr u }, simp [finsupp.total_apply, finsupp.sum_fintype, h.equiv_fun_apply] end @[simp] lemma is_basis.equiv_fun_self (i j : ι) : h.equiv_fun (v i) j = if i = j then 1 else 0 := by { rw [h.equiv_fun_apply, h.repr_self_apply] } @[simp] theorem is_basis.constr_apply_fintype (f : ι → M') (x : M) : (h.constr f : M → M') x = ∑ i, (h.equiv_fun x i) • f i := by simp [h.constr_apply, h.equiv_fun_apply, finsupp.sum_fintype] end module section vector_space variables {v : ι → V} [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end theorem linear_independent_insert (hxs : x ∉ s) : linear_independent K (λ b : insert x s, (b : V)) ↔ linear_independent K (λ b : s, (b : V)) ∧ x ∉ submodule.span K s := ⟨λ h, ⟨h.mono $ set.subset_insert x s, have (λ (b : ↥(insert x s)), ↑b) '' (set.univ \ {⟨x, set.mem_insert x s⟩}) = s, from set.ext $ λ b, ⟨λ ⟨y, hy1, hy2⟩, hy2 ▸ y.2.resolve_left (λ H, hy1.2 $ subtype.eq H), λ hb, ⟨⟨b, set.mem_insert_of_mem x hb⟩, ⟨trivial, λ H, hxs $ (show b = x, from congr_arg subtype.val H) ▸ hb⟩, rfl⟩⟩, this ▸ linear_independent_iff_not_mem_span.1 h ⟨x, set.mem_insert x s⟩⟩, λ ⟨h1, h2⟩, h1.insert h2⟩ theorem linear_independent_insert' {ι} {s : set ι} {a : ι} {f : ι → V} (has : a ∉ s) : linear_independent K (λ x : insert a s, f x) ↔ linear_independent K (λ x : s, f x) ∧ f a ∉ submodule.span K (f '' s) := begin refine ⟨λ h, _, λ h, _⟩, { have hfas : f a ∉ f '' s := λ ⟨x, hxs, hfxa⟩, has (set.mem_of_eq_of_mem (congr_arg subtype.val $ (@id _ (h.injective) ⟨x, or.inr hxs⟩ ⟨a, or.inl rfl⟩ hfxa)).symm hxs), have := h.image', rwa [set.image_insert_eq, linear_independent_insert hfas, ← linear_independent_image] at this, exact (set.inj_on_iff_injective.2 h.injective).mono (set.subset_insert _ _) }, { cases h with h1 h2, have : set.inj_on f (insert a s) := (set.inj_on_insert has).2 ⟨set.inj_on_iff_injective.2 h1.injective, λ h, h2 $ submodule.subset_span h⟩, have hfas : f a ∉ f '' s := λ ⟨x, hxs, hfxa⟩, has (set.mem_of_eq_of_mem (this (or.inr hxs) (or.inl rfl) hfxa).symm hxs), rw [linear_independent_image this, set.image_insert_eq, linear_independent_insert hfas], exact ⟨h1.image', h2⟩ } end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (coe : b → V) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ lemma exists_sum_is_basis (hs : linear_independent K v) : ∃ (ι' : Type u) (v' : ι' → V), is_basis K (sum.elim v v') := begin -- This is a hack: we jump through hoops to reuse `exists_subset_is_basis`. let s := set.range v, let e : ι ≃ s := equiv.set.range v hs.injective, have : (λ x, x : s → V) = v ∘ e.symm := by { funext, dsimp, rw [equiv.set.apply_range_symm v], }, have : linear_independent K (λ x, x : s → V), { rw this, exact linear_independent.comp hs _ (e.symm.injective), }, obtain ⟨b, ss, is⟩ := exists_subset_is_basis this, let e' : ι ⊕ (b \ s : set V) ≃ b := calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : equiv.set.sum_diff_subset ss, refine ⟨(b \ s : set V), λ x, x.1, _⟩, convert is_basis.comp is e' _, { funext x, cases x; simp; refl, }, { exact e'.bijective, }, end variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i, i : b → V) := let ⟨b, _, hb⟩ := exists_subset_is_basis (linear_independent_empty K V : _) in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), rwa subtype.range_coe at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hB.ext (λ b, _), rw image_subset_iff at BC, have : f b = (⟨f b, BC b.2⟩ : C) := rfl, dsimp, rw [this, constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hC.ext (λ c, _), simp [constr_basis hC, right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) open fintype variables (K) (V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := exists.elim (exists_is_basis K V) $ λ b hb, ⟨card b, module.card_fintype hb⟩ end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variable [fintype η] lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R η) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), unit), (std_basis R (λ (i : η), R) (ji.fst)) 1) := @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _) lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply (is_basis_fun₀ R η).comp (λ i, ⟨i, punit.star⟩), apply bijective_iff_has_inverse.2, use sigma.fst, simp [function.left_inverse, function.right_inverse] end end end module end pi
4e20e163bc7cbcea87ea075b4029a95432e69814
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/matcherElimUniv.lean
5bcfeef68bd028b47b76c96e8096f709e0e82eb1
[ "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
164
lean
universes u def len {α : Type u} : List α → List α → Nat | [], bs => bs.length | a::as, bs => len as bs + 1 theorem ex1 : len [1, 2] [3, 4] = 4 := rfl
6302c2535c00ca3574f4b6eaf826f10f23be9b9b
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/init/nat.hlean
30d1ad053a5d80d364059415d92b00b75ddd971f
[ "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
10,296
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import init.wf init.tactic init.hedberg init.util init.types open eq decidable sum lift is_trunc notation `ℕ` := nat namespace nat /- basic definitions on natural numbers -/ inductive le (a : ℕ) : ℕ → Type₀ := | refl : le a a | step : Π {b}, le a b → le a (succ b) infix `≤` := le attribute le.refl [refl] definition lt [reducible] (n m : ℕ) := succ n ≤ m definition ge [reducible] (n m : ℕ) := m ≤ n definition gt [reducible] (n m : ℕ) := succ m ≤ n infix `<` := lt infix `≥` := ge infix `>` := gt definition pred [unfold 1] (a : nat) : nat := nat.cases_on a zero (λ a₁, a₁) -- add is defined in init.num definition sub (a b : nat) : nat := nat.rec_on b a (λ b₁ r, pred r) definition mul (a b : nat) : nat := nat.rec_on b zero (λ b₁ r, r + a) notation a - b := sub a b notation a * b := mul a b /- properties of ℕ -/ protected definition is_inhabited [instance] : inhabited nat := inhabited.mk zero protected definition has_decidable_eq [instance] : ∀ x y : nat, decidable (x = y) | has_decidable_eq zero zero := inl rfl | has_decidable_eq (succ x) zero := inr (by contradiction) | has_decidable_eq zero (succ y) := inr (by contradiction) | has_decidable_eq (succ x) (succ y) := match has_decidable_eq x y with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ x = succ y, by injection h with xeqy; exact absurd xeqy xney) end /- properties of inequality -/ definition le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ le.refl n definition le_succ (n : ℕ) : n ≤ succ n := by repeat constructor definition pred_le (n : ℕ) : pred n ≤ n := by cases n;all_goals (repeat constructor) definition le.trans [trans] {n m k : ℕ} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k := by induction H2 with n H2 IH;exact H1;exact le.step IH definition le_succ_of_le {n m : ℕ} (H : n ≤ m) : n ≤ succ m := le.trans H !le_succ definition le_of_succ_le {n m : ℕ} (H : succ n ≤ m) : n ≤ m := le.trans !le_succ H definition le_of_lt {n m : ℕ} (H : n < m) : n ≤ m := le_of_succ_le H definition succ_le_succ [unfold 3] {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m := by induction H;reflexivity;exact le.step v_0 definition pred_le_pred [unfold 3] {n m : ℕ} (H : n ≤ m) : pred n ≤ pred m := by induction H;reflexivity;cases b;exact v_0;exact le.step v_0 definition le_of_succ_le_succ [unfold 3] {n m : ℕ} (H : succ n ≤ succ m) : n ≤ m := pred_le_pred H definition le_succ_of_pred_le [unfold 1] {n m : ℕ} (H : pred n ≤ m) : n ≤ succ m := by cases n;exact le.step H;exact succ_le_succ H definition not_succ_le_self {n : ℕ} : ¬succ n ≤ n := by induction n with n IH;all_goals intros;cases a;apply IH;exact le_of_succ_le_succ a definition zero_le (n : ℕ) : 0 ≤ n := by induction n with n IH;apply le.refl;exact le.step IH definition lt.step {n m : ℕ} (H : n < m) : n < succ m := le.step H definition zero_lt_succ (n : ℕ) : 0 < succ n := by induction n with n IH;apply le.refl;exact le.step IH definition lt.trans [trans] {n m k : ℕ} (H1 : n < m) (H2 : m < k) : n < k := le.trans (le.step H1) H2 definition lt_of_le_of_lt [trans] {n m k : ℕ} (H1 : n ≤ m) (H2 : m < k) : n < k := le.trans (succ_le_succ H1) H2 definition lt_of_lt_of_le [trans] {n m k : ℕ} (H1 : n < m) (H2 : m ≤ k) : n < k := le.trans H1 H2 definition le.antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m := begin cases H1 with m' H1', { reflexivity}, { cases H2 with n' H2', { reflexivity}, { exfalso, apply not_succ_le_self, exact lt.trans H1' H2'}}, end definition not_succ_le_zero (n : ℕ) : ¬succ n ≤ zero := by intro H; cases H definition lt.irrefl (n : ℕ) : ¬n < n := not_succ_le_self definition self_lt_succ (n : ℕ) : n < succ n := !le.refl definition lt.base (n : ℕ) : n < succ n := !le.refl definition le_lt_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m < n) : empty := !lt.irrefl (lt_of_le_of_lt H1 H2) definition lt_le_antisymm {n m : ℕ} (H1 : n < m) (H2 : m ≤ n) : empty := le_lt_antisymm H2 H1 definition lt.asymm {n m : ℕ} (H1 : n < m) (H2 : m < n) : empty := le_lt_antisymm (le_of_lt H1) H2 definition lt.trichotomy (a b : ℕ) : a < b ⊎ a = b ⊎ b < a := begin revert b, induction a with a IH, { intro b, cases b, exact inr (inl idp), exact inl !zero_lt_succ}, { intro b, cases b with b, exact inr (inr !zero_lt_succ), { cases IH b with H H, exact inl (succ_le_succ H), cases H with H H, exact inr (inl (ap succ H)), exact inr (inr (succ_le_succ H))}} end definition lt.by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := by induction (lt.trichotomy a b) with H H; exact H1 H; cases H with H H; exact H2 H;exact H3 H definition lt_ge_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a ≥ b → P) : P := lt.by_cases H1 (λH, H2 (le_of_eq H⁻¹)) (λH, H2 (le_of_lt H)) definition lt_or_ge (a b : ℕ) : (a < b) ⊎ (a ≥ b) := lt_ge_by_cases inl inr definition not_lt_zero (a : ℕ) : ¬ a < zero := by intro H; cases H -- less-than is well-founded definition lt.wf [instance] : well_founded lt := begin constructor, intro n, induction n with n IH, { constructor, intros n H, exfalso, exact !not_lt_zero H}, { constructor, intros m H, assert aux : ∀ {n₁} (hlt : m < n₁), succ n = n₁ → acc lt m, { intros n₁ hlt, induction hlt, { intro p, injection p with q, exact q ▸ IH}, { intro p, injection p with q, exact (acc.inv (q ▸ IH) a)}}, apply aux H idp}, end definition measure {A : Type} (f : A → ℕ) : A → A → Type₀ := inv_image lt f definition measure.wf {A : Type} (f : A → ℕ) : well_founded (measure f) := inv_image.wf f lt.wf definition succ_lt_succ {a b : ℕ} (H : a < b) : succ a < succ b := succ_le_succ H definition lt_of_succ_lt {a b : ℕ} (H : succ a < b) : a < b := le_of_succ_le H definition lt_of_succ_lt_succ {a b : ℕ} (H : succ a < succ b) : a < b := le_of_succ_le_succ H definition decidable_le [instance] : decidable_rel le := begin intros n, induction n with n IH, { intro m, left, apply zero_le}, { intro m, cases m with m, { right, apply not_succ_le_zero}, { let H := IH m, clear IH, cases H with H H, left, exact succ_le_succ H, right, intro H2, exact H (le_of_succ_le_succ H2)}} end definition decidable_lt [instance] : decidable_rel lt := _ definition decidable_gt [instance] : decidable_rel gt := _ definition decidable_ge [instance] : decidable_rel ge := _ definition eq_or_lt_of_le {a b : ℕ} (H : a ≤ b) : a = b ⊎ a < b := by cases H with b' H; exact sum.inl rfl; exact sum.inr (succ_le_succ H) definition le_of_eq_or_lt {a b : ℕ} (H : a = b ⊎ a < b) : a ≤ b := by cases H with H H; exact le_of_eq H; exact le_of_lt H definition eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ⊎ b < a := sum.rec_on (lt.trichotomy a b) (λ hlt, absurd hlt hnlt) (λ h, h) definition lt_succ_of_le {a b : ℕ} (h : a ≤ b) : a < succ b := succ_le_succ h definition lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h definition succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h definition max (a b : ℕ) : ℕ := if a < b then b else a definition min (a b : ℕ) : ℕ := if a < b then a else b definition max_self (a : ℕ) : max a a = a := eq.rec_on !if_t_t rfl definition max_eq_right {a b : ℕ} (H : a < b) : max a b = b := if_pos H definition max_eq_left {a b : ℕ} (H : ¬ a < b) : max a b = a := if_neg H definition eq_max_right {a b : ℕ} (H : a < b) : b = max a b := eq.rec_on (max_eq_right H) rfl definition eq_max_left {a b : ℕ} (H : ¬ a < b) : a = max a b := eq.rec_on (max_eq_left H) rfl definition le_max_left (a b : ℕ) : a ≤ max a b := by_cases (λ h : a < b, le_of_lt (eq.rec_on (eq_max_right h) h)) (λ h : ¬ a < b, eq.rec_on (eq_max_left h) !le.refl) definition le_max_right (a b : ℕ) : b ≤ max a b := by_cases (λ h : a < b, eq.rec_on (eq_max_right h) !le.refl) (λ h : ¬ a < b, sum.rec_on (eq_or_lt_of_not_lt h) (λ heq, eq.rec_on heq (eq.rec_on (inverse (max_self a)) !le.refl)) (λ h : b < a, have aux : a = max a b, from eq_max_left (lt.asymm h), eq.rec_on aux (le_of_lt h))) definition succ_sub_succ_eq_sub (a b : ℕ) : succ a - succ b = a - b := by induction b with b IH; reflexivity; apply ap pred IH definition sub_eq_succ_sub_succ (a b : ℕ) : a - b = succ a - succ b := eq.rec_on (succ_sub_succ_eq_sub a b) rfl definition zero_sub_eq_zero (a : ℕ) : zero - a = zero := nat.rec_on a rfl (λ a₁ (ih : zero - a₁ = zero), ap pred ih) definition zero_eq_zero_sub (a : ℕ) : zero = zero - a := eq.rec_on (zero_sub_eq_zero a) rfl definition sub_lt {a b : ℕ} : zero < a → zero < b → a - b < a := have aux : Π {a}, zero < a → Π {b}, zero < b → a - b < a, from λa h₁, le.rec_on h₁ (λb h₂, le.cases_on h₂ (lt.base zero) (λ b₁ bpos, eq.rec_on (sub_eq_succ_sub_succ zero b₁) (eq.rec_on (zero_eq_zero_sub b₁) (lt.base zero)))) (λa₁ apos ih b h₂, le.cases_on h₂ (lt.base a₁) (λ b₁ bpos, eq.rec_on (sub_eq_succ_sub_succ a₁ b₁) (lt.trans (@ih b₁ bpos) (lt.base a₁)))), λ h₁ h₂, aux h₁ h₂ definition sub_le (a b : ℕ) : a - b ≤ a := nat.rec_on b (le.refl a) (λ b₁ ih, le.trans !pred_le ih) lemma sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le (sub_le a b) end nat namespace nat_esimp open nat attribute add mul sub [unfold 2] attribute of_num [unfold 1] end nat_esimp
4470843f84afff0effa4339bbf99c8cae5cd849f
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/aggregateGroupingSetsProjectMerge.lean
3a92de1bc5106588cf1dd351fb0cc407944b74be
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
1,212
lean
import ..extra_constants import ..sql import ..u_semiring import ..meta.cosette_tactics import ..meta.TDP open SQL open Proj open Pred open Expr theorem rule : forall (Γ scm_s : Schema) (rel_r : relation scm_s) (s_a : Column datatypes.int scm_s) (s_b : Column datatypes.int scm_s) (s_c : Column datatypes.int scm_s), denoteSQL (SELECT (combineGroupByProj PLAIN(@uvariable datatypes.int (Γ ++ scm_s) (right⋅s_a)) $ combineGroupByProj PLAIN(@uvariable datatypes.int (Γ ++ scm_s) (right⋅s_b)) $ COUNT(@uvariable datatypes.int (Γ ++ scm_s) (right⋅s_c))) FROM1 table rel_r GROUP BY combine (right⋅s_a) (right⋅s_b) : SQL Γ _) = denoteSQL (SELECT (combineGroupByProj PLAIN(@uvariable datatypes.int (Γ ++ scm_s) (right⋅s_a)) $ combineGroupByProj PLAIN(@uvariable datatypes.int (Γ ++ scm_s) (right⋅s_b)) $ COUNT(@uvariable datatypes.int (Γ ++ scm_s) (right⋅s_c))) FROM1 table rel_r GROUP BY combine (right⋅s_b) (right⋅s_a) : SQL Γ _) := begin intros, unfold_all_denotations, funext, simp, print_size, sorry end
5204ed0220ecac316621509d65dd3d4f5b8c5988
b2e508d02500f1512e1618150413e6be69d9db10
/src/category_theory/yoneda.lean
6f676127ddc863b32e677957dd59d51910aa193b
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
6,672
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 an instance that it is `fully_faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. -/ import category_theory.opposites namespace category_theory open opposite universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def yoneda : C ⥤ (Cᵒᵖ ⥤ Sort v₁) := { obj := λ X, { obj := λ Y, unop Y ⟶ X, map := λ Y Y' f g, f.unop ≫ g, map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext1, dsimp, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } } def coyoneda : Cᵒᵖ ⥤ (C ⥤ Sort v₁) := { obj := λ X, { obj := λ Y, unop X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext1, dsimp, erw [category.comp_id] end }, map := λ X X' f, { app := λ Y g, f.unop ≫ g }, map_comp' := λ _ _ _ f g, begin ext1, ext1, dsimp, erw [category.assoc] end, map_id' := λ X, begin ext1, ext1, dsimp, erw [category.id_comp] end } namespace yoneda @[simp] lemma obj_obj (X : C) (Y : Cᵒᵖ) : (yoneda.obj X).obj Y = (unop Y ⟶ X) := rfl @[simp] lemma obj_map (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') : (yoneda.obj X).map f = λ g, f.unop ≫ g := rfl @[simp] lemma map_app {X X' : C} (f : X ⟶ X') (Y : Cᵒᵖ) : (yoneda.map f).app Y = λ g, g ≫ f := rfl lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) : ((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) := by obviously @[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) := begin erw [functor_to_types.naturality], refl end instance yoneda_fully_faithful : fully_faithful (@yoneda C _) := { preimage := λ X Y f, (f.app (op X)) (𝟙 X), injectivity' := λ X Y f g p, begin injection p with h, convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp, end } /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := @preimage_iso _ _ _ _ yoneda _ _ _ _ (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) end yoneda namespace coyoneda @[simp] lemma obj_obj (X : Cᵒᵖ) (Y : C) : (coyoneda.obj X).obj Y = (unop X ⟶ Y) := rfl @[simp] lemma obj_map {X' X : C} (f : X' ⟶ X) (Y : Cᵒᵖ) : (coyoneda.obj Y).map f = λ g, g ≫ f := rfl @[simp] lemma map_app (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') : (coyoneda.map f).app X = λ g, f.unop ≫ g := rfl end coyoneda class representable (F : Cᵒᵖ ⥤ Sort v₁) := (X : C) (w : yoneda.obj X ≅ F) end category_theory namespace category_theory -- For the rest of the file, we are using product categories, -- so need to restrict to the case we are in 'Type', not 'Sort', -- for both objects and morphisms universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation open opposite variables (C : Type u₁) [𝒞 : category.{v₁+1} C] include 𝒞 -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) := category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) := category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁) open yoneda def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := functor.prod yoneda.op (functor.id (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁) @[simp] lemma yoneda_pairing_map (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))), naturality' := begin intros X Y f, ext1, ext1, cases f, cases Y, cases X, dsimp, erw [category.id_comp, ←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end }, inv := { app := λ F x, { app := λ X a, (F.2.map a.op) x.down, naturality' := begin intros X Y f, ext1, cases x, cases F, dsimp, erw [functor_to_types.map_comp] end }, naturality' := begin intros X Y f, ext1, ext1, ext1, cases x, cases f, cases Y, cases X, dsimp, erw [←functor_to_types.naturality, functor_to_types.map_comp] end }, hom_inv_id' := begin ext1, ext1, ext1, ext1, cases X, dsimp, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id], refl, end, inv_hom_id' := begin ext1, ext1, ext1, cases x, cases X, dsimp, erw [functor_to_types.map_id] end }. variables {C} @[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) := (yoneda_lemma C).app (op X, F) omit 𝒞 @[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟶ F) ≅ F.obj (op X) := yoneda_sections X F ≪≫ ulift_trivial _ end category_theory
40ff9f9a9bcc94b89bf6a7c45093956540df53d7
964a8bb66c2eb89b920fe65d0ec2f77eab0d5f65
/src/listplayground.lean
4ee38229dd1e672da0285b30e1ad9448958c92c8
[ "MIT" ]
permissive
SnobbyDragon/leanhanoi
9990a7b586f1d843d39c3c7aab7ac0b5eefbe653
a42811ce5ab55e0451880a8c111c75b082936d39
refs/heads/master
1,675,735,182,689
1,609,387,288,000
1,609,387,288,000
284,167,126
8
1
MIT
1,609,262,129,000
1,596,247,349,000
Lean
UTF-8
Lean
false
false
2,486
lean
import data.list namespace listplayground example (l : list ℕ) (hl : list.sorted nat.lt l) (hl' : l ≠ []) : list.sorted nat.lt l.tail := list.sorted.tail hl example (l : list ℕ) (h : l ≠ []) : l = l.head :: l.tail := (list.cons_head_tail h).symm -- surprised this isn't in mathlib... maybe bc this is too simple or something similar is? -- either in head or tail example (l : list ℕ) (a ∈ l) : a = l.head ∨ a ∈ l.tail := begin induction l, { right, exact H }, { cases H, { left, exact H }, { right, exact H } } end -- ahah this version is more succinct example (l : list ℕ) (h : l ≠ []) (a ∈ l) : a = l.head ∨ a ∈ l.tail := begin rw (list.cons_head_tail h).symm at H, exact (list.mem_cons_iff a (list.head l) (list.tail l)).mp H, end -- cons smol is still sorted in lt order lemma cons_smol_sorted (l : list ℕ) (hl : list.sorted nat.lt l) (hl' : l ≠ []) (a : ℕ) (h : a < l.head) : list.sorted nat.lt (a :: l) := begin rw list.sorted_cons, split, { intros b hb, rw <- list.cons_head_tail hl' at hl, have hb' := list.rel_of_sorted_cons hl, rw (list.cons_head_tail hl').symm at hb, rw list.mem_cons_iff b (list.head l) (list.tail l) at hb, cases hb, { rwa hb }, { specialize hb' b hb, exact lt_trans h hb' } }, { exact hl } end example (a : ℕ) : list.sorted nat.lt (a :: []) := begin exact list.sorted_singleton a, end example (a : ℕ) : [a] = a :: [] := rfl example (l : list ℕ) (h : l ≠ []) : ∃ x, x ∈ l := begin use l.head, exact list.mem_of_mem_head' (list.head_mem_head' h), end example (l : list ℕ) (h : ∀ x x' ∈ l, x ≠ x') : l = [] := begin contrapose! h, use [l.head, l.head], repeat { split, exact list.mem_of_mem_head' (list.head_mem_head' h) }, refl, end example (l l' t : list ℕ) (h : l ~ l') : l ++ t ~ t ++ l' := begin calc l ++ t ~ t ++ l : list.perm_append_comm ... ~ t ++ l' : list.perm.append_left t h, end example (l : list ℕ) (a : ℕ) : list.cons a l = [a] ++ l := list.singleton_append.symm -- TODO define as appending all lists together def flatten_lists : list (list ℕ) → list ℕ | list.nil := list.nil | [list.nil] := list.nil | [h :: x] := h :: x | sorry example (l l' : list (list ℕ)) (h : l ~ l') : flatten_lists l ~ flatten_lists l' := begin sorry end example (a : ℕ) (l l' : list ℕ) : list.cons a (l ++ l') = a :: l ++ l' := (list.cons_append a l l').symm end listplayground
9c525255048e0a24ee14380475814df253e9bc08
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/intro.lean
77217fa78ef45ae0237ff0eee707079c2e644b37
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
2,155
lean
/- # The Natural Number Game, version 1.08beta [see "what's new" below] [will be ready to go after some updates to the engine which generates the web pages] ## By Kevin Buzzard and Mohammad Pedramfar. Special thanks to Rob Lewis for tactic hackery, Sian Carey for power world (world 4), and, last but not least, all the people who fed back comments, including the 2019-20 Imperial College 1st year maths beta tester students, Marie-Amélie Lawn, Toby Gee, Joseph Myers, and all the people who have been in touch via the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a> or the <a href="https://xenaproject.wordpress.com/" target="blank">Xena Project blog</a> or via <a href="https://twitter.com/home" target="blank">Twitter</a>. The natural number game is brought to you by the Xena project, a project based at Imperial College London whose aim is to get mathematics undergraduates using computer theorem provers. Lean is a computer theorem prover being developed at Microsoft Research. # What is this game? Welcome to the natural number game -- a game which shows the power of induction. In this game, you get own version of the natural numbers, called `mynat`, in a programming language called Lean. Your version of the natural numbers satisfies something called the principle of mathematical induction, and a couple of other things too (Peano's axioms). Unfortunately, nobody has proved any theorems about these natural numbers yet. For example, addition will be defined for you, but nobody has proved that `x + y = y + x` yet. This is your job. You're going to prove mathematical theorems using the Lean theorem prover. In other words, you're going to solve levels in a computer game. You're going to prove these theorems using *tactics*. This introductory world, Tutorial World, will take you through some of these tactics. During your proofs, your "goal" (i.e. what you're supposed to be proving) will be displayed with a `⊢` symbol in front of it. If the top right hand box reports "Theorem Proved!", you have closed all the goals in the level and can move on to the next level in the world you're in. -/
0cfc5bbb3b2651f757b6938d09de2d9dd318eeb0
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/not_in_use/velocityEval.lean
cf80d04ae42f7f7ce47ed4643da42466fb6cc6e9
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
779
lean
import ..imperative_DSL.environment open lang.classicalVelocity def classicalVelocityEval : lang.classicalVelocity.expr → environment.env → classicalVelocity | (expr.lit v) i := v | (lang.classicalVelocity.expr.var v) i := i.v v | (expr.div g t) i := match g with | (lang.classicalGeometry.expr.lit e) := match t with | (lang.classicalTime.expr.lit e2) := classicalVelocity.mk 0 e e2 | (lang.classicalTime.expr.var v2) := classicalVelocity.mk 0 (e) (i.t v2) end | (lang.classicalGeometry.expr.var v) := match t with | (lang.classicalTime.expr.lit e2) := classicalVelocity.mk 0 (i.g v) (e2) | (lang.classicalTime.expr.var v2) := classicalVelocity.mk 0 (i.g v) (i.t v2) end end
68a9978cb20d8cfa9c553c8aaded09ed77dfe87b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/add_decl_namespace.lean
4c399356d94e9efaedfbd0cdee6bbe0ba1421d33
[ "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
130
lean
namespace A def x := 1 def _root_.B.x := 1 end A def C.x := 1 run_cmd tactic.add_aux_decl `D.x `(ℕ) `(1) ff open A B C D
1b93d264005a07ddd2e27d9847339e8f1936d6cd
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/metric_space/isometry.lean
eff286b60df98997c0491d92c49388973304f076
[ "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
13,218
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Isometries of emetric and metric spaces Authors: Sébastien Gouëzel We define isometries, i.e., maps between emetric spaces that preserve the edistance (on metric spaces, these are exactly the maps that preserve distances), and prove their basic properties. We also introduce isometric bijections. -/ import topology.metric_space.basic topology.bounded_continuous_function analysis.normed_space.basic topology.opens noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open function set /-- An isometry (also known as isometric embedding) is a map preserving the edistance between emetric spaces, or equivalently the distance between metric space. -/ def isometry [emetric_space α] [emetric_space β] (f : α → β) : Prop := ∀x1 x2 : α, edist (f x1) (f x2) = edist x1 x2 /-- On metric spaces, a map is an isometry if and only if it preserves distances. -/ lemma isometry_emetric_iff_metric [metric_space α] [metric_space β] {f : α → β} : isometry f ↔ (∀x y, dist (f x) (f y) = dist x y) := ⟨assume H x y, by simp [dist_edist, H x y], assume H x y, by simp [edist_dist, H x y]⟩ /-- An isometry preserves edistances. -/ theorem isometry.edist_eq [emetric_space α] [emetric_space β] {f : α → β} {x y : α} (hf : isometry f) : edist (f x) (f y) = edist x y := hf x y /-- An isometry preserves distances. -/ theorem isometry.dist_eq [metric_space α] [metric_space β] {f : α → β} {x y : α} (hf : isometry f) : dist (f x) (f y) = dist x y := by rw [dist_edist, dist_edist, hf] section emetric_isometry variables [emetric_space α] [emetric_space β] [emetric_space γ] variables {f : α → β} {x y z : α} {s : set α} /-- An isometry is injective -/ lemma isometry.injective (h : isometry f) : injective f := λx y hxy, edist_eq_zero.1 $ calc edist x y = edist (f x) (f y) : (h x y).symm ... = 0 : by rw [hxy]; simp /-- Any map on a subsingleton is an isometry -/ theorem isometry_subsingleton [subsingleton α] : isometry f := λx y, by rw subsingleton.elim x y; simp /-- The identity is an isometry -/ lemma isometry_id : isometry (id : α → α) := λx y, rfl /-- The composition of isometries is an isometry -/ theorem isometry.comp {g : β → γ} {f : α → β} (hg : isometry g) (hf : isometry f) : isometry (g ∘ f) := assume x y, calc edist ((g ∘ f) x) ((g ∘ f) y) = edist (f x) (f y) : hg _ _ ... = edist x y : hf _ _ /-- An isometry is an embedding -/ theorem isometry.uniform_embedding (hf : isometry f) : uniform_embedding f := begin refine emetric.uniform_embedding_iff'.2 ⟨_, _⟩, { assume ε εpos, existsi [ε, εpos], simp [hf.edist_eq] }, { assume δ δpos, existsi [δ, δpos], simp [hf.edist_eq] } end /-- An isometry is continuous. -/ lemma isometry.continuous (hf : isometry f) : continuous f := hf.uniform_embedding.embedding.continuous /-- The inverse of an isometry is an isometry. -/ lemma isometry.inv (e : α ≃ β) (h : isometry e.to_fun) : isometry e.inv_fun := λx y, by rw [← h, e.right_inv _, e.right_inv _] /-- Isometries preserve the diameter -/ lemma emetric.isometry.diam_image (hf : isometry f) {s : set α}: emetric.diam (f '' s) = emetric.diam s := begin refine le_antisymm _ _, { apply lattice.Sup_le _, simp only [and_imp, set.mem_image, set.mem_prod, exists_imp_distrib, prod.exists], assume b x x' z zs xz z' z's x'z' hb, rw [← hb, ← xz, ← x'z', hf z z'], exact emetric.edist_le_diam_of_mem zs z's }, { apply lattice.Sup_le _, simp only [and_imp, set.mem_image, set.mem_prod, exists_imp_distrib, prod.exists], assume b x x' xs x's hb, rw [← hb, ← hf x x'], exact emetric.edist_le_diam_of_mem (mem_image_of_mem _ xs) (mem_image_of_mem _ x's) } end /-- The injection from a subtype is an isometry -/ lemma isometry_subtype_val {s : set α} : isometry (subtype.val : s → α) := λx y, rfl end emetric_isometry --section /-- An isometry preserves the diameter in metric spaces -/ lemma metric.isometry.diam_image [metric_space α] [metric_space β] {f : α → β} {s : set α} (hf : isometry f) : metric.diam (f '' s) = metric.diam s := by rw [metric.diam, metric.diam, emetric.isometry.diam_image hf] /-- α and β are isometric if there is an isometric bijection between them. -/ structure isometric (α : Type*) (β : Type*) [emetric_space α] [emetric_space β] extends α ≃ β := (isometry_to_fun : isometry to_fun) (isometry_inv_fun : isometry inv_fun) infix ` ≃ᵢ `:25 := isometric namespace isometric variables [emetric_space α] [emetric_space β] [emetric_space γ] instance : has_coe_to_fun (α ≃ᵢ β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq_to_equiv (h : α ≃ᵢ β) (a : α) : h a = h.to_equiv a := rfl /-- The (bundled) homeomorphism associated to an isometric isomorphism. -/ protected def to_homeomorph (h : α ≃ᵢ β) : α ≃ₜ β := { continuous_to_fun := (isometry_to_fun h).continuous, continuous_inv_fun := (isometry_inv_fun h).continuous, .. h.to_equiv } lemma coe_eq_to_homeomorph (h : α ≃ᵢ β) (a : α) : h a = h.to_homeomorph a := rfl lemma to_homeomorph_to_equiv (h : α ≃ᵢ β) : h.to_homeomorph.to_equiv = h.to_equiv := by ext; refl /-- The identity isometry of a space. -/ protected def refl (α : Type*) [emetric_space α] : α ≃ᵢ α := { isometry_to_fun := isometry_id, isometry_inv_fun := isometry_id, .. equiv.refl α } /-- The composition of two isometric isomorphisms, as an isometric isomorphism. -/ protected def trans (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) : α ≃ᵢ γ := { isometry_to_fun := h₂.isometry_to_fun.comp h₁.isometry_to_fun, isometry_inv_fun := h₁.isometry_inv_fun.comp h₂.isometry_inv_fun, .. equiv.trans h₁.to_equiv h₂.to_equiv } /-- The inverse of an isometric isomorphism, as an isometric isomorphism. -/ protected def symm (h : α ≃ᵢ β) : β ≃ᵢ α := { isometry_to_fun := h.isometry_inv_fun, isometry_inv_fun := h.isometry_to_fun, .. h.to_equiv.symm } protected lemma isometry (h : α ≃ᵢ β) : isometry h := h.isometry_to_fun lemma symm_comp_self (h : α ≃ᵢ β) : ⇑h.symm ∘ ⇑h = id := funext $ assume a, h.to_equiv.left_inv a lemma self_comp_symm (h : α ≃ᵢ β) : ⇑h ∘ ⇑h.symm = id := funext $ assume a, h.to_equiv.right_inv a lemma range_coe (h : α ≃ᵢ β) : range h = univ := eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩ lemma image_symm (h : α ≃ᵢ β) : image h.symm = preimage h := image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv lemma preimage_symm (h : α ≃ᵢ β) : preimage h.symm = image h := (image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm end isometric /-- An isometry induces an isometric isomorphism between the source space and the range of the isometry. -/ def isometry.isometric_on_range [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) : α ≃ᵢ range f := { isometry_to_fun := λx y, begin change edist ((equiv.set.range f _) x) ((equiv.set.range f _) y) = edist x y, rw [equiv.set.range_apply f h.injective, equiv.set.range_apply f h.injective], exact h x y end, isometry_inv_fun := begin apply isometry.inv, assume x y, change edist ((equiv.set.range f _) x) ((equiv.set.range f _) y) = edist x y, rw [equiv.set.range_apply f h.injective, equiv.set.range_apply f h.injective], exact h x y end, .. equiv.set.range f h.injective } lemma isometry.isometric_on_range_apply [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) (x : α) : h.isometric_on_range x = ⟨f x, mem_range_self _⟩ := begin dunfold isometry.isometric_on_range, rw ← equiv.set.range_apply f h.injective x, refl end /-- The space of bounded sequences, with its sup norm -/ @[reducible] def ℓ_infty_ℝ : Type := bounded_continuous_function ℕ ℝ open bounded_continuous_function metric topological_space namespace Kuratowski_embedding /- In this section, we show that any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/ variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α) /-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in a fixed countable set, if this set is dense. This map is given in the next definition, without density assumptions. -/ def embedding_of_subset : ℓ_infty_ℝ := of_normed_group_discrete (λn, dist a (x n) - dist (x 0) (x n)) (dist a (x 0)) (λ_, abs_dist_sub_le _ _ _) lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl /-- The embedding map is always a semi-contraction. -/ lemma embedding_of_subset_dist_le (a b : α) : dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b := begin refine (dist_le dist_nonneg).2 (λn, _), have A : dist a (x n) + (dist (x 0) (x n) + (-dist b (x n) + -dist (x 0) (x n))) = dist a (x n) - dist b (x n), by ring, simp only [embedding_of_subset_coe, real.dist_eq, A, add_comm, neg_add_rev, _root_.neg_neg, sub_eq_add_neg, add_left_comm], exact abs_dist_sub_le _ _ _ end /-- When the reference set is dense, the embedding map is an isometry on its image. -/ lemma embedding_of_subset_isometry (H : closure (range x) = univ) : isometry (embedding_of_subset x) := begin refine isometry_emetric_iff_metric.2 (λa b, _), refine le_antisymm (embedding_of_subset_dist_le x a b) (real.le_of_forall_epsilon_le (λe epos, _)), /- First step: find n with dist a (x n) < e -/ have A : a ∈ closure (range x), by { have B := mem_univ a, rwa [← H] at B }, rcases mem_closure_iff'.1 A (e/2) (half_pos epos) with ⟨d, ⟨drange, hd⟩⟩, cases drange with n dn, rw [← dn] at hd, /- Second step: use the norm control at index n to conclude -/ have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n := by { simp [embedding_of_subset_coe] }, have := calc dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _ ... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring } ... ≤ 2 * dist a (x n) + abs (dist b (x n) - dist a (x n)) : by apply_rules [add_le_add_left, le_abs_self] ... ≤ 2 * (e/2) + abs (embedding_of_subset x b n - embedding_of_subset x a n) : begin rw [C], apply_rules [add_le_add, mul_le_mul_of_nonneg_left, le_of_lt hd, le_refl], norm_num end ... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) : begin rw [← coe_diff], apply add_le_add_left, rw [coe_diff, ←real.dist_eq], apply dist_coe_le_dist end ... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring, simpa [dist_comm] using this end /-- Every separable metric space embeds isometrically in ℓ_infty_ℝ. -/ theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] : ∃(f : α → ℓ_infty_ℝ), isometry f := begin classical, by_cases h : (univ : set α) = ∅, { use (λ_, 0), assume x, exact (ne_empty_of_mem (mem_univ x) h).elim }, { /- We construct a map x : ℕ → α with dense image -/ rcases exists_mem_of_ne_empty h with basepoint, haveI : inhabited α := ⟨basepoint⟩, have : ∃s:set α, countable s ∧ closure s = univ := separable_space.exists_countable_closure_eq_univ _, rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩, rcases countable_iff_exists_surjective.1 S_countable with ⟨x, x_range⟩, have : closure (range x) = univ := univ_subset_iff.1 (by { rw [← S_dense], apply closure_mono, assumption }), /- Use embedding_of_subset to construct the desired isometry -/ exact ⟨embedding_of_subset x, embedding_of_subset_isometry x this⟩ } end end Kuratowski_embedding open topological_space Kuratowski_embedding /-- The Kuratowski embedding is an isometric embedding of a separable metric space in ℓ^∞(ℝ) -/ def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ := classical.some (Kuratowski_embedding.exists_isometric_embedding α) /-- The Kuratowski embedding is an isometry -/ protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] : isometry (Kuratowski_embedding α) := classical.some_spec (exists_isometric_embedding α) /-- Version of the Kuratowski embedding for nonempty compacts -/ def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] : nonempty_compacts ℓ_infty_ℝ := ⟨range (Kuratowski_embedding α), begin split, { rcases exists_mem_of_nonempty α with ⟨x, hx⟩, have A : Kuratowski_embedding α x ∈ range (Kuratowski_embedding α) := ⟨x, by simp⟩, apply ne_empty_of_mem A }, { rw ← image_univ, exact compact_image compact_univ (Kuratowski_embedding.isometry α).continuous }, end⟩
a77f074b09cafb61eeeee0a4f0e561fd968c454e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_multiple_nots.lean
5ab9b9259f50ac11fc6efb55868d65bf0072d512
[ "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
601
lean
constants a b c d : Prop set_option blast.strategy "unit" example (H : ¬ a → ¬ b → ¬ c ∨ ¬ d) : ¬ a → c → d → ¬ b → false := by blast set_option blast.strategy "preprocess" example : ¬¬¬¬¬a → ¬¬a → false := by blast example : ¬¬¬¬¬a → ¬¬¬¬a → false := by blast example : ¬¬¬¬¬a → a → false := by blast example : ¬¬a → ¬¬¬¬¬a → false := by blast example : ¬¬¬¬¬a → ¬¬¬¬¬¬¬¬a → false := by blast example : ¬¬¬¬¬a → a → false := by blast example : ¬¬¬¬¬¬¬¬a → ¬¬¬¬¬a → false := by blast
0ef9a01a9f41aee47d1a70b0cf0a7986e3ef4438
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/perm/list.lean
8a0a66e3ce1fe97a2fe7fbcf7c52198043e46c2f
[ "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
16,377
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.list.rotate import group_theory.perm.support /-! # Permutations from a list A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. When there are duplicate elements in `l`, how and in what arrangement with respect to the other elements they appear in the list determines the formed permutation. This is because `list.form_perm` is implemented as a product of `equiv.swap`s. That means that presence of a sublist of two adjacent duplicates like `[..., x, x, ...]` will produce the same permutation as if the adjacent duplicates were not present. The `list.form_perm` definition is meant to primarily be used with `nodup l`, so that the resulting permutation is cyclic (if `l` has at least two elements). The presence of duplicates in a particular placement can lead `list.form_perm` to produce a nontrivial permutation that is noncyclic. -/ namespace list variables {α β : Type*} section form_perm variables [decidable_eq α] (l : list α) open equiv equiv.perm /-- A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. -/ def form_perm : equiv.perm α := (zip_with equiv.swap l l.tail).prod @[simp] lemma form_perm_nil : form_perm ([] : list α) = 1 := rfl @[simp] lemma form_perm_singleton (x : α) : form_perm [x] = 1 := rfl @[simp] lemma form_perm_cons_cons (x y : α) (l : list α) : form_perm (x :: y :: l) = swap x y * form_perm (y :: l) := prod_cons lemma form_perm_pair (x y : α) : form_perm [x, y] = swap x y := rfl lemma form_perm_apply_of_not_mem (x : α) (l : list α) (h : x ∉ l) : form_perm l x = x := begin cases l with y l, { simp }, induction l with z l IH generalizing x y, { simp }, { specialize IH x z (mt (mem_cons_of_mem y) h), simp only [not_or_distrib, mem_cons_iff] at h, simp [IH, swap_apply_of_ne_of_ne, h] } end lemma form_perm_apply_mem_of_mem (x : α) (l : list α) (h : x ∈ l) : form_perm l x ∈ l := begin cases l with y l, { simpa }, induction l with z l IH generalizing x y, { simpa using h }, { by_cases hx : x ∈ z :: l, { rw [form_perm_cons_cons, mul_apply, swap_apply_def], split_ifs; simp [IH _ _ hx] }, { replace h : x = y := or.resolve_right h hx, simp [form_perm_apply_of_not_mem _ _ hx, ←h] } } end @[simp] lemma form_perm_cons_concat_apply_last (x y : α) (xs : list α) : form_perm (x :: (xs ++ [y])) y = x := begin induction xs with z xs IH generalizing x y, { simp }, { simp [IH] } end @[simp] lemma form_perm_apply_last (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).last (cons_ne_nil x xs)) = x := begin induction xs using list.reverse_rec_on with xs y IH generalizing x; simp end @[simp] lemma form_perm_apply_nth_le_length (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).nth_le xs.length (by simp)) = x := by rw [nth_le_cons_length, form_perm_apply_last] lemma form_perm_apply_head (x y : α) (xs : list α) (h : nodup (x :: y :: xs)) : form_perm (x :: y :: xs) x = y := by simp [form_perm_apply_of_not_mem _ _ (not_mem_of_nodup_cons h)] lemma form_perm_apply_nth_le_zero (l : list α) (h : nodup l) (hl : 1 < l.length) : form_perm l (l.nth_le 0 (zero_lt_one.trans hl)) = l.nth_le 1 hl := begin rcases l with (_|⟨x, _|⟨y, tl⟩⟩), { simp }, { simp }, { simpa using form_perm_apply_head _ _ _ h } end lemma form_perm_eq_head_iff_eq_last (x y : α) : form_perm (y :: l) x = y ↔ x = last (y :: l) (cons_ne_nil _ _) := iff.trans (by rw form_perm_apply_last) (form_perm (y :: l)).injective.eq_iff lemma zip_with_swap_prod_support' (l l' : list α) : {x | (zip_with swap l l').prod x ≠ x} ≤ l.to_finset ⊔ l'.to_finset := begin simp only [set.sup_eq_union, set.le_eq_subset], induction l with y l hl generalizing l', { simp }, { cases l' with z l', { simp }, { intro x, simp only [set.union_subset_iff, mem_cons_iff, zip_with_cons_cons, foldr, prod_cons, mul_apply], intro hx, by_cases h : x ∈ {x | (zip_with swap l l').prod x ≠ x}, { specialize hl l' h, refine set.mem_union.elim hl (λ hm, _) (λ hm, _); { simp only [finset.coe_insert, set.mem_insert_iff, finset.mem_coe, to_finset_cons, mem_to_finset] at hm ⊢, simp [hm] } }, { simp only [not_not, set.mem_set_of_eq] at h, simp only [h, set.mem_set_of_eq] at hx, rw swap_apply_ne_self_iff at hx, rcases hx with ⟨hyz, rfl|rfl⟩; simp } } } end lemma zip_with_swap_prod_support [fintype α] (l l' : list α) : (zip_with swap l l').prod.support ≤ l.to_finset ⊔ l'.to_finset := begin intros x hx, have hx' : x ∈ {x | (zip_with swap l l').prod x ≠ x} := by simpa using hx, simpa using zip_with_swap_prod_support' _ _ hx' end lemma support_form_perm_le' : {x | form_perm l x ≠ x} ≤ l.to_finset := begin refine (zip_with_swap_prod_support' l l.tail).trans _, simpa [finset.subset_iff] using tail_subset l end lemma support_form_perm_le [fintype α] : support (form_perm l) ≤ l.to_finset := begin intros x hx, have hx' : x ∈ {x | form_perm l x ≠ x} := by simpa using hx, simpa using support_form_perm_le' _ hx' end lemma form_perm_apply_lt (xs : list α) (h : nodup xs) (n : ℕ) (hn : n + 1 < xs.length) : form_perm xs (xs.nth_le n ((nat.lt_succ_self n).trans hn)) = xs.nth_le (n + 1) hn := begin induction n with n IH generalizing xs, { simpa using form_perm_apply_nth_le_zero _ h _ }, { rcases xs with (_|⟨x, _|⟨y, l⟩⟩), { simp }, { simp }, { specialize IH (y :: l) (nodup_of_nodup_cons h) _, { simpa [nat.succ_lt_succ_iff] using hn }, simp only [swap_apply_eq_iff, coe_mul, form_perm_cons_cons, nth_le], generalize_proofs at IH, rw [IH, swap_apply_of_ne_of_ne, nth_le]; { rintro rfl, simpa [nth_le_mem _ _ _] using h } } } end lemma form_perm_apply_nth_le (xs : list α) (h : nodup xs) (n : ℕ) (hn : n < xs.length) : form_perm xs (xs.nth_le n hn) = xs.nth_le ((n + 1) % xs.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases xs with x xs, { simp }, { have : n ≤ xs.length, { refine nat.le_of_lt_succ _, simpa using hn }, rcases this.eq_or_lt with rfl|hn', { simp }, { simp [form_perm_apply_lt, h, nat.mod_eq_of_lt, nat.succ_lt_succ hn'] } } end lemma support_form_perm_of_nodup' (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : {x | form_perm l x ≠ x} = l.to_finset := begin apply le_antisymm, { exact support_form_perm_le' l }, { intros x hx, simp only [finset.mem_coe, mem_to_finset] at hx, obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, rw [set.mem_set_of_eq, form_perm_apply_nth_le _ h], intro H, rw nodup_iff_nth_le_inj at h, specialize h _ _ _ _ H, cases (nat.succ_le_of_lt hn).eq_or_lt with hn' hn', { simp only [←hn', nat.mod_self] at h, refine not_exists.mpr h' _, simpa [←h, eq_comm, length_eq_one] using hn' }, { simpa [nat.mod_eq_of_lt hn'] using h } } end lemma support_form_perm_of_nodup [fintype α] (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : support (form_perm l) = l.to_finset := begin rw ←finset.coe_inj, convert support_form_perm_of_nodup' _ h h', simp [set.ext_iff] end lemma form_perm_rotate_one (l : list α) (h : nodup l) : form_perm (l.rotate 1) = form_perm l := begin have h' : nodup (l.rotate 1), { simpa using h }, by_cases hl : ∀ (x : α), l ≠ [x], { have hl' : ∀ (x : α), l.rotate 1 ≠ [x], { intro, rw [ne.def, rotate_eq_iff], simpa using hl _ }, ext x, by_cases hx : x ∈ l.rotate 1, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ h', nth_le_rotate l, nth_le_rotate l, form_perm_apply_nth_le _ h], simp }, { rw [form_perm_apply_of_not_mem _ _ hx, form_perm_apply_of_not_mem], simpa using hx } }, { push_neg at hl, obtain ⟨x, rfl⟩ := hl, simp } end lemma form_perm_rotate (l : list α) (h : nodup l) (n : ℕ) : form_perm (l.rotate n) = form_perm l := begin induction n with n hn, { simp }, { rw [nat.succ_eq_add_one, ←rotate_rotate, form_perm_rotate_one, hn], rwa is_rotated.nodup_iff, exact is_rotated.forall l n } end lemma form_perm_eq_of_is_rotated {l l' : list α} (hd : nodup l) (h : l ~r l') : form_perm l = form_perm l' := begin obtain ⟨n, rfl⟩ := h, exact (form_perm_rotate l hd n).symm end lemma form_perm_reverse (l : list α) (h : nodup l) : form_perm l.reverse = (form_perm l)⁻¹ := begin -- Let's show `form_perm l` is an inverse to `form_perm l.reverse`. rw [eq_comm, inv_eq_iff_mul_eq_one], ext x, -- We only have to check for `x ∈ l` that `form_perm l (form_perm l.reverse x)` rw [mul_apply, one_apply], by_cases hx : x ∈ l, swap, { rw [form_perm_apply_of_not_mem x l.reverse, form_perm_apply_of_not_mem _ _ hx], simpa using hx }, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem (mem_reverse.mpr hx), rw [form_perm_apply_nth_le l.reverse (nodup_reverse.mpr h), nth_le_reverse', form_perm_apply_nth_le _ h, nth_le_reverse'], { congr, rw [length_reverse, ←nat.succ_le_iff, nat.succ_eq_add_one] at hk, cases hk.eq_or_lt with hk' hk', { simp [←hk'] }, { rw [length_reverse, nat.mod_eq_of_lt hk', tsub_add_eq_add_tsub (nat.le_pred_of_lt hk'), nat.mod_eq_of_lt], { simp }, { rw tsub_add_cancel_of_le, refine tsub_lt_self _ (nat.zero_lt_succ _), all_goals { simpa using (nat.zero_le _).trans_lt hk' } } } }, all_goals { rw [← tsub_add_eq_tsub_tsub, ←length_reverse], refine tsub_lt_self _ (zero_lt_one.trans_le (le_add_right le_rfl)), exact k.zero_le.trans_lt hk } }, end lemma form_perm_pow_apply_nth_le (l : list α) (h : nodup l) (n k : ℕ) (hk : k < l.length) : (form_perm l ^ n) (l.nth_le k hk) = l.nth_le ((k + n) % l.length) (nat.mod_lt _ (k.zero_le.trans_lt hk)) := begin induction n with n hn, { simp [nat.mod_eq_of_lt hk] }, { simp [pow_succ, mul_apply, hn, form_perm_apply_nth_le _ h, nat.succ_eq_add_one, ←nat.add_assoc] } end lemma form_perm_pow_apply_head (x : α) (l : list α) (h : nodup (x :: l)) (n : ℕ) : (form_perm (x :: l) ^ n) x = (x :: l).nth_le (n % (x :: l).length) (nat.mod_lt _ (nat.zero_lt_succ _)) := by { convert form_perm_pow_apply_nth_le _ h n 0 _; simp } lemma form_perm_ext_iff {x y x' y' : α} {l l' : list α} (hd : nodup (x :: y :: l)) (hd' : nodup (x' :: y' :: l')) : form_perm (x :: y :: l) = form_perm (x' :: y' :: l') ↔ (x :: y :: l) ~r (x' :: y' :: l') := begin refine ⟨λ h, _, λ hr, form_perm_eq_of_is_rotated hd hr⟩, rw equiv.perm.ext_iff at h, have hx : x' ∈ (x :: y :: l), { have : x' ∈ {z | form_perm (x :: y :: l) z ≠ z}, { rw [set.mem_set_of_eq, h x', form_perm_apply_head _ _ _ hd'], simp only [mem_cons_iff, nodup_cons] at hd', push_neg at hd', exact hd'.left.left.symm }, simpa using support_form_perm_le' _ this }, obtain ⟨n, hn, hx'⟩ := nth_le_of_mem hx, have hl : (x :: y :: l).length = (x' :: y' :: l').length, { rw [←erase_dup_eq_self.mpr hd, ←erase_dup_eq_self.mpr hd', ←card_to_finset, ←card_to_finset], refine congr_arg finset.card _, rw [←finset.coe_inj, ←support_form_perm_of_nodup' _ hd (by simp), ←support_form_perm_of_nodup' _ hd' (by simp)], simp only [h] }, use n, apply list.ext_le, { rw [length_rotate, hl] }, { intros k hk hk', rw nth_le_rotate, induction k with k IH, { simp_rw [nat.zero_add, nat.mod_eq_of_lt hn], simpa }, { have : k.succ = (k + 1) % (x' :: y' :: l').length, { rw [←nat.succ_eq_add_one, nat.mod_eq_of_lt hk'] }, simp_rw this, rw [←form_perm_apply_nth_le _ hd' k (k.lt_succ_self.trans hk'), ←IH (k.lt_succ_self.trans hk), ←h, form_perm_apply_nth_le _ hd], congr' 1, have h1 : 1 = 1 % (x' :: y' :: l').length := by simp, rw [hl, nat.mod_eq_of_lt hk', h1, ←nat.add_mod, nat.succ_add] } } end lemma form_perm_apply_mem_eq_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = x ↔ length l ≤ 1 := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ hl, hl.nth_le_inj_iff], cases hn : l.length, { exact absurd k.zero_le (hk.trans_le hn.le).not_le }, { rw hn at hk, cases (nat.le_of_lt_succ hk).eq_or_lt with hk' hk', { simp [←hk', nat.succ_le_succ_iff, eq_comm] }, { simpa [nat.mod_eq_of_lt (nat.succ_lt_succ hk'), nat.succ_lt_succ_iff] using k.zero_le.trans_lt hk' } } end lemma form_perm_apply_mem_ne_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x ≠ x ↔ 2 ≤ l.length := begin rw [ne.def, form_perm_apply_mem_eq_self_iff _ hl x hx, not_le], exact ⟨nat.succ_le_of_lt, nat.lt_of_succ_le⟩ end lemma mem_of_form_perm_ne_self (l : list α) (x : α) (h : form_perm l x ≠ x) : x ∈ l := begin suffices : x ∈ {y | form_perm l y ≠ y}, { rw ←mem_to_finset, exact support_form_perm_le' _ this }, simpa using h end lemma form_perm_eq_self_of_not_mem (l : list α) (x : α) (h : x ∉ l) : form_perm l x = x := by_contra (λ H, h $ mem_of_form_perm_ne_self _ _ H) lemma form_perm_eq_one_iff (hl : nodup l) : form_perm l = 1 ↔ l.length ≤ 1 := begin cases l with hd tl, { simp }, { rw ←form_perm_apply_mem_eq_self_iff _ hl hd (mem_cons_self _ _), split, { simp {contextual := tt} }, { intro h, simp only [(hd :: tl).form_perm_apply_mem_eq_self_iff hl hd (mem_cons_self hd tl), add_le_iff_nonpos_left, length, nonpos_iff_eq_zero, length_eq_zero] at h, simp [h] } } end lemma form_perm_eq_form_perm_iff {l l' : list α} (hl : l.nodup) (hl' : l'.nodup) : l.form_perm = l'.form_perm ↔ l ~r l' ∨ l.length ≤ 1 ∧ l'.length ≤ 1 := begin rcases l with (_ | ⟨x, _ | ⟨y, l⟩⟩), { suffices : l'.length ≤ 1 ↔ l' = nil ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero] }, refine ⟨λ h, or.inr h, _⟩, rintro (rfl | h), { simp }, { exact h } }, { suffices : l'.length ≤ 1 ↔ [x] ~r l' ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero, le_rfl] }, refine ⟨λ h, or.inr h, _⟩, rintro (h | h), { simp [←h.perm.length_eq] }, { exact h } }, { rcases l' with (_ | ⟨x', _ | ⟨y', l'⟩⟩), { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, { suffices : ¬ (x :: y :: l) ~r [x'], { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, intro h, simpa using h.perm.length_eq }, { simp [-form_perm_cons_cons, form_perm_ext_iff hl hl'] } } end lemma form_perm_zpow_apply_mem_imp_mem (l : list α) (x : α) (hx : x ∈ l) (n : ℤ) : ((form_perm l) ^ n) x ∈ l := begin by_cases h : (l.form_perm ^ n) x = x, { simpa [h] using hx }, { have : x ∈ {x | (l.form_perm ^ n) x ≠ x} := h, rw ←set_support_apply_mem at this, replace this := set_support_zpow_subset _ _ this, simpa using support_form_perm_le' _ this } end lemma form_perm_pow_length_eq_one_of_nodup (hl : nodup l) : (form_perm l) ^ (length l) = 1 := begin ext x, by_cases hx : x ∈ l, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, simp [form_perm_pow_apply_nth_le _ hl, nat.mod_eq_of_lt hk] }, { have : x ∉ {x | (l.form_perm ^ l.length) x ≠ x}, { intros H, refine hx _, replace H := set_support_zpow_subset l.form_perm l.length H, simpa using support_form_perm_le' _ H }, simpa } end end form_perm end list
5453b21a94bcc830f7a5c946d81c86adef10aa6b
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/types/trunc.hlean
c8a17fc4b8e9763ae7ffb9c68b65c679f5cdb30e
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,889
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Properties of is_trunc and trunctype -/ -- NOTE: the fact that (is_trunc n A) is a mere proposition is proved in .hprop_trunc import types.pi types.eq types.equiv ..function open eq sigma sigma.ops pi function equiv is_trunc.trunctype is_equiv prod is_trunc.trunc_index pointed nat namespace is_trunc variables {A B : Type} {n : trunc_index} /- theorems about trunctype -/ protected definition trunctype.sigma_char.{l} (n : trunc_index) : (trunctype.{l} n) ≃ (Σ (A : Type.{l}), is_trunc n A) := begin fapply equiv.MK, { intro A, exact (⟨carrier A, struct A⟩)}, { intro S, exact (trunctype.mk S.1 S.2)}, { intro S, induction S with S1 S2, reflexivity}, { intro A, induction A with A1 A2, reflexivity}, end definition trunctype_eq_equiv (n : trunc_index) (A B : n-Type) : (A = B) ≃ (carrier A = carrier B) := calc (A = B) ≃ (to_fun (trunctype.sigma_char n) A = to_fun (trunctype.sigma_char n) B) : eq_equiv_fn_eq_of_equiv ... ≃ ((to_fun (trunctype.sigma_char n) A).1 = (to_fun (trunctype.sigma_char n) B).1) : equiv.symm (!equiv_subtype) ... ≃ (carrier A = carrier B) : equiv.refl theorem is_trunc_is_embedding_closed (f : A → B) [Hf : is_embedding f] [HB : is_trunc n B] (Hn : -1 ≤ n) : is_trunc n A := begin induction n with n, {exact !empty.elim Hn}, {apply is_trunc_succ_intro, intro a a', fapply @is_trunc_is_equiv_closed_rev _ _ n (ap f)} end theorem is_trunc_is_retraction_closed (f : A → B) [Hf : is_retraction f] (n : trunc_index) [HA : is_trunc n A] : is_trunc n B := begin revert A B f Hf HA, induction n with n IH, { intro A B f Hf HA, induction Hf with g ε, fapply is_contr.mk, { exact f (center A)}, { intro b, apply concat, { apply (ap f), exact (center_eq (g b))}, { apply ε}}}, { intro A B f Hf HA, induction Hf with g ε, apply is_trunc_succ_intro, intro b b', fapply (IH (g b = g b')), { intro q, exact ((ε b)⁻¹ ⬝ ap f q ⬝ ε b')}, { apply (is_retraction.mk (ap g)), { intro p, induction p, {rewrite [↑ap, con.left_inv]}}}, { apply is_trunc_eq}} end definition is_embedding_to_fun (A B : Type) : is_embedding (@to_fun A B) := λf f', !is_equiv_ap_to_fun theorem is_trunc_trunctype [instance] (n : trunc_index) : is_trunc n.+1 (n-Type) := begin apply is_trunc_succ_intro, intro X Y, fapply is_trunc_equiv_closed, {apply equiv.symm, apply trunctype_eq_equiv}, fapply is_trunc_equiv_closed, {apply equiv.symm, apply eq_equiv_equiv}, induction n, {apply @is_contr_of_inhabited_hprop, {apply is_trunc_is_embedding_closed, {apply is_embedding_to_fun} , {exact unit.star}}, {apply equiv_of_is_contr_of_is_contr}}, {apply is_trunc_is_embedding_closed, {apply is_embedding_to_fun}, {exact unit.star}} end /- theorems about decidable equality and axiom K -/ theorem is_hset_of_axiom_K {A : Type} (K : Π{a : A} (p : a = a), p = idp) : is_hset A := is_hset.mk _ (λa b p q, eq.rec_on q K p) theorem is_hset_of_relation.{u} {A : Type.{u}} (R : A → A → Type.{u}) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) : is_hset A := is_hset_of_axiom_K (λa p, have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from !apd, have H3 : Π(r : R a a), transport (λx, a = x) p (imp r) = imp (transport (λx, R a x) p r), from to_fun (equiv.symm !heq_pi) H2, have H4 : imp (refl a) ⬝ p = imp (refl a), from calc imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : transport_eq_r ... = imp (transport (λx, R a x) p (refl a)) : H3 ... = imp (refl a) : is_hprop.elim, cancel_left H4) definition relation_equiv_eq {A : Type} (R : A → A → Type) (mere : Π(a b : A), is_hprop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b := @equiv_of_is_hprop _ _ _ (@is_trunc_eq _ _ (is_hset_of_relation R mere refl @imp) a b) imp (λp, p ▸ refl a) local attribute not [reducible] theorem is_hset_of_double_neg_elim {A : Type} (H : Π(a b : A), ¬¬a = b → a = b) : is_hset A := is_hset_of_relation (λa b, ¬¬a = b) _ (λa n, n idp) H section open decidable --this is proven differently in init.hedberg theorem is_hset_of_decidable_eq (A : Type) [H : decidable_eq A] : is_hset A := is_hset_of_double_neg_elim (λa b, by_contradiction) end theorem is_trunc_of_axiom_K_of_leq {A : Type} (n : trunc_index) (H : -1 ≤ n) (K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_leq H (λp, eq.rec_on p !K)) theorem is_trunc_succ_of_is_trunc_loop (Hn : -1 ≤ n) (Hp : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := begin apply is_trunc_succ_intro, intros a a', apply is_trunc_of_imp_is_trunc_of_leq Hn, intro p, induction p, apply Hp end theorem is_trunc_succ_iff_is_trunc_loop (A : Type) (Hn : -1 ≤ n) : is_trunc (n.+1) A ↔ Π(a : A), is_trunc n (a = a) := iff.intro _ (is_trunc_succ_of_is_trunc_loop Hn) theorem is_trunc_iff_is_contr_loop_succ (n : ℕ) (A : Type) : is_trunc n A ↔ Π(a : A), is_contr (Ω[succ n](Pointed.mk a)) := begin revert A, induction n with n IH, { intros, esimp [Iterated_loop_space], apply iff.intro, { intros H a, apply is_contr.mk idp, apply is_hprop.elim}, { intro H, apply is_hset_of_axiom_K, intros, apply is_hprop.elim}}, { intros, transitivity _, apply @is_trunc_succ_iff_is_trunc_loop n, constructor, apply iff.pi_iff_pi, intros, transitivity _, apply IH, assert H : Πp : a = a, Ω(Pointed.mk p) = Ω(Pointed.mk (idpath a)), { intros, fapply Pointed_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}}, transitivity _, apply iff.pi_iff_pi, intro p, rewrite [↑Iterated_loop_space,H], apply iff.refl, apply iff.imp_iff, reflexivity} end theorem is_trunc_iff_is_contr_loop (n : ℕ) (A : Type) : is_trunc (n.-2.+1) A ↔ (Π(a : A), is_contr (Ω[n](pointed.Mk a))) := begin induction n with n, { esimp [sub_two,Iterated_loop_space], apply iff.intro, intro H a, exact is_contr_of_inhabited_hprop a, intro H, apply is_hprop_of_imp_is_contr, exact H}, { apply is_trunc_iff_is_contr_loop_succ}, end end is_trunc open is_trunc namespace trunc variable {A : Type} protected definition code (n : trunc_index) (aa aa' : trunc n.+1 A) : n-Type := trunc.rec_on aa (λa, trunc.rec_on aa' (λa', trunctype.mk' n (trunc n (a = a')))) protected definition encode (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' → trunc.code n aa aa' := begin intro p, induction p, apply (trunc.rec_on aa), intro a, esimp [trunc.code,trunc.rec_on], exact (tr idp) end protected definition decode (n : trunc_index) (aa aa' : trunc n.+1 A) : trunc.code n aa aa' → aa = aa' := begin eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, apply (trunc.rec_on x), intro p, exact (ap tr p) end definition trunc_eq_equiv [constructor] (n : trunc_index) (aa aa' : trunc n.+1 A) : aa = aa' ≃ trunc.code n aa aa' := begin fapply equiv.MK, { apply trunc.encode}, { apply trunc.decode}, { eapply (trunc.rec_on aa'), eapply (trunc.rec_on aa), intro a a' x, esimp [trunc.code, trunc.rec_on] at x, refine (@trunc.rec_on n _ _ x _ _), intro x, apply is_trunc_eq, intro p, induction p, reflexivity}, { intro p, induction p, apply (trunc.rec_on aa), intro a, exact idp}, end definition tr_eq_tr_equiv [constructor] (n : trunc_index) (a a' : A) : (tr a = tr a' :> trunc n.+1 A) ≃ trunc n (a = a') := !trunc_eq_equiv definition is_trunc_trunc_of_is_trunc [instance] [priority 500] (A : Type) (n m : trunc_index) [H : is_trunc n A] : is_trunc n (trunc m A) := begin revert A m H, eapply (trunc_index.rec_on n), { clear n, intro A m H, apply is_contr_equiv_closed, { apply equiv.symm, apply trunc_equiv, apply (@is_trunc_of_leq _ -2), exact unit.star} }, { clear n, intro n IH A m H, induction m with m, { apply (@is_trunc_of_leq _ -2), exact unit.star}, { apply is_trunc_succ_intro, intro aa aa', apply (@trunc.rec_on _ _ _ aa (λy, !is_trunc_succ_of_is_hprop)), eapply (@trunc.rec_on _ _ _ aa' (λy, !is_trunc_succ_of_is_hprop)), intro a a', apply (is_trunc_equiv_closed_rev), { apply tr_eq_tr_equiv}, { exact (IH _ _ _)}}} end open equiv.ops definition unique_choice {P : A → Type} [H : Πa, is_hprop (P a)] (f : Πa, ∥ P a ∥) (a : A) : P a := !trunc_equiv (f a) end trunc open trunc namespace function variables {A B : Type} definition is_surjective_of_is_equiv [instance] (f : A → B) [H : is_equiv f] : is_surjective f := λb, !center definition is_equiv_equiv_is_embedding_times_is_surjective [constructor] (f : A → B) : is_equiv f ≃ (is_embedding f × is_surjective f) := equiv_of_is_hprop (λH, (_, _)) (λP, prod.rec_on P (λH₁ H₂, !is_equiv_of_is_surjective_of_is_embedding)) end function
1833ade015a28f47fc851222c813360b25853580
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/hole_issue2.lean
4925bf537a6c09a21af927429b91fd837918baab
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,845
lean
constant bag_setoid : ∀ A, setoid (list A) attribute [instance] bag_setoid noncomputable definition bag (A : Type) : Type := quotient (bag_setoid A) constant subcount : ∀ {A}, list A → list A → bool constant list.count : ∀ {A}, A → list A → nat constant all_of_subcount_eq_tt : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ constant ex_of_subcount_eq_ff : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ noncomputable definition count {A} (a : A) (b : bag A) : nat := quotient.lift_on b (λ l, list.count a l) (λ l₁ l₂ h, sorry) noncomputable definition subbag {A} (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix ⊆ := subbag noncomputable definition decidable_subbag_1 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, _)) end) noncomputable definition decidable_subbag_2 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) _) end) noncomputable definition decidable_subbag_3 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, _) end)
2d2b47fa93a77e2878ca7be3aee462b8429ef389
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/rat/order.lean
7e5b5842ec7c487c1d79b094fc407d80a6e8ea04
[ "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
8,179
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.basic /-! # Order for Rational Numbers ## Summary We define the order on `ℚ`, prove that `ℚ` is a discrete, linearly ordered field, and define functions such as `abs` and `sqrt` that depend on this order. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, order, ordering, sqrt, abs -/ namespace rat variables (a b c : ℚ) open_locale rat /-- A rational number is called nonnegative if its numerator is nonnegative. -/ protected def nonneg (r : ℚ) : Prop := 0 ≤ r.num @[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : 0 < b) : (a /. b).nonneg ↔ 0 ≤ a := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, simp [rat.nonneg], have d0 := int.coe_nat_lt.2 h₁, have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha, constructor; intro h₂, { apply nonneg_of_mul_nonneg_right _ d0, rw this, exact mul_nonneg h₂ (le_of_lt h) }, { apply nonneg_of_mul_nonneg_right _ h, rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) }, end protected lemma nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], intros n₁0 n₂0, apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}, end protected lemma nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0, mul_nonneg] { contextual := tt } end protected lemma nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 := num_denom_cases_on' a $ λ n d h, begin have d0 : 0 < (d:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h), simp [d0, h], exact λ h₁ h₂, le_antisymm h₂ h₁ end protected lemma nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) := by cases a with n; exact or.imp_right neg_nonneg_of_nonpos (le_total 0 n) instance decidable_nonneg : decidable (rat.nonneg a) := by cases a; unfold rat.nonneg; apply_instance /-- Relation `a ≤ b` on `ℚ` defined as `a ≤ b ↔ rat.nonneg (b - a)`. Use `a ≤ b` instead of `rat.le a b`. -/ protected def le (a b : ℚ) := rat.nonneg (b - a) instance : has_le ℚ := ⟨rat.le⟩ instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop) | a b := show decidable (rat.nonneg (b - a)), by apply_instance protected theorem le_def {a b c d : ℤ} (b0 : 0 < b) (d0 : 0 < d) : a /. b ≤ c /. d ↔ a * d ≤ c * b := begin show rat.nonneg _ ↔ _, rw ← sub_nonneg, simp [sub_eq_add_neg, ne_of_gt b0, ne_of_gt d0, mul_pos d0 b0] end protected theorem le_refl : a ≤ a := show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ) protected theorem le_total : a ≤ b ∨ b ≤ a := by have := rat.nonneg_total (b - a); rwa neg_sub at this protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b := by { have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by rwa [← sub_eq_add_neg, neg_sub]), rwa neg_neg at this } protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc, by simpa [sub_eq_add_neg, add_comm, add_left_comm] instance : linear_order ℚ := { le := rat.le, le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := rat.le_total, decidable_eq := by apply_instance, decidable_le := assume a b, rat.decidable_nonneg (b - a) } /- Extra instances to short-circuit type class resolution -/ instance : has_lt ℚ := by apply_instance instance : distrib_lattice ℚ := by apply_instance instance : lattice ℚ := by apply_instance instance : semilattice_inf ℚ := by apply_instance instance : semilattice_sup ℚ := by apply_instance instance : has_inf ℚ := by apply_instance instance : has_sup ℚ := by apply_instance instance : partial_order ℚ := by apply_instance instance : preorder ℚ := by apply_instance protected lemma le_def' {p q : ℚ} : p ≤ q ↔ p.num * q.denom ≤ q.num * p.denom := begin rw [←(@num_denom q), ←(@num_denom p)], conv_rhs { simp only [num_denom] }, exact rat.le_def (by exact_mod_cast p.pos) (by exact_mod_cast q.pos) end protected lemma lt_def {p q : ℚ} : p < q ↔ p.num * q.denom < q.num * p.denom := begin rw [lt_iff_le_and_ne, rat.le_def'], suffices : p ≠ q ↔ p.num * q.denom ≠ q.num * p.denom, by { split; intro h, { exact lt_iff_le_and_ne.elim_right ⟨h.left, (this.elim_left h.right)⟩ }, { have tmp := lt_iff_le_and_ne.elim_left h, exact ⟨tmp.left, this.elim_right tmp.right⟩ }}, exact (not_iff_not.elim_right eq_iff_mul_eq_mul) end theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a := show rat.nonneg a ↔ rat.nonneg (a - 0), by simp theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a | ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩ protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b := by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb instance : linear_ordered_field ℚ := { zero_le_one := dec_trivial, add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab, mul_pos := assume a b ha hb, lt_of_le_of_ne (rat.mul_nonneg (le_of_lt ha) (le_of_lt hb)) (mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm, ..rat.field, ..rat.linear_order, ..rat.semiring } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_ring ℚ := by apply_instance instance : ordered_ring ℚ := by apply_instance instance : linear_ordered_semiring ℚ := by apply_instance instance : ordered_semiring ℚ := by apply_instance instance : linear_ordered_add_comm_group ℚ := by apply_instance instance : ordered_add_comm_group ℚ := by apply_instance instance : ordered_cancel_add_comm_monoid ℚ := by apply_instance instance : ordered_add_comm_monoid ℚ := by apply_instance attribute [irreducible] rat.le theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a := lt_iff_lt_of_le_iff_le $ by simpa [(by cases a; refl : (-a).num = -a.num)] using @num_nonneg_iff_zero_le (-a) lemma div_lt_div_iff_mul_lt_mul {a b c d : ℤ} (b_pos : 0 < b) (d_pos : 0 < d) : (a : ℚ) / b < c / d ↔ a * d < c * b := begin simp only [lt_iff_le_not_le], apply and_congr, { simp [div_num_denom, (rat.le_def b_pos d_pos)] }, { apply not_iff_not_of_iff, simp [div_num_denom, (rat.le_def d_pos b_pos)] } end lemma lt_one_iff_num_lt_denom {q : ℚ} : q < 1 ↔ q.num < q.denom := by simp [rat.lt_def] theorem abs_def (q : ℚ) : |q| = q.num.nat_abs /. q.denom := begin cases le_total q 0 with hq hq, { rw [abs_of_nonpos hq], rw [←(@num_denom q), ← mk_zero_one, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one, mul_one, zero_mul] at hq, rw [int.of_nat_nat_abs_of_nonpos hq, ← neg_def, num_denom] }, { rw [abs_of_nonneg hq], rw [←(@num_denom q), ← mk_zero_one, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos), mul_one, zero_mul] at hq, rw [int.nat_abs_of_nonneg hq, num_denom] } end end rat
e9bc66795e60619b0ba22070f0f8bcced813b791
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/regular/smul.lean
38c15a93eeaac9258bff61652c62a6c8f02d170c
[ "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
7,102
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.smul_with_zero import algebra.regular.basic /-! # Action of regular elements on a module We introduce `M`-regular elements, in the context of an `R`-module `M`. The corresponding predicate is called `is_smul_regular`. There are very limited typeclass assumptions on `R` and `M`, but the "mathematical" case of interest is a commutative ring `R` acting an a module `M`. Since the properties are "multiplicative", there is no actual requirement of having an addition, but there is a zero in both `R` and `M`. Smultiplications involving `0` are, of course, all trivial. The defining property is that an element `a ∈ R` is `M`-regular if the smultiplication map `M → M`, defined by `m ↦ a • m`, is injective. This property is the direct generalization to modules of the property `is_left_regular` defined in `algebra/regular`. Lemma `is_smul_regular.is_left_regular_iff` shows that indeed the two notions coincide. -/ variables {R S : Type*} (M : Type*) {a b : R} {s : S} /-- An `M`-regular element is an element `c` such that multiplication on the left by `c` is an injective map `M → M`. -/ def is_smul_regular [has_scalar R M] (c : R) := function.injective ((•) c : M → M) lemma is_left_regular.is_smul_regular [has_mul R] {c : R} (h : is_left_regular c) : is_smul_regular R c := h /-- Left-regular multiplication on `R` is equivalent to `R`-regularity of `R` itself. -/ lemma is_left_regular_iff [has_mul R] {a : R} : is_left_regular a ↔ is_smul_regular R a := iff.rfl lemma is_right_regular.is_smul_regular [has_mul R] {c : R} (h : is_right_regular c) : is_smul_regular R (opposite.op c) := h /-- Right-regular multiplication on `R` is equivalent to `Rᵒᵖ`-regularity of `R` itself. -/ lemma is_right_regular_iff [has_mul R] {a : R} : is_right_regular a ↔ is_smul_regular R (opposite.op a) := iff.rfl namespace is_smul_regular variables {M} section has_scalar variables [has_scalar R M] [has_scalar R S] [has_scalar S M] [is_scalar_tower R S M] /-- The product of `M`-regular elements is `M`-regular. -/ lemma smul (ra : is_smul_regular M a) (rs : is_smul_regular M s) : is_smul_regular M (a • s) := λ a b ab, rs (ra ((smul_assoc _ _ _).symm.trans (ab.trans (smul_assoc _ _ _)))) /-- If an element `b` becomes `M`-regular after multiplying it on the left by an `M`-regular element, then `b` is `M`-regular. -/ lemma of_smul (a : R) (ab : is_smul_regular M (a • s)) : is_smul_regular M s := @function.injective.of_comp _ _ _ (λ m : M, a • m) _ (λ c d cd, ab (by rwa [smul_assoc, smul_assoc])) /-- An element is `M`-regular if and only if multiplying it on the left by an `M`-regular element is `M`-regular. -/ @[simp] lemma smul_iff (b : S) (ha : is_smul_regular M a) : is_smul_regular M (a • b) ↔ is_smul_regular M b := ⟨of_smul _, ha.smul⟩ lemma is_left_regular [has_mul R] {a : R} (h : is_smul_regular R a) : is_left_regular a := h lemma is_right_regular [has_mul R] {a : R} (h : is_smul_regular R (opposite.op a)) : is_right_regular a := h end has_scalar section monoid variables [monoid R] [mul_action R M] variable (M) /-- One is `M`-regular always. -/ @[simp] lemma one : is_smul_regular M (1 : R) := λ a b ab, by rwa [one_smul, one_smul] at ab variable {M} lemma mul (ra : is_smul_regular M a) (rb : is_smul_regular M b) : is_smul_regular M (a * b) := ra.smul rb lemma of_mul (ab : is_smul_regular M (a * b)) : is_smul_regular M b := by { rw ← smul_eq_mul at ab, exact ab.of_smul _ } @[simp] lemma mul_iff_right (ha : is_smul_regular M a) : is_smul_regular M (a * b) ↔ is_smul_regular M b := ⟨of_mul, ha.mul⟩ /-- Two elements `a` and `b` are `M`-regular if and only if both products `a * b` and `b * a` are `M`-regular. -/ lemma mul_and_mul_iff : is_smul_regular M (a * b) ∧ is_smul_regular M (b * a) ↔ is_smul_regular M a ∧ is_smul_regular M b := begin refine ⟨_, _⟩, { rintros ⟨ab, ba⟩, refine ⟨ba.of_mul, ab.of_mul⟩ }, { rintros ⟨ha, hb⟩, exact ⟨ha.mul hb, hb.mul ha⟩ } end /-- Any power of an `M`-regular element is `M`-regular. -/ lemma pow (n : ℕ) (ra : is_smul_regular M a) : is_smul_regular M (a ^ n) := begin induction n with n hn, { simp only [one, pow_zero] }, { rw pow_succ, exact (ra.smul_iff (a ^ n)).mpr hn } end /-- An element `a` is `M`-regular if and only if a positive power of `a` is `M`-regular. -/ lemma pow_iff {n : ℕ} (n0 : 0 < n) : is_smul_regular M (a ^ n) ↔ is_smul_regular M a := begin refine ⟨_, pow n⟩, rw [← nat.succ_pred_eq_of_pos n0, pow_succ', ← smul_eq_mul], exact of_smul _, end end monoid section monoid_with_zero variables [monoid_with_zero R] [monoid_with_zero S] [has_zero M] [mul_action_with_zero R M] [mul_action_with_zero R S] [mul_action_with_zero S M] [is_scalar_tower R S M] /-- The element `0` is `M`-regular if and only if `M` is trivial. -/ protected lemma subsingleton (h : is_smul_regular M (0 : R)) : subsingleton M := ⟨λ a b, h (by repeat { rw mul_action_with_zero.zero_smul })⟩ /-- The element `0` is `M`-regular if and only if `M` is trivial. -/ lemma zero_iff_subsingleton : is_smul_regular M (0 : R) ↔ subsingleton M := ⟨λ h, h.subsingleton, λ H a b h, @subsingleton.elim _ H a b⟩ /-- The `0` element is not `M`-regular, on a non-trivial module. -/ lemma not_zero_iff : ¬ is_smul_regular M (0 : R) ↔ nontrivial M := begin rw [nontrivial_iff, not_iff_comm, zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is `M`-regular when `M` is trivial. -/ lemma zero [sM : subsingleton M] : is_smul_regular M (0 : R) := zero_iff_subsingleton.mpr sM /-- The `0` element is not `M`-regular, on a non-trivial module. -/ lemma not_zero [nM : nontrivial M] : ¬ is_smul_regular M (0 : R) := not_zero_iff.mpr nM /-- An element of `S` admitting a left inverse in `R` is `M`-regular. -/ lemma of_smul_eq_one (h : a • s = 1) : is_smul_regular M s := of_smul a (by { rw h, exact one M }) /-- An element of `R` admitting a left inverse is `M`-regular. -/ lemma of_mul_eq_one (h : a * b = 1) : is_smul_regular M b := of_mul (by { rw h, exact one M }) end monoid_with_zero section comm_monoid variables [comm_monoid R] [mul_action R M] /-- A product is `M`-regular if and only if the factors are. -/ lemma mul_iff : is_smul_regular M (a * b) ↔ is_smul_regular M a ∧ is_smul_regular M b := begin rw ← mul_and_mul_iff, exact ⟨λ ab, ⟨ab, by rwa mul_comm⟩, λ rab, rab.1⟩ end end comm_monoid end is_smul_regular variables [monoid_with_zero R] [has_zero M] [mul_action_with_zero R M] /-- Any element in `units R` is `M`-regular. -/ lemma units.is_smul_regular (a : units R) : is_smul_regular M (a : R) := is_smul_regular.of_mul_eq_one a.inv_val /-- A unit is `M`-regular. -/ lemma is_unit.is_smul_regular (ua : is_unit a) : is_smul_regular M a := begin rcases ua with ⟨a, rfl⟩, exact a.is_smul_regular M end
d29f3464d5f6f79d3495fffe143972fb7c80491c
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/multiplication/9.lean
96c2e6112114a803678e9eb90a0874d6861425e6
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
125
lean
lemma mul_left_comm (a b c : mynat) : a * (b * c) = b * (a * c) := begin rwa [← mul_assoc, mul_comm a b, mul_assoc], end
b4cfba10934992be84e2235e47dd4b45e8712989
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/module/ordered.lean
251baaedae4ea114ab0539c04c511b51b6b62c58
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,687
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.pi import Mathlib.algebra.ordered_pi import Mathlib.algebra.module.prod import Mathlib.algebra.ordered_field import Mathlib.PostPort universes u_1 u_2 l u_3 namespace Mathlib /-! # Ordered semimodules In this file we define * `ordered_semimodule R M` : an ordered additive commutative monoid `M` is an `ordered_semimodule` over an `ordered_semiring` `R` if the scalar product respects the order relation on the monoid and on the ring. There is a correspondence between this structure and convex cones, which is proven in `analysis/convex/cone.lean`. ## Implementation notes * We choose to define `ordered_semimodule` as a `Prop`-valued mixin, so that it can be used for both modules and algebras (the axioms for an "ordered algebra" are exactly that the algebra is ordered as a module). * To get ordered modules and ordered vector spaces, it suffices to the replace the `order_add_comm_monoid` and the `ordered_semiring` as desired. ## References * https://en.wikipedia.org/wiki/Ordered_vector_space ## Tags ordered semimodule, ordered module, ordered vector space -/ /-- An ordered semimodule is an ordered additive commutative monoid with a partial order in which the scalar multiplication is compatible with the order. -/ class ordered_semimodule (R : Type u_1) (M : Type u_2) [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] where smul_lt_smul_of_pos : ∀ {a b : M} {c : R}, a < b → 0 < c → c • a < c • b lt_of_smul_lt_smul_of_pos : ∀ {a b : M} {c : R}, c • a < c • b → 0 < c → a < b theorem smul_lt_smul_of_pos {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} : a < b → 0 < c → c • a < c • b := ordered_semimodule.smul_lt_smul_of_pos theorem smul_le_smul_of_nonneg {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c • a ≤ c • b := sorry theorem eq_of_smul_eq_smul_of_pos_of_le {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} (h₁ : c • a = c • b) (hc : 0 < c) (hle : a ≤ b) : a = b := or.resolve_left (has_le.le.lt_or_eq hle) fun (hlt : a < b) => has_lt.lt.ne (smul_lt_smul_of_pos hlt hc) h₁ theorem lt_of_smul_lt_smul_of_nonneg {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} (h : c • a < c • b) (hc : 0 ≤ c) : a < b := sorry theorem smul_lt_smul_iff_of_pos {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {b : M} {c : R} (hc : 0 < c) : c • a < c • b ↔ a < b := { mp := fun (h : c • a < c • b) => lt_of_smul_lt_smul_of_nonneg h (has_lt.lt.le hc), mpr := fun (h : a < b) => smul_lt_smul_of_pos h hc } theorem smul_pos_iff_of_pos {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] {a : M} {c : R} (hc : 0 < c) : 0 < c • a ↔ 0 < a := iff.trans (eq.mpr (id (Eq._oldrec (Eq.refl (0 < c • a ↔ c • 0 < c • a)) (smul_zero c))) (iff.refl (0 < c • a))) (smul_lt_smul_iff_of_pos hc) /-- If `R` is a linear ordered semifield, then it suffices to verify only the first axiom of `ordered_semimodule`. Moreover, it suffices to verify that `a < b` and `0 < c` imply `c • a ≤ c • b`. We have no semifields in `mathlib`, so we use the assumption `∀ c ≠ 0, is_unit c` instead. -/ theorem ordered_semimodule.mk'' {R : Type u_1} {M : Type u_2} [linear_ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] (hR : ∀ {c : R}, c ≠ 0 → is_unit c) (hlt : ∀ {a b : M} {c : R}, a < b → 0 < c → c • a ≤ c • b) : ordered_semimodule R M := sorry /-- If `R` is a linear ordered field, then it suffices to verify only the first axiom of `ordered_semimodule`. -/ theorem ordered_semimodule.mk' {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_monoid M] [semimodule k M] (hlt : ∀ {a b : M} {c : k}, a < b → 0 < c → c • a ≤ c • b) : ordered_semimodule k M := ordered_semimodule.mk'' (fun (c : k) (hc : c ≠ 0) => is_unit.mk0 c hc) hlt protected instance linear_ordered_semiring.to_ordered_semimodule {R : Type u_1} [linear_ordered_semiring R] : ordered_semimodule R R := ordered_semimodule.mk ordered_semiring.mul_lt_mul_of_pos_left fun (_x _x_1 _x_2 : R) (h : _x_2 • _x < _x_2 • _x_1) (hc : 0 < _x_2) => lt_of_mul_lt_mul_left h (has_lt.lt.le hc) theorem smul_le_smul_iff_of_pos {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : 0 < c) : c • a ≤ c • b ↔ a ≤ b := sorry theorem smul_le_smul_iff_of_neg {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : c < 0) : c • a ≤ c • b ↔ b ≤ a := sorry theorem smul_lt_iff_of_pos {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : 0 < c) : c • a < b ↔ a < c⁻¹ • b := sorry theorem smul_le_iff_of_pos {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : 0 < c) : c • a ≤ b ↔ a ≤ c⁻¹ • b := sorry theorem le_smul_iff_of_pos {k : Type u_1} {M : Type u_2} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] {a : M} {b : M} {c : k} (hc : 0 < c) : a ≤ c • b ↔ c⁻¹ • a ≤ b := sorry protected instance prod.ordered_semimodule {k : Type u_1} {M : Type u_2} {N : Type u_3} [linear_ordered_field k] [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] [ordered_add_comm_group N] [semimodule k N] [ordered_semimodule k N] : ordered_semimodule k (M × N) := ordered_semimodule.mk' fun (v u : M × N) (c : k) (h : v < u) (hc : 0 < c) => { left := smul_le_smul_of_nonneg (and.left (and.left h)) (has_lt.lt.le hc), right := smul_le_smul_of_nonneg (and.right (and.left h)) (has_lt.lt.le hc) } protected instance pi.ordered_semimodule {k : Type u_1} [linear_ordered_field k] {ι : Type u_2} {M : ι → Type u_3} [(i : ι) → ordered_add_comm_group (M i)] [(i : ι) → semimodule k (M i)] [∀ (i : ι), ordered_semimodule k (M i)] : ordered_semimodule k ((i : ι) → M i) := ordered_semimodule.mk' fun (v u : (i : ι) → M i) (c : k) (h : v < u) (hc : 0 < c) (i : ι) => id (smul_le_smul_of_nonneg (has_lt.lt.le h i) (has_lt.lt.le hc)) -- Sometimes Lean fails to apply the dependent version to non-dependent functions, -- so we define another instance protected instance pi.ordered_semimodule' {k : Type u_1} [linear_ordered_field k] {ι : Type u_2} {M : Type u_3} [ordered_add_comm_group M] [semimodule k M] [ordered_semimodule k M] : ordered_semimodule k (ι → M) := pi.ordered_semimodule protected instance order_dual.has_scalar {R : Type u_1} {M : Type u_2} [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : has_scalar R (order_dual M) := has_scalar.mk has_scalar.smul protected instance order_dual.mul_action {R : Type u_1} {M : Type u_2} [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : mul_action R (order_dual M) := mul_action.mk sorry sorry protected instance order_dual.distrib_mul_action {R : Type u_1} {M : Type u_2} [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : distrib_mul_action R (order_dual M) := distrib_mul_action.mk sorry sorry protected instance order_dual.semimodule {R : Type u_1} {M : Type u_2} [semiring R] [ordered_add_comm_monoid M] [semimodule R M] : semimodule R (order_dual M) := semimodule.mk sorry sorry protected instance order_dual.ordered_semimodule {R : Type u_1} {M : Type u_2} [ordered_semiring R] [ordered_add_comm_monoid M] [semimodule R M] [ordered_semimodule R M] : ordered_semimodule R (order_dual M) := ordered_semimodule.mk (fun (a b : order_dual M) => ordered_semimodule.smul_lt_smul_of_pos) fun (a b : order_dual M) => ordered_semimodule.lt_of_smul_lt_smul_of_pos
a5658ce76e02ffdca29fc5c31a764c2c610e22db
35452ce8e77eaf9e0aa9367a9e20bafbf92730d4
/src/main.lean
cac8490b5420fc83b7538441bc873718decbf6e6
[]
no_license
ADedecker/wedderburn
6935f44f922080df5d673051737881d9f8a94e9c
1ed28ff8cf64e1652d540557765e379b3901ad19
refs/heads/master
1,692,935,097,444
1,634,302,432,000
1,634,302,432,000
412,828,531
0
0
null
null
null
null
UTF-8
Lean
false
false
6,086
lean
import linear_algebra.finite_dimensional import field_theory.finite.basic import ring_theory.polynomial.cyclotomic import .aux open ring finite_dimensional fintype mul_action polynomial open_locale big_operators variables {A : Type*} [division_ring A] [fintype A] [fintype (subring.center A)] -- we keep "unnecessary" fintype instances to avoid diamonds local notation `K` := subring.center A local notation `q` := card K local notation `n` := finrank K A lemma card_ring : card A = q^n := card_eq_pow_finrank lemma commutative_mul_iff : commutative ((*) : A → A → A) ↔ n = 1 := begin rw [← subring.center_eq_top_iff, subring.eq_top_iff', finrank_eq_one_iff_of_nonzero' (1 : A) one_ne_zero], simp_rw [subring.smul_def, smul_eq_mul, mul_one], exact ⟨λ h x, ⟨⟨x, h x⟩, rfl⟩, λ h x, let ⟨c, hc⟩ := h x in hc ▸ c.2⟩ end local notation `d` := λ (x : A), finrank K (submodule.centralizer x) local notation `e` := λ (x : A), finrank (subring.centralizer x) A lemma card_centralizer (x : units A) [fintype (subring.centralizer (x : A))] : card (subring.centralizer (x : A)) = q^(d x) := card_eq_pow_finrank lemma card_ring' (x : units A) [fintype (subring.centralizer (x : A))] : card A = (q^(d x))^(e x) := begin rw ← card_centralizer, exact card_eq_pow_finrank' end lemma finrank_centralizer_dvd_finrank_ring (x : units A) [fintype (subring.centralizer (x : A))] : (d x) ∣ n := begin have := card_ring' x, rw [← pow_mul, card_ring, (nat.pow_right_injective one_lt_card).eq_iff] at this, exact ⟨_, this⟩, apply_instance end def conj_action : mul_action (units A) (units A) := mul_action.comp_hom (units A) mul_aut.conj lemma stabilizer_conj_eq_centralizer (x : units A) : @stabilizer (units A) (units A) _ conj_action x = subgroup.centralizer x := begin ext y, change y * x * y⁻¹ = x ↔ x * y = y * x, split; intro h; nth_rewrite 0 ← h; group end def units_subring_centralizer_equiv_subgroup_centralizer (x : units A) : units (subring.centralizer (x : A)) ≃ subgroup.centralizer x := calc units (subring.centralizer (x : A)) ≃ {y : units A // (y : A) ∈ subring.centralizer (x : A)} : units_submonoid_equiv (subring.centralizer (x : A)).to_submonoid begin intros y, change _ = _ → _ = _, norm_cast, exact semiconj_by.inv_right end ... ≃ subgroup.centralizer x : equiv.set.of_eq begin ext y, rw [set_like.mem_coe, set_like.mem_coe], change (↑x * ↑y = ↑y * ↑x) ↔ (x * y = y * x), norm_cast end lemma card_stabilizer_conj_eq {x : units A} [fintype (@stabilizer (units A) (units A) _ conj_action x)] [fintype (subgroup.centralizer x)] [fintype (subring.centralizer (x : A))] : card (@stabilizer (units A) (units A) _ conj_action x) = q^(d x) - 1 := by rw [card_congr (mul_equiv.subgroup_congr $ stabilizer_conj_eq_centralizer x).to_equiv, card_congr (units_subring_centralizer_equiv_subgroup_centralizer x).symm, card_units', card_centralizer] local notation `Ω` := (quotient $ @orbit_rel (units A) (units A) _ conj_action) lemma key₀ [Π (x : units A), decidable_pred (λ u, u ∈ subring.centralizer (x : A))] (ω : Ω) : (d ω.out' = n) ↔ (ω.out' : A) ∈ K := begin rw [← (nat.pow_right_injective (one_lt_card : 1 < q)).eq_iff], dsimp only, rw [← card_centralizer, ← card_ring], change card {x // x ∈ _} = _ ↔ _, rw card_subtype_eq_iff A, exact forall_congr (λ x, ⟨λ h, eq.symm h, λ h, eq.symm h⟩) end #check units_submonoid_equiv def foo [fintype Ω] : units K ≃ {ω : Ω // ¬ d ω.out' < n} := { to_fun := λ k, ⟨@orbit (units A) (units A) _ conj_action (k : units A), _⟩} lemma key₁ [fintype Ω] : ∑ ω in finset.filter (λ (ω : Ω), ¬ d ω.out' < n) finset.univ, (q^n - 1) / (q^(d ω.out') - 1) = q - 1 := begin sorry end lemma key₂ [fintype Ω] [Π (x : units A), fintype (@stabilizer _ _ _ conj_action x)] [Π (x : units A), fintype (subring.centralizer (x : A))] [Π (x : units A), fintype (subgroup.centralizer x)] : q^n - 1 = (q - 1) + ∑ ω in finset.filter (λ (ω : Ω), d ω.out' < n) finset.univ, (q^n - 1) / (q^(d ω.out') - 1) := calc q^n - 1 = card (units A) : by rw [← card_ring, ← card_units'] ... = ∑ (ω : Ω), card (units A) / card (@stabilizer _ _ _ conj_action ω.out') : @card_eq_sum_card_group_div_card_stabilizer _ _ _ conj_action _ _ _ _ ... = ∑ (ω : Ω), (q^n - 1) / (q^(d ω.out') - 1) : by conv in (_ / _) {rw [card_units', card_ring, card_stabilizer_conj_eq]} ... = (∑ ω in finset.filter (λ (ω : Ω), d ω.out' < n) finset.univ, (q^n - 1) / (q^(d ω.out') - 1)) + (∑ ω in finset.filter (λ (ω : Ω), ¬ d ω.out' < n) finset.univ, (q^n - 1) / (q^(d ω.out') - 1)) : by rw finset.sum_filter_add_sum_filter_not finset.univ (λ (ω : Ω), (d ω.out') < n) _ ... = (∑ ω in finset.filter (λ (ω : Ω), d ω.out' < n) finset.univ, (q^n - 1) / (q^(d ω.out') - 1)) + (q - 1) : by rw key₁ ... = (q - 1) + ∑ ω in finset.filter (λ (ω : Ω), d ω.out' < n) finset.univ, (q^n - 1) / (q^(d ω.out') - 1) : add_comm _ _ lemma key₃ [fintype Ω] [Π (x : units A), fintype (@stabilizer _ _ _ conj_action x)] [Π (x : units A), fintype (subring.centralizer (x : A))] [Π (x : units A), fintype (subgroup.centralizer x)] : (q - 1 : ℤ) = (q^n - 1 : ℤ) + ∑ ω in finset.filter (λ (ω : Ω), d ω.out' < n) finset.univ, (q^n - 1) / (q^(d ω.out') - 1) := begin end lemma key_dvd : (cyclotomic n ℤ).eval (q : ℤ) ∣ q - 1 := begin end -- --lemma key_divides {x : units A} -- [fintype (@stabilizer (units A) (units A) _ conj_action x)] -- [fintype (subgroup.centralizer x)] [fintype (subring.centralizer (x : A))] : -- q^(d x) - 1 ∣ q^n - 1 := --begin -- rw [← card_stabilizer_conj_eq, ← card_ring, ← card_units'], -- exact subgroup.card_subgroup_dvd_card _ --end
6c19460bbe5a6ae7584e73e21296b70339828d67
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/data/option/basic.lean
263d869cfd89c232540842dbe5e42719fb3d05d4
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
2,895
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.core init.control.monad init.control.alternative init.coe open Decidable universes u v namespace Option def toMonad {m : Type → Type} [Monad m] [Alternative m] {A} : Option A → m A | none := failure | (some a) := pure a @[macroInline] def getOrElse {α : Type u} : Option α → α → α | (some x) _ := x | none e := e @[inline] def get {α : Type u} [Inhabited α] : Option α → α | (some x) := x | none := default α @[inline] def toBool {α : Type u} : Option α → Bool | (some _) := true | none := false @[inline] def isSome {α : Type u} : Option α → Bool | (some _) := true | none := false @[inline] def isNone {α : Type u} : Option α → Bool | (some _) := false | none := true @[inline] protected def bind {α : Type u} {β : Type v} : Option α → (α → Option β) → Option β | none b := none | (some a) b := b a @[inline] protected def map {α β} (f : α → β) (o : Option α) : Option β := Option.bind o (some ∘ f) theorem mapId {α} : (Option.map id : Option α → Option α) = id := funext (fun o => match o with | none => rfl | some x => rfl) instance : Monad Option := {pure := @some, bind := @Option.bind, map := @Option.map} @[macroInline] protected def orelse {α : Type u} : Option α → Option α → Option α | (some a) _ := some a | none b := b /- Remark: when using the polymorphic notation `a <|> b` is not a `[macroInline]`. Thus, `a <|> b` will make `Option.orelse` to behave like it was marked as `[inline]`. -/ instance : Alternative Option := { failure := @none, orelse := @Option.orelse, ..Option.Monad } @[inline] protected def lt {α : Type u} (r : α → α → Prop) : Option α → Option α → Prop | none (some x) := True | (some x) (some y) := r x y | _ _ := False instance decidableRelLt {α : Type u} (r : α → α → Prop) [s : DecidableRel r] : DecidableRel (Option.lt r) | none (some y) := isTrue trivial | (some x) (some y) := s x y | (some x) none := isFalse notFalse | none none := isFalse notFalse end Option instance (α : Type u) : Inhabited (Option α) := ⟨none⟩ instance {α : Type u} [DecidableEq α] : DecidableEq (Option α) := {decEq := fun a b => match a, b with | none, none => isTrue rfl | none, (some v₂) => isFalse (fun h => Option.noConfusion h) | (some v₁), none => isFalse (fun h => Option.noConfusion h) | (some v₁), (some v₂) => match decEq v₁ v₂ with | (isTrue e) => isTrue (congrArg (@some α) e) | (isFalse n) => isFalse (fun h => Option.noConfusion h (fun e => absurd e n))} instance {α : Type u} [HasLess α] : HasLess (Option α) := ⟨Option.lt HasLess.Less⟩
95fd7f9400b5f7fa66d153de3a2fc455d9327bc3
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/AuxDef.lean
d662cdab6ad9f63d3d5a336db389d2ff65dc2eab
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,372
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Lean.Elab.Command namespace Lean.Elab.Command open Lean.Parser.Command open Lean.Parser.Term /-- Declares an auxiliary definition with an automatically generated name. For example, `aux_def foo : Nat := 42` creates a definition with an internal, unused name based on the suggestion `foo`. -/ scoped syntax (name := aux_def) docComment ? attributes ? "aux_def" ident+ ":" term ":=" term : command @[builtinCommandElab «aux_def»] def elabAuxDef : CommandElab | `($[$doc?:docComment]? $[$attrs?:attributes]? aux_def $suggestion* : $ty := $body) => do let id := suggestion.map (·.getId.eraseMacroScopes) |>.foldl (· ++ ·) Name.anonymous let id := `_aux ++ (← getMainModule) ++ `_ ++ id let id := String.intercalate "_" <| id.components.map (·.toString (escape := false)) let ns ← getCurrNamespace -- make sure we only add a single component so that scoped workes let id ← mkAuxName (ns.mkStr id) 1 let id := id.replacePrefix ns Name.anonymous -- TODO: replace with def _root_.id elabCommand <| ← `($[$doc?:docComment]? $[$attrs?:attributes]? def $(mkIdentFrom (mkNullNode suggestion) id):ident : $ty := $body) | _ => throwUnsupportedSyntax
fa978eebeda41532e304309d4984ad31685f9665
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Init/Data/UInt.lean
e1af60c2ac5d4149a72ef4d7be04013e0b3e3a0e
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,374
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Fin.Basic import Init.System.Platform open Nat def uint8Sz : Nat := 256 structure UInt8 := (val : Fin uint8Sz) @[extern "lean_uint8_of_nat"] def UInt8.ofNat (n : @& Nat) : UInt8 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt8 := UInt8.ofNat @[extern "lean_uint8_to_nat"] def UInt8.toNat (n : UInt8) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt8.add (a b : UInt8) : UInt8 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt8.sub (a b : UInt8) : UInt8 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt8.mul (a b : UInt8) : UInt8 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt8.div (a b : UInt8) : UInt8 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def UInt8.mod (a b : UInt8) : UInt8 := ⟨a.val % b.val⟩ @[extern "lean_uint8_modn"] def UInt8.modn (a : UInt8) (n : @& Nat) : UInt8 := ⟨a.val %ₙ n⟩ @[extern c inline "#1 & #2"] def UInt8.land (a b : UInt8) : UInt8 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt8.lor (a b : UInt8) : UInt8 := ⟨Fin.lor a.val b.val⟩ def UInt8.lt (a b : UInt8) : Prop := a.val < b.val def UInt8.le (a b : UInt8) : Prop := a.val ≤ b.val instance : HasZero UInt8 := ⟨UInt8.ofNat 0⟩ instance : HasOne UInt8 := ⟨UInt8.ofNat 1⟩ instance : HasOfNat UInt8 := ⟨UInt8.ofNat⟩ instance : HasAdd UInt8 := ⟨UInt8.add⟩ instance : HasSub UInt8 := ⟨UInt8.sub⟩ instance : HasMul UInt8 := ⟨UInt8.mul⟩ instance : HasMod UInt8 := ⟨UInt8.mod⟩ instance : HasModN UInt8 := ⟨UInt8.modn⟩ instance : HasDiv UInt8 := ⟨UInt8.div⟩ instance : HasLess UInt8 := ⟨UInt8.lt⟩ instance : HasLessEq UInt8 := ⟨UInt8.le⟩ instance : Inhabited UInt8 := ⟨0⟩ @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (a = b) := UInt8.casesOn a $ fun n => UInt8.casesOn b $ fun m => if h : n = m then isTrue (h ▸ rfl) else isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h)) @[extern c inline "#1 < #2"] def UInt8.decLt (a b : UInt8) : Decidable (a < b) := UInt8.casesOn a $ fun n => UInt8.casesOn b $ fun m => inferInstanceAs (Decidable (n < m)) @[extern c inline "#1 <= #2"] def UInt8.decLe (a b : UInt8) : Decidable (a ≤ b) := UInt8.casesOn a $ fun n => UInt8.casesOn b $ fun m => inferInstanceAs (Decidable (n <= m)) instance : DecidableEq UInt8 := UInt8.decEq instance UInt8.hasDecidableLt (a b : UInt8) : Decidable (a < b) := UInt8.decLt a b instance UInt8.hasDecidableLe (a b : UInt8) : Decidable (a ≤ b) := UInt8.decLe a b def uint16Sz : Nat := 65536 structure UInt16 := (val : Fin uint16Sz) @[extern "lean_uint16_of_nat"] def UInt16.ofNat (n : @& Nat) : UInt16 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt16 := UInt16.ofNat @[extern "lean_uint16_to_nat"] def UInt16.toNat (n : UInt16) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt16.add (a b : UInt16) : UInt16 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt16.sub (a b : UInt16) : UInt16 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt16.mul (a b : UInt16) : UInt16 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt16.div (a b : UInt16) : UInt16 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def UInt16.mod (a b : UInt16) : UInt16 := ⟨a.val % b.val⟩ @[extern "lean_uint16_modn"] def UInt16.modn (a : UInt16) (n : @& Nat) : UInt16 := ⟨a.val %ₙ n⟩ @[extern c inline "#1 & #2"] def UInt16.land (a b : UInt16) : UInt16 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt16.lor (a b : UInt16) : UInt16 := ⟨Fin.lor a.val b.val⟩ def UInt16.lt (a b : UInt16) : Prop := a.val < b.val def UInt16.le (a b : UInt16) : Prop := a.val ≤ b.val instance : HasZero UInt16 := ⟨UInt16.ofNat 0⟩ instance : HasOne UInt16 := ⟨UInt16.ofNat 1⟩ instance : HasOfNat UInt16 := ⟨UInt16.ofNat⟩ instance : HasAdd UInt16 := ⟨UInt16.add⟩ instance : HasSub UInt16 := ⟨UInt16.sub⟩ instance : HasMul UInt16 := ⟨UInt16.mul⟩ instance : HasMod UInt16 := ⟨UInt16.mod⟩ instance : HasModN UInt16 := ⟨UInt16.modn⟩ instance : HasDiv UInt16 := ⟨UInt16.div⟩ instance : HasLess UInt16 := ⟨UInt16.lt⟩ instance : HasLessEq UInt16 := ⟨UInt16.le⟩ instance : Inhabited UInt16 := ⟨0⟩ @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (a = b) := UInt16.casesOn a $ fun n => UInt16.casesOn b $ fun m => if h : n = m then isTrue (h ▸ rfl) else isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h)) @[extern c inline "#1 < #2"] def UInt16.decLt (a b : UInt16) : Decidable (a < b) := UInt16.casesOn a $ fun n => UInt16.casesOn b $ fun m => inferInstanceAs (Decidable (n < m)) @[extern c inline "#1 <= #2"] def UInt16.decLe (a b : UInt16) : Decidable (a ≤ b) := UInt16.casesOn a $ fun n => UInt16.casesOn b $ fun m => inferInstanceAs (Decidable (n <= m)) instance : DecidableEq UInt16 := UInt16.decEq instance UInt16.hasDecidableLt (a b : UInt16) : Decidable (a < b) := UInt16.decLt a b instance UInt16.hasDecidableLe (a b : UInt16) : Decidable (a ≤ b) := UInt16.decLe a b def uint32Sz : Nat := 4294967296 structure UInt32 := (val : Fin uint32Sz) @[extern "lean_uint32_of_nat"] def UInt32.ofNat (n : @& Nat) : UInt32 := ⟨Fin.ofNat n⟩ @[extern "lean_uint32_of_nat"] def UInt32.ofNat' (n : Nat) (h : n < uint32Sz) : UInt32 := ⟨⟨n, h⟩⟩ abbrev Nat.toUInt32 := UInt32.ofNat @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt32.add (a b : UInt32) : UInt32 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt32.sub (a b : UInt32) : UInt32 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt32.mul (a b : UInt32) : UInt32 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt32.div (a b : UInt32) : UInt32 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def UInt32.mod (a b : UInt32) : UInt32 := ⟨a.val % b.val⟩ @[extern "lean_uint32_modn"] def UInt32.modn (a : UInt32) (n : @& Nat) : UInt32 := ⟨a.val %ₙ n⟩ @[extern c inline "#1 & #2"] def UInt32.land (a b : UInt32) : UInt32 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt32.lor (a b : UInt32) : UInt32 := ⟨Fin.lor a.val b.val⟩ def UInt32.lt (a b : UInt32) : Prop := a.val < b.val def UInt32.le (a b : UInt32) : Prop := a.val ≤ b.val @[extern c inline "((uint8_t)#1)"] def UInt32.toUInt8 (a : UInt32) : UInt8 := a.toNat.toUInt8 @[extern c inline "((uint16_t)#1)"] def UInt32.toUInt16 (a : UInt32) : UInt16 := a.toNat.toUInt16 @[extern c inline "((uint32_t)#1)"] def UInt8.toUInt32 (a : UInt8) : UInt32 := a.toNat.toUInt32 instance : HasZero UInt32 := ⟨UInt32.ofNat 0⟩ instance : HasOne UInt32 := ⟨UInt32.ofNat 1⟩ instance : HasOfNat UInt32 := ⟨UInt32.ofNat⟩ instance : HasAdd UInt32 := ⟨UInt32.add⟩ instance : HasSub UInt32 := ⟨UInt32.sub⟩ instance : HasMul UInt32 := ⟨UInt32.mul⟩ instance : HasMod UInt32 := ⟨UInt32.mod⟩ instance : HasModN UInt32 := ⟨UInt32.modn⟩ instance : HasDiv UInt32 := ⟨UInt32.div⟩ instance : HasLess UInt32 := ⟨UInt32.lt⟩ instance : HasLessEq UInt32 := ⟨UInt32.le⟩ instance : Inhabited UInt32 := ⟨0⟩ @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (a = b) := UInt32.casesOn a $ fun n => UInt32.casesOn b $ fun m => if h : n = m then isTrue (h ▸ rfl) else isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h)) @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (a < b) := UInt32.casesOn a $ fun n => UInt32.casesOn b $ fun m => inferInstanceAs (Decidable (n < m)) @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (a ≤ b) := UInt32.casesOn a $ fun n => UInt32.casesOn b $ fun m => inferInstanceAs (Decidable (n <= m)) @[extern c inline "#1 << #2"] constant UInt32.shiftLeft (a b : UInt32) : UInt32 := (arbitrary Nat).toUInt32 @[extern c inline "#1 >> #2"] constant UInt32.shiftRight (a b : UInt32) : UInt32 := (arbitrary Nat).toUInt32 instance : DecidableEq UInt32 := UInt32.decEq instance UInt32.hasDecidableLt (a b : UInt32) : Decidable (a < b) := UInt32.decLt a b instance UInt32.hasDecidableLe (a b : UInt32) : Decidable (a ≤ b) := UInt32.decLe a b def uint64Sz : Nat := 18446744073709551616 structure UInt64 := (val : Fin uint64Sz) @[extern "lean_uint64_of_nat"] def UInt64.ofNat (n : @& Nat) : UInt64 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt64 := UInt64.ofNat @[extern "lean_uint64_to_nat"] def UInt64.toNat (n : UInt64) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt64.add (a b : UInt64) : UInt64 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt64.sub (a b : UInt64) : UInt64 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt64.mul (a b : UInt64) : UInt64 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt64.div (a b : UInt64) : UInt64 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def UInt64.mod (a b : UInt64) : UInt64 := ⟨a.val % b.val⟩ @[extern "lean_uint64_modn"] def UInt64.modn (a : UInt64) (n : @& Nat) : UInt64 := ⟨a.val %ₙ n⟩ @[extern c inline "#1 & #2"] def UInt64.land (a b : UInt64) : UInt64 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt64.lor (a b : UInt64) : UInt64 := ⟨Fin.lor a.val b.val⟩ def UInt64.lt (a b : UInt64) : Prop := a.val < b.val def UInt64.le (a b : UInt64) : Prop := a.val ≤ b.val @[extern c inline "((uint8_t)#1)"] def UInt64.toUInt8 (a : UInt64) : UInt8 := a.toNat.toUInt8 @[extern c inline "((uint16_t)#1)"] def UInt64.toUInt16 (a : UInt64) : UInt16 := a.toNat.toUInt16 @[extern c inline "((uint32_t)#1)"] def UInt64.toUInt32 (a : UInt64) : UInt32 := a.toNat.toUInt32 @[extern c inline "((uint64_t)#1)"] def UInt32.toUInt64 (a : UInt32) : UInt64 := a.toNat.toUInt64 -- TODO(Leo): give reference implementation for shiftLeft and shiftRight, and define them for other UInt types @[extern c inline "#1 << #2"] constant UInt64.shiftLeft (a b : UInt64) : UInt64 := (arbitrary Nat).toUInt64 @[extern c inline "#1 >> #2"] constant UInt64.shiftRight (a b : UInt64) : UInt64 := (arbitrary Nat).toUInt64 instance : HasZero UInt64 := ⟨UInt64.ofNat 0⟩ instance : HasOne UInt64 := ⟨UInt64.ofNat 1⟩ instance : HasOfNat UInt64 := ⟨UInt64.ofNat⟩ instance : HasAdd UInt64 := ⟨UInt64.add⟩ instance : HasSub UInt64 := ⟨UInt64.sub⟩ instance : HasMul UInt64 := ⟨UInt64.mul⟩ instance : HasMod UInt64 := ⟨UInt64.mod⟩ instance : HasModN UInt64 := ⟨UInt64.modn⟩ instance : HasDiv UInt64 := ⟨UInt64.div⟩ instance : HasLess UInt64 := ⟨UInt64.lt⟩ instance : HasLessEq UInt64 := ⟨UInt64.le⟩ instance : Inhabited UInt64 := ⟨0⟩ @[extern c inline "(uint64_t)#1"] def Bool.toUInt64 (b : Bool) : UInt64 := if b then 1 else 0 @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (a = b) := UInt64.casesOn a $ fun n => UInt64.casesOn b $ fun m => if h : n = m then isTrue (h ▸ rfl) else isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h)) @[extern c inline "#1 < #2"] def UInt64.decLt (a b : UInt64) : Decidable (a < b) := UInt64.casesOn a $ fun n => UInt64.casesOn b $ fun m => inferInstanceAs (Decidable (n < m)) @[extern c inline "#1 <= #2"] def UInt64.decLe (a b : UInt64) : Decidable (a ≤ b) := UInt64.casesOn a $ fun n => UInt64.casesOn b $ fun m => inferInstanceAs (Decidable (n <= m)) instance : DecidableEq UInt64 := UInt64.decEq instance UInt64.hasDecidableLt (a b : UInt64) : Decidable (a < b) := UInt64.decLt a b instance UInt64.hasDecidableLe (a b : UInt64) : Decidable (a ≤ b) := UInt64.decLe a b def usizeSz : Nat := (2:Nat) ^ System.Platform.numBits structure USize := (val : Fin usizeSz) theorem usizeSzGt0 : usizeSz > 0 := Nat.posPowOfPos System.Platform.numBits (Nat.zeroLtSucc _) @[extern "lean_usize_of_nat"] def USize.ofNat (n : @& Nat) : USize := ⟨Fin.ofNat' n usizeSzGt0⟩ abbrev Nat.toUSize := USize.ofNat @[extern "lean_usize_to_nat"] def USize.toNat (n : USize) : Nat := n.val.val @[extern c inline "#1 + #2"] def USize.add (a b : USize) : USize := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def USize.sub (a b : USize) : USize := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def USize.mul (a b : USize) : USize := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def USize.div (a b : USize) : USize := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def USize.mod (a b : USize) : USize := ⟨a.val % b.val⟩ @[extern "lean_usize_modn"] def USize.modn (a : USize) (n : @& Nat) : USize := ⟨a.val %ₙ n⟩ @[extern c inline "#1 & #2"] def USize.land (a b : USize) : USize := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def USize.lor (a b : USize) : USize := ⟨Fin.lor a.val b.val⟩ @[extern c inline "#1"] def UInt32.toUSize (a : UInt32) : USize := a.toNat.toUSize @[extern c inline "((size_t)#1)"] def UInt64.toUSize (a : UInt64) : USize := a.toNat.toUSize @[extern c inline "(uint32_t)#1"] def USize.toUInt32 (a : USize) : UInt32 := a.toNat.toUInt32 -- TODO(Leo): give reference implementation for shiftLeft and shiftRight, and define them for other UInt types @[extern c inline "#1 << #2"] constant USize.shiftLeft (a b : USize) : USize := (arbitrary Nat).toUSize @[extern c inline "#1 >> #2"] constant USize.shiftRight (a b : USize) : USize := (arbitrary Nat).toUSize def USize.lt (a b : USize) : Prop := a.val < b.val def USize.le (a b : USize) : Prop := a.val ≤ b.val instance : HasZero USize := ⟨USize.ofNat 0⟩ instance : HasOne USize := ⟨USize.ofNat 1⟩ instance : HasOfNat USize := ⟨USize.ofNat⟩ instance : HasAdd USize := ⟨USize.add⟩ instance : HasSub USize := ⟨USize.sub⟩ instance : HasMul USize := ⟨USize.mul⟩ instance : HasMod USize := ⟨USize.mod⟩ instance : HasModN USize := ⟨USize.modn⟩ instance : HasDiv USize := ⟨USize.div⟩ instance : HasLess USize := ⟨USize.lt⟩ instance : HasLessEq USize := ⟨USize.le⟩ instance : Inhabited USize := ⟨0⟩ @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (a = b) := USize.casesOn a $ fun n => USize.casesOn b $ fun m => if h : n = m then isTrue (h ▸ rfl) else isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h)) @[extern c inline "#1 < #2"] def USize.decLt (a b : USize) : Decidable (a < b) := USize.casesOn a $ fun n => USize.casesOn b $ fun m => inferInstanceAs (Decidable (n < m)) @[extern c inline "#1 <= #2"] def USize.decLe (a b : USize) : Decidable (a ≤ b) := USize.casesOn a $ fun n => USize.casesOn b $ fun m => inferInstanceAs (Decidable (n <= m)) instance : DecidableEq USize := USize.decEq instance USize.hasDecidableLt (a b : USize) : Decidable (a < b) := USize.decLt a b instance USize.hasDecidableLe (a b : USize) : Decidable (a ≤ b) := USize.decLe a b theorem USize.modnLt {m : Nat} : ∀ (u : USize), m > 0 → USize.toNat (u %ₙ m) < m | ⟨u⟩, h => Fin.modnLt u h
d63ce4013b87e9d2e63a61ca27217774a87d5c1f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/sheaves/sheaf_condition/equalizer_products.lean
e75084455b9397c3e68f4ff7dff35495c9a6dc6d
[ "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
15,797
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.products import topology.sheaves.sheaf_condition.pairwise_intersections /-! # The sheaf condition in terms of an equalizer of products > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Here we set up the machinery for the "usual" definition of the sheaf condition, e.g. as in https://stacks.math.columbia.edu/tag/0072 in terms of an equalizer diagram where the two objects are `∏ F.obj (U i)` and `∏ F.obj (U i) ⊓ (U j)`. We show that this sheaf condition is equivalent to the `pairwise_intersections` sheaf condition when the presheaf is valued in a category with products, and thereby equivalent to the default sheaf condition. -/ universes v' v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] [has_products.{v'} C] variables {X : Top.{v'}} (F : presheaf C X) {ι : Type v'} (U : ι → opens X) namespace presheaf namespace sheaf_condition_equalizer_products /-- The product of the sections of a presheaf over a family of open sets. -/ def pi_opens : C := ∏ (λ i : ι, F.obj (op (U i))) /-- The product of the sections of a presheaf over the pairwise intersections of a family of open sets. -/ def pi_inters : C := ∏ (λ p : ι × ι, F.obj (op (U p.1 ⊓ U p.2))) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U i` to `U i ⊓ U j`. -/ def left_res : pi_opens F U ⟶ pi_inters.{v'} F U := pi.lift (λ p : ι × ι, pi.π _ p.1 ≫ F.map (inf_le_left (U p.1) (U p.2)).op) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def right_res : pi_opens F U ⟶ pi_inters.{v'} F U := pi.lift (λ p : ι × ι, pi.π _ p.2 ≫ F.map (inf_le_right (U p.1) (U p.2)).op) /-- The morphism `F.obj U ⟶ Π F.obj (U i)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def res : F.obj (op (supr U)) ⟶ pi_opens.{v'} F U := pi.lift (λ i : ι, F.map (topological_space.opens.le_supr U i).op) @[simp, elementwise] lemma res_π (i : ι) : res F U ≫ limit.π _ ⟨i⟩ = F.map (opens.le_supr U i).op := by rw [res, limit.lift_π, fan.mk_π_app] @[elementwise] lemma w : res F U ≫ left_res F U = res F U ≫ right_res F U := begin dsimp [res, left_res, right_res], ext, simp only [limit.lift_π, limit.lift_π_assoc, fan.mk_π_app, category.assoc], rw [←F.map_comp], rw [←F.map_comp], congr, end /-- The equalizer diagram for the sheaf condition. -/ @[reducible] def diagram : walking_parallel_pair ⥤ C := parallel_pair (left_res.{v'} F U) (right_res F U) /-- The restriction map `F.obj U ⟶ Π F.obj (U i)` gives a cone over the equalizer diagram for the sheaf condition. The sheaf condition asserts this cone is a limit cone. -/ def fork : fork.{v} (left_res F U) (right_res F U) := fork.of_ι _ (w F U) @[simp] lemma fork_X : (fork F U).X = F.obj (op (supr U)) := rfl @[simp] lemma fork_ι : (fork F U).ι = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_zero : (fork F U).π.app walking_parallel_pair.zero = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_one : (fork F U).π.app walking_parallel_pair.one = res F U ≫ left_res F U := rfl variables {F} {G : presheaf C X} /-- Isomorphic presheaves have isomorphic `pi_opens` for any cover `U`. -/ @[simp] def pi_opens.iso_of_iso (α : F ≅ G) : pi_opens F U ≅ pi_opens.{v'} G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic `pi_inters` for any cover `U`. -/ @[simp] def pi_inters.iso_of_iso (α : F ≅ G) : pi_inters F U ≅ pi_inters.{v'} G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic sheaf condition diagrams. -/ def diagram.iso_of_iso (α : F ≅ G) : diagram F U ≅ diagram.{v'} G U := nat_iso.of_components begin rintro ⟨⟩, exact pi_opens.iso_of_iso U α, exact pi_inters.iso_of_iso U α end begin rintro ⟨⟩ ⟨⟩ ⟨⟩, { simp, }, { ext, simp [left_res], }, { ext, simp [right_res], }, { simp, }, end. /-- If `F G : presheaf C X` are isomorphic presheaves, then the `fork F U`, the canonical cone of the sheaf condition diagram for `F`, is isomorphic to `fork F G` postcomposed with the corresponding isomorphism between sheaf condition diagrams. -/ def fork.iso_of_iso (α : F ≅ G) : fork F U ≅ (cones.postcompose (diagram.iso_of_iso U α).inv).obj (fork G U) := begin fapply fork.ext, { apply α.app, }, { ext, dunfold fork.ι, -- Ugh, `simp` can't unfold abbreviations. simp [res, diagram.iso_of_iso], } end end sheaf_condition_equalizer_products /-- The sheaf condition for a `F : presheaf C X` requires that the morphism `F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ F.obj (U i) ⟶ ∏ F.obj (U i) ⊓ (U j)`. -/ def is_sheaf_equalizer_products (F : presheaf.{v' v u} C X) : Prop := ∀ ⦃ι : Type v'⦄ (U : ι → opens X), nonempty (is_limit (sheaf_condition_equalizer_products.fork F U)) /-! The remainder of this file shows that the equalizer_products sheaf condition is equivalent to the pariwise_intersections sheaf condition. -/ namespace sheaf_condition_pairwise_intersections open category_theory.pairwise category_theory.pairwise.hom /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor_obj (c : cone ((diagram U).op ⋙ F)) : cone (sheaf_condition_equalizer_products.diagram F U) := { X := c.X, π := { app := λ Z, walking_parallel_pair.cases_on Z (pi.lift (λ (i : ι), c.π.app (op (single i)))) (pi.lift (λ (b : ι × ι), c.π.app (op (pair b.1 b.2)))), naturality' := λ Y Z f, begin cases Y; cases Z; cases f, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.left_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (quiver.hom.op (hom.left i j)), dsimp at h, simpa using h, }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.right_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (quiver.hom.op (hom.right i j)), dsimp at h, simpa using h, }, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, end, }, } section local attribute [tidy] tactic.case_bash /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor : limits.cone ((diagram U).op ⋙ F) ⥤ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { obj := λ c, cone_equiv_functor_obj F U c, map := λ c c' f, { hom := f.hom, w' := λ j, begin cases j; { ext, simp only [limits.fan.mk_π_app, limits.cone_morphism.w, limits.limit.lift_π, category.assoc, cone_equiv_functor_obj_π_app], }, end }, }. end /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse_obj (c : limits.cone (sheaf_condition_equalizer_products.diagram F U)) : limits.cone ((diagram U).op ⋙ F) := { X := c.X, π := { app := begin intro x, induction x using opposite.rec, rcases x with (⟨i⟩|⟨i,j⟩), { exact c.π.app (walking_parallel_pair.zero) ≫ pi.π _ i, }, { exact c.π.app (walking_parallel_pair.one) ≫ pi.π _ (i, j), } end, naturality' := begin intros x y f, induction x using opposite.rec, induction y using opposite.rec, have ef : f = f.unop.op := rfl, revert ef, generalize : f.unop = f', rintro rfl, rcases x with ⟨i⟩|⟨⟩; rcases y with ⟨⟩|⟨j,j⟩; rcases f' with ⟨⟩, { dsimp, erw [F.map_id], simp, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.left), dsimp [sheaf_condition_equalizer_products.left_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (i, j), rw h', simp only [category.assoc, limit.lift_π, fan.mk_π_app], refl, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.right), dsimp [sheaf_condition_equalizer_products.right_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (j, i), rw h', simp, refl, }, { dsimp, erw [F.map_id], simp, }, end, }, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse : limits.cone (sheaf_condition_equalizer_products.diagram F U) ⥤ limits.cone ((diagram U).op ⋙ F) := { obj := λ c, cone_equiv_inverse_obj F U c, map := λ c c' f, { hom := f.hom, w' := begin intro x, induction x using opposite.rec, rcases x with (⟨i⟩|⟨i,j⟩), { dsimp, dunfold fork.ι, rw [←(f.w walking_parallel_pair.zero), category.assoc], }, { dsimp, rw [←(f.w walking_parallel_pair.one), category.assoc], }, end }, }. /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso_app (c : cone ((diagram U).op ⋙ F)) : (𝟭 (cone ((diagram U).op ⋙ F))).obj c ≅ (cone_equiv_functor F U ⋙ cone_equiv_inverse F U).obj c := { hom := { hom := 𝟙 _, w' := λ j, begin induction j using opposite.rec, rcases j; { dsimp, simp only [limits.fan.mk_π_app, category.id_comp, limits.limit.lift_π], } end, }, inv := { hom := 𝟙 _, w' := λ j, begin induction j using opposite.rec, rcases j; { dsimp, simp only [limits.fan.mk_π_app, category.id_comp, limits.limit.lift_π], } end }, hom_inv_id' := begin ext, simp only [category.comp_id, limits.cone.category_comp_hom, limits.cone.category_id_hom], end, inv_hom_id' := begin ext, simp only [category.comp_id, limits.cone.category_comp_hom, limits.cone.category_id_hom], end, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso : 𝟭 (limits.cone ((diagram U).op ⋙ F)) ≅ cone_equiv_functor F U ⋙ cone_equiv_inverse F U := nat_iso.of_components (cone_equiv_unit_iso_app F U) (by tidy) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_counit_iso : cone_equiv_inverse F U ⋙ cone_equiv_functor F U ≅ 𝟭 (limits.cone (sheaf_condition_equalizer_products.diagram F U)) := nat_iso.of_components (λ c, { hom := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext ⟨j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, { ext ⟨i,j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext ⟨j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, { ext ⟨i,j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, end, }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, }) (λ c d f, by { ext, dsimp, simp only [category.comp_id, category.id_comp], }) /-- Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram. -/ @[simps] def cone_equiv : limits.cone ((diagram U).op ⋙ F) ≌ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { functor := cone_equiv_functor F U, inverse := cone_equiv_inverse F U, unit_iso := cone_equiv_unit_iso F U, counit_iso := cone_equiv_counit_iso F U, } local attribute [reducible] sheaf_condition_equalizer_products.res sheaf_condition_equalizer_products.left_res /-- If `sheaf_condition_equalizer_products.fork` is an equalizer, then `F.map_cone (cone U)` is a limit cone. -/ def is_limit_map_cone_of_is_limit_sheaf_condition_fork (P : is_limit (sheaf_condition_equalizer_products.fork F U)) : is_limit (F.map_cone (cocone U).op) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U).symm).symm P) { hom := { hom := 𝟙 _, w' := begin intro x, induction x using opposite.rec, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin intro x, induction x using opposite.rec, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, } /-- If `F.map_cone (cone U)` is a limit cone, then `sheaf_condition_equalizer_products.fork` is an equalizer. -/ def is_limit_sheaf_condition_fork_of_is_limit_map_cone (Q : is_limit (F.map_cone (cocone U).op)) : is_limit (sheaf_condition_equalizer_products.fork F U) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U)).symm Q) { hom := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, } end sheaf_condition_pairwise_intersections open sheaf_condition_pairwise_intersections /-- The sheaf condition in terms of an equalizer diagram is equivalent to the default sheaf condition. -/ lemma is_sheaf_iff_is_sheaf_equalizer_products (F : presheaf C X) : F.is_sheaf ↔ F.is_sheaf_equalizer_products := (is_sheaf_iff_is_sheaf_pairwise_intersections F).trans $ iff.intro (λ h ι U, ⟨is_limit_sheaf_condition_fork_of_is_limit_map_cone F U (h U).some⟩) (λ h ι U, ⟨is_limit_map_cone_of_is_limit_sheaf_condition_fork F U (h U).some⟩) end presheaf end Top
e7e4a7a7ae07063e0975c08e4aa8abc95059aaa3
4727251e0cd73359b15b664c3170e5d754078599
/src/data/list/dedup.lean
f8c65923d023bf80cbcc3f8e62b5bc41933351f3
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,450
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.nodup /-! # Erasure of duplicates in a list This file proves basic results about `list.dedup` (definition in `data.list.defs`). `dedup l` returns `l` without its duplicates. It keeps the earliest (that is, rightmost) occurrence of each. ## Tags duplicate, multiplicity, nodup, `nub` -/ universes u namespace list variables {α : Type u} [decidable_eq α] @[simp] theorem dedup_nil : dedup [] = ([] : list α) := rfl theorem dedup_cons_of_mem' {a : α} {l : list α} (h : a ∈ dedup l) : dedup (a :: l) = dedup l := pw_filter_cons_of_neg $ by simpa only [forall_mem_ne] using h theorem dedup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ dedup l) : dedup (a :: l) = a :: dedup l := pw_filter_cons_of_pos $ by simpa only [forall_mem_ne] using h @[simp] theorem mem_dedup {a : α} {l : list α} : a ∈ dedup l ↔ a ∈ l := by simpa only [dedup, forall_mem_ne, not_not] using not_congr (@forall_mem_pw_filter α (≠) _ (λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l) @[simp] theorem dedup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) : dedup (a :: l) = dedup l := dedup_cons_of_mem' $ mem_dedup.2 h @[simp] theorem dedup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) : dedup (a :: l) = a :: dedup l := dedup_cons_of_not_mem' $ mt mem_dedup.1 h theorem dedup_sublist : ∀ (l : list α), dedup l <+ l := pw_filter_sublist theorem dedup_subset : ∀ (l : list α), dedup l ⊆ l := pw_filter_subset theorem subset_dedup (l : list α) : l ⊆ dedup l := λ a, mem_dedup.2 theorem nodup_dedup : ∀ l : list α, nodup (dedup l) := pairwise_pw_filter theorem dedup_eq_self {l : list α} : dedup l = l ↔ nodup l := pw_filter_eq_self protected lemma nodup.dedup {l : list α} (h : l.nodup) : l.dedup = l := list.dedup_eq_self.2 h @[simp] theorem dedup_idempotent {l : list α} : dedup (dedup l) = dedup l := pw_filter_idempotent theorem dedup_append (l₁ l₂ : list α) : dedup (l₁ ++ l₂) = l₁ ∪ dedup l₂ := begin induction l₁ with a l₁ IH, {refl}, rw [cons_union, ← IH], show dedup (a :: (l₁ ++ l₂)) = insert a (dedup (l₁ ++ l₂)), by_cases a ∈ dedup (l₁ ++ l₂); [ rw [dedup_cons_of_mem' h, insert_of_mem h], rw [dedup_cons_of_not_mem' h, insert_of_not_mem h]] end end list
8c9244c30f0844280922676a8e72edd7eedb24f8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/degree/definitions_auto.lean
21442c4ed94be7b1e2eae8c3234f44c0304a0821
[]
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
32,316
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.coeff import Mathlib.data.nat.with_bot import Mathlib.PostPort universes u v u_1 namespace Mathlib /-! # Theory of univariate polynomials The definitions include `degree`, `monic`, `leading_coeff` Results include - `degree_mul` : The degree of the product is the sum of degrees - `leading_coeff_add_of_degree_eq` and `leading_coeff_add_of_degree_lt` : The leading_coefficient of a sum is determined by the leading coefficients and degrees -/ namespace polynomial /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree {R : Type u} [semiring R] (p : polynomial R) : with_bot ℕ := finset.sup (finsupp.support p) some theorem degree_lt_wf {R : Type u} [semiring R] : well_founded fun (p q : polynomial R) => degree p < degree q := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) protected instance has_well_founded {R : Type u} [semiring R] : has_well_founded (polynomial R) := has_well_founded.mk (fun (p q : polynomial R) => degree p < degree q) degree_lt_wf /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree {R : Type u} [semiring R] (p : polynomial R) : ℕ := option.get_or_else (degree p) 0 /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff {R : Type u} [semiring R] (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic {R : Type u} [semiring R] (p : polynomial R) := leading_coeff p = 1 theorem monic_of_subsingleton {R : Type u} [semiring R] [subsingleton R] (p : polynomial R) : monic p := subsingleton.elim (leading_coeff p) 1 theorem monic.def {R : Type u} [semiring R] {p : polynomial R} : monic p ↔ leading_coeff p = 1 := iff.rfl protected instance monic.decidable {R : Type u} [semiring R] {p : polynomial R} [DecidableEq R] : Decidable (monic p) := eq.mpr sorry (_inst_2 (leading_coeff p) 1) @[simp] theorem monic.leading_coeff {R : Type u} [semiring R] {p : polynomial R} (hp : monic p) : leading_coeff p = 1 := hp theorem monic.coeff_nat_degree {R : Type u} [semiring R] {p : polynomial R} (hp : monic p) : coeff p (nat_degree p) = 1 := hp @[simp] theorem degree_zero {R : Type u} [semiring R] : degree 0 = ⊥ := rfl @[simp] theorem nat_degree_zero {R : Type u} [semiring R] : nat_degree 0 = 0 := rfl @[simp] theorem coeff_nat_degree {R : Type u} [semiring R] {p : polynomial R} : coeff p (nat_degree p) = leading_coeff p := rfl theorem degree_eq_bot {R : Type u} [semiring R] {p : polynomial R} : degree p = ⊥ ↔ p = 0 := sorry theorem degree_of_subsingleton {R : Type u} [semiring R] {p : polynomial R} [subsingleton R] : degree p = ⊥ := eq.mpr (id (Eq._oldrec (Eq.refl (degree p = ⊥)) (subsingleton.elim p 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (degree 0 = ⊥)) degree_zero)) (Eq.refl ⊥)) theorem nat_degree_of_subsingleton {R : Type u} [semiring R] {p : polynomial R} [subsingleton R] : nat_degree p = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (nat_degree p = 0)) (subsingleton.elim p 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_degree 0 = 0)) nat_degree_zero)) (Eq.refl 0)) theorem degree_eq_nat_degree {R : Type u} [semiring R] {p : polynomial R} (hp : p ≠ 0) : degree p = ↑(nat_degree p) := sorry theorem degree_eq_iff_nat_degree_eq {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : degree p = ↑n ↔ nat_degree p = n := eq.mpr (id (Eq._oldrec (Eq.refl (degree p = ↑n ↔ nat_degree p = n)) (degree_eq_nat_degree hp))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_degree p) = ↑n ↔ nat_degree p = n)) (propext with_bot.coe_eq_coe))) (iff.refl (nat_degree p = n))) theorem degree_eq_iff_nat_degree_eq_of_pos {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} (hn : 0 < n) : degree p = ↑n ↔ nat_degree p = n := sorry theorem nat_degree_eq_of_degree_eq_some {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} (h : degree p = ↑n) : nat_degree p = n := sorry @[simp] theorem degree_le_nat_degree {R : Type u} [semiring R] {p : polynomial R} : degree p ≤ ↑(nat_degree p) := galois_connection.le_u_l (galois_insertion.gc with_bot.gi_get_or_else_bot) (degree p) theorem nat_degree_eq_of_degree_eq {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S] {q : polynomial S} (h : degree p = degree q) : nat_degree p = nat_degree q := sorry theorem le_degree_of_ne_zero {R : Type u} {n : ℕ} [semiring R] {p : polynomial R} (h : coeff p n ≠ 0) : ↑n ≤ degree p := (fun (this : some n ≤ finset.sup (finsupp.support p) some) => this) (finset.le_sup (iff.mpr finsupp.mem_support_iff h)) theorem le_nat_degree_of_ne_zero {R : Type u} {n : ℕ} [semiring R] {p : polynomial R} (h : coeff p n ≠ 0) : n ≤ nat_degree p := sorry theorem le_nat_degree_of_mem_supp {R : Type u} [semiring R] {p : polynomial R} (a : ℕ) : a ∈ finsupp.support p → a ≤ nat_degree p := le_nat_degree_of_ne_zero ∘ iff.mp mem_support_iff_coeff_ne_zero theorem supp_subset_range {R : Type u} {m : ℕ} [semiring R] {p : polynomial R} (h : nat_degree p < m) : finsupp.support p ⊆ finset.range m := fun (n : ℕ) (hn : n ∈ finsupp.support p) => iff.mpr finset.mem_range (has_le.le.trans_lt (le_nat_degree_of_mem_supp n hn) h) theorem supp_subset_range_nat_degree_succ {R : Type u} [semiring R] {p : polynomial R} : finsupp.support p ⊆ finset.range (nat_degree p + 1) := supp_subset_range (nat.lt_succ_self (nat_degree p)) theorem degree_le_degree {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := dite (p = 0) (fun (hp : p = 0) => eq.mpr (id (Eq._oldrec (Eq.refl (degree p ≤ degree q)) hp)) bot_le) fun (hp : ¬p = 0) => eq.mpr (id (Eq._oldrec (Eq.refl (degree p ≤ degree q)) (degree_eq_nat_degree hp))) (le_degree_of_ne_zero h) theorem degree_ne_of_nat_degree_ne {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} : nat_degree p ≠ n → degree p ≠ ↑n := sorry theorem nat_degree_le_iff_degree_le {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} : nat_degree p ≤ n ↔ degree p ≤ ↑n := with_bot.get_or_else_bot_le_iff theorem degree_le_of_nat_degree_le {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} : nat_degree p ≤ n → degree p ≤ ↑n := iff.mp nat_degree_le_iff_degree_le theorem nat_degree_le_nat_degree {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hpq : degree p ≤ degree q) : nat_degree p ≤ nat_degree q := galois_connection.monotone_l (galois_insertion.gc with_bot.gi_get_or_else_bot) hpq @[simp] theorem degree_C {R : Type u} {a : R} [semiring R] (ha : a ≠ 0) : degree (coe_fn C a) = 0 := (fun (this : finset.sup (ite (a = 0) ∅ (singleton 0)) some = 0) => this) (eq.mpr (id (Eq._oldrec (Eq.refl (finset.sup (ite (a = 0) ∅ (singleton 0)) some = 0)) (if_neg ha))) (Eq.refl (finset.sup (singleton 0) some))) theorem degree_C_le {R : Type u} {a : R} [semiring R] : degree (coe_fn C a) ≤ 0 := sorry theorem degree_one_le {R : Type u} [semiring R] : degree 1 ≤ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (degree 1 ≤ 0)) (Eq.symm C_1))) degree_C_le @[simp] theorem nat_degree_C {R : Type u} [semiring R] (a : R) : nat_degree (coe_fn C a) = 0 := sorry @[simp] theorem nat_degree_one {R : Type u} [semiring R] : nat_degree 1 = 0 := nat_degree_C 1 @[simp] theorem nat_degree_nat_cast {R : Type u} [semiring R] (n : ℕ) : nat_degree ↑n = 0 := sorry @[simp] theorem degree_monomial {R : Type u} {a : R} [semiring R] (n : ℕ) (ha : a ≠ 0) : degree (coe_fn (monomial n) a) = ↑n := sorry @[simp] theorem degree_C_mul_X_pow {R : Type u} {a : R} [semiring R] (n : ℕ) (ha : a ≠ 0) : degree (coe_fn C a * X ^ n) = ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (degree (coe_fn C a * X ^ n) = ↑n)) (Eq.symm single_eq_C_mul_X))) (eq.mpr (id (Eq._oldrec (Eq.refl (degree (coe_fn (monomial n) a) = ↑n)) (degree_monomial n ha))) (Eq.refl ↑n)) theorem degree_monomial_le {R : Type u} [semiring R] (n : ℕ) (a : R) : degree (coe_fn (monomial n) a) ≤ ↑n := sorry theorem degree_C_mul_X_pow_le {R : Type u} [semiring R] (n : ℕ) (a : R) : degree (coe_fn C a * X ^ n) ≤ ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (degree (coe_fn C a * X ^ n) ≤ ↑n)) (C_mul_X_pow_eq_monomial a n))) (degree_monomial_le n a) @[simp] theorem nat_degree_C_mul_X_pow {R : Type u} [semiring R] (n : ℕ) (a : R) (ha : a ≠ 0) : nat_degree (coe_fn C a * X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_C_mul_X_pow n ha) @[simp] theorem nat_degree_C_mul_X {R : Type u} [semiring R] (a : R) (ha : a ≠ 0) : nat_degree (coe_fn C a * X) = 1 := sorry @[simp] theorem nat_degree_monomial {R : Type u} [semiring R] (i : ℕ) (r : R) (hr : r ≠ 0) : nat_degree (coe_fn (monomial i) r) = i := eq.mpr (id (Eq._oldrec (Eq.refl (nat_degree (coe_fn (monomial i) r) = i)) (Eq.symm (C_mul_X_pow_eq_monomial r i)))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_degree (coe_fn C r * X ^ i) = i)) (nat_degree_C_mul_X_pow i r hr))) (Eq.refl i)) theorem coeff_eq_zero_of_degree_lt {R : Type u} {n : ℕ} [semiring R] {p : polynomial R} (h : degree p < ↑n) : coeff p n = 0 := iff.mp not_not (mt le_degree_of_ne_zero (not_le_of_gt h)) theorem coeff_eq_zero_of_nat_degree_lt {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} (h : nat_degree p < n) : coeff p n = 0 := sorry @[simp] theorem coeff_nat_degree_succ_eq_zero {R : Type u} [semiring R] {p : polynomial R} : coeff p (nat_degree p + 1) = 0 := coeff_eq_zero_of_nat_degree_lt (lt_add_one (nat_degree p)) -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! theorem ite_le_nat_degree_coeff {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) (I : Decidable (n < 1 + nat_degree p)) : ite (n < 1 + nat_degree p) (coeff p n) 0 = coeff p n := sorry theorem as_sum_support {R : Type u} [semiring R] (p : polynomial R) : p = finset.sum (finsupp.support p) fun (i : ℕ) => coe_fn (monomial i) (coeff p i) := Eq.symm (finsupp.sum_single p) theorem as_sum_support_C_mul_X_pow {R : Type u} [semiring R] (p : polynomial R) : p = finset.sum (finsupp.support p) fun (i : ℕ) => coe_fn C (coeff p i) * X ^ i := sorry /-- We can reexpress a sum over `p.support` as a sum over `range n`, for any `n` satisfying `p.nat_degree < n`. -/ theorem sum_over_range' {R : Type u} {S : Type v} [semiring R] [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ (n : ℕ), f n 0 = 0) (n : ℕ) (w : nat_degree p < n) : finsupp.sum p f = finset.sum (finset.range n) fun (a : ℕ) => f a (coeff p a) := finsupp.sum_of_support_subset p (supp_subset_range w) f fun (n_1 : ℕ) (hn : n_1 ∈ finset.range n) => h n_1 /-- We can reexpress a sum over `p.support` as a sum over `range (p.nat_degree + 1)`. -/ theorem sum_over_range {R : Type u} {S : Type v} [semiring R] [add_comm_monoid S] (p : polynomial R) {f : ℕ → R → S} (h : ∀ (n : ℕ), f n 0 = 0) : finsupp.sum p f = finset.sum (finset.range (nat_degree p + 1)) fun (a : ℕ) => f a (coeff p a) := sum_over_range' p h (nat_degree p + 1) (lt_add_one (nat_degree p)) theorem as_sum_range' {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) (w : nat_degree p < n) : p = finset.sum (finset.range n) fun (i : ℕ) => coe_fn (monomial i) (coeff p i) := Eq.trans (Eq.symm (finsupp.sum_single p)) (sum_over_range' p (fun (n : ℕ) => finsupp.single_zero) n w) theorem as_sum_range {R : Type u} [semiring R] (p : polynomial R) : p = finset.sum (finset.range (nat_degree p + 1)) fun (i : ℕ) => coe_fn (monomial i) (coeff p i) := Eq.trans (Eq.symm (finsupp.sum_single p)) (sum_over_range p fun (n : ℕ) => finsupp.single_zero) theorem as_sum_range_C_mul_X_pow {R : Type u} [semiring R] (p : polynomial R) : p = finset.sum (finset.range (nat_degree p + 1)) fun (i : ℕ) => coe_fn C (coeff p i) * X ^ i := sorry theorem coeff_ne_zero_of_eq_degree {R : Type u} {n : ℕ} [semiring R] {p : polynomial R} (hn : degree p = ↑n) : coeff p n ≠ 0 := fun (h : coeff p n = 0) => iff.mp finsupp.mem_support_iff (finset.mem_of_max hn) h theorem eq_X_add_C_of_degree_le_one {R : Type u} [semiring R] {p : polynomial R} (h : degree p ≤ 1) : p = coe_fn C (coeff p 1) * X + coe_fn C (coeff p 0) := sorry theorem eq_X_add_C_of_degree_eq_one {R : Type u} [semiring R] {p : polynomial R} (h : degree p = 1) : p = coe_fn C (leading_coeff p) * X + coe_fn C (coeff p 0) := sorry theorem eq_X_add_C_of_nat_degree_le_one {R : Type u} [semiring R] {p : polynomial R} (h : nat_degree p ≤ 1) : p = coe_fn C (coeff p 1) * X + coe_fn C (coeff p 0) := eq_X_add_C_of_degree_le_one (degree_le_of_nat_degree_le h) theorem exists_eq_X_add_C_of_nat_degree_le_one {R : Type u} [semiring R] {p : polynomial R} (h : nat_degree p ≤ 1) : ∃ (a : R), ∃ (b : R), p = coe_fn C a * X + coe_fn C b := Exists.intro (coeff p 1) (Exists.intro (coeff p 0) (eq_X_add_C_of_nat_degree_le_one h)) theorem degree_X_pow_le {R : Type u} [semiring R] (n : ℕ) : degree (X ^ n) ≤ ↑n := sorry theorem degree_X_le {R : Type u} [semiring R] : degree X ≤ 1 := degree_monomial_le 1 1 theorem nat_degree_X_le {R : Type u} [semiring R] : nat_degree X ≤ 1 := nat_degree_le_of_degree_le degree_X_le theorem support_C_mul_X_pow {R : Type u} [semiring R] (c : R) (n : ℕ) : finsupp.support (coe_fn C c * X ^ n) ⊆ singleton n := eq.mpr (id (Eq._oldrec (Eq.refl (finsupp.support (coe_fn C c * X ^ n) ⊆ singleton n)) (C_mul_X_pow_eq_monomial c n))) finsupp.support_single_subset theorem mem_support_C_mul_X_pow {R : Type u} [semiring R] {n : ℕ} {a : ℕ} {c : R} (h : a ∈ finsupp.support (coe_fn C c * X ^ n)) : a = n := iff.mp finset.mem_singleton (support_C_mul_X_pow c n h) theorem card_support_C_mul_X_pow_le_one {R : Type u} [semiring R] {c : R} {n : ℕ} : finset.card (finsupp.support (coe_fn C c * X ^ n)) ≤ 1 := sorry theorem card_supp_le_succ_nat_degree {R : Type u} [semiring R] (p : polynomial R) : finset.card (finsupp.support p) ≤ nat_degree p + 1 := sorry theorem le_degree_of_mem_supp {R : Type u} [semiring R] {p : polynomial R} (a : ℕ) : a ∈ finsupp.support p → ↑a ≤ degree p := le_degree_of_ne_zero ∘ iff.mp mem_support_iff_coeff_ne_zero theorem nonempty_support_iff {R : Type u} [semiring R] {p : polynomial R} : finset.nonempty (finsupp.support p) ↔ p ≠ 0 := sorry theorem support_C_mul_X_pow_nonzero {R : Type u} [semiring R] {c : R} {n : ℕ} (h : c ≠ 0) : finsupp.support (coe_fn C c * X ^ n) = singleton n := eq.mpr (id (Eq._oldrec (Eq.refl (finsupp.support (coe_fn C c * X ^ n) = singleton n)) (C_mul_X_pow_eq_monomial c n))) (finsupp.support_single_ne_zero h) @[simp] theorem degree_one {R : Type u} [semiring R] [nontrivial R] : degree 1 = 0 := degree_C ((fun (this : 1 ≠ 0) => this) (ne.symm zero_ne_one)) @[simp] theorem degree_X {R : Type u} [semiring R] [nontrivial R] : degree X = 1 := degree_monomial 1 one_ne_zero @[simp] theorem nat_degree_X {R : Type u} [semiring R] [nontrivial R] : nat_degree X = 1 := nat_degree_eq_of_degree_eq_some degree_X theorem coeff_mul_X_sub_C {R : Type u} [ring R] {p : polynomial R} {r : R} {a : ℕ} : coeff (p * (X - coe_fn C r)) (a + 1) = coeff p a - coeff p (a + 1) * r := sorry theorem C_eq_int_cast {R : Type u} [ring R] (n : ℤ) : coe_fn C ↑n = ↑n := ring_hom.map_int_cast C n @[simp] theorem degree_neg {R : Type u} [ring R] (p : polynomial R) : degree (-p) = degree p := sorry @[simp] theorem nat_degree_neg {R : Type u} [ring R] (p : polynomial R) : nat_degree (-p) = nat_degree p := sorry @[simp] theorem nat_degree_int_cast {R : Type u} [ring R] (n : ℤ) : nat_degree ↑n = 0 := sorry /-- The second-highest coefficient, or 0 for constants -/ def next_coeff {R : Type u} [semiring R] (p : polynomial R) : R := ite (nat_degree p = 0) 0 (coeff p (nat_degree p - 1)) @[simp] theorem next_coeff_C_eq_zero {R : Type u} [semiring R] (c : R) : next_coeff (coe_fn C c) = 0 := sorry theorem next_coeff_of_pos_nat_degree {R : Type u} [semiring R] (p : polynomial R) (hp : 0 < nat_degree p) : next_coeff p = coeff p (nat_degree p - 1) := sorry theorem coeff_nat_degree_eq_zero_of_degree_lt {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) theorem ne_zero_of_degree_gt {R : Type u} [semiring R] {p : polynomial R} {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt (iff.mpr degree_eq_bot) (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) theorem eq_C_of_degree_le_zero {R : Type u} [semiring R] {p : polynomial R} (h : degree p ≤ 0) : p = coe_fn C (coeff p 0) := sorry theorem eq_C_of_degree_eq_zero {R : Type u} [semiring R] {p : polynomial R} (h : degree p = 0) : p = coe_fn C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl (degree p)) theorem degree_le_zero_iff {R : Type u} [semiring R] {p : polynomial R} : degree p ≤ 0 ↔ p = coe_fn C (coeff p 0) := { mp := eq_C_of_degree_le_zero, mpr := fun (h : p = coe_fn C (coeff p 0)) => Eq.symm h ▸ degree_C_le } theorem degree_add_le {R : Type u} [semiring R] (p : polynomial R) (q : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := sorry @[simp] theorem leading_coeff_zero {R : Type u} [semiring R] : leading_coeff 0 = 0 := rfl @[simp] theorem leading_coeff_eq_zero {R : Type u} [semiring R] {p : polynomial R} : leading_coeff p = 0 ↔ p = 0 := sorry theorem leading_coeff_eq_zero_iff_deg_eq_bot {R : Type u} [semiring R] {p : polynomial R} : leading_coeff p = 0 ↔ degree p = ⊥ := eq.mpr (id (Eq._oldrec (Eq.refl (leading_coeff p = 0 ↔ degree p = ⊥)) (propext leading_coeff_eq_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (p = 0 ↔ degree p = ⊥)) (propext degree_eq_bot))) (iff.refl (p = 0))) theorem nat_degree_mem_support_of_nonzero {R : Type u} [semiring R] {p : polynomial R} (H : p ≠ 0) : nat_degree p ∈ finsupp.support p := iff.mpr (finsupp.mem_support_to_fun p (nat_degree p)) (iff.mpr (not_congr leading_coeff_eq_zero) H) theorem nat_degree_eq_support_max' {R : Type u} [semiring R] {p : polynomial R} (h : p ≠ 0) : nat_degree p = finset.max' (finsupp.support p) (iff.mpr nonempty_support_iff h) := sorry theorem nat_degree_C_mul_X_pow_le {R : Type u} [semiring R] (a : R) (n : ℕ) : nat_degree (coe_fn C a * X ^ n) ≤ n := iff.mpr nat_degree_le_iff_degree_le (degree_C_mul_X_pow_le n a) theorem degree_add_eq_left_of_degree_lt {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : degree q < degree p) : degree (p + q) = degree p := sorry theorem degree_add_eq_right_of_degree_lt {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : degree p < degree q) : degree (p + q) = degree q := eq.mpr (id (Eq._oldrec (Eq.refl (degree (p + q) = degree q)) (add_comm p q))) (eq.mpr (id (Eq._oldrec (Eq.refl (degree (q + p) = degree q)) (degree_add_eq_left_of_degree_lt h))) (Eq.refl (degree q))) theorem degree_add_C {R : Type u} {a : R} [semiring R] {p : polynomial R} (hp : 0 < degree p) : degree (p + coe_fn C a) = degree p := Eq.subst (add_comm (coe_fn C a) p) degree_add_eq_right_of_degree_lt (lt_of_le_of_lt degree_C_le hp) theorem degree_add_eq_of_leading_coeff_add_ne_zero {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max (degree p) (degree q) := sorry theorem degree_erase_le {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) : degree (finsupp.erase n p) ≤ degree p := sorry theorem degree_erase_lt {R : Type u} [semiring R] {p : polynomial R} (hp : p ≠ 0) : degree (finsupp.erase (nat_degree p) p) < degree p := sorry theorem degree_sum_le {R : Type u} [semiring R] {ι : Type u_1} (s : finset ι) (f : ι → polynomial R) : degree (finset.sum s fun (i : ι) => f i) ≤ finset.sup s fun (b : ι) => degree (f b) := sorry theorem degree_mul_le {R : Type u} [semiring R] (p : polynomial R) (q : polynomial R) : degree (p * q) ≤ degree p + degree q := sorry theorem degree_pow_le {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) : degree (p ^ n) ≤ n •ℕ degree p := sorry @[simp] theorem leading_coeff_monomial {R : Type u} [semiring R] (a : R) (n : ℕ) : leading_coeff (coe_fn (monomial n) a) = a := sorry theorem leading_coeff_C_mul_X_pow {R : Type u} [semiring R] (a : R) (n : ℕ) : leading_coeff (coe_fn C a * X ^ n) = a := eq.mpr (id (Eq._oldrec (Eq.refl (leading_coeff (coe_fn C a * X ^ n) = a)) (C_mul_X_pow_eq_monomial a n))) (eq.mpr (id (Eq._oldrec (Eq.refl (leading_coeff (coe_fn (monomial n) a) = a)) (leading_coeff_monomial a n))) (Eq.refl a)) @[simp] theorem leading_coeff_C {R : Type u} [semiring R] (a : R) : leading_coeff (coe_fn C a) = a := leading_coeff_monomial a 0 @[simp] theorem leading_coeff_X_pow {R : Type u} [semiring R] (n : ℕ) : leading_coeff (X ^ n) = 1 := sorry @[simp] theorem leading_coeff_X {R : Type u} [semiring R] : leading_coeff X = 1 := sorry @[simp] theorem monic_X_pow {R : Type u} [semiring R] (n : ℕ) : monic (X ^ n) := leading_coeff_X_pow n @[simp] theorem monic_X {R : Type u} [semiring R] : monic X := leading_coeff_X @[simp] theorem leading_coeff_one {R : Type u} [semiring R] : leading_coeff 1 = 1 := leading_coeff_C 1 @[simp] theorem monic_one {R : Type u} [semiring R] : monic 1 := leading_coeff_C 1 theorem monic.ne_zero {R : Type u_1} [semiring R] [nontrivial R] {p : polynomial R} (hp : monic p) : p ≠ 0 := sorry theorem monic.ne_zero_of_ne {R : Type u} [semiring R] (h : 0 ≠ 1) {p : polynomial R} (hp : monic p) : p ≠ 0 := monic.ne_zero hp theorem monic.ne_zero_of_polynomial_ne {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} {r : polynomial R} (hp : monic p) (hne : q ≠ r) : p ≠ 0 := monic.ne_zero hp theorem leading_coeff_add_of_degree_lt {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := sorry theorem leading_coeff_add_of_degree_eq {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := sorry @[simp] theorem coeff_mul_degree_add_degree {R : Type u} [semiring R] (p : polynomial R) (q : polynomial R) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := sorry theorem degree_mul' {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := sorry theorem degree_mul_monic {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hq : monic q) : degree (p * q) = degree p + degree q := sorry theorem nat_degree_mul' {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := sorry theorem leading_coeff_mul' {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := sorry theorem leading_coeff_pow' {R : Type u} {n : ℕ} [semiring R] {p : polynomial R} : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := sorry theorem degree_pow' {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} : leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n •ℕ degree p := sorry theorem nat_degree_pow' {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := sorry theorem leading_coeff_mul_monic {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hq : monic q) : leading_coeff (p * q) = leading_coeff p := sorry @[simp] theorem leading_coeff_mul_X_pow {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := leading_coeff_mul_monic (monic_X_pow n) @[simp] theorem leading_coeff_mul_X {R : Type u} [semiring R] {p : polynomial R} : leading_coeff (p * X) = leading_coeff p := leading_coeff_mul_monic monic_X theorem nat_degree_mul_le {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} : nat_degree (p * q) ≤ nat_degree p + nat_degree q := sorry theorem subsingleton_of_monic_zero {R : Type u} [semiring R] (h : monic 0) : (∀ (p q : polynomial R), p = q) ∧ ∀ (a b : R), a = b := sorry theorem zero_le_degree_iff {R : Type u} [semiring R] {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ degree p ↔ p ≠ 0)) (ne.def p 0))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ degree p ↔ ¬p = 0)) (Eq.symm (propext degree_eq_bot)))) (option.cases_on (degree p) (of_as_true trivial) fun (val : ℕ) => of_as_true trivial)) theorem degree_nonneg_iff_ne_zero {R : Type u} [semiring R] {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := sorry theorem nat_degree_eq_zero_iff_degree_le_zero {R : Type u} [semiring R] {p : polynomial R} : nat_degree p = 0 ↔ degree p ≤ 0 := eq.mpr (id (Eq._oldrec (Eq.refl (nat_degree p = 0 ↔ degree p ≤ 0)) (Eq.symm (propext nonpos_iff_eq_zero)))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_degree p ≤ 0 ↔ degree p ≤ 0)) (propext nat_degree_le_iff_degree_le))) (eq.mpr (id (Eq._oldrec (Eq.refl (degree p ≤ ↑0 ↔ degree p ≤ 0)) with_bot.coe_zero)) (iff.refl (degree p ≤ 0)))) theorem degree_le_iff_coeff_zero {R : Type u} [semiring R] (f : polynomial R) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ (m : ℕ), n < ↑m → coeff f m = 0 := sorry theorem degree_lt_iff_coeff_zero {R : Type u} [semiring R] (f : polynomial R) (n : ℕ) : degree f < ↑n ↔ ∀ (m : ℕ), n ≤ m → coeff f m = 0 := sorry theorem degree_lt_degree_mul_X {R : Type u} [semiring R] {p : polynomial R} (hp : p ≠ 0) : degree p < degree (p * X) := sorry theorem nat_degree_pos_iff_degree_pos {R : Type u} [semiring R] {p : polynomial R} : 0 < nat_degree p ↔ 0 < degree p := lt_iff_lt_of_le_iff_le nat_degree_le_iff_degree_le theorem eq_C_of_nat_degree_le_zero {R : Type u} [semiring R] {p : polynomial R} (h : nat_degree p ≤ 0) : p = coe_fn C (coeff p 0) := eq_C_of_degree_le_zero (degree_le_of_nat_degree_le h) theorem eq_C_of_nat_degree_eq_zero {R : Type u} [semiring R] {p : polynomial R} (h : nat_degree p = 0) : p = coe_fn C (coeff p 0) := eq_C_of_nat_degree_le_zero (eq.le h) @[simp] theorem degree_X_pow {R : Type u} [semiring R] [nontrivial R] (n : ℕ) : degree (X ^ n) = ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (degree (X ^ n) = ↑n)) (X_pow_eq_monomial n))) (eq.mpr (id (Eq._oldrec (Eq.refl (degree (coe_fn (monomial n) 1) = ↑n)) (degree_monomial n one_ne_zero))) (Eq.refl ↑n)) @[simp] theorem nat_degree_X_pow {R : Type u} [semiring R] [nontrivial R] (n : ℕ) : nat_degree (X ^ n) = n := nat_degree_eq_of_degree_eq_some (degree_X_pow n) theorem not_is_unit_X {R : Type u} [semiring R] [nontrivial R] : ¬is_unit X := sorry @[simp] theorem degree_mul_X {R : Type u} [semiring R] [nontrivial R] {p : polynomial R} : degree (p * X) = degree p + 1 := sorry @[simp] theorem degree_mul_X_pow {R : Type u} {n : ℕ} [semiring R] [nontrivial R] {p : polynomial R} : degree (p * X ^ n) = degree p + ↑n := sorry theorem degree_sub_le {R : Type u} [ring R] (p : polynomial R) (q : polynomial R) : degree (p - q) ≤ max (degree p) (degree q) := sorry theorem degree_sub_lt {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := sorry theorem nat_degree_X_sub_C_le {R : Type u} [ring R] {r : R} : nat_degree (X - coe_fn C r) ≤ 1 := iff.mpr nat_degree_le_iff_degree_le (le_trans (degree_sub_le X (coe_fn C r)) (max_le degree_X_le (le_trans degree_C_le (iff.mpr with_bot.coe_le_coe zero_le_one)))) theorem degree_sum_fin_lt {R : Type u} [ring R] {n : ℕ} (f : fin n → R) : degree (finset.sum finset.univ fun (i : fin n) => coe_fn C (f i) * X ^ ↑i) < ↑n := sorry theorem degree_sub_eq_left_of_degree_lt {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} (h : degree q < degree p) : degree (p - q) = degree p := sorry theorem degree_sub_eq_right_of_degree_lt {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} (h : degree p < degree q) : degree (p - q) = degree q := sorry @[simp] theorem degree_X_sub_C {R : Type u} [nontrivial R] [ring R] (a : R) : degree (X - coe_fn C a) = 1 := sorry @[simp] theorem nat_degree_X_sub_C {R : Type u} [nontrivial R] [ring R] (x : R) : nat_degree (X - coe_fn C x) = 1 := nat_degree_eq_of_degree_eq_some (degree_X_sub_C x) @[simp] theorem next_coeff_X_sub_C {R : Type u} [nontrivial R] [ring R] (c : R) : next_coeff (X - coe_fn C c) = -c := sorry theorem degree_X_pow_sub_C {R : Type u} [nontrivial R] [ring R] {n : ℕ} (hn : 0 < n) (a : R) : degree (X ^ n - coe_fn C a) = ↑n := sorry theorem X_pow_sub_C_ne_zero {R : Type u} [nontrivial R] [ring R] {n : ℕ} (hn : 0 < n) (a : R) : X ^ n - coe_fn C a ≠ 0 := sorry theorem X_sub_C_ne_zero {R : Type u} [nontrivial R] [ring R] (r : R) : X - coe_fn C r ≠ 0 := pow_one X ▸ X_pow_sub_C_ne_zero zero_lt_one r theorem nat_degree_X_pow_sub_C {R : Type u} [nontrivial R] [ring R] {n : ℕ} (hn : 0 < n) {r : R} : nat_degree (X ^ n - coe_fn C r) = n := sorry @[simp] theorem degree_mul {R : Type u} [comm_semiring R] [no_zero_divisors R] {p : polynomial R} {q : polynomial R} : degree (p * q) = degree p + degree q := sorry @[simp] theorem degree_pow {R : Type u} [comm_semiring R] [no_zero_divisors R] [nontrivial R] (p : polynomial R) (n : ℕ) : degree (p ^ n) = n •ℕ degree p := sorry @[simp] theorem leading_coeff_mul {R : Type u} [comm_semiring R] [no_zero_divisors R] (p : polynomial R) (q : polynomial R) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := sorry @[simp] theorem leading_coeff_X_add_C {R : Type u} [comm_semiring R] [no_zero_divisors R] [nontrivial R] (a : R) (b : R) (ha : a ≠ 0) : leading_coeff (coe_fn C a * X + coe_fn C b) = a := sorry /-- `polynomial.leading_coeff` bundled as a `monoid_hom` when `R` has `no_zero_divisors`, and thus `leading_coeff` is multiplicative -/ def leading_coeff_hom {R : Type u} [comm_semiring R] [no_zero_divisors R] : polynomial R →* R := monoid_hom.mk leading_coeff sorry leading_coeff_mul @[simp] theorem leading_coeff_hom_apply {R : Type u} [comm_semiring R] [no_zero_divisors R] (p : polynomial R) : coe_fn leading_coeff_hom p = leading_coeff p := rfl @[simp] theorem leading_coeff_pow {R : Type u} [comm_semiring R] [no_zero_divisors R] (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := monoid_hom.map_pow leading_coeff_hom p n end Mathlib
21210218f7de504af77a5fb0d6d09cfc20720115
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/logic/default.lean
8353bc33c99a7aed0633264dd910471a77061078
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
285
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: logic.default Author: Jeremy Avigad -/ import logic.eq logic.connectives logic.cast import logic.quantifiers logic.instances logic.identities
068aad89d03e8a47c3329bb7e426cb916f1fb85a
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/meta/interactive_base.lean
786f450ae9ff86f353b3bb0c897674d6e4619b2b
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
8,431
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.option.basic import init.meta.lean.parser init.meta.tactic init.meta.has_reflect open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace interactive /-- (parse p) as the parameter type of an interactive tactic will instruct the Lean parser to run `p` when parsing the parameter and to pass the parsed value as an argument to the tactic. -/ @[reducible] meta def parse {α : Type} (p : parser α) [lean.parser.reflectable p] : Type := α /-- A `loc` is either a 'wildcard', which means "everywhere", or a list of `option name`s. `none` means `target` and `some n` means `n` in the local context.-/ inductive loc : Type | wildcard : loc | ns : list (option name) → loc meta def loc.include_goal : loc → bool | loc.wildcard := tt | (loc.ns ls) := (ls.map option.is_none).bor meta def loc.get_locals : loc → tactic (list expr) | loc.wildcard := tactic.local_context | (loc.ns xs) := xs.mfoldl (λ ls n, match n with | none := pure ls | some n := do l ← tactic.get_local n, pure $ l :: ls end) [] meta def loc.apply (hyp_tac : expr → tactic unit) (goal_tac : tactic unit) (l : loc) : tactic unit := do hs ← l.get_locals, hs.mmap' hyp_tac, if l.include_goal then goal_tac else pure () meta def loc.try_apply (hyp_tac : expr → tactic unit) (goal_tac : tactic unit) (l : loc) : tactic unit := do hs ← l.get_locals, let hts := hs.map hyp_tac, tactic.try_lst $ if l.include_goal then hts ++ [goal_tac] else hts /-- Use `desc` as the interactive description of `p`. -/ meta def with_desc {α : Type} (desc : format) (p : parser α) : parser α := p namespace types variables {α β : Type} -- optimized pretty printer meta def brackets (l r : string) (p : parser α) := tk l *> p <* tk r meta def list_of (p : parser α) := brackets "[" "]" $ sep_by (skip_info (tk ",")) p precedence `⊢` : 0 precedence `|-` : 0 /-- The right-binding power 2 will terminate expressions by '<|>' (rbp 2), ';' (rbp 1), and ',' (rbp 0). It should be used for any (potentially) trailing expression parameters. -/ meta def tac_rbp := 2 /-- A 'tactic expression', which uses right-binding power 2 so that it is terminated by '<|>' (rbp 2), ';' (rbp 1), and ',' (rbp 0). It should be used for any (potentially) trailing expression parameters. -/ meta def texpr := parser.pexpr tac_rbp /-- Parse an identifier or a '_' -/ meta def ident_ : parser name := ident <|> tk "_" *> return `_ meta def using_ident := (tk "using" *> ident)? meta def with_ident_list := (tk "with" *> ident_*) <|> return [] meta def without_ident_list := (tk "without" *> ident*) <|> return [] meta def location := (tk "at" *> (tk "*" *> return loc.wildcard <|> (loc.ns <$> (((with_desc "⊢" $ tk "⊢" <|> tk "|-") *> return none) <|> some <$> ident)*))) <|> return (loc.ns [none]) meta def pexpr_list := list_of (parser.pexpr 0) meta def opt_pexpr_list := pexpr_list <|> return [] meta def pexpr_list_or_texpr := pexpr_list <|> list.ret <$> texpr meta def only_flag : parser bool := (tk "only" *> return tt) <|> return ff end types precedence only:0 open expr format tactic types private meta def maybe_paren : list format → format | [] := "" | [f] := f | fs := paren (join fs) private meta def unfold (e : expr) : tactic expr := do (expr.const f_name f_lvls) ← return e.get_app_fn | failed, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, head_beta (expr.mk_app new_f e.get_app_args) private meta def concat (f₁ f₂ : list format) := if f₁.empty then f₂ else if f₂.empty then f₁ else f₁ ++ [" "] ++ f₂ private meta def parser_desc_aux : expr → tactic (list format) | `(ident) := return ["id"] | `(ident_) := return ["id"] | `(parser.pexpr %%v) := return ["expr"] | `(tk %%c) := list.ret <$> to_fmt <$> eval_expr string c | `(cur_pos) := return [] | `(pure ._) := return [] | `(._ <$> %%p) := parser_desc_aux p | `(skip_info %%p) := parser_desc_aux p | `(set_goal_info_pos %%p) := parser_desc_aux p | `(with_desc %%desc %%p) := list.ret <$> eval_expr format desc | `(%%p₁ <*> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(%%p₁ <* %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(%%p₁ *> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(many %%p) := do f ← parser_desc_aux p, return [maybe_paren f ++ "*"] | `(optional %%p) := do f ← parser_desc_aux p, return [maybe_paren f ++ "?"] | `(sep_by %%sep %%p) := do f₁ ← parser_desc_aux sep, f₂ ← parser_desc_aux p, return [maybe_paren f₂ ++ join f₁, " ..."] | `(%%p₁ <|> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ if f₁.empty then [maybe_paren f₂ ++ "?"] else if f₂.empty then [maybe_paren f₁ ++ "?"] else [paren $ join $ f₁ ++ [to_fmt " | "] ++ f₂] | `(brackets %%l %%r %%p) := do f ← parser_desc_aux p, l ← eval_expr string l, r ← eval_expr string r, -- much better than the naive [l, " ", f, " ", r] return [to_fmt l ++ join f ++ to_fmt r] | e := do e' ← (do e' ← unfold e, guard $ e' ≠ e, return e') <|> (do f ← pp e, fail $ to_fmt "don't know how to pretty print " ++ f), parser_desc_aux e' meta def param_desc : expr → tactic format | `(parse %%p) := join <$> parser_desc_aux p | `(opt_param %%t ._) := (++ "?") <$> pp t | e := if is_constant e ∧ (const_name e).components.ilast = `itactic then return $ to_fmt "{ tactic }" else paren <$> pp e private meta constant parse_binders_core (rbp : ℕ) : parser (list pexpr) meta def parse_binders (rbp := std.prec.max) := with_desc "<binders>" (parse_binders_core rbp) meta constant decl_attributes : Type meta constant decl_attributes.apply : decl_attributes → name → parser unit meta structure decl_modifiers := (is_private : bool) (is_protected : bool) (is_meta : bool) (is_mutual : bool) (is_noncomputable : bool) meta structure decl_meta_info := (attrs : decl_attributes) (modifiers : decl_modifiers) (doc_string : option string) meta structure single_inductive_decl := (attrs : decl_attributes) (sig : expr) (intros : list expr) meta def single_inductive_decl.name (d : single_inductive_decl) : name := d.sig.app_fn.const_name meta structure inductive_decl := (u_names : list name) (params : list expr) (decls : list single_inductive_decl) /-- Parses and elaborates a single or multiple mutual inductive declarations (without the `inductive` keyword), depending on `is_mutual` -/ meta constant inductive_decl.parse : decl_meta_info → parser inductive_decl end interactive section macros open interaction_monad open interactive private meta def parse_format : string → list char → parser pexpr | acc [] := pure ``(to_fmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_format "" s, pure ``(to_fmt %%(reflect acc) ++ format.line ++ %%f) | acc ('{'::'{'::s) := parse_format (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_format "" s, pure ``(to_fmt %%(reflect acc) ++ to_fmt %%e ++ %%f) | acc (c::s) := parse_format (acc.str c) s reserve prefix `format! `:100 @[user_notation] meta def format_macro (_ : parse $ tk "format!") (s : string) : parser pexpr := parse_format "" s.to_list private meta def parse_sformat : string → list char → parser pexpr | acc [] := pure $ pexpr.of_expr (reflect acc) | acc ('{'::'{'::s) := parse_sformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_sformat "" s, pure ``(%%(reflect acc) ++ to_string %%e ++ %%f) | acc (c::s) := parse_sformat (acc.str c) s reserve prefix `sformat! `:100 @[user_notation] meta def sformat_macro (_ : parse $ tk "sformat!") (s : string) : parser pexpr := parse_sformat "" s.to_list end macros
5022025a7a983642b93e6c1550a0eb00dfff78a7
222111140d2023e142b07e9cd5119ac2829b36f5
/src/matrix_repr.lean
ecf417e1c8a4c365f4696b19d0b3bdb7f129c636
[]
no_license
jjcrawford/lean-gaussian-elimination
740dfdf2de89dc99c088c53e5221d9dfad3c0b92
c473d33c07fa6f141d17d9dc42ad07956c33dd03
refs/heads/master
1,585,793,867,436
1,540,443,865,000
1,540,443,865,000
153,901,939
0
0
null
null
null
null
UTF-8
Lean
false
false
1,913
lean
import ring_theory.matrix @[pattern] def vector.mk {α : Type*} {n : ℕ} (l : list α) (pr : l.length = n) : vector α n := ⟨l, pr⟩ notation `![` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := vector.mk l (refl _) universes u variables {m n : ℕ} {α : Type u} def matrix.bang : (vector (vector α n) m) → (matrix (fin m) (fin n) α) := λ M i j, (M.nth i).nth j variables {β : Type u} def matrix.fold_row_aux (M : matrix (fin m) (fin n) α) : Π (j : fin n) (i : fin m) (f : fin m → fin n → α → β → β) (b : β), β | ⟨0, h₁⟩ k₂ f b := f k₂ ⟨0, h₁⟩ (M k₂ ⟨0, h₁⟩) b | ⟨k₁ + 1, h₁⟩ k₂ f b := matrix.fold_row_aux ⟨k₁, nat.lt_of_succ_lt h₁⟩ k₂ f (f k₂ ⟨k₁ + 1, h₁⟩ (M k₂ ⟨k₁ + 1, h₁⟩) b) def matrix.fold_row (M : matrix (fin m) (fin n) α) : Π (i : fin m) (f : fin m → fin n → α → β → β) (b : β), β := begin intros, cases n, from b, from matrix.fold_row_aux M ⟨n, nat.lt_succ_self n⟩ i f b, end def matrix.list_of_row (M : matrix (fin m) (fin n) α) : Π (i : fin m), list α := λ j, matrix.fold_row M j (λ _ _ (b : α) (l : list α), l.cons b) list.nil def matrix.to_list_of_lists_aux (M : matrix (fin m) (fin n) α) : Π (i : fin m) (b : list (list α)), list (list α) | ⟨0, h₁⟩ b := b.cons (M.list_of_row ⟨0, h₁⟩) | ⟨k+1, h₁⟩ b := matrix.to_list_of_lists_aux ⟨k, nat.lt_of_succ_lt h₁⟩ (b.cons (M.list_of_row ⟨k+1, h₁⟩)) def matrix.to_list_of_lists (M : matrix (fin m) (fin n) α) : list (list α) := begin cases m, from list.nil, from matrix.to_list_of_lists_aux M ⟨m, nat.lt_succ_self m⟩ list.nil, end variable [has_repr α] instance matrix.has_repr : has_repr (matrix (fin m) (fin n) α) := begin constructor, intros M, from repr (matrix.to_list_of_lists M) end
0c3ee7c729f2cdd5a5441e5811dd696ff64f81c6
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/category_theory/adjunction/limits.lean
4d132d05f168d125d4bbceb3f8aa7c0cba1e3f4c
[ "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
7,695
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.adjunction.basic import category_theory.limits.preserves open opposite namespace category_theory.adjunction open category_theory open category_theory.functor open category_theory.limits universes u₁ u₂ v variables {C : Type u₁} [𝒞 : category.{v} C] {D : Type u₂} [𝒟 : category.{v} D] include 𝒞 𝒟 variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) include adj section preservation_colimits variables {J : Type v} [small_category J] (K : J ⥤ C) def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K := (cocones.functoriality G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)) local attribute [reducible] functoriality_right_adjoint @[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality F ⋙ functoriality_right_adjoint adj K := { app := λ c, { hom := adj.unit.app c.X } } @[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality F ⟶ 𝟭 (cocone (K ⋙ F)) := { app := λ c, { hom := adj.counit.app c.X } } def functoriality_is_left_adjoint : is_left_adjoint (@cocones.functoriality _ _ _ _ K _ _ F) := { right := functoriality_right_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit adj K, counit := functoriality_counit adj K } } /-- A left adjoint preserves colimits. -/ def left_adjoint_preserves_colimits : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI { preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv (λ s, (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _).unique_of_equiv $ is_colimit.iso_unique_cocone_morphism.hom hc _ ) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E := left_adjoint_preserves_colimits E.adjunction -- verify the preserve_colimits instance works as expected: example (E : C ⥤ D) [is_equivalence E] (c : cocone K) (h : is_colimit c) : is_colimit (E.map_cocone c) := preserves_colimit.preserves E h instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] : has_colimit (K ⋙ E) := { cocone := E.map_cocone (colimit.cocone K), is_colimit := preserves_colimit.preserves E (colimit.is_colimit K) } def has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] : has_colimit K := @has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((functor.right_unitor _).symm ≪≫ (iso_whisker_left K (fun_inv_id E)).symm) end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K := (cones.functoriality F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)) local attribute [reducible] functoriality_left_adjoint @[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality G := { app := λ c, { hom := adj.unit.app c.X, } } @[simps] def functoriality_counit' : cones.functoriality G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) := { app := λ c, { hom := adj.counit.app c.X, } } def functoriality_is_right_adjoint : is_right_adjoint (@cones.functoriality _ _ _ _ K _ _ G) := { left := functoriality_left_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit' adj K, counit := functoriality_counit' adj K } } /-- A right adjoint preserves limits. -/ def right_adjoint_preserves_limits : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI { preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv (λ s, (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm.unique_of_equiv $ is_limit.iso_unique_cone_morphism.hom hc _) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E := right_adjoint_preserves_limits E.inv.adjunction -- verify the preserve_limits instance works as expected: example (E : D ⥤ C) [is_equivalence E] (c : cone K) [h : is_limit c] : is_limit (E.map_cone c) := preserves_limit.preserves E h instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] : has_limit (K ⋙ E) := { cone := E.map_cone (limit.cone K), is_limit := preserves_limit.preserves E (limit.is_limit K) } def has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] : has_limit K := @has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((iso_whisker_left K (fun_inv_id E)) ≪≫ (functor.right_unitor _)) end preservation_limits /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : ((cocones J D).obj (op (K ⋙ F))).obj Y) : (G ⋙ (cocones J C).obj (op K)).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j), naturality' := λ j j' f, by erw [← adj.hom_equiv_naturality_left, t.naturality]; dsimp; simp } /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : (G ⋙ (cocones J C).obj (op K)).obj Y) : ((cocones J D).obj (op (K ⋙ F))).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality], dsimp, simp end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} : (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) := nat_iso.of_components (λ Y, { hom := cocones_iso_component_hom adj Y, inv := cocones_iso_component_inv adj Y, }) (by tidy) /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : (functor.op F ⋙ (cones J D).obj K).obj X) : ((cones J C).obj (K ⋙ G)).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp], refl end } /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : ((cones J C).obj (K ⋙ G)).obj X) : (functor.op F ⋙ (cones J D).obj K).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp] end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} : F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) := nat_iso.of_components (λ X, { hom := cones_iso_component_hom adj X, inv := cones_iso_component_inv adj X, } ) (by tidy) end category_theory.adjunction
cc1c3e78d2892a2305fd6588a83bf9fa9f13a114
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Elab/BuiltinNotation.lean
795d5d25dcb0e0bdd145519545cf12623543ff62
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
16,853
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.BorrowedAnnotation import Lean.Meta.KAbstract import Lean.Meta.MatchUtil import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta @[builtin_term_elab coeNotation] def elabCoe : TermElab := fun stx expectedType? => do let stx := stx[1] tryPostponeIfNoneOrMVar expectedType? let e ← elabTerm stx none if expectedType?.isNone then throwError "invalid coercion notation, expected type is not known" ensureHasType expectedType? e @[builtin_term_elab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? => match stx with | `(⟨$args,*⟩) => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => let expectedType ← whnf expectedType matchConstInduct expectedType.getAppFn (fun _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}") (fun ival _ => do match ival.ctors with | [ctor] => if isPrivateNameFromImportedModule (← getEnv) ctor then throwError "invalid ⟨...⟩ notation, constructor for `{ival.name}` is marked as private" let cinfo ← getConstInfoCtor ctor let numExplicitFields ← forallTelescopeReducing cinfo.type fun xs _ => do let mut n := 0 for i in [cinfo.numParams:xs.size] do if (← getFVarLocalDecl xs[i]!).binderInfo.isExplicit then n := n + 1 return n let args := args.getElems if args.size < numExplicitFields then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided" let newStx ← if args.size == numExplicitFields then `($(mkCIdentFrom stx ctor (canonical := true)) $(args)*) else if numExplicitFields == 0 then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided" else let extra := args[numExplicitFields-1:args.size] let newLast ← `(⟨$[$extra],*⟩) let newArgs := args[0:numExplicitFields-1].toArray.push newLast `($(mkCIdentFrom stx ctor (canonical := true)) $(newArgs)*) withMacroExpansion stx newStx $ elabTerm newStx expectedType? | _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}") | none => throwError "invalid constructor ⟨...⟩, expected type must be known" | _ => throwUnsupportedSyntax @[builtin_term_elab borrowed] def elabBorrowed : TermElab := fun stx expectedType? => match stx with | `(@& $e) => return markBorrowed (← elabTerm e expectedType?) | _ => throwUnsupportedSyntax @[builtin_macro Lean.Parser.Term.show] def expandShow : Macro := fun stx => match stx with | `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let_fun $thisId : $type := $val; $thisId) | `(show $type by%$b $tac) => `(show $type from by%$b $tac) | _ => Macro.throwUnsupported @[builtin_macro Lean.Parser.Term.have] def expandHave : Macro := fun stx => match stx with | `(have $x $bs* $[: $type]? := $val; $body) => `(let_fun $x $bs* $[: $type]? := $val; $body) | `(have%$tk $[: $type]? := $val; $body) => `(have $(mkIdentFrom tk `this (canonical := true)) $[: $type]? := $val; $body) | `(have $x $bs* $[: $type]? $alts; $body) => `(let_fun $x $bs* $[: $type]? $alts; $body) | `(have%$tk $[: $type]? $alts:matchAlts; $body) => `(have $(mkIdentFrom tk `this (canonical := true)) $[: $type]? $alts:matchAlts; $body) | `(have $pattern:term $[: $type]? := $val:term; $body) => `(let_fun $pattern:term $[: $type]? := $val:term ; $body) | _ => Macro.throwUnsupported @[builtin_macro Lean.Parser.Term.suffices] def expandSuffices : Macro | `(suffices%$tk $[$x :]? $type from $val; $body) => `(have%$tk $[$x]? : $type := $body; $val) | `(suffices%$tk $[$x :]? $type by%$b $tac:tacticSeq; $body) => `(have%$tk $[$x]? : $type := $body; by%$b $tac) | _ => Macro.throwUnsupported open Lean.Parser in private def elabParserMacroAux (prec e : Term) (withAnonymousAntiquot : Bool) : TermElabM Syntax := do let (some declName) ← getDeclName? | throwError "invalid `leading_parser` macro, it must be used in definitions" match extractMacroScopes declName with | { name := .str _ s, .. } => let kind := quote declName let mut p ← ``(withAntiquot (mkAntiquot $(quote s) $kind $(quote withAnonymousAntiquot)) (leadingNode $kind $prec $e)) -- cache only unparameterized parsers if (← getLCtx).all (·.isAuxDecl) then p ← ``(withCache $kind $p) return p | _ => throwError "invalid `leading_parser` macro, unexpected declaration name" @[builtin_term_elab «leading_parser»] def elabLeadingParserMacro : TermElab := adaptExpander fun | `(leading_parser $[: $prec?]? $[(withAnonymousAntiquot := $anon?)]? $e) => elabParserMacroAux (prec?.getD (quote Parser.maxPrec)) e (anon?.all (·.raw.isOfKind ``Parser.Term.trueVal)) | _ => throwUnsupportedSyntax private def elabTParserMacroAux (prec lhsPrec e : Term) : TermElabM Syntax := do let declName? ← getDeclName? match declName? with | some declName => let kind := quote declName; ``(Lean.Parser.trailingNode $kind $prec $lhsPrec $e) | none => throwError "invalid `trailing_parser` macro, it must be used in definitions" @[builtin_term_elab «trailing_parser»] def elabTrailingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) => elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e | _ => throwUnsupportedSyntax @[builtin_term_elab Lean.Parser.Term.panic] def elabPanic : TermElab := fun stx expectedType? => do match stx with | `(panic! $arg) => let pos ← getRefPosition let env ← getEnv let stxNew ← match (← getDeclName?) with | some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg) | none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax @[builtin_macro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun _ => `(panic! "unreachable code has been reached") @[builtin_macro Lean.Parser.Term.assert] def expandAssert : Macro | `(assert! $cond; $body) => -- TODO: support for disabling runtime assertions match cond.raw.reprint with | some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code))) | none => `(if $cond then $body else panic! ("assertion violation")) | _ => Macro.throwUnsupported @[builtin_macro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro | `(dbg_trace $arg:interpolatedStr; $body) => `(dbgTrace (s! $arg) fun _ => $body) | `(dbg_trace $arg:term; $body) => `(dbgTrace (toString $arg) fun _ => $body) | _ => Macro.throwUnsupported @[builtin_term_elab «sorry»] def elabSorry : TermElab := fun stx expectedType? => do let stxNew ← `(sorryAx _ false) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ partial def mkPairs (elems : Array Term) : MacroM Term := let rec loop (i : Nat) (acc : Term) := do if i > 0 then let i := i - 1 let elem := elems[i]! let acc ← `(Prod.mk $elem $acc) loop i acc else pure acc loop (elems.size - 1) elems.back open Parser in partial def hasCDot : Syntax → Bool | Syntax.node _ k args => if k == ``Term.paren || k == ``Term.typeAscription || k == ``Term.tuple then false else if k == ``Term.cdot then true else args.any hasCDot | _ => false /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ partial def expandCDot? (stx : Term) : MacroM (Option Term) := do if hasCDot stx then let (newStx, binders) ← (go stx).run #[] `(fun $binders* => $(⟨newStx⟩)) else pure none where /-- Auxiliary function for expanding the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ go : Syntax → StateT (Array Ident) MacroM Syntax | stx@`(($(_))) => pure stx | stx@`(·) => withFreshMacroScope do let id ← mkFreshIdent stx (canonical := true) modify (·.push id) pure id | stx => match stx with | .node _ k args => do let args ← args.mapM go return .node (.fromRef stx (canonical := true)) k args | _ => pure stx /-- Helper method for elaborating terms such as `(.+.)` where a constant name is expected. This method is usually used to implement tactics that function names as arguments (e.g., `simp`). -/ def elabCDotFunctionAlias? (stx : Term) : TermElabM (Option Expr) := do let some stx ← liftMacroM <| expandCDotArg? stx | pure none let stx ← liftMacroM <| expandMacros stx match stx with | `(fun $binders* => $f $args*) => if binders == args then try Term.resolveId? f catch _ => return none else return none | `(fun $binders* => binop% $f $a $b) => if binders == #[a, b] then try Term.resolveId? f catch _ => return none else return none | _ => return none where expandCDotArg? (stx : Term) : MacroM (Option Term) := match stx with | `(($e)) => Term.expandCDot? e | _ => Term.expandCDot? stx @[builtin_macro Lean.Parser.Term.paren] def expandParen : Macro | `(($e)) => return (← expandCDot? e).getD e | _ => Macro.throwUnsupported @[builtin_macro Lean.Parser.Term.tuple] def expandTuple : Macro | `(()) => ``(Unit.unit) | `(($e, $es,*)) => do let pairs ← mkPairs (#[e] ++ es) return (← expandCDot? pairs).getD pairs | _ => Macro.throwUnsupported @[builtin_macro Lean.Parser.Term.typeAscription] def expandTypeAscription : Macro | `(($e : $(type)?)) => do match (← expandCDot? e) with | some e => `(($e : $(type)?)) | none => Macro.throwUnsupported | _ => Macro.throwUnsupported @[builtin_term_elab typeAscription] def elabTypeAscription : TermElab | `(($e : $type)), _ => do let type ← withSynthesize (mayPostpone := true) <| elabType type let e ← elabTerm e type ensureHasType type e | `(($e :)), expectedType? => do let e ← withSynthesize (mayPostpone := false) <| elabTerm e none ensureHasType expectedType? e | _, _ => throwUnsupportedSyntax /-- Return `true` if `lhs` is a free variable and `rhs` does not depend on it. -/ private def isSubstCandidate (lhs rhs : Expr) : MetaM Bool := if lhs.isFVar then return !(← dependsOn rhs lhs.fvarId!) else return false /-- Given an expression `e` that is the elaboration of `stx`, if `e` is a free variable, then return `k stx`. Otherwise, return `(fun x => k x) e` -/ private def withLocalIdentFor (stx : Term) (e : Expr) (k : Term → TermElabM Expr) : TermElabM Expr := do if e.isFVar then k stx else let id ← mkFreshUserName `h let aux ← withLocalDeclD id (← inferType e) fun x => do mkLambdaFVars #[x] (← k (mkIdentFrom stx id)) return mkApp aux e @[builtin_term_elab subst] def elabSubst : TermElab := fun stx expectedType? => do let expectedType? ← tryPostponeIfHasMVars? expectedType? match stx with | `($heqStx ▸ $hStx) => do synthesizeSyntheticMVars let mut heq ← withSynthesize <| elabTerm heqStx none let heqType ← inferType heq let heqType ← instantiateMVars heqType match (← Meta.matchEq? heqType) with | none => throwError "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected" | some (α, lhs, rhs) => let mut lhs := lhs let mut rhs := rhs let mkMotive (lhs typeWithLooseBVar : Expr) := do withLocalDeclD (← mkFreshUserName `x) α fun x => do withLocalDeclD (← mkFreshUserName `h) (← mkEq lhs x) fun h => do mkLambdaFVars #[x, h] $ typeWithLooseBVar.instantiate1 x match expectedType? with | some expectedType => let mut expectedAbst ← kabstract expectedType rhs unless expectedAbst.hasLooseBVars do expectedAbst ← kabstract expectedType lhs unless expectedAbst.hasLooseBVars do throwError "invalid `▸` notation, expected result type of cast is {indentExpr expectedType}\nhowever, the equality {indentExpr heq}\nof type {indentExpr heqType}\ndoes not contain the expected result type on either the left or the right hand side" heq ← mkEqSymm heq (lhs, rhs) := (rhs, lhs) let hExpectedType := expectedAbst.instantiate1 lhs let (h, badMotive?) ← withRef hStx do let h ← elabTerm hStx hExpectedType try return (← ensureHasType hExpectedType h, none) catch ex => -- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too let hType ← inferType h let hTypeAbst ← kabstract hType rhs unless hTypeAbst.hasLooseBVars do throw ex let hTypeNew := hTypeAbst.instantiate1 lhs unless (← isDefEq hExpectedType hTypeNew) do throw ex let motive ← mkMotive rhs hTypeAbst if !(← isTypeCorrect motive) then return (h, some motive) else return (← mkEqRec motive h (← mkEqSymm heq), none) let motive ← mkMotive lhs expectedAbst if badMotive?.isSome || !(← isTypeCorrect motive) then -- Before failing try tos use `subst` if ← (isSubstCandidate lhs rhs <||> isSubstCandidate rhs lhs) then withLocalIdentFor heqStx heq fun heqStx => do let h ← instantiateMVars h if h.hasMVar then -- If `h` has metavariables, we try to elaborate `hStx` again after we substitute `heqStx` -- Remark: re-elaborating `hStx` may be problematic if `hStx` contains the `lhs` of `heqStx` which will be eliminated by `subst` let stxNew ← `(by subst $heqStx; exact $hStx) withMacroExpansion stx stxNew (elabTerm stxNew expectedType) else withLocalIdentFor hStx h fun hStx => do let stxNew ← `(by subst $heqStx; exact $hStx) withMacroExpansion stx stxNew (elabTerm stxNew expectedType) else throwError "invalid `▸` notation, failed to compute motive for the substitution" else mkEqRec motive h heq | none => let h ← elabTerm hStx none let hType ← inferType h let hTypeAbst ← kabstract hType lhs let motive ← mkMotive lhs hTypeAbst unless (← isTypeCorrect motive) do throwError "invalid `▸` notation, failed to compute motive for the substitution" mkEqRec motive h heq | _ => throwUnsupportedSyntax @[builtin_term_elab stateRefT] def elabStateRefT : TermElab := fun stx _ => do let σ ← elabType stx[1] let mut mStx := stx[2] if mStx.getKind == ``Lean.Parser.Term.macroDollarArg then mStx := mStx[1] let m ← elabTerm mStx (← mkArrow (mkSort levelOne) (mkSort levelOne)) let ω ← mkFreshExprMVar (mkSort levelOne) let stWorld ← mkAppM ``STWorld #[ω, m] discard <| mkInstMVar stWorld mkAppM ``StateRefT' #[ω, σ, m] @[builtin_term_elab noindex] def elabNoindex : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return DiscrTree.mkNoindexAnnotation e end Lean.Elab.Term
65b871ed1835251361a6a875f2e7741b3d2d3978
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/e14.lean
a9aae9ac95cc9dbb9037e847fb1d488fe7183ecb
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
858
lean
inductive nat : Type := zero : nat, succ : nat → nat namespace nat end nat open nat inductive list (A : Type) : Type := nil {} : list A, cons : A → list A → list A definition nil := @list.nil definition cons := @list.cons check nil check nil.{1} check @nil.{1} nat check @nil nat check cons nat.zero nil inductive vector (A : Type) : nat → Type := vnil {} : vector A zero, vcons : forall {n : nat}, A → vector A n → vector A (succ n) namespace vector end vector open vector check vcons zero vnil constant n : nat check vcons n vnil check vector.rec definition vector_to_list {A : Type} {n : nat} (v : vector A n) : list A := vector.rec (@nil A) (fun (n : nat) (a : A) (v : vector A n) (l : list A), cons a l) v coercion vector_to_list constant f : forall {A : Type}, list A → nat check f (cons zero nil) check f (vcons zero vnil)
2bc1f97e016bde595418cafb7bca2064fb0e305a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/UnificationHint.lean
9c3957537f71ece43fc589fa8d070252cf2ec210
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
5,268
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.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.DiscrTree import Lean.Meta.SynthInstance namespace Lean.Meta structure UnificationHintEntry where keys : Array DiscrTree.Key val : Name deriving Inhabited structure UnificationHints where discrTree : DiscrTree Name := DiscrTree.empty deriving Inhabited instance : ToFormat UnificationHints where format h := format h.discrTree def UnificationHints.add (hints : UnificationHints) (e : UnificationHintEntry) : UnificationHints := { hints with discrTree := hints.discrTree.insertCore e.keys e.val } builtin_initialize unificationHintExtension : SimpleScopedEnvExtension UnificationHintEntry UnificationHints ← registerSimpleScopedEnvExtension { name := `unifHints addEntry := UnificationHints.add initial := {} } structure UnificationConstraint where lhs : Expr rhs : Expr structure UnificationHint where pattern : UnificationConstraint constraints : List UnificationConstraint private partial def decodeUnificationHint (e : Expr) : ExceptT MessageData Id UnificationHint := do decode e #[] where decodeConstraint (e : Expr) : ExceptT MessageData Id UnificationConstraint := match e.eq? with | some (_, lhs, rhs) => return UnificationConstraint.mk lhs rhs | none => throw m!"invalid unification hint constraint, unexpected term{indentExpr e}" decode (e : Expr) (cs : Array UnificationConstraint) : ExceptT MessageData Id UnificationHint := do match e with | Expr.forallE _ d b _ => do let c ← decodeConstraint d if b.hasLooseBVars then throw m!"invalid unification hint constraint, unexpected dependency{indentExpr e}" decode b (cs.push c) | _ => do let p ← decodeConstraint e return { pattern := p, constraints := cs.toList } private partial def validateHint (hint : UnificationHint) : MetaM Unit := do hint.constraints.forM fun c => do unless (← isDefEq c.lhs c.rhs) do throwError "invalid unification hint, failed to unify constraint left-hand-side{indentExpr c.lhs}\nwith right-hand-side{indentExpr c.rhs}" unless (← isDefEq hint.pattern.lhs hint.pattern.rhs) do throwError "invalid unification hint, failed to unify pattern left-hand-side{indentExpr hint.pattern.lhs}\nwith right-hand-side{indentExpr hint.pattern.rhs}" def addUnificationHint (declName : Name) (kind : AttributeKind) : MetaM Unit := withNewMCtxDepth do let info ← getConstInfo declName match info.value? with | none => throwError "invalid unification hint, it must be a definition" | some val => let (_, _, body) ← lambdaMetaTelescope val match decodeUnificationHint body with | Except.error msg => throwError msg | Except.ok hint => let keys ← DiscrTree.mkPath hint.pattern.lhs validateHint hint unificationHintExtension.add { keys := keys, val := declName } kind builtin_initialize registerBuiltinAttribute { name := `unificationHint descr := "unification hint" add := fun declName stx kind => do Attribute.Builtin.ensureNoArgs stx discard <| addUnificationHint declName kind |>.run } def tryUnificationHints (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.hint] "{t} =?= {s}" unless (← read).config.unificationHints do return false if t.isMVar then return false let hints := unificationHintExtension.getState (← getEnv) let candidates ← hints.discrTree.getMatch t for candidate in candidates do if (← tryCandidate candidate) then return true return false where isDefEqPattern p e := withReducible <| Meta.isExprDefEqAux p e tryCandidate candidate : MetaM Bool := withTraceNode `Meta.isDefEq.hint (return m!"{exceptBoolEmoji ·} hint {candidate} at {t} =?= {s}") do checkpointDefEq do let cinfo ← getConstInfo candidate let us ← cinfo.levelParams.mapM fun _ => mkFreshLevelMVar let val ← instantiateValueLevelParams cinfo us let (xs, bis, body) ← lambdaMetaTelescope val let hint? ← withConfig (fun cfg => { cfg with unificationHints := false }) do match decodeUnificationHint body with | Except.error _ => return none | Except.ok hint => if (← isDefEqPattern hint.pattern.lhs t <&&> isDefEqPattern hint.pattern.rhs s) then return some hint else return none match hint? with | none => return false | some hint => trace[Meta.isDefEq.hint] "{candidate} succeeded, applying constraints" for c in hint.constraints do unless (← Meta.isExprDefEqAux c.lhs c.rhs) do return false for x in xs, bi in bis do if bi == BinderInfo.instImplicit then match (← trySynthInstance (← inferType x)) with | LOption.some val => unless (← isDefEq x val) do return false | _ => return false return true builtin_initialize registerTraceClass `Meta.isDefEq.hint end Lean.Meta
6dede9290466e20602695c52567c590700a599c7
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/data/real/hyperreal.lean
2c6d9f50e5c242b1428fa46baf0376a178b537da
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
36,498
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir Construction of the hyperreal numbers as an ultraproduct of real sequences. -/ import data.real.basic algebra.field order.filter.filter_product analysis.specific_limits open filter filter.filter_product open_locale topological_space classical /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ @[reducible] def hyperreal := filter.filterprod ℝ (@hyperfilter ℕ) namespace hyperreal notation `ℝ*` := hyperreal private def U : is_ultrafilter (@hyperfilter ℕ) := is_ultrafilter_hyperfilter noncomputable instance : discrete_linear_ordered_field ℝ* := filter_product.discrete_linear_ordered_field U /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := of_seq (λ n, n⁻¹) /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := of_seq (λ n, n) localized "notation `ε` := hyperreal.epsilon" in hyperreal localized "notation `ω` := hyperreal.omega" in hyperreal lemma epsilon_eq_inv_omega : ε = ω⁻¹ := rfl lemma inv_epsilon_eq_omega : ε⁻¹ = ω := inv_inv' ω lemma epsilon_pos : 0 < ε := have h0' : {n : ℕ | ¬ n > 0} = {0} := by simp only [not_lt, (set.set_of_eq_eq_singleton).symm]; ext; exact nat.le_zero_iff, begin rw lt_def U, show {i : ℕ | (0 : ℝ) < i⁻¹} ∈ hyperfilter.sets, simp only [inv_pos', nat.cast_pos], exact mem_hyperfilter_of_finite_compl (by convert set.finite_singleton _), end lemma epsilon_ne_zero : ε ≠ 0 := ne_of_gt epsilon_pos lemma omega_pos : 0 < ω := by rw ←inv_epsilon_eq_omega; exact inv_pos epsilon_pos lemma omega_ne_zero : ω ≠ 0 := ne_of_gt omega_pos theorem epsilon_mul_omega : ε * ω = 1 := @inv_mul_cancel _ _ ω omega_ne_zero lemma lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r > 0 → of_seq f < (r : ℝ*) := begin simp only [metric.tendsto_at_top, dist_zero_right, norm, lt_def U] at hf ⊢, intros r hr, cases hf r hr with N hf', have hs : -{i : ℕ | f i < r} ⊆ {i : ℕ | i ≤ N} := λ i hi1, le_of_lt (by simp only [lt_iff_not_ge]; exact λ hi2, hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N), exact mem_hyperfilter_of_finite_compl (set.finite_subset (set.finite_le_nat N) hs) end lemma neg_lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r > 0 → (-r : ℝ*) < of_seq f := λ r hr, have hg : _ := hf.neg, neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr) lemma gt_of_tendsto_zero_of_neg {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r < 0 → (r : ℝ*) < of_seq f := λ r hr, by rw [←of_eq_coe, ←neg_neg r, of_neg]; exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) lemma epsilon_lt_pos (x : ℝ) : x > 0 → ε < of x := lt_of_tendsto_zero_of_pos tendsto_inverse_at_top_nhds_0_nat /-- Standard part predicate -/ def is_st (x : ℝ*) (r : ℝ) := ∀ δ : ℝ, δ > 0 → (r - δ : ℝ*) < x ∧ x < r + δ /-- Standard part function: like a "round" to ℝ instead of ℤ -/ noncomputable def st : ℝ* → ℝ := λ x, if h : ∃ r, is_st x r then classical.some h else 0 /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def infinitesimal (x : ℝ*) := is_st x 0 /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def infinite_pos (x : ℝ*) := ∀ r : ℝ, x > r /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def infinite_neg (x : ℝ*) := ∀ r : ℝ, x < r /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def infinite (x : ℝ*) := infinite_pos x ∨ infinite_neg x -- SOME FACTS ABOUT ST private lemma is_st_unique' (x : ℝ*) (r s : ℝ) (hr : is_st x r) (hs : is_st x s) (hrs : r < s) : false := have hrs' : _ := half_pos $ sub_pos_of_lt hrs, have hr' : _ := (hr _ hrs').2, have hs' : _ := (hs _ hrs').1, have h : s + -((s - r) / 2) = r + (s - r) / 2 := by linarith, by simp only [(of_eq_coe _).symm, sub_eq_add_neg (of s), (of_neg _).symm, (of_add _ _).symm, h] at hr' hs'; exact not_lt_of_lt hs' hr' theorem is_st_unique {x : ℝ*} {r s : ℝ} (hr : is_st x r) (hs : is_st x s) : r = s := begin rcases lt_trichotomy r s with h | h | h, { exact false.elim (is_st_unique' x r s hr hs h) }, { exact h }, { exact false.elim (is_st_unique' x s r hs hr h) } end theorem not_infinite_of_exists_st {x : ℝ*} : (∃ r : ℝ, is_st x r) → ¬ infinite x := λ he hi, Exists.dcases_on he $ λ r hr, hi.elim (λ hip, not_lt_of_lt (hr 2 two_pos).2 (hip $ r + 2)) (λ hin, not_lt_of_lt (hr 2 two_pos).1 (hin $ r - 2)) theorem is_st_Sup {x : ℝ*} (hni : ¬ infinite x) : is_st x (real.Sup {y : ℝ | of y < x}) := let S : set ℝ := {y : ℝ | of y < x} in let R : _ := real.Sup S in have hnile : _ := not_forall.mp (not_or_distrib.mp hni).1, have hnige : _ := not_forall.mp (not_or_distrib.mp hni).2, Exists.dcases_on hnile $ Exists.dcases_on hnige $ λ r₁ hr₁ r₂ hr₂, have HR₁ : ∃ y : ℝ, y ∈ S := ⟨ r₁ - 1, lt_of_lt_of_le (of_lt_of_lt U (sub_one_lt _)) (not_lt.mp hr₁) ⟩, have HR₂ : ∃ z : ℝ, ∀ y ∈ S, y ≤ z := ⟨ r₂, λ y hy, le_of_lt ((of_lt U).mpr (lt_of_lt_of_le hy (not_lt.mp hr₂))) ⟩, λ δ hδ, ⟨ lt_of_not_ge' $ λ c, have hc : ∀ y ∈ S, y ≤ R - δ := λ y hy, (of_le U.1).mpr $ le_of_lt $ lt_of_lt_of_le hy c, not_lt_of_le ((real.Sup_le _ HR₁ HR₂).mpr hc) $ sub_lt_self R hδ, lt_of_not_ge' $ λ c, have hc : of (R + δ / 2) < x := lt_of_lt_of_le (add_lt_add_left (of_lt_of_lt U (half_lt_self hδ)) (of R)) c, not_lt_of_le (real.le_Sup _ HR₂ hc) $ (lt_add_iff_pos_right _).mpr $ half_pos hδ⟩ theorem exists_st_of_not_infinite {x : ℝ*} (hni : ¬ infinite x) : ∃ r : ℝ, is_st x r := ⟨ real.Sup {y : ℝ | of y < x}, is_st_Sup hni ⟩ theorem st_eq_Sup {x : ℝ*} : st x = real.Sup {y : ℝ | of y < x} := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) (is_st_Sup (not_infinite_of_exists_st h)) }, { cases not_imp_comm.mp exists_st_of_not_infinite h with H H, { rw (set.ext (λ i, ⟨λ hi, set.mem_univ i, λ hi, H i⟩) : {y : ℝ | of y < x} = set.univ), exact (real.Sup_univ).symm }, { rw (set.ext (λ i, ⟨λ hi, false.elim (not_lt_of_lt (H i) hi), λ hi, false.elim (set.not_mem_empty i hi)⟩) : {y : ℝ | of y < x} = ∅), exact (real.Sup_empty).symm } } end theorem exists_st_iff_not_infinite {x : ℝ*} : (∃ r : ℝ, is_st x r) ↔ ¬ infinite x := ⟨ not_infinite_of_exists_st, exists_st_of_not_infinite ⟩ theorem infinite_iff_not_exists_st {x : ℝ*} : infinite x ↔ ¬ ∃ r : ℝ, is_st x r := iff_not_comm.mp exists_st_iff_not_infinite theorem st_infinite {x : ℝ*} (hi : infinite x) : st x = 0 := begin unfold st, split_ifs, { exact false.elim ((infinite_iff_not_exists_st.mp hi) h) }, { refl } end lemma st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : st x = r := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) hxr }, { exact false.elim (h ⟨r, hxr⟩) } end lemma is_st_st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st x (st x) := by rwa [st_of_is_st hxr] lemma is_st_st_of_exists_st {x : ℝ*} (hx : ∃ r : ℝ, is_st x r) : is_st x (st x) := Exists.dcases_on hx (λ r, is_st_st_of_is_st) lemma is_st_st {x : ℝ*} (hx : st x ≠ 0) : is_st x (st x) := begin unfold st, split_ifs, { exact classical.some_spec h }, { exact false.elim (hx (by unfold st; split_ifs; refl)) } end lemma is_st_st' {x : ℝ*} (hx : ¬ infinite x) : is_st x (st x) := is_st_st_of_exists_st $ exists_st_of_not_infinite hx lemma is_st_refl_real (r : ℝ) : is_st r r := λ δ hδ, ⟨ sub_lt_self _ (of_lt_of_lt U hδ), (lt_add_of_pos_right _ (of_lt_of_lt U hδ)) ⟩ lemma st_id_real (r : ℝ) : st r = r := st_of_is_st (is_st_refl_real r) lemma eq_of_is_st_real {r s : ℝ} : is_st r s → r = s := is_st_unique (is_st_refl_real r) lemma is_st_real_iff_eq {r s : ℝ} : is_st r s ↔ r = s := ⟨eq_of_is_st_real, λ hrs, by rw [hrs]; exact is_st_refl_real s⟩ lemma is_st_symm_real {r s : ℝ} : is_st r s ↔ is_st s r := by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm] lemma is_st_trans_real {r s t : ℝ} : is_st r s → is_st s t → is_st r t := by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq]; exact eq.trans lemma is_st_inj_real {r₁ r₂ s : ℝ} (h1 : is_st r₁ s) (h2 : is_st r₂ s) : r₁ = r₂ := eq.trans (eq_of_is_st_real h1) (eq_of_is_st_real h2).symm lemma is_st_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : is_st x r ↔ ∀ (δ : ℝ), δ > 0 → abs (x - r) < δ := by simp only [abs_sub_lt_iff, @sub_lt _ _ (r : ℝ*) x _, @sub_lt_iff_lt_add' _ _ x (r : ℝ*) _, and_comm]; refl lemma is_st_add {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x + y) (r + s) := λ hxr hys d hd, have hxr' : _ := hxr (d / 2) (half_pos hd), have hys' : _ := hys (d / 2) (half_pos hd), by rw [←of_eq_coe, ←of_eq_coe, ←add_halves d, of_add, of_add, add_sub_comm, norm_num.add_comm_middle, ←add_assoc, add_assoc _ _ (of s), add_comm _ (of s)]; exact ⟨ add_lt_add hxr'.1 hys'.1, add_lt_add hxr'.2 hys'.2 ⟩ lemma is_st_neg {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st (-x) (-r) := λ d hd, by show -(r : ℝ*) - d < -x ∧ -x < -r + d; cases (hxr d hd); split; linarith lemma is_st_sub {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x - y) (r - s) := λ hxr hys, by rw [sub_eq_add_neg, sub_eq_add_neg]; exact is_st_add hxr (is_st_neg hys) /- (st x < st y) → (x < y) → (x ≤ y) → (st x ≤ st y) -/ lemma lt_of_is_st_lt {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : r < s → x < y := λ hrs, have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs), have hxr' : _ := (hxr _ hrs').2, have hys' : _ := (hys _ hrs').1, have H1 : r + ((s - r) / 2) = (r + s) / 2 := by linarith, have H2 : s - ((s - r) / 2) = (r + s) / 2 := by linarith, by simp only [(of_eq_coe _).symm, (of_add _ _).symm, (of_sub _ _).symm, H1, H2] at hxr' hys'; exact lt_trans hxr' hys' lemma is_st_le_of_le {x y : ℝ*} {r s : ℝ} (hrx : is_st x r) (hsy : is_st y s) : x ≤ y → r ≤ s := by rw [←not_lt, ←not_lt, not_imp_not]; exact lt_of_is_st_lt hsy hrx lemma st_le_of_le {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : x ≤ y → st x ≤ st y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, is_st_le_of_le hx' hy' lemma lt_of_st_lt {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : st x < st y → x < y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, lt_of_is_st_lt hx' hy' -- BASIC LEMMAS ABOUT INFINITE lemma infinite_pos_def {x : ℝ*} : infinite_pos x ↔ ∀ r : ℝ, x > r := by rw iff_eq_eq; refl lemma infinite_neg_def {x : ℝ*} : infinite_neg x ↔ ∀ r : ℝ, x < r := by rw iff_eq_eq; refl lemma ne_zero_of_infinite {x : ℝ*} : infinite x → x ≠ 0 := λ hI h0, or.cases_on hI (λ hip, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_pos 0) 0)) (λ hin, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_neg 0) 0)) lemma not_infinite_zero : ¬ infinite 0 := λ hI, ne_zero_of_infinite hI rfl lemma pos_of_infinite_pos {x : ℝ*} : infinite_pos x → x > 0 := λ hip, hip 0 lemma neg_of_infinite_neg {x : ℝ*} : infinite_neg x → x < 0 := λ hin, hin 0 lemma not_infinite_pos_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinite_pos x := λ hn hp, not_lt_of_lt (hn 1) (hp 1) lemma not_infinite_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinite_neg x := imp_not_comm.mp not_infinite_pos_of_infinite_neg lemma infinite_neg_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → infinite_neg (-x) := λ hp r, neg_lt.mp (hp (-r)) lemma infinite_pos_neg_of_infinite_neg {x : ℝ*} : infinite_neg x → infinite_pos (-x) := λ hp r, lt_neg.mp (hp (-r)) lemma infinite_pos_iff_infinite_neg_neg {x : ℝ*} : infinite_pos x ↔ infinite_neg (-x) := ⟨ infinite_neg_neg_of_infinite_pos, λ hin, neg_neg x ▸ infinite_pos_neg_of_infinite_neg hin ⟩ lemma infinite_neg_iff_infinite_pos_neg {x : ℝ*} : infinite_neg x ↔ infinite_pos (-x) := ⟨ infinite_pos_neg_of_infinite_neg, λ hin, neg_neg x ▸ infinite_neg_neg_of_infinite_pos hin ⟩ lemma infinite_iff_infinite_neg {x : ℝ*} : infinite x ↔ infinite (-x) := ⟨ λ hi, or.cases_on hi (λ hip, or.inr (infinite_neg_neg_of_infinite_pos hip)) (λ hin, or.inl (infinite_pos_neg_of_infinite_neg hin)), λ hi, or.cases_on hi (λ hipn, or.inr (infinite_neg_iff_infinite_pos_neg.mpr hipn)) (λ hinp, or.inl (infinite_pos_iff_infinite_neg_neg.mpr hinp))⟩ lemma not_infinite_of_infinitesimal {x : ℝ*} : infinitesimal x → ¬ infinite x := λ hi hI, have hi' : _ := (hi 2 two_pos), or.dcases_on hI (λ hip, have hip' : _ := hip 2, not_lt_of_lt hip' (by convert hi'.2; exact (zero_add 2).symm)) (λ hin, have hin' : _ := hin (-2), not_lt_of_lt hin' (by convert hi'.1; exact (zero_sub 2).symm)) lemma not_infinitesimal_of_infinite {x : ℝ*} : infinite x → ¬ infinitesimal x := imp_not_comm.mp not_infinite_of_infinitesimal lemma not_infinitesimal_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinitesimal x := λ hp, not_infinitesimal_of_infinite (or.inl hp) lemma not_infinitesimal_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinitesimal x := λ hn, not_infinitesimal_of_infinite (or.inr hn) lemma infinite_pos_iff_infinite_and_pos {x : ℝ*} : infinite_pos x ↔ (infinite x ∧ x > 0) := ⟨ λ hip, ⟨or.inl hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hip, hip) (λ hin, false.elim (not_lt_of_lt hp (hin 0))) ⟩ lemma infinite_neg_iff_infinite_and_neg {x : ℝ*} : infinite_neg x ↔ (infinite x ∧ x < 0) := ⟨ λ hip, ⟨or.inr hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hin, false.elim (not_lt_of_lt hp (hin 0))) (λ hip, hip) ⟩ lemma infinite_pos_iff_infinite_of_pos {x : ℝ*} (hp : x > 0) : infinite_pos x ↔ infinite x := by rw [infinite_pos_iff_infinite_and_pos]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hp⟩⟩ lemma infinite_pos_iff_infinite_of_nonneg {x : ℝ*} (hp : x ≥ 0) : infinite_pos x ↔ infinite x := or.cases_on (lt_or_eq_of_le hp) (infinite_pos_iff_infinite_of_pos) (λ h, by rw h.symm; exact ⟨λ hIP, false.elim (not_infinite_zero (or.inl hIP)), λ hI, false.elim (not_infinite_zero hI)⟩) lemma infinite_neg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : infinite_neg x ↔ infinite x := by rw [infinite_neg_iff_infinite_and_neg]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hn⟩⟩ lemma infinite_pos_abs_iff_infinite_abs {x : ℝ*} : infinite_pos (abs x) ↔ infinite (abs x) := infinite_pos_iff_infinite_of_nonneg (abs_nonneg _) lemma infinite_iff_infinite_pos_abs {x : ℝ*} : infinite x ↔ infinite_pos (abs x) := ⟨ λ hi d, or.cases_on hi (λ hip, by rw [abs_of_pos (hip 0)]; exact hip d) (λ hin, by rw [abs_of_neg (hin 0)]; exact lt_neg.mp (hin (-d))), λ hipa, by { rcases (lt_trichotomy x 0) with h | h | h, { exact or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa abs_of_neg h at hipa)) }, { exact false.elim (ne_zero_of_infinite (or.inl (by rw [h]; rwa [h, abs_zero] at hipa)) h) }, { exact or.inl (by rwa abs_of_pos h at hipa) } } ⟩ lemma infinite_iff_infinite_abs {x : ℝ*} : infinite x ↔ infinite (abs x) := by rw [←infinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs] lemma infinite_iff_abs_lt_abs {x : ℝ*} : infinite x ↔ ∀ r : ℝ, (abs r : ℝ*) < abs x := ⟨ λ hI r, (of_abs U r) ▸ infinite_iff_infinite_pos_abs.mp hI (abs r), λ hR, or.cases_on (max_choice x (-x)) (λ h, or.inl $ λ r, lt_of_le_of_lt (le_abs_self _) (h ▸ (hR r))) (λ h, or.inr $ λ r, neg_lt_neg_iff.mp $ lt_of_le_of_lt (neg_le_abs_self _) (h ▸ (hR r)))⟩ lemma infinite_pos_add_not_infinite_neg {x y : ℝ*} : infinite_pos x → ¬ infinite_neg y → infinite_pos (x + y) := begin intros hip hnin r, cases not_forall.mp hnin with r₂ hr₂, convert (add_lt_add_of_lt_of_le (hip (r + -r₂)) (not_lt.mp hr₂)), rw [←of_eq_coe, ←of_eq_coe, ←of_eq_coe, of_add, of_neg, ←sub_eq_add_neg, sub_add_cancel] end lemma not_infinite_neg_add_infinite_pos {x y : ℝ*} : ¬ infinite_neg x → infinite_pos y → infinite_pos (x + y) := λ hx hy, by rw [add_comm]; exact infinite_pos_add_not_infinite_neg hy hx lemma infinite_neg_add_not_infinite_pos {x y : ℝ*} : infinite_neg x → ¬ infinite_pos y → infinite_neg (x + y) := by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y, @infinite_neg_iff_infinite_pos_neg (x + y), neg_add]; exact infinite_pos_add_not_infinite_neg lemma not_infinite_pos_add_infinite_neg {x y : ℝ*} : ¬ infinite_pos x → infinite_neg y → infinite_neg (x + y) := λ hx hy, by rw [add_comm]; exact infinite_neg_add_not_infinite_pos hy hx lemma infinite_pos_add_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_infinite_neg_of_infinite_pos hy) lemma infinite_neg_add_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_infinite_pos_of_infinite_neg hy) lemma infinite_pos_add_not_infinite {x y : ℝ*} : infinite_pos x → ¬ infinite y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_or_distrib.mp hy).2 lemma infinite_neg_add_not_infinite {x y : ℝ*} : infinite_neg x → ¬ infinite y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_or_distrib.mp hy).1 theorem infinite_pos_of_tendsto_top {f : ℕ → ℝ} (hf : tendsto f at_top at_top) : infinite_pos (of_seq f) := λ r, have hf' : _ := (tendsto_at_top_at_top _).mp hf, Exists.cases_on (hf' (r + 1)) $ λ i hi, have hi' : ∀ (a : ℕ), f a < (r + 1) → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : - {a : ℕ | r < f a} ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))), (lt_def U).mpr $ mem_hyperfilter_of_finite_compl $ set.finite_subset (set.finite_le_nat _) hS theorem infinite_neg_of_tendsto_bot {f : ℕ → ℝ} (hf : tendsto f at_top at_bot) : infinite_neg (of_seq f) := λ r, have hf' : _ := (tendsto_at_top_at_bot _).mp hf, Exists.cases_on (hf' (r - 1)) $ λ i hi, have hi' : ∀ (a : ℕ), r - 1 < f a → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : - {a : ℕ | f a < r} ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)), (lt_def U).mpr $ mem_hyperfilter_of_finite_compl $ set.finite_subset (set.finite_le_nat _) hS lemma not_infinite_neg {x : ℝ*} : ¬ infinite x → ¬ infinite (-x) := not_imp_not.mpr infinite_iff_infinite_neg.mpr lemma not_infinite_add {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x + y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s + r, is_st_add hs hr⟩ theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : ¬ infinite x ↔ ∃ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨ λ hni, Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).1) $ Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).2) $ λ r hr s hs, by rw [not_lt] at hr hs; exact ⟨r - 1, s + 1, ⟨ lt_of_lt_of_le (by rw [←of_eq_coe, of_sub]; exact sub_one_lt _) hr, lt_of_le_of_lt hs (by rw [←of_eq_coe (s + 1), of_add]; exact lt_add_one _)⟩ ⟩, λ hrs, Exists.dcases_on hrs $ λ r hr, Exists.dcases_on hr $ λ s hs, not_or_distrib.mpr ⟨not_forall.mpr ⟨s, lt_asymm (hs.2)⟩, not_forall.mpr ⟨r, lt_asymm (hs.1) ⟩⟩⟩ theorem not_infinite_real (r : ℝ) : ¬ infinite r := by rw not_infinite_iff_exist_lt_gt; exact ⟨ r - 1, r + 1, by rw [←of_eq_coe, ←of_eq_coe, ←of_lt U]; exact sub_one_lt _, by rw [←of_eq_coe, ←of_eq_coe, ←of_lt U]; exact lt_add_one _⟩ theorem not_real_of_infinite {x : ℝ*} : infinite x → ∀ r : ℝ, x ≠ of r := λ hi r hr, not_infinite_real r $ @eq.subst _ infinite _ _ hr hi -- FACTS ABOUT ST THAT REQUIRE SOME INFINITE MACHINERY private lemma is_st_mul' {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) (hs : s ≠ 0) : is_st (x * y) (r * s) := have hxr' : _ := is_st_iff_abs_sub_lt_delta.mp hxr, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys, have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, is_st_iff_abs_sub_lt_delta.mpr $ λ d hd, calc abs (x * y - of (r * s)) = abs (x * y - (of r) * (of s)) : by rw of_mul ... = abs (x * (y - of s) + (x - of r) * (of s)) : by rw [mul_sub, sub_mul, add_sub, sub_add_cancel] ... ≤ abs (x * (y - of s)) + abs ((x - of r) * (of s)) : abs_add _ _ ... ≤ abs x * abs (y - of s) + abs (x - of r) * abs (of s) : by simp only [abs_mul] ... ≤ abs x * of ((d / t) / 2) + of ((d / abs s) / 2) * abs (of s) : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt $ hys' _ $ half_pos $ div_pos hd $ (of_lt U).mpr $ lt_of_le_of_lt (abs_nonneg _) ht) $ abs_nonneg _ ) (mul_le_mul_of_nonneg_right (le_of_lt $ hxr' _ $ half_pos $ div_pos hd $ abs_pos_of_ne_zero hs) $ abs_nonneg _) ... = (of d) / 2 * (abs x / of t) + ((of d) / 2) : by { rw [div_div_eq_div_mul, mul_comm t 2, ←div_div_eq_div_mul, of_div U, div_div_eq_div_mul, mul_comm (abs s) 2, ←div_div_eq_div_mul, mul_div_comm, of_div U, of_div U, of_div U, of_abs U, div_mul_cancel _ (ne_of_gt (abs_pos_of_ne_zero ((of_ne_zero U.1 _).mp hs)))], refl } ... < (of d) / 2 * 1 + ((of d) / 2) : add_lt_add_right (mul_lt_mul_of_pos_left ((div_lt_one_iff_lt $ lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) $ half_pos $ of_lt_of_lt U hd) _ ... = of d : by rw [mul_one, add_halves] lemma is_st_mul {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : is_st (x * y) (r * s) := have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, begin by_cases hs : s = 0, { apply is_st_iff_abs_sub_lt_delta.mpr, intros d hd, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t) (div_pos hd ((of_lt U).mpr (lt_of_le_of_lt (abs_nonneg x) ht))), rw [hs, ←of_eq_coe _, of_zero, sub_zero] at hys', rw [hs, mul_zero, (of_eq_coe _).symm, of_zero, sub_zero, abs_mul, mul_comm, ←div_mul_cancel (d : ℝ*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)), ←of_eq_coe d, ←of_eq_coe t, ←of_div U], exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) }, exact is_st_mul' hxr hys hs, end --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY lemma not_infinite_mul {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x * y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s * r, is_st_mul hs hr⟩ --- lemma st_add {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x + y) = st x + st y := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_add hx hy), have hxy' : _ := is_st_add hx' hy', is_st_unique hxy hxy' lemma st_neg (x : ℝ*) : st (-x) = - st x := if h : infinite x then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero] else is_st_unique (is_st_st' (not_infinite_neg h)) (is_st_neg (is_st_st' h)) lemma st_mul {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x * y) = (st x) * (st y) := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_mul hx hy), have hxy' : _ := is_st_mul hx' hy', is_st_unique hxy hxy' -- BASIC LEMMAS ABOUT INFINITESIMAL theorem infinitesimal_def {x : ℝ*} : infinitesimal x ↔ (∀ r : ℝ, r > 0 → -(r : ℝ*) < x ∧ x < r) := ⟨ λ hi r hr, by { convert (hi r hr), exact (zero_sub (of r)).symm, exact (zero_add (of r)).symm }, λ hi d hd, by { convert (hi d hd), exact zero_sub (of d), exact zero_add (of d) } ⟩ theorem lt_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r > 0 → x < r := λ hi r hr, ((infinitesimal_def.mp hi) r hr).2 theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r > 0 → x > -r := λ hi r hr, ((infinitesimal_def.mp hi) r hr).1 theorem gt_of_neg_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r < 0 → x > r := λ hi r hr, by convert ((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1; exact (neg_neg (of r)).symm theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : infinitesimal x ↔ ∀ r : ℝ, r ≠ 0 → abs x < abs r := ⟨ λ hi r hr, abs_lt.mpr (by rw [←of_eq_coe, ←of_abs U]; exact infinitesimal_def.mp hi (abs r) (abs_pos_of_ne_zero hr)), λ hR, infinitesimal_def.mpr $ λ r hr, abs_lt.mp $ (abs_of_pos $ of_lt_of_lt U hr : abs (r : ℝ*) = r) ▸ hR r $ ne_of_gt hr ⟩ lemma infinitesimal_zero : infinitesimal 0 := is_st_refl_real 0 lemma zero_of_infinitesimal_real {r : ℝ} : infinitesimal r → r = 0 := eq_of_is_st_real lemma zero_iff_infinitesimal_real {r : ℝ} : infinitesimal r ↔ r = 0 := ⟨zero_of_infinitesimal_real, λ hr, by rw hr; exact infinitesimal_zero⟩ lemma infinitesimal_add {x y : ℝ*} : infinitesimal x → infinitesimal y → infinitesimal (x + y) := zero_add 0 ▸ is_st_add lemma infinitesimal_neg {x : ℝ*} : infinitesimal x → infinitesimal (-x) := (neg_zero : -(0 : ℝ) = 0) ▸ is_st_neg lemma infinitesimal_neg_iff {x : ℝ*} : infinitesimal x ↔ infinitesimal (-x) := ⟨infinitesimal_neg, λ h, (neg_neg x) ▸ @infinitesimal_neg (-x) h⟩ lemma infinitesimal_mul {x y : ℝ*} : infinitesimal x → infinitesimal y → infinitesimal (x * y) := zero_mul 0 ▸ is_st_mul theorem infinitesimal_of_tendsto_zero {f : ℕ → ℝ} : tendsto f at_top (𝓝 0) → infinitesimal (of_seq f) := λ hf d hd, by rw [←of_eq_coe, ←of_eq_coe, sub_eq_add_neg, ←of_neg, ←of_add, ←of_add, zero_add, zero_add, of_eq_coe, of_eq_coe]; exact ⟨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hd⟩ theorem infinitesimal_epsilon : infinitesimal ε := infinitesimal_of_tendsto_zero tendsto_inverse_at_top_nhds_0_nat lemma not_real_of_infinitesimal_ne_zero (x : ℝ*) : infinitesimal x → x ≠ 0 → ∀ r : ℝ, x ≠ of r := λ hi hx r hr, hx (is_st_unique (hr.symm ▸ is_st_refl_real r : is_st x r) hi ▸ hr : x = of 0) theorem infinitesimal_sub_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : infinitesimal (x - r) := show is_st (x + -r) 0, by rw ←add_neg_self r; exact is_st_add hxr (is_st_refl_real (-r)) theorem infinitesimal_sub_st {x : ℝ*} (hx : ¬infinite x) : infinitesimal (x - st x) := infinitesimal_sub_is_st $ is_st_st' hx lemma infinite_pos_iff_infinitesimal_inv_pos {x : ℝ*} : infinite_pos x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ > 0) := ⟨ λ hip, ⟨ infinitesimal_def.mpr $ λ r hr, ⟨ lt_trans (of_lt_of_lt U (neg_neg_of_pos hr)) (inv_pos (hip 0)), (inv_lt (of_lt_of_lt U hr) (hip 0)).mp (by convert hip r⁻¹) ⟩, inv_pos $ hip 0 ⟩, λ ⟨hi, hp⟩ r, @classical.by_cases (r = 0) (x > (r : ℝ*)) (λ h, eq.substr h (inv_pos'.mp hp)) $ λ h, lt_of_le_of_lt (of_le_of_le (le_abs_self r)) ((inv_lt_inv (inv_pos'.mp hp) (of_lt_of_lt U (abs_pos_of_ne_zero h))).mp ((infinitesimal_def.mp hi) ((abs r)⁻¹) (inv_pos (abs_pos_of_ne_zero h))).2) ⟩ lemma infinite_neg_iff_infinitesimal_inv_neg {x : ℝ*} : infinite_neg x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ < 0) := ⟨ λ hin, have hin' : _ := infinite_pos_iff_infinitesimal_inv_pos.mp (infinite_pos_neg_of_infinite_neg hin), by rwa [infinitesimal_neg_iff, ←neg_pos, neg_inv (λ h0, lt_irrefl x (by convert hin 0) : x ≠ 0)], λ hin, have h0 : x ≠ 0 := λ h0, (lt_irrefl (0 : ℝ*) (by convert hin.2; rw [h0, inv_zero])), by rwa [←neg_pos, infinitesimal_neg_iff, neg_inv h0, ←infinite_pos_iff_infinitesimal_inv_pos, ←infinite_neg_iff_infinite_pos_neg] at hin ⟩ theorem infinitesimal_inv_of_infinite {x : ℝ*} : infinite x → infinitesimal x⁻¹ := λ hi, or.cases_on hi (λ hip, (infinite_pos_iff_infinitesimal_inv_pos.mp hip).1) (λ hin, (infinite_neg_iff_infinitesimal_inv_neg.mp hin).1) theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) (hi : infinitesimal x⁻¹ ) : infinite x := begin cases (lt_or_gt_of_ne h0) with hn hp, { exact or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_neg'.mpr hn⟩) }, { exact or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos'.mpr hp⟩) } end theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) : infinite x ↔ infinitesimal x⁻¹ := ⟨ infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0 ⟩ lemma infinitesimal_pos_iff_infinite_pos_inv {x : ℝ*} : infinite_pos x⁻¹ ↔ (infinitesimal x ∧ x > 0) := begin convert infinite_pos_iff_infinitesimal_inv_pos, all_goals { by_cases h : x = 0, rw [h, inv_zero, inv_zero], exact (division_ring.inv_inv $ show x ≠ 0, from h).symm } end lemma infinitesimal_neg_iff_infinite_neg_inv {x : ℝ*} : infinite_neg x⁻¹ ↔ (infinitesimal x ∧ x < 0) := begin convert infinite_neg_iff_infinitesimal_inv_neg, all_goals { by_cases h : x = 0, rw [h, inv_zero, inv_zero], exact (division_ring.inv_inv $ show x ≠ 0, from h).symm } end theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x ≠ 0) : infinitesimal x ↔ infinite x⁻¹ := begin convert (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm, exact (division_ring.inv_inv h).symm end -- ST STUFF THAT REQUIRES INFINITESIMAL MACHINERY theorem is_st_of_tendsto {f : ℕ → ℝ} {r : ℝ} (hf : tendsto f at_top (𝓝 r)) : is_st (of_seq f) r := have hg : tendsto (λ n, f n - r) at_top (𝓝 0) := (sub_self r) ▸ (hf.sub tendsto_const_nhds), by rw [←(zero_add r), ←(sub_add_cancel f (λ n, r))]; exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r) lemma is_st_inv {x : ℝ*} {r : ℝ} (hi : ¬ infinitesimal x) : is_st x r → is_st x⁻¹ r⁻¹ := λ hxr, have h : x ≠ 0 := (λ h, hi (h.symm ▸ infinitesimal_zero)), have H : _ := exists_st_of_not_infinite $ not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi, Exists.cases_on H $ λ s hs, have H' : is_st 1 (r * s) := mul_inv_cancel h ▸ is_st_mul hxr hs, have H'' : s = r⁻¹ := one_div_eq_inv r ▸ eq_one_div_of_mul_eq_one (eq_of_is_st_real H').symm, H'' ▸ hs lemma st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := begin by_cases h0 : x = 0, rw [h0, inv_zero, ←of_zero, of_eq_coe, st_id_real, inv_zero], by_cases h1 : infinitesimal x, rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero], by_cases h2 : infinite x, rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero], exact st_of_is_st (is_st_inv h1 (is_st_st' h2)), end -- INFINITE STUFF THAT REQUIRES INFINITESIMAL MACHINERY lemma infinite_pos_omega : infinite_pos ω := infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ lemma infinite_omega : infinite ω := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon lemma infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → y > 0 → infinite_pos (x * y) := λ hx hy₁ hy₂ r, have hy₁' : _ := not_forall.mp (by rw infinitesimal_def at hy₁; exact hy₁), Exists.dcases_on hy₁' $ λ r₁ hy₁'', have hyr : _ := by rw [not_imp, ←abs_lt, not_lt, abs_of_pos hy₂] at hy₁''; exact hy₁'', by rw [←div_mul_cancel r (ne_of_gt hyr.1), ←of_eq_coe, of_mul]; exact mul_lt_mul (hx (r / r₁)) hyr.2 (of_lt_of_lt U hyr.1) (le_of_lt (hx 0)) lemma infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_pos y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → y < 0 → infinite_pos (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, ←neg_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_neg y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → y < 0 → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_pos y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → 0 < y → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → x > 0 → infinite_neg y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_neg_mul_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_pos_mul_infinite_neg {x y : ℝ*} : infinite_pos x → infinite_neg y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_neg_mul_infinite_pos {x y : ℝ*} : infinite_neg x → infinite_pos y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : infinite x → ¬ infinitesimal y → infinite (x * y) := λ hx hy, have h0 : y < 0 ∨ y > 0 := lt_or_gt_of_ne (λ H0, hy (eq.substr H0 (is_st_refl_real 0))), or.dcases_on hx (or.dcases_on h0 (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hx hy H0))) (or.dcases_on h0 (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hx hy H0))) lemma infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : ¬ infinitesimal x → infinite y → infinite (x * y) := λ hx hy, by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx lemma infinite_mul_infinite {x y : ℝ*} : infinite x → infinite y → infinite (x * y) := λ hx hy, infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy) end hyperreal
b72f0e3efe89edf6af0ce94b6691c88a9dfc0922
e0b0b1648286e442507eb62344760d5cd8d13f2d
/stage0/src/Lean/Elab/Tactic/Induction.lean
e7c67329b1e251211da41903d6f5769ad66acef7
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,155
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, Sebastian Ullrich -/ import Lean.Util.CollectFVars import Lean.Parser.Term import Lean.Meta.RecursorInfo import Lean.Meta.CollectMVars import Lean.Meta.Tactic.ElimInfo import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases import Lean.Meta.GeneralizeVars import Lean.Elab.App import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Generalize namespace Lean.Elab.Tactic open Meta /- Given an `inductionAlt` of the form ``` nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> termParser ``` -/ private def getAltName (alt : Syntax) : Name := -- alt[1] is of the form (("@"? ident) <|> "_") if alt[1].hasArgs then alt[1][1].getId.eraseMacroScopes else `_ private def altHasExplicitModifier (alt : Syntax) : Bool := alt[1].hasArgs && !alt[1][0].isNone private def getAltVarNames (alt : Syntax) : Array Name := alt[2].getArgs.map getNameOfIdent' private def getAltRHS (alt : Syntax) : Syntax := alt[4] private def getAltDArrow (alt : Syntax) : Syntax := alt[3] -- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic def isHoleRHS (rhs : Syntax) : Bool := rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole def evalAlt (mvarId : MVarId) (alt : Syntax) (remainingGoals : Array MVarId) : TacticM (Array MVarId) := let rhs := getAltRHS alt withCaseRef (getAltDArrow alt) rhs do if isHoleRHS rhs then let gs' ← withMVarContext mvarId $ withRef rhs do let mvarDecl ← getMVarDecl mvarId let val ← elabTermEnsuringType rhs mvarDecl.type assignExprMVar mvarId val let gs' ← getMVarsNoDelayed val tagUntaggedGoals mvarDecl.userName `induction gs'.toList pure gs' return remainingGoals ++ gs' else setGoals [mvarId] closeUsingOrAdmit (withTacticInfoContext alt (evalTactic rhs)) return remainingGoals /- Helper method for creating an user-defined eliminator/recursor application. -/ namespace ElimApp structure Context where elimInfo : ElimInfo targets : Array Expr -- targets provided by the user structure State where argPos : Nat := 0 -- current argument position targetPos : Nat := 0 -- current target at targetsStx f : Expr fType : Expr alts : Array (Name × MVarId) := #[] insts : Array MVarId := #[] abbrev M := ReaderT Context $ StateRefT State TermElabM private def addNewArg (arg : Expr) : M Unit := modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } /- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! private def getFType : M Expr := do let fType ← whnfForall (← get).fType modify fun s => { s with fType := fType } pure fType structure Result where elimApp : Expr alts : Array (Name × MVarId) := #[] others : Array MVarId := #[] /-- Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for the eliminator. For example, the indices of builtin recursors are considered implicit targets. Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets from the explicit ones. -/ partial def mkElimApp (elimName : Name) (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do let rec loop : M Unit := do match (← getFType) with | Expr.forallE binderName _ _ c => let ctx ← read let argPos := (← get).argPos if ctx.elimInfo.motivePos == argPos then let motive ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.syntheticOpaque addNewArg motive else if ctx.elimInfo.targetsPos.contains argPos then let s ← get let ctx ← read unless s.targetPos < ctx.targets.size do throwError "insufficient number of targets for '{elimName}'" let target := ctx.targets[s.targetPos] let expectedType ← getArgExpectedType let target ← Term.ensureHasType expectedType target modify fun s => { s with targetPos := s.targetPos + 1 } addNewArg target else match c.binderInfo with | BinderInfo.implicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | BinderInfo.instImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName) modify fun s => { s with insts := s.insts.push arg.mvarId! } addNewArg arg | _ => let arg ← mkFreshExprSyntheticOpaqueMVar (← getArgExpectedType) (tag := appendTag tag binderName) let x ← getBindingName modify fun s => { s with alts := s.alts.push (x, arg.mvarId!) } addNewArg arg loop | _ => pure () let f ← Term.mkConst elimName let fType ← inferType f let (_, s) ← loop.run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType } let mut others := #[] for mvarId in s.insts do try unless (← Term.synthesizeInstMVarCore mvarId) do setMVarKind mvarId MetavarKind.syntheticOpaque others := others.push mvarId catch _ => setMVarKind mvarId MetavarKind.syntheticOpaque others := others.push mvarId return { elimApp := (← instantiateMVars s.f), alts := s.alts, others := others } /- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign `motiveArg := fun targets => C[targets]` -/ def setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do let type ← inferType (mkMVar mvarId) let motive ← mkLambdaFVars (targets.map mkFVar) type let motiverInferredType ← inferType motive let motiveType ← inferType (mkMVar motiveArg) unless (← isDefEqGuarded motiverInferredType motiveType) do throwError "type mismatch when assigning motive{indentExpr motive}\n{← mkHasTypeButIsExpectedMsg motiverInferredType motiveType}" assignExprMVar motiveArg motive private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do for altInfo in elimInfo.altsInfo do if altInfo.name == altName then return altInfo.numFields throwError "unknown alternative name '{altName}'" private def checkAltNames (alts : Array (Name × MVarId)) (altsSyntax : Array Syntax) : TacticM Unit := for altStx in altsSyntax do let altName := getAltName altStx if altName != `_ then unless alts.any fun (n, _) => n == altName do throwErrorAt altStx "invalid alternative name '{altName}'" def evalAlts (elimInfo : ElimInfo) (alts : Array (Name × MVarId)) (optPreTac : Syntax) (altsSyntax : Array Syntax) (numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do checkAltNames alts altsSyntax let hasAlts := altsSyntax.size > 0 if hasAlts then -- default to initial state outside of alts withInfoContext go (Info.ofTacticInfo ⟨← getMCtx, ← getGoals, ← getRef, ← getMCtx, ← getGoals⟩) else go where go := do let hasAlts := altsSyntax.size > 0 let mut usedWildcard := false let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here let mut altsSyntax := altsSyntax for (altName, altMVarId) in alts do let numFields ← getAltNumFields elimInfo altName let mut isWildcard := false let altStx? ← match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with | some idx => let altStx := altsSyntax[idx] altsSyntax := altsSyntax.eraseIdx idx pure (some altStx) | none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with | some idx => isWildcard := true pure (some altsSyntax[idx]) | none => pure none match altStx? with | none => let mut (_, altMVarId) ← introN altMVarId numFields match (← Cases.unifyEqs numEqs altMVarId {}) with | none => pure () -- alternative is not reachable | some (altMVarId, _) => let (_, altMVarId) ← introNP altMVarId numGeneralized for fvarId in toClear do altMVarId ← tryClear altMVarId fvarId let altMVarIds ← applyPreTac altMVarId if !hasAlts then -- User did not provide alternatives using `|` subgoals := subgoals ++ altMVarIds.toArray else if altMVarIds.isEmpty then pure () else logError m!"alternative '{altName}' has not been provided" altMVarIds.forM admitGoal | some altStx => (subgoals, usedWildcard) ← withRef altStx do let unusedAlt := if isWildcard then pure (#[], usedWildcard) else throwError "alternative '{altName}' is not needed" let altVarNames := getAltVarNames altStx if altVarNames.size > numFields then logError m!"too many variable names provided at alternative '{altName}', #{altVarNames.size} provided, but #{numFields} expected" let mut (_, altMVarId) ← introN altMVarId numFields altVarNames.toList (useNamesForExplicitOnly := !altHasExplicitModifier altStx) match (← Cases.unifyEqs numEqs altMVarId {}) with | none => unusedAlt | some (altMVarId, _) => let (_, altMVarId) ← introNP altMVarId numGeneralized for fvarId in toClear do altMVarId ← tryClear altMVarId fvarId let altMVarIds ← applyPreTac altMVarId if altMVarIds.isEmpty then unusedAlt else let mut subgoals := subgoals for altMVarId in altMVarIds do subgoals ← evalAlt altMVarId altStx subgoals pure (subgoals, usedWildcard || isWildcard) if usedWildcard then altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_ unless altsSyntax.isEmpty do logErrorAt altsSyntax[0] "unused alternative" setGoals subgoals.toList applyPreTac (mvarId : MVarId) : TacticM (List MVarId) := if optPreTac.isNone then return [mvarId] else evalTacticAt optPreTac[0] mvarId end ElimApp /- Recall that ``` generalizingVars := optional (" generalizing " >> many1 ident) «induction» := leading_parser nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts ``` `stx` is syntax for `induction`. -/ private def getUserGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) := withRef stx do let generalizingStx := stx[3] if generalizingStx.isNone then pure #[] else trace[Elab.induction] "{generalizingStx}" let vars := generalizingStx[1].getArgs getFVarIds vars -- process `generalizingVars` subterm of induction Syntax `stx`. private def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat × MVarId) := withMVarContext mvarId do let userFVarIds ← getUserGeneralizingFVarIds stx let forbidden ← mkGeneralizationForbiddenSet targets let mut s ← getFVarSetToGeneralize targets forbidden for userFVarId in userFVarIds do if forbidden.contains userFVarId then throwError "variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}" if s.contains userFVarId then throwError "unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically" s := s.insert userFVarId let fvarIds ← sortFVars s let (fvarIds, mvarId') ← Meta.revert mvarId fvarIds return (fvarIds.size, mvarId') -- syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) private def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax := inductionAlts[2].getArgs private def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax := if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0] private def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax := if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1] /- We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names. The idea is to make sure users do not write unstructured tactics. -/ private def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit := unless optInductionAlts.isNone do let mut found := false for alt in getAltsOfInductionAlts optInductionAlts[0] do let n := getAltName alt if n == `_ then unless (getAltVarNames alt).isEmpty do throwErrorAt alt "wildcard alternative must not specify variable names" if found then throwErrorAt alt "more than one wildcard alternative '| _ => ...' used" found := true def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal := liftMetaMAtMain fun mvarId => do let majorType ← inferType major let majorType ← whnf majorType matchConstInduct majorType.getAppFn (fun _ => Meta.throwTacticEx `induction mvarId m!"major premise type is not an inductive type {indentExpr majorType}") (fun val _ => pure val) private def generalizeTerm (term : Expr) : TacticM Expr := do match term with | Expr.fvar .. => pure term | _ => liftMetaTacticAux fun mvarId => do let mvarId ← Meta.generalize mvarId term `x false let (fvarId, mvarId) ← Meta.intro1 mvarId pure (mkFVar fvarId, [mvarId]) -- `optElimId` is of the form `("using" ident)?` private def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM (Name × ElimInfo) := do if optElimId.isNone then unless targets.size == 1 do throwError "eliminator must be provided when multiple targets are used (use 'using <eliminator-name>')" let indVal ← getInductiveValFromMajor targets[0] let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name pure (elimName, ← getElimInfo elimName) else let elimId := optElimId[1] let elimName ← withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId elimId.getId.eraseMacroScopes pure (elimName, ← withRef elimId do getElimInfo elimName) @[builtinTactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx => focus do let targets ← stx[1].getSepArgs.mapM fun target => do let target ← withMainContext <| elabTerm target none generalizeTerm target let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := true) let mvarId ← getMainGoal let tag ← getMVarTag mvarId withMVarContext mvarId do let targets ← addImplicitTargets elimInfo targets checkTargets targets let targetFVarIds := targets.map (·.fvarId!) let (n, mvarId) ← generalizeVars mvarId stx targets withMVarContext mvarId do let result ← withRef stx[1] do -- use target position as reference ElimApp.mkElimApp elimName elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let motiveType ← inferType elimArgs[elimInfo.motivePos] ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetFVarIds let optInductionAlts := stx[4] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts assignExprMVar mvarId result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts (numGeneralized := n) (toClear := targetFVarIds) appendGoals result.others.toList where checkTargets (targets : Array Expr) : MetaM Unit := do let mut foundFVars : NameSet := {} for target in targets do unless target.isFVar do throwError "index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}" if foundFVars.contains target.fvarId! then throwError "target (or one of its indices) occurs more than once{indentExpr target}" -- Recall that -- majorPremise := leading_parser optional (try (ident >> " : ")) >> termParser private def getTargetHypothesisName? (target : Syntax) : Option Name := if target[0].isNone then none else some target[0][0].getId private def getTargetTerm (target : Syntax) : Syntax := target[1] private def elabTaggedTerm (h? : Option Name) (termStx : Syntax) : TacticM Expr := withMainContext <| withRef termStx do let term ← elabTerm termStx none match h? with | none => pure term | some h => let lctx ← getLCtx let x ← mkFreshUserName `x evalGeneralizeAux h? term x withMainContext do let lctx ← getLCtx match lctx.findFromUserName? x with | some decl => pure decl.toExpr | none => throwError "failed to generalize" def elabTargets (targets : Array Syntax) : TacticM (Array Expr) := targets.mapM fun target => do let h? := getTargetHypothesisName? target let term ← elabTaggedTerm h? (getTargetTerm target) generalizeTerm term builtin_initialize registerTraceClass `Elab.cases @[builtinTactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx => focus do -- leading_parser nonReservedSymbol "cases " >> sepBy1 (group majorPremise) ", " >> usingRec >> optInductionAlts let targets ← elabTargets stx[1].getSepArgs let optInductionAlts := stx[3] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts let targetRef := stx[1] let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := false) let mvarId ← getMainGoal let tag ← getMVarTag mvarId withMVarContext mvarId do let targets ← addImplicitTargets elimInfo targets let result ← withRef targetRef <| ElimApp.mkElimApp elimName elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let targets ← elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i] let motiveType ← inferType elimArgs[elimInfo.motivePos] let mvarId ← generalizeTargets mvarId motiveType targets let (targetsNew, mvarId) ← introN mvarId targets.size withMVarContext mvarId do ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetsNew assignExprMVar mvarId result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts (numEqs := targets.size) (toClear := targetsNew) end Lean.Elab.Tactic
5cbf5ad8b0388894bacdd04d9a9b03d8d4fd20a3
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/doc_string6.lean
2425b851b5a300cc3582513d7698d8cd1108b913
[ "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
265
lean
/-- /- /- /- nested docstring -/ -/ -/ -/ def foo : string := "/- /- /- nested docstring -/ -/ -/" open tactic run_cmd do doc ← doc_string `foo, if doc = foo then skip else fail ("doc string of `foo` was:\n" ++ doc ++ "\n\nexpected:\n" ++ foo)
92e3a3b5c131312589bf0a025d870429e82cdab8
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/app/Types.lean
931953ca93ea69f1cf0784c59eb16b1355495045
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
13,069
lean
import Galois.Data.ByteArray import LeanLLVM.AST import LeanLLVM.PP import Main.Elf import ReoptVCG.Annotations import ReoptVCG.VCGBackend import ReoptVCG.MCStdLib import SMTLIB.Syntax import DecodeX86.DecodeX86 -- TODO move these (or similar fns) to lean-llvm def LLVM.Ident.pp : LLVM.Ident → String := LLVM.Doc.render ∘ LLVM.HasPP.pp def LLVM.LLVMType.pp : LLVM.LLVMType → String := LLVM.Doc.render ∘ LLVM.HasPP.pp def LLVM.BlockLabel.pp : LLVM.BlockLabel → String := LLVM.Doc.render ∘ LLVM.HasPP.pp namespace LLVM namespace BlockLabel def lt : forall (x y : BlockLabel), Prop | { label := x }, {label := y } => x < y instance : HasLess BlockLabel := ⟨lt⟩ instance decideableBlockLabelLt : ∀(x y:BlockLabel), Decidable (x < y) | { label := x }, { label := y } => (match Ident.decideLt x y with | Decidable.isTrue p => Decidable.isTrue p | Decidable.isFalse p => Decidable.isFalse p ) end BlockLabel end LLVM namespace ReoptVCG -- FIXME double check on which interface/API/etc to use here =\ -- The SMT.Raw namespace feels like it has the direct equivalents -- to the What4.Protocol.SMTLib2.Syntax module in Haskell, but... -- it's the "Raw" interface which feels a little off... open SMT @[reducible] def FnName := String inductive VerificationMode | defaultMode : VerificationMode | exportMode : String → VerificationMode | runSolverMode : String → List String → VerificationMode def VerificationMode.isDefault : VerificationMode → Bool | VerificationMode.defaultMode => true | _ => false -- Like VCGArgs in Main but with all mandatory fields no longer as Options. structure VCGConfig := (annFile : String) (mode : VerificationMode) (verbose : Bool) -- TODO / FIXME see comment below about moving away from IO -- FIXME(AMK) don't use the raw interface to SMT? structure ProverInterface := (addSMTCallback : SMT.smtM Unit → IO Unit) (addCommandCallback : command → IO Unit) (proveFalseCallback : term sort.smt_bool → String → IO Unit) (proveTrueCallback : term sort.smt_bool → String → IO Unit) (blockErrorCallback : Nat → Nat → String → IO Unit) -- what do we do there? Do nothing for now...? namespace ProverInterface open SMT (smtM) def runsmtM {a : Type} (p : ProverInterface) (idGen : IdGen) (m : smtM a) : IO (a × IdGen) := match SMT.runsmtM idGen m with | (r, (idGen', cmds)) => do _ <- List.mapM p.addCommandCallback cmds; pure (r, idGen') end ProverInterface structure ProverSessionGenerator := (blockCallback : FnName → LLVM.BlockLabel → (ProverInterface → IO Unit) → IO Unit) (sessionComplete : IO UInt32) @[reducible] def LLVMTypeMap := RBMap String (Option LLVM.LLVMType) Lean.strLt structure ModuleVCGContext := (annotations : ModuleAnnotations) -- ^ Annotations for module. (decoder : decodex86.decoder ) -- ^ Machine code memory / decoder state (symbolAddrMap : RBMap String (elf.word elf.elf_class.ELF64) Lean.strLt) -- ^ Maps bytes to the symbol name (writeStderr : Bool) -- ^ Controls whether logs, warnings or errors -- chould be written to stderr. -- -- If false, the messages are droped, but warning -- count is increased. (errorCount : IO.Ref Nat) -- ^ Counts numbers of warnings generated during -- verification for display at end of run. (proverGen : ProverSessionGenerator) -- ^ Interface for generating prover sessions. (moduleTypeMap : LLVMTypeMap) -- ^ type map for module. ------------------------------------------------------- -- Error/Exception Data ------------------------------------------------------- /-- Errors that are tied to a specific function. --/ inductive FnError | notFound : FnError | argTypeUnsupported : LLVM.Ident -> LLVM.LLVMType -> FnError | missingEntryBlock : FnError | entryUnreachable : FnError | custom : String -> FnError namespace FnError --instance : HasCoe String FnError := ⟨FnError.custom⟩ def pp : FnError → String | notFound => "Could not find definition in LLVM." | argTypeUnsupported x t => "Function argument "++x.pp++"has unsupported type "++t.pp++"." | missingEntryBlock => "Function body is missing an entry block." | entryUnreachable => "Function entry marked unreachable." | custom msg => msg instance : HasToString FnError := ⟨pp⟩ end FnError inductive BlockError | annParseFailure : String → BlockError | missingAnnotations : BlockError | unsupportedPhiVarType : LLVM.Ident → LLVM.LLVMType → BlockError | blockAddrInvalid : elf.word elf.elf_class.ELF64 → BlockError namespace BlockError def pp : BlockError → String | annParseFailure msg => "Annotation parse failure: " ++ msg | missingAnnotations => "Could not find block annotations." | unsupportedPhiVarType x t => "Phi variable "++x.pp++" has unsupported type "++t.pp++"." | blockAddrInvalid addr => "Annotated block address "++addr.pp_hex++" is not not in code segment." end BlockError inductive ModuleError | custom : String → ModuleError | function : FnName → FnError → ModuleError | block : FnName → LLVM.BlockLabel → BlockError → ModuleError | io : IO.Error -> ModuleError namespace ModuleError def pp : ModuleError → String | custom msg => msg | function fnm ferr => fnm++". "++ferr.pp | block fnm lbl err => fnm++"."++lbl.pp++". "++err.pp | io err => err.toString def toIOError : ModuleError → IO.Error | io ioErr => ioErr | e => IO.userError $ "Uncaught module VCG error: " ++ e.pp def liftIO {α} (m : EIO IO.Error α) : EIO ModuleError α := m.adaptExcept io instance : MonadIO (EIO ModuleError) := {monadLift := @liftIO} end ModuleError ------------------------------------------------------- -- ModuleVCG (monad and some basic helpers) ------------------------------------------------------- -- A monad for running verification of an entire module -- TODO / FIXME we'll want to move away from EIO at, see -- https://github.com/GaloisInc/reopt-vcg/pull/53#discussion_r408440682 @[reducible] def ModuleVCG := ReaderT ModuleVCGContext (EIO ModuleError) namespace ModuleVCG instance : Functor ModuleVCG := inferInstanceAs (Functor (ReaderT ModuleVCGContext (EIO ModuleError))) instance : Applicative ModuleVCG := inferInstanceAs (Applicative (ReaderT ModuleVCGContext (EIO ModuleError))) instance : Monad ModuleVCG := inferInstanceAs (Monad (ReaderT ModuleVCGContext (EIO ModuleError))) -- Run "standard" IO by wrapping any exceptions thrown in our Module.Error.IO wrapper. def liftIO {α} (m : IO α) : ModuleVCG α := monadLift $ m.adaptExcept ModuleError.io instance ModuleVCG.MonadIO : MonadIO ModuleVCG := {monadLift := @ModuleVCG.liftIO} instance : MonadReader ModuleVCGContext ModuleVCG := inferInstanceAs (MonadReader ModuleVCGContext (ReaderT ModuleVCGContext (EIO ModuleError))) end ModuleVCG def runModuleVCG (ctx : ModuleVCGContext) (m : ModuleVCG Unit) : IO Unit := EIO.adaptExcept ModuleError.toIOError (m.run ctx) def vcgLog (msg : String) : ModuleVCG Unit := do ctx ← read; when ctx.writeStderr $ IO.println msg -- FIXME can't find the handle for stderr =\ -- A warning that stops execution until catch. def functionError {α} (fnm : FnName) (e : FnError) : ModuleVCG α := throw $ ModuleError.function fnm e -- A warning that stops execution until catch. def blockError {α} (fnm : FnName) (lbl : LLVM.BlockLabel) (e : BlockError) : ModuleVCG α := throw $ ModuleError.block fnm lbl e -- A warning that stops execution until catch. def moduleThrow {α} (errMsg : String) : ModuleVCG α := throw $ ModuleError.custom errMsg -- Catch a VCG error, print it to the screen and keep going. def moduleCatch (m : ModuleVCG Unit) : ModuleVCG Unit := λ ctx => catch (m.run ctx) $ λ (e : ModuleError) => (do when ctx.writeStderr $ IO.println $ "Error: " ++ e.pp; -- FIXME use stderr or similar? ctx.errorCount.modify (λ n => n + 1)) ------------------------------------------------------- -- Annotated Block ------------------------------------------------------- @[reducible] def BlockLabelValMap := RBMap LLVM.BlockLabel LLVM.Value (λ x y => x < y) abbrev PhiVarMap := RBMap LLVM.Ident (LLVM.LLVMType × BlockLabelValMap) (λ x y => x<y) structure AnnotatedBlock := (annotation: BlockAnn) (label : LLVM.BlockLabel) (phiVarMap : PhiVarMap) (stmts : List LLVM.Stmt) /-- Maps LLM block labels to their associated annotations. --/ @[reducible] def ReachableBlockAnnMap := RBMap LLVM.BlockLabel AnnotatedBlock (λ x y => x<y) -- | Find a block with the given label in the config. def findBlock (m : ReachableBlockAnnMap) (lbl: LLVM.BlockLabel) : Option (BlockAnn × PhiVarMap) := do ab <- m.find? lbl; pure (ab.annotation, ab.phiVarMap) ------------------------------------------------------- -- BlockVCG ------------------------------------------------------- abbrev MemAddr := Nat abbrev MCBlockAnnMap := RBMap MemAddr MemoryAnn (λ x y => x < y) -- Information that does not change during execution of a BlockVCG action. structure BlockVCGContext := (mcModuleVCGContext : ModuleVCGContext) -- ^ Information at module level about CFG. (llvmFunName : String) -- ^ Annotations for the current function. (funBlkAnnotations : ReachableBlockAnnMap) -- ^ Annotations for blocks in the CFG. (firstBlockLabel : LLVM.BlockLabel) -- ^ Label for first block in this function (currentBlock : LLVM.BlockLabel) -- ^ Label for block we are verifying. (callbackFns : ProverInterface) -- ^ Functions for interacting with SMT solver. (mcBlockEndAddr : MemAddr) -- ^ The end address of the block. (mcBlockMap : MCBlockAnnMap) -- ^ Map from addresses to annotations of events on that address. (mcStdLib : x86.vcg.MCStdLib) -- State that changes during execution of a BlockVCG action. structure BlockVCGState := (mcCurAddr : MemAddr) -- ^ Address of the current instruction (mcCurSize : Nat) -- ^ Size of current instruction. --(mcX87Top : Nat) -- TODO...? later -- ^ Top index in x86 stack (starts at 7 and grows down). -- (mcDF : Bool) -- FIXME -- ^ Direction flag (mcCurRegs : x86.vcg.RegState) -- ^ Map registers to the SMT term. (mcCurMem : x86.vcg.memory) -- ^ Current memory object (mcEvents : List x86.vcg.Event) -- ^ Unprocessed events from last instruction. (idGen : IdGen) -- ^ Used to generate unique/fresh local variables for machine code SMT terms. -- (mcPendingAllocaOffsetMap : RBMap LocalIdent AllocaAnn (λ x y => x < y)) -- TODO use later -- ^ This is a map from allocation names to the annotations about their -- size and offset. (llvmInstIndex : Nat) -- ^ Index of next LLVM instruction within block to execute -- Used for error reporting --(activeAllocaSet : RBTree LocalIdent (λ x y => x < y)) -- TODO use later -- ^ Set of allocation names that are active. (llvmIdentMap : RBMap LLVM.Ident (Sigma SMT.term) (fun x y => x < y)) -- ^ Mapping from llvm ident to their SMT equivalent. inductive BlockVCGError | localErr : String → BlockVCGError -- ^ The was an error processing the current block which, -- has halted its verification, but it is reasonable to -- continue on with the next block's verification. | globalErr : String → BlockVCGError -- ^ There is a globally fatal error; it is not reasonable to continue -- verifying blocks. def BlockVCG := ReaderT BlockVCGContext (StateT BlockVCGState (ExceptT BlockVCGError IO)) namespace BlockVCG instance : Monad BlockVCG := inferInstanceAs (Monad (ReaderT BlockVCGContext (StateT BlockVCGState (ExceptT BlockVCGError IO)))) instance : MonadReader BlockVCGContext BlockVCG := inferInstanceAs (MonadReader BlockVCGContext (ReaderT BlockVCGContext (StateT BlockVCGState (ExceptT BlockVCGError IO)))) instance : MonadState BlockVCGState BlockVCG := inferInstanceAs (MonadState BlockVCGState (ReaderT BlockVCGContext (StateT BlockVCGState (ExceptT BlockVCGError IO)))) instance : MonadExcept BlockVCGError BlockVCG := inferInstanceAs (MonadExcept BlockVCGError (ReaderT BlockVCGContext (StateT BlockVCGState (ExceptT BlockVCGError IO)))) instance : HasMonadLiftT IO BlockVCG := inferInstanceAs (HasMonadLiftT IO (ReaderT BlockVCGContext (StateT BlockVCGState (ExceptT BlockVCGError IO)))) def liftIO {a : Type} (m : IO a) : BlockVCG a := monadLift m -- | Thow an error to terminate the current block's verification, but continue with -- other blocks verification. def localThrow {a} (msg : String) : BlockVCG a := throw $ BlockVCGError.localErr msg -- | Thow an error to terminate all verification. def globalThrow {a} (msg : String) : BlockVCG a := throw $ BlockVCGError.globalErr msg end BlockVCG -- FIXME: move /-- Lift an Except to IO, throwing any occurring error with the given prefix at the front of the message. --/ def elseThrowPrefixed {ε α : Type} [HasToString ε] (e : Except ε α) (pfx : String) : IO α := match e with | Except.ok a => pure a | Except.error e => throw (IO.userError $ pfx ++ (toString e)) /-- Maps between LLVM argument and machine code name. --/ structure LLVMMCArgBinding := (llvmArgName : LLVM.Ident) (smtSort: SMT.sort) (register: x86.reg64) end ReoptVCG
43d9d0650d3e1c89ec8ada3d4438d3a6c5ba2e7a
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/measure_theory/outer_measure.lean
1b67f31fabe9ea73acd35f89e40daaf5f4662cd5
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
61,166
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 analysis.specific_limits import measure_theory.measurable_space import measure_theory.pi_system import data.matrix.notation import topology.algebra.infinite_sum /-! # Outer Measures An outer measure is a function `μ : set α → ℝ≥0∞`, from the powerset of a type to the extended nonnegative real numbers that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is monotone; 3. `μ` is countably subadditive. This means that the outer measure of a countable union is at most the sum of the outer measure on the individual sets. Note that we do not need `α` to be measurable to define an outer measure. The outer measures on a type `α` form a complete lattice. Given an arbitrary function `m : set α → ℝ≥0∞` that sends `∅` to `0` we can define an outer measure on `α` that on `s` is defined to be the infimum of `∑ᵢ, m (sᵢ)` for all collections of sets `sᵢ` that cover `s`. This is the unique maximal outer measure that is at most the given function. We also define this for functions `m` defined on a subset of `set α`, by treating the function as having value `∞` outside its domain. Given an outer measure `m`, the Carathéodory-measurable sets are the sets `s` such that for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. This forms a measurable space. ## Main definitions and statements * `outer_measure.bounded_by` is the greatest outer measure that is at most the given function. If you know that the given functions sends `∅` to `0`, then `outer_measure.of_function` is a special case. * `caratheodory` is the Carathéodory-measurable space of an outer measure. * `Inf_eq_of_function_Inf_gen` is a characterization of the infimum of outer measures. * `induced_outer_measure` is the measure induced by a function on a subset of `set α` ## References * <https://en.wikipedia.org/wiki/Outer_measure> * <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_criterion> ## Tags outer measure, Carathéodory-measurable, Carathéodory's criterion -/ noncomputable theory open set finset function filter encodable open_locale classical big_operators nnreal topological_space ennreal namespace measure_theory /-- An outer measure is a countably subadditive monotone function that sends `∅` to `0`. -/ structure outer_measure (α : Type*) := (measure_of : set α → ℝ≥0∞) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ ∑'i, measure_of (s i)) namespace outer_measure section basic variables {α : Type*} {β : Type*} {ms : set (outer_measure α)} {m : outer_measure α} instance : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ @[simp] lemma measure_of_eq_coe (m : outer_measure α) : m.measure_of = m := rfl @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ ∑'i, m (s i) := rel_supr_tsum m m.empty (≤) m.Union_nat s lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma Union_finset (m : outer_measure α) (s : β → set α) (t : finset β) : m (⋃i ∈ t, s i) ≤ ∑ i in t, m (s i) := rel_supr_sum m m.empty (≤) m.Union_nat s t protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := rel_sup_add m m.empty (≤) m.Union_nat s₁ s₂ /-- If `s : ι → set α` is a sequence of sets, `S = ⋃ n, s n`, and `m (S \ s n)` tends to zero along some nontrivial filter (usually `at_top` on `α = ℕ`), then `m S = ⨆ n, m (s n)`. -/ lemma Union_of_tendsto_zero {ι} (m : outer_measure α) {s : ι → set α} (l : filter ι) [ne_bot l] (h0 : tendsto (λ k, m ((⋃ n, s n) \ s k)) l (𝓝 0)) : m (⋃ n, s n) = ⨆ n, m (s n) := begin set S := ⋃ n, s n, set M := ⨆ n, m (s n), have hsS : ∀ {k}, s k ⊆ S, from λ k, subset_Union _ _, refine le_antisymm _ (supr_le $ λ n, m.mono hsS), have A : ∀ k, m S ≤ M + m (S \ s k), from λ k, calc m S = m (s k ∪ S \ s k) : by rw [union_diff_self, union_eq_self_of_subset_left hsS] ... ≤ m (s k) + m (S \ s k) : m.union _ _ ... ≤ M + m (S \ s k) : add_le_add_right (le_supr _ k) _, have B : tendsto (λ k, M + m (S \ s k)) l (𝓝 (M + 0)), from tendsto_const_nhds.add h0, rw add_zero at B, exact ge_of_tendsto' B A end /-- If `s : ℕ → set α` is a monotone sequence of sets such that `∑' k, m (s (k + 1) \ s k) ≠ ∞`, then `m (⋃ n, s n) = ⨆ n, m (s n)`. -/ lemma Union_nat_of_monotone_of_tsum_ne_top (m : outer_measure α) {s : ℕ → set α} (h_mono : ∀ n, s n ⊆ s (n + 1)) (h0 : ∑' k, m (s (k + 1) \ s k) ≠ ∞) : m (⋃ n, s n) = ⨆ n, m (s n) := begin refine m.Union_of_tendsto_zero at_top _, refine tendsto_nhds_bot_mono' (ennreal.tendsto_sum_nat_add _ h0) (λ n, _), refine (m.mono _).trans (m.Union _), /- Current goal: `(⋃ k, s k) \ s n ⊆ ⋃ k, s (k + n + 1) \ s (k + n)` -/ have h' : monotone s := @monotone_of_monotone_nat (set α) _ _ h_mono, simp only [diff_subset_iff, Union_subset_iff], intros i x hx, rcases nat.find_x ⟨i, hx⟩ with ⟨j, hj, hlt⟩, clear hx i, cases le_or_lt j n with hjn hnj, { exact or.inl (h' hjn hj) }, have : j - (n + 1) + n + 1 = j, by rw [add_assoc, nat.sub_add_cancel hnj], refine or.inr (mem_Union.2 ⟨j - (n + 1), _, hlt _ _⟩), { rwa this }, { rw [← nat.succ_le_iff, nat.succ_eq_add_one, this] } end lemma le_inter_add_diff {m : outer_measure α} {t : set α} (s : set α) : m t ≤ m (t ∩ s) + m (t \ s) := by { convert m.union _ _, rw inter_union_diff t s } lemma diff_null (m : outer_measure α) (s : set α) {t : set α} (ht : m t = 0) : m (s \ t) = m s := begin refine le_antisymm (m.mono $ diff_subset _ _) _, calc m s ≤ m (s ∩ t) + m (s \ t) : le_inter_add_diff _ ... ≤ m t + m (s \ t) : add_le_add_right (m.mono $ inter_subset_right _ _) _ ... = m (s \ t) : by rw [ht, zero_add] end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ lemma coe_fn_injective : injective (λ (μ : outer_measure α) (s : set α), μ s) := λ μ₁ μ₂ h, by { cases μ₁, cases μ₂, congr, exact h } @[ext] lemma ext {μ₁ μ₂ : outer_measure α} (h : ∀ s, μ₁ s = μ₂ s) : μ₁ = μ₂ := coe_fn_injective $ funext h /-- A version of `measure_theory.outer_measure.ext` that assumes `μ₁ s = μ₂ s` on all *nonempty* sets `s`, and gets `μ₁ ∅ = μ₂ ∅` from `measure_theory.outer_measure.empty'`. -/ lemma ext_nonempty {μ₁ μ₂ : outer_measure α} (h : ∀ s : set α, s.nonempty → μ₁ s = μ₂ s) : μ₁ = μ₂ := ext $ λ s, s.eq_empty_or_nonempty.elim (λ he, by rw [he, empty', empty']) (h s) instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem coe_zero : ⇑(0 : outer_measure α) = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem coe_add (m₁ m₂ : outer_measure α) : ⇑(m₁ + m₂) = m₁ + m₂ := rfl theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), .. injective.add_comm_monoid (show outer_measure α → set α → ℝ≥0∞, from coe_fn) coe_fn_injective rfl (λ _ _, rfl) } instance : has_scalar ℝ≥0∞ (outer_measure α) := ⟨λ c m, { measure_of := λ s, c * m s, empty := by simp, mono := λ s t h, ennreal.mul_left_mono $ m.mono h, Union_nat := λ s, by { rw [ennreal.tsum_mul_left], exact ennreal.mul_left_mono (m.Union _) } }⟩ @[simp] lemma coe_smul (c : ℝ≥0∞) (m : outer_measure α) : ⇑(c • m) = c • m := rfl lemma smul_apply (c : ℝ≥0∞) (m : outer_measure α) (s : set α) : (c • m) s = c * m s := rfl instance : module ℝ≥0∞ (outer_measure α) := { smul := (•), .. injective.module ℝ≥0∞ ⟨show outer_measure α → set α → ℝ≥0∞, from coe_fn, coe_zero, coe_add⟩ coe_fn_injective coe_smul } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆ m ∈ ms, (m : outer_measure α) s, empty := nonpos_iff_eq_zero.1 $ bsupr_le $ λ m h, le_of_eq m.empty, mono := assume s₁ s₂ hs, bsupr_le_bsupr $ assume m hm, m.mono hs, Union_nat := assume f, bsupr_le $ assume m hm, calc m (⋃i, f i) ≤ ∑' (i : ℕ), m (f i) : m.Union_nat _ ... ≤ ∑'i, (⨆ m ∈ ms, (m : outer_measure α) (f i)) : ennreal.tsum_le_tsum $ assume i, le_bsupr m hm }⟩ instance : complete_lattice (outer_measure α) := { .. outer_measure.order_bot, .. complete_lattice_of_Sup (outer_measure α) (λ ms, ⟨λ m hm s, le_bsupr m hm, λ m hm s, bsupr_le (λ m' hm', hm hm' s)⟩) } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m ∈ ms, (m : outer_measure α) s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := by rw [supr, Sup_apply, supr_range, supr] @[norm_cast] theorem coe_supr {ι} (f : ι → outer_measure α) : ⇑(⨆ i, f i) = ⨆ i, f i := funext $ λ s, by rw [supr_apply, _root_.supr_apply] @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this theorem smul_supr {ι} (f : ι → outer_measure α) (c : ℝ≥0∞) : c • (⨆ i, f i) = ⨆ i, c • f i := ext $ λ s, by simp only [smul_apply, supr_apply, ennreal.mul_supr] end supremum @[mono] lemma mono'' {m₁ m₂ : outer_measure α} {s₁ s₂ : set α} (hm : m₁ ≤ m₂) (hs : s₁ ⊆ s₂) : m₁ s₁ ≤ m₂ s₂ := (hm s₁).trans (m₂.mono hs) /-- The pushforward of `m` along `f`. The outer measure on `s` is defined to be `m (f ⁻¹' s)`. -/ def map {β} (f : α → β) : outer_measure α →ₗ[ℝ≥0∞] outer_measure β := { to_fun := λ m, { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) }, map_add' := λ m₁ m₂, coe_fn_injective rfl, map_smul' := λ c m, coe_fn_injective rfl } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl @[mono] theorem map_mono {β} (f : α → β) : monotone (map f) := λ m m' h s, h _ @[simp] theorem map_sup {β} (f : α → β) (m m' : outer_measure α) : map f (m ⊔ m') = map f m ⊔ map f m' := ext $ λ s, by simp only [map_apply, sup_apply] @[simp] theorem map_supr {β ι} (f : α → β) (m : ι → outer_measure α) : map f (⨆ i, m i) = ⨆ i, map f (m i) := ext $ λ s, by simp only [map_apply, supr_apply] instance : functor outer_measure := {map := λ α β f, map f} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, indicator s (λ _, 1) a, empty := by simp, mono := λ s t h, indicator_le_indicator_of_subset h (λ _, zero_le _) a, Union_nat := λ s, if hs : a ∈ ⋃ n, s n then let ⟨i, hi⟩ := mem_Union.1 hs in calc indicator (⋃ n, s n) (λ _, (1 : ℝ≥0∞)) a = 1 : indicator_of_mem hs _ ... = indicator (s i) (λ _, 1) a : (indicator_of_mem hi _).symm ... ≤ ∑' n, indicator (s n) (λ _, 1) a : ennreal.le_tsum _ else by simp only [indicator_of_not_mem hs, zero_le]} @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = indicator s (λ _, 1) a := rfl /-- The sum of an (arbitrary) collection of outer measures. -/ def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl theorem smul_dirac_apply (a : ℝ≥0∞) (b : α) (s : set α) : (a • dirac b) s = indicator s (λ _, a) b := by simp only [smul_apply, dirac_apply, ← indicator_mul_right _ (λ _, a), mul_one] /-- Pullback of an `outer_measure`: `comap f μ s = μ (f '' s)`. -/ def comap {β} (f : α → β) : outer_measure β →ₗ[ℝ≥0∞] outer_measure α := { to_fun := λ m, { measure_of := λ s, m (f '' s), empty := by simp, mono := λ s t h, m.mono $ image_subset f h, Union_nat := λ s, by { rw [image_Union], apply m.Union_nat } }, map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } @[simp] lemma comap_apply {β} (f : α → β) (m : outer_measure β) (s : set α) : comap f m s = m (f '' s) := rfl @[mono] lemma comap_mono {β} (f : α → β) : monotone (comap f) := λ m m' h s, h _ @[simp] theorem comap_supr {β ι} (f : α → β) (m : ι → outer_measure β) : comap f (⨆ i, m i) = ⨆ i, comap f (m i) := ext $ λ s, by simp only [comap_apply, supr_apply] /-- Restrict an `outer_measure` to a set. -/ def restrict (s : set α) : outer_measure α →ₗ[ℝ≥0∞] outer_measure α := (map coe).comp (comap (coe : s → α)) @[simp] lemma restrict_apply (s t : set α) (m : outer_measure α) : restrict s m t = m (t ∩ s) := by simp [restrict] @[mono] lemma restrict_mono {s t : set α} (h : s ⊆ t) {m m' : outer_measure α} (hm : m ≤ m') : restrict s m ≤ restrict t m' := λ u, by { simp only [restrict_apply], exact (hm _).trans (m'.mono $ inter_subset_inter_right _ h) } @[simp] lemma restrict_univ (m : outer_measure α) : restrict univ m = m := ext $ λ s, by simp @[simp] lemma restrict_empty (m : outer_measure α) : restrict ∅ m = 0 := ext $ λ s, by simp @[simp] lemma restrict_supr {ι} (s : set α) (m : ι → outer_measure α) : restrict s (⨆ i, m i) = ⨆ i, restrict s (m i) := by simp [restrict] lemma map_comap {β} (f : α → β) (m : outer_measure β) : map f (comap f m) = restrict (range f) m := ext $ λ s, congr_arg m $ by simp only [image_preimage_eq_inter_range, subtype.range_coe] lemma map_comap_le {β} (f : α → β) (m : outer_measure β) : map f (comap f m) ≤ m := λ s, m.mono $ image_preimage_subset _ _ lemma restrict_le_self (m : outer_measure α) (s : set α) : restrict s m ≤ m := map_comap_le _ _ @[simp] lemma map_le_restrict_range {β} {ma : outer_measure α} {mb : outer_measure β} {f : α → β} : map f ma ≤ restrict (range f) mb ↔ map f ma ≤ mb := ⟨λ h, h.trans (restrict_le_self _ _), λ h s, by simpa using h (s ∩ range f)⟩ lemma map_comap_of_surjective {β} {f : α → β} (hf : surjective f) (m : outer_measure β) : map f (comap f m) = m := ext $ λ s, by rw [map_apply, comap_apply, hf.image_preimage] lemma le_comap_map {β} (f : α → β) (m : outer_measure α) : m ≤ comap f (map f m) := λ s, m.mono $ subset_preimage_image _ _ lemma comap_map {β} {f : α → β} (hf : injective f) (m : outer_measure α) : comap f (map f m) = m := ext $ λ s, by rw [comap_apply, map_apply, hf.preimage_image] @[simp] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ∞ := let ⟨a, as⟩ := h in top_unique $ le_trans (by simp [smul_dirac_apply, as]) (le_bsupr (∞ • dirac a) trivial) theorem top_apply' (s : set α) : (⊤ : outer_measure α) s = ⨅ (h : s = ∅), 0 := s.eq_empty_or_nonempty.elim (λ h, by simp [h]) (λ h, by simp [h, h.ne_empty]) @[simp] theorem comap_top (f : α → β) : comap f ⊤ = ⊤ := ext_nonempty $ λ s hs, by rw [comap_apply, top_apply hs, top_apply (hs.image _)] theorem map_top (f : α → β) : map f ⊤ = restrict (range f) ⊤ := ext $ λ s, by rw [map_apply, restrict_apply, ← image_preimage_eq_inter_range, top_apply', top_apply', set.image_eq_empty] theorem map_top_of_surjective (f : α → β) (hf : surjective f) : map f ⊤ = ⊤ := by rw [map_top, hf.range_eq, restrict_univ] end basic section of_function set_option eqn_compiler.zeta true variables {α : Type*} (m : set α → ℝ≥0∞) (m_empty : m ∅ = 0) include m_empty /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_pos_le_add $ begin assume ε hε (hb : ∑'i, μ (s i) < ∞), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left (le_of_lt hl) _), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ ∑'i, m (f i) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← equiv.nat_prod_nat_equiv_nat.symm.tsum_eq], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } lemma of_function_apply (s : set α) : outer_measure.of_function m m_empty s = (⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, m (t n)) := rfl variables {m m_empty} theorem of_function_le (s : set α) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.cases_on i s (λ _, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ tsum_eq_single 0 $ by rintro (_|i); simp [f, m_empty] theorem of_function_eq (s : set α) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ ∑'i, m (s i)) : outer_measure.of_function m m_empty s = m s := le_antisymm (of_function_le s) $ le_infi $ λ f, le_infi $ λ hf, le_trans (m_mono hf) (m_subadd f) theorem le_of_function {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H s) (of_function_le s), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ lemma is_greatest_of_function : is_greatest {μ : outer_measure α | ∀ s, μ s ≤ m s} (outer_measure.of_function m m_empty) := ⟨λ s, of_function_le _, λ μ, le_of_function.2⟩ lemma of_function_eq_Sup : outer_measure.of_function m m_empty = Sup {μ | ∀ s, μ s ≤ m s} := (@is_greatest_of_function α m m_empty).is_lub.Sup_eq.symm /-- If `m u = ∞` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = measure_theory.outer_measure.of_function m m_empty`. E.g., if `α` is an (e)metric space and `m u = ∞` on any set of diameter `≥ r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma of_function_union_of_top_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → m u = ∞) : outer_measure.of_function m m_empty (s ∪ t) = outer_measure.of_function m m_empty s + outer_measure.of_function m m_empty t := begin refine le_antisymm (outer_measure.union _ _ _) (le_infi $ λ f, le_infi $ λ hf, _), set μ := outer_measure.of_function m m_empty, rcases em (∃ i, (s ∩ f i).nonempty ∧ (t ∩ f i).nonempty) with ⟨i, hs, ht⟩|he, { calc μ s + μ t ≤ ∞ : le_top ... = m (f i) : (h (f i) hs ht).symm ... ≤ ∑' i, m (f i) : ennreal.le_tsum i }, set I := λ s, {i : ℕ | (s ∩ f i).nonempty}, have hd : disjoint (I s) (I t), from λ i hi, he ⟨i, hi⟩, have hI : ∀ u ⊆ s ∪ t, μ u ≤ ∑' i : I u, μ (f i), from λ u hu, calc μ u ≤ μ (⋃ i : I u, f i) : μ.mono (λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hf (hu hx)) in mem_Union.2 ⟨⟨i, ⟨x, hx, hi⟩⟩, hi⟩) ... ≤ ∑' i : I u, μ (f i) : μ.Union _, calc μ s + μ t ≤ (∑' i : I s, μ (f i)) + (∑' i : I t, μ (f i)) : add_le_add (hI _ $ subset_union_left _ _) (hI _ $ subset_union_right _ _) ... = ∑' i : I s ∪ I t, μ (f i) : (@tsum_union_disjoint _ _ _ _ _ (λ i, μ (f i)) _ _ _ hd ennreal.summable ennreal.summable).symm ... ≤ ∑' i, μ (f i) : tsum_le_tsum_of_inj coe subtype.coe_injective (λ _ _, zero_le _) (λ _, le_rfl) ennreal.summable ennreal.summable ... ≤ ∑' i, m (f i) : ennreal.tsum_le_tsum (λ i, of_function_le _) end lemma comap_of_function {β} (f : β → α) (h : monotone m ∨ surjective f) : comap f (outer_measure.of_function m m_empty) = outer_measure.of_function (λ s, m (f '' s)) (by rwa set.image_empty) := begin refine le_antisymm (le_of_function.2 $ λ s, _) (λ s, _), { rw comap_apply, apply of_function_le }, { rw [comap_apply, of_function_apply, of_function_apply], refine infi_le_infi2 (λ t, ⟨λ k, f ⁻¹' (t k), _⟩), refine infi_le_infi2 (λ ht, _), rw [set.image_subset_iff, preimage_Union] at ht, refine ⟨ht, ennreal.tsum_le_tsum $ λ n, _⟩, cases h, exacts [h (image_preimage_subset _ _), (congr_arg m (h.image_preimage (t n))).le] } end lemma map_of_function_le {β} (f : α → β) : map f (outer_measure.of_function m m_empty) ≤ outer_measure.of_function (λ s, m (f ⁻¹' s)) m_empty := le_of_function.2 $ λ s, by { rw map_apply, apply of_function_le } lemma map_of_function {β} {f : α → β} (hf : injective f) : map f (outer_measure.of_function m m_empty) = outer_measure.of_function (λ s, m (f ⁻¹' s)) m_empty := begin refine (map_of_function_le _).antisymm (λ s, _), simp only [of_function_apply, map_apply, le_infi_iff], intros t ht, refine infi_le_of_le (λ n, (range f)ᶜ ∪ f '' (t n)) (infi_le_of_le _ _), { rw [← union_Union, ← inter_subset, ← image_preimage_eq_inter_range, ← image_Union], exact image_subset _ ht }, { refine ennreal.tsum_le_tsum (λ n, le_of_eq _), simp [hf.preimage_image] } end lemma restrict_of_function (s : set α) (hm : monotone m) : restrict s (outer_measure.of_function m m_empty) = outer_measure.of_function (λ t, m (t ∩ s)) (by rwa set.empty_inter) := by simp only [restrict, linear_map.comp_apply, comap_of_function _ (or.inl hm), map_of_function subtype.coe_injective, subtype.image_preimage_coe] lemma smul_of_function {c : ℝ≥0∞} (hc : c ≠ ∞) : c • outer_measure.of_function m m_empty = outer_measure.of_function (c • m) (by simp [m_empty]) := begin ext1 s, haveI : nonempty {t : ℕ → set α // s ⊆ ⋃ i, t i} := ⟨⟨λ _, s, subset_Union (λ _, s) 0⟩⟩, simp only [smul_apply, of_function_apply, ennreal.tsum_mul_left, pi.smul_apply, smul_eq_mul, infi_subtype', ennreal.infi_mul_left (λ h, (hc h).elim)], end end of_function section bounded_by variables {α : Type*} (m : set α → ℝ≥0∞) /-- Given any function `m` assigning measures to sets, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. This is the same as `outer_measure.of_function`, except that it doesn't require `m ∅ = 0`. -/ def bounded_by : outer_measure α := outer_measure.of_function (λ s, ⨆ (h : s.nonempty), m s) (by simp [empty_not_nonempty]) variables {m} theorem bounded_by_le (s : set α) : bounded_by m s ≤ m s := (of_function_le _).trans supr_const_le theorem bounded_by_eq_of_function (m_empty : m ∅ = 0) (s : set α) : bounded_by m s = outer_measure.of_function m m_empty s := begin have : (λ s : set α, ⨆ (h : s.nonempty), m s) = m, { ext1 t, cases t.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty, m_empty] }, simp [bounded_by, this] end theorem bounded_by_apply (s : set α) : bounded_by m s = ⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, ⨆ (h : (t n).nonempty), m (t n) := by simp [bounded_by, of_function_apply] theorem bounded_by_eq (s : set α) (m_empty : m ∅ = 0) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ ∑'i, m (s i)) : bounded_by m s = m s := by rw [bounded_by_eq_of_function m_empty, of_function_eq s m_mono m_subadd] theorem le_bounded_by {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s, μ s ≤ m s := begin rw [bounded_by, le_of_function, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty] end theorem le_bounded_by' {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s : set α, s.nonempty → μ s ≤ m s := by { rw [le_bounded_by, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h] } lemma smul_bounded_by {c : ℝ≥0∞} (hc : c ≠ ∞) : c • bounded_by m = bounded_by (c • m) := begin simp only [bounded_by, smul_of_function hc], congr' 1 with s : 1, rcases s.eq_empty_or_nonempty with rfl|hs; simp * end lemma comap_bounded_by {β} (f : β → α) (h : monotone (λ s : {s : set α // s.nonempty}, m s) ∨ surjective f) : comap f (bounded_by m) = bounded_by (λ s, m (f '' s)) := begin refine (comap_of_function _ _).trans _, { refine h.imp (λ H s t hst, supr_le $ λ hs, _) id, have ht : t.nonempty := hs.mono hst, exact (@H ⟨s, hs⟩ ⟨t, ht⟩ hst).trans (le_supr (λ h : t.nonempty, m t) ht) }, { dunfold bounded_by, congr' with s : 1, rw nonempty_image_iff } end /-- If `m u = ∞` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = measure_theory.outer_measure.bounded_by m`. E.g., if `α` is an (e)metric space and `m u = ∞` on any set of diameter `≥ r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma bounded_by_union_of_top_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → m u = ∞) : bounded_by m (s ∪ t) = bounded_by m s + bounded_by m t := of_function_union_of_top_of_nonempty_inter $ λ u hs ht, top_unique $ (h u hs ht).ge.trans $ le_supr (λ h, m u) (hs.mono $ inter_subset_right s u) end bounded_by section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} /-- A set `s` is Carathéodory-measurable for an outer measure `m` if for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. -/ def is_caratheodory (s : set α) : Prop := ∀t, m t = m (t ∩ s) + m (t \ s) lemma is_caratheodory_iff_le' {s : set α} : is_caratheodory s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ le_inter_add_diff _ @[simp] lemma is_caratheodory_empty : is_caratheodory ∅ := by simp [is_caratheodory, m.empty, diff_empty] lemma is_caratheodory_compl : is_caratheodory s₁ → is_caratheodory s₁ᶜ := by simp [is_caratheodory, diff_eq, add_comm] @[simp] lemma is_caratheodory_compl_iff : is_caratheodory sᶜ ↔ is_caratheodory s := ⟨λ h, by simpa using is_caratheodory_compl m h, is_caratheodory_compl⟩ lemma is_caratheodory_union (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : is_caratheodory s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] lemma is_caratheodory_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, is_caratheodory (s i)) → is_caratheodory (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact is_caratheodory_union m (h n (le_refl (n + 1))) (is_caratheodory_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) lemma is_caratheodory_inter (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∩ s₂) := by { rw [← is_caratheodory_compl_iff, compl_inter], exact is_caratheodory_union _ (is_caratheodory_compl _ h₁) (is_caratheodory_compl _ h₂) } lemma is_caratheodory_sum {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, ∑ i in finset.range n, m (t ∩ s i) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), is_caratheodory_sum], intro a, simpa [range_succ] using λ (h₁ : a ∈ s n) i (hi : i < n) h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end lemma is_caratheodory_Union_nat {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : is_caratheodory (⋃i, s i) := is_caratheodory_iff_le'.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, is_caratheodory_sum m h hd] } }, refine le_trans (add_le_add_right hp _) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left _ _) (ge_of_eq (is_caratheodory_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end lemma f_Union {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @is_caratheodory_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end /-- The Carathéodory-measurable sets for an outer measure `m` form a Dynkin system. -/ def caratheodory_dynkin : measurable_space.dynkin_system α := { has := is_caratheodory, has_empty := is_caratheodory_empty, has_compl := assume s, is_caratheodory_compl, has_Union_nat := assume f hf hn, is_caratheodory_Union_nat hn hf } /-- Given an outer measure `μ`, the Carathéodory-measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, is_caratheodory_inter lemma is_caratheodory_iff {s : set α} : caratheodory.measurable_set' s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_iff_le {s : set α} : caratheodory.measurable_set' s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := is_caratheodory_iff_le' protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.measurable_set' (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma of_function_caratheodory {m : set α → ℝ≥0∞} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.measurable_set' s := begin apply (is_caratheodory_iff_le _).mpr, refine λ t, le_infi (λ f, le_infi $ λ hf, _), refine le_trans (add_le_add (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end lemma bounded_by_caratheodory {m : set α → ℝ≥0∞} {s : set α} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (bounded_by m).caratheodory.measurable_set' s := begin apply of_function_caratheodory, intro t, cases t.eq_empty_or_nonempty with h h, { simp [h, empty_not_nonempty] }, { convert le_trans _ (hs t), { simp [h] }, exact add_le_add supr_const_le supr_const_le } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_iff_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.measurable_set_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ℝ≥0∞) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases ht : a ∈ t, swap, by simp [ht], by_cases hs : a ∈ s; simp* end section Inf_gen /-- Given a set of outer measures, we define a new function that on a set `s` is defined to be the infimum of `μ(s)` for the outer measures `μ` in the collection. We ensure that this function is defined to be `0` on `∅`, even if the collection of outer measures is empty. The outer measure generated by this function is the infimum of the given outer measures. -/ def Inf_gen (m : set (outer_measure α)) (s : set α) : ℝ≥0∞ := ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s lemma Inf_gen_def (m : set (outer_measure α)) (t : set α) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := rfl lemma Inf_eq_bounded_by_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.bounded_by (Inf_gen m) := begin refine le_antisymm _ _, { refine (le_bounded_by.2 $ λ s, _), refine le_binfi _, intros μ hμ, refine (show Inf m ≤ μ, from Inf_le hμ) s }, { refine le_Inf _, intros μ hμ t, refine le_trans (bounded_by_le t) (binfi_le μ hμ) } end lemma supr_Inf_gen_nonempty {m : set (outer_measure α)} (h : m.nonempty) (t : set α) : (⨆ (h : t.nonempty), Inf_gen m t) = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin rcases t.eq_empty_or_nonempty with rfl|ht, { rcases h with ⟨μ, hμ⟩, rw [eq_false_intro empty_not_nonempty, supr_false, eq_comm], simp_rw [empty'], apply bot_unique, refine infi_le_of_le μ (infi_le _ hμ) }, { simp [ht, Inf_gen_def] } end /-- The value of the Infimum of a nonempty set of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply {m : set (outer_measure α)} {s : set α} (h : m.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := by simp_rw [Inf_eq_bounded_by_Inf_gen, bounded_by_apply, supr_Inf_gen_nonempty h] /-- The value of the Infimum of a set of outer measures on a nonempty set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply' {m : set (outer_measure α)} {s : set α} (h : s.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := m.eq_empty_or_nonempty.elim (λ hm, by simp [hm, h]) Inf_apply /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma infi_apply {ι} [nonempty ι] (m : ι → outer_measure α) (s : set α) : (⨅ i, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i, m i (t n) := by { rw [infi, Inf_apply (range_nonempty m)], simp only [infi_range] } /-- The value of the Infimum of a family of outer measures on a nonempty set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma infi_apply' {ι} (m : ι → outer_measure α) {s : set α} (hs : s.nonempty) : (⨅ i, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i, m i (t n) := by { rw [infi, Inf_apply' hs], simp only [infi_range] } /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma binfi_apply {ι} {I : set ι} (hI : I.nonempty) (m : ι → outer_measure α) (s : set α) : (⨅ i ∈ I, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i ∈ I, m i (t n) := by { haveI := hI.to_subtype, simp only [← infi_subtype'', infi_apply] } /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma binfi_apply' {ι} (I : set ι) (m : ι → outer_measure α) {s : set α} (hs : s.nonempty) : (⨅ i ∈ I, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i ∈ I, m i (t n) := by { simp only [← infi_subtype'', infi_apply' _ hs] } lemma map_infi_le {ι β} (f : α → β) (m : ι → outer_measure α) : map f (⨅ i, m i) ≤ ⨅ i, map f (m i) := (map_mono f).map_infi_le lemma comap_infi {ι β} (f : α → β) (m : ι → outer_measure β) : comap f (⨅ i, m i) = ⨅ i, comap f (m i) := begin refine ext_nonempty (λ s hs, _), refine ((comap_mono f).map_infi_le s).antisymm _, simp only [comap_apply, infi_apply' _ hs, infi_apply' _ (hs.image _), le_infi_iff, set.image_subset_iff, preimage_Union], refine λ t ht, infi_le_of_le _ (infi_le_of_le ht $ ennreal.tsum_le_tsum $ λ k, _), exact infi_le_infi (λ i, (m i).mono (image_preimage_subset _ _)) end lemma map_infi {ι β} {f : α → β} (hf : injective f) (m : ι → outer_measure α) : map f (⨅ i, m i) = restrict (range f) (⨅ i, map f (m i)) := begin refine eq.trans _ (map_comap _ _), simp only [comap_infi, comap_map hf] end lemma map_infi_comap {ι β} [nonempty ι] {f : α → β} (m : ι → outer_measure β) : map f (⨅ i, comap f (m i)) = ⨅ i, map f (comap f (m i)) := begin refine (map_infi_le _ _).antisymm (λ s, _), simp only [map_apply, comap_apply, infi_apply, le_infi_iff], refine λ t ht, infi_le_of_le (λ n, f '' (t n) ∪ (range f)ᶜ) (infi_le_of_le _ _), { rw [← Union_union, set.union_comm, ← inter_subset, ← image_Union, ← image_preimage_eq_inter_range], exact image_subset _ ht }, { refine ennreal.tsum_le_tsum (λ n, infi_le_infi (λ i, (m i).mono _)), simp } end lemma map_binfi_comap {ι β} {I : set ι} (hI : I.nonempty) {f : α → β} (m : ι → outer_measure β) : map f (⨅ i ∈ I, comap f (m i)) = ⨅ i ∈ I, map f (comap f (m i)) := by { haveI := hI.to_subtype, rw [← infi_subtype'', ← infi_subtype''], exact map_infi_comap _ } lemma restrict_infi_restrict {ι} (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i, restrict s (m i)) = restrict s (⨅ i, m i) := calc restrict s (⨅ i, restrict s (m i)) = restrict (range (coe : s → α)) (⨅ i, restrict s (m i)) : by rw [subtype.range_coe] ... = map (coe : s → α) (⨅ i, comap coe (m i)) : (map_infi subtype.coe_injective _).symm ... = restrict s (⨅ i, m i) : congr_arg (map coe) (comap_infi _ _).symm lemma restrict_infi {ι} [nonempty ι] (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i, m i) = ⨅ i, restrict s (m i) := (congr_arg (map coe) (comap_infi _ _)).trans (map_infi_comap _) lemma restrict_binfi {ι} {I : set ι} (hI : I.nonempty) (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i ∈ I, m i) = ⨅ i ∈ I, restrict s (m i) := by { haveI := hI.to_subtype, rw [← infi_subtype'', ← infi_subtype''], exact restrict_infi _ _ } /-- This proves that Inf and restrict commute for outer measures, so long as the set of outer measures is nonempty. -/ lemma restrict_Inf_eq_Inf_restrict (m : set (outer_measure α)) {s : set α} (hm : m.nonempty) : restrict s (Inf m) = Inf ((restrict s) '' m) := by simp only [Inf_eq_infi, restrict_binfi, hm, infi_image] end Inf_gen end outer_measure open outer_measure /-! ### Induced Outer Measure We can extend a function defined on a subset of `set α` to an outer measure. The underlying function is called `extend`, and the measure it induces is called `induced_outer_measure`. Some lemmas below are proven twice, once in the general case, and one where the function `m` is only defined on measurable sets (i.e. when `P = measurable_set`). In the latter cases, we can remove some hypotheses in the statement. The general version has the same name, but with a prime at the end. -/ section extend variables {α : Type*} {P : α → Prop} variables (m : Π (s : α), P s → ℝ≥0∞) /-- We can trivially extend a function defined on a subclass of objects (with codomain `ℝ≥0∞`) to all objects by defining it to be `∞` on the objects not in the class. -/ def extend (s : α) : ℝ≥0∞ := ⨅ h : P s, m s h lemma extend_eq {s : α} (h : P s) : extend m s = m s h := by simp [extend, h] lemma le_extend {s : α} (h : P s) : m s h ≤ extend m s := by { simp only [extend, le_infi_iff], intro, refl' } -- TODO: why this is a bad `congr` lemma? lemma extend_congr {β : Type*} {Pb : β → Prop} {mb : Π s : β, Pb s → ℝ≥0∞} {sa : α} {sb : β} (hP : P sa ↔ Pb sb) (hm : ∀ (ha : P sa) (hb : Pb sb), m sa ha = mb sb hb) : extend m sa = extend mb sb := infi_congr_Prop hP (λ h, hm _ _) end extend section extend_set variables {α : Type*} {P : set α → Prop} variables {m : Π (s : set α), P s → ℝ≥0∞} variables (P0 : P ∅) (m0 : m ∅ P0 = 0) variables (PU : ∀{{f : ℕ → set α}} (hm : ∀i, P (f i)), P (⋃i, f i)) variables (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), pairwise (disjoint on f) → m (⋃i, f i) (PU hm) = ∑'i, m (f i) (hm i)) variables (msU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), m (⋃i, f i) (PU hm) ≤ ∑'i, m (f i) (hm i)) variables (m_mono : ∀⦃s₁ s₂ : set α⦄ (hs₁ : P s₁) (hs₂ : P s₂), s₁ ⊆ s₂ → m s₁ hs₁ ≤ m s₂ hs₂) lemma extend_empty : extend m ∅ = 0 := (extend_eq _ P0).trans m0 lemma extend_Union_nat {f : ℕ → set α} (hm : ∀i, P (f i)) (mU : m (⋃i, f i) (PU hm) = ∑'i, m (f i) (hm i)) : extend m (⋃i, f i) = ∑'i, extend m (f i) := (extend_eq _ _).trans $ mU.trans $ by { congr' with i, rw extend_eq } section subadditive include PU msU lemma extend_Union_le_tsum_nat' (s : ℕ → set α) : extend m (⋃i, s i) ≤ ∑'i, extend m (s i) := begin by_cases h : ∀i, P (s i), { rw [extend_eq _ (PU h), congr_arg tsum _], { apply msU h }, funext i, apply extend_eq _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } end end subadditive section mono include m_mono lemma extend_mono' ⦃s₁ s₂ : set α⦄ (h₁ : P s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := by { refine le_infi _, intro h₂, rw [extend_eq m h₁], exact m_mono h₁ h₂ hs } end mono section unions include P0 m0 PU mU lemma extend_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (hm : ∀i, P (f i)) : extend m (⋃i, f i) = ∑'i, extend m (f i) := begin rw [← encodable.Union_decode2, ← tsum_Union_decode2], { exact extend_Union_nat PU (λ n, encodable.Union_decode2_cases P0 hm) (mU _ (encodable.Union_decode2_disjoint_on hd)) }, { exact extend_empty P0 m0 } end lemma extend_union {s₁ s₂ : set α} (hd : disjoint s₁ s₂) (h₁ : P s₁) (h₂ : P s₂) : extend m (s₁ ∪ s₂) = extend m s₁ + extend m s₂ := begin rw [union_eq_Union, extend_Union P0 m0 PU mU (pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩), tsum_fintype], simp end end unions variable (m) /-- Given an arbitrary function on a subset of sets, we can define the outer measure corresponding to it (this is the unique maximal outer measure that is at most `m` on the domain of `m`). -/ def induced_outer_measure : outer_measure α := outer_measure.of_function (extend m) (extend_empty P0 m0) variables {m P0 m0} lemma le_induced_outer_measure {μ : outer_measure α} : μ ≤ induced_outer_measure m P0 m0 ↔ ∀ s (hs : P s), μ s ≤ m s hs := le_of_function.trans $ forall_congr $ λ s, le_infi_iff /-- If `P u` is `false` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = induced_outer_measure m P0 m0`. E.g., if `α` is an (e)metric space and `P u = diam u < r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma induced_outer_measure_union_of_false_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → ¬P u) : induced_outer_measure m P0 m0 (s ∪ t) = induced_outer_measure m P0 m0 s + induced_outer_measure m P0 m0 t := of_function_union_of_top_of_nonempty_inter $ λ u hsu htu, infi_of_empty' $ h u hsu htu include msU m_mono lemma induced_outer_measure_eq_extend' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = extend m s := of_function_eq s (λ t, extend_mono' m_mono hs) (extend_Union_le_tsum_nat' PU msU) lemma induced_outer_measure_eq' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = m s hs := (induced_outer_measure_eq_extend' PU msU m_mono hs).trans $ extend_eq _ _ lemma induced_outer_measure_eq_infi (s : set α) : induced_outer_measure m P0 m0 s = ⨅ (t : set α) (ht : P t) (h : s ⊆ t), m t ht := begin apply le_antisymm, { simp only [le_infi_iff], intros t ht, simp only [le_infi_iff], intro hs, refine le_trans (mono' _ hs) _, exact le_of_eq (induced_outer_measure_eq' _ msU m_mono _) }, { refine le_infi _, intro f, refine le_infi _, intro hf, refine le_trans _ (extend_Union_le_tsum_nat' _ msU _), refine le_infi _, intro h2f, refine infi_le_of_le _ (infi_le_of_le h2f $ infi_le _ hf) } end lemma induced_outer_measure_preimage (f : α ≃ α) (Pm : ∀ (s : set α), P (f ⁻¹' s) ↔ P s) (mm : ∀ (s : set α) (hs : P s), m (f ⁻¹' s) ((Pm _).mpr hs) = m s hs) {A : set α} : induced_outer_measure m P0 m0 (f ⁻¹' A) = induced_outer_measure m P0 m0 A := begin simp only [induced_outer_measure_eq_infi _ msU m_mono], symmetry, refine infi_congr (preimage f) f.injective.preimage_surjective _, intro s, refine infi_congr_Prop (Pm s) _, intro hs, refine infi_congr_Prop f.surjective.preimage_subset_preimage_iff _, intro h2s, exact mm s hs end lemma induced_outer_measure_exists_set {s : set α} (hs : induced_outer_measure m P0 m0 s < ∞) {ε : ℝ≥0} (hε : 0 < ε) : ∃ (t : set α) (ht : P t), s ⊆ t ∧ induced_outer_measure m P0 m0 t ≤ induced_outer_measure m P0 m0 s + ε := begin have := ennreal.lt_add_right hs (ennreal.zero_lt_coe_iff.2 hε), conv at this {to_lhs, rw induced_outer_measure_eq_infi _ msU m_mono }, simp only [infi_lt_iff] at this, rcases this with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h1t, h2t, le_trans (le_of_eq $ induced_outer_measure_eq' _ msU m_mono h1t) (le_of_lt h3t)⟩ end /-- To test whether `s` is Carathéodory-measurable we only need to check the sets `t` for which `P t` holds. See `of_function_caratheodory` for another way to show the Carathéodory-measurability of `s`. -/ lemma induced_outer_measure_caratheodory (s : set α) : (induced_outer_measure m P0 m0).caratheodory.measurable_set' s ↔ ∀ (t : set α), P t → induced_outer_measure m P0 m0 (t ∩ s) + induced_outer_measure m P0 m0 (t \ s) ≤ induced_outer_measure m P0 m0 t := begin rw is_caratheodory_iff_le, split, { intros h t ht, exact h t }, { intros h u, conv_rhs { rw induced_outer_measure_eq_infi _ msU m_mono }, refine le_infi _, intro t, refine le_infi _, intro ht, refine le_infi _, intro h2t, refine le_trans _ (le_trans (h t ht) $ le_of_eq $ induced_outer_measure_eq' _ msU m_mono ht), refine add_le_add (mono' _ $ set.inter_subset_inter_left _ h2t) (mono' _ $ diff_subset_diff_left h2t) } end end extend_set /-! If `P` is `measurable_set` for some measurable space, then we can remove some hypotheses of the above lemmas. -/ section measurable_space variables {α : Type*} [measurable_space α] variables {m : Π (s : set α), measurable_set s → ℝ≥0∞} variables (m0 : m ∅ measurable_set.empty = 0) variable (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃i, f i) (measurable_set.Union hm) = ∑'i, m (f i) (hm i)) include m0 mU lemma extend_mono {s₁ s₂ : set α} (h₁ : measurable_set s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := begin refine le_infi _, intro h₂, have := extend_union measurable_set.empty m0 measurable_set.Union mU disjoint_diff h₁ (h₂.diff h₁), rw union_diff_cancel hs at this, rw ← extend_eq m, exact le_iff_exists_add.2 ⟨_, this⟩, end lemma extend_Union_le_tsum_nat : ∀ (s : ℕ → set α), extend m (⋃i, s i) ≤ ∑'i, extend m (s i) := begin refine extend_Union_le_tsum_nat' measurable_set.Union _, intros f h, simp [Union_disjointed.symm] {single_pass := tt}, rw [mU (measurable_set.disjointed h) disjoint_disjointed], refine ennreal.tsum_le_tsum (λ i, _), rw [← extend_eq m, ← extend_eq m], exact extend_mono m0 mU (measurable_set.disjointed h _) (inter_subset_left _ _) end lemma induced_outer_measure_eq_extend {s : set α} (hs : measurable_set s) : induced_outer_measure m measurable_set.empty m0 s = extend m s := of_function_eq s (λ t, extend_mono m0 mU hs) (extend_Union_le_tsum_nat m0 mU) lemma induced_outer_measure_eq {s : set α} (hs : measurable_set s) : induced_outer_measure m measurable_set.empty m0 s = m s hs := (induced_outer_measure_eq_extend m0 mU hs).trans $ extend_eq _ _ end measurable_space namespace outer_measure variables {α : Type*} [measurable_space α] (m : outer_measure α) /-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider `m.trim`, the unique maximal outer measure less than that function. -/ def trim : outer_measure α := induced_outer_measure (λ s _, m s) measurable_set.empty m.empty theorem le_trim : m ≤ m.trim := le_of_function.mpr $ λ s, le_infi $ λ _, le_refl _ theorem trim_eq {s : set α} (hs : measurable_set s) : m.trim s = m s := induced_outer_measure_eq' measurable_set.Union (λ f hf, m.Union_nat f) (λ _ _ _ _ h, m.mono h) hs theorem trim_congr {m₁ m₂ : outer_measure α} (H : ∀ {s : set α}, measurable_set s → m₁ s = m₂ s) : m₁.trim = m₂.trim := by { unfold trim, congr, funext s hs, exact H hs } @[mono] theorem trim_mono : monotone (trim : outer_measure α → outer_measure α) := λ m₁ m₂ H s, binfi_le_binfi $ λ f hs, ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _ theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔ ∀ s, measurable_set s → m₁ s ≤ m₂ s := le_of_function.trans $ forall_congr $ λ s, le_infi_iff theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : measurable_set t), m t := by { simp only [infi_comm] {single_pass := tt}, exact induced_outer_measure_eq_infi measurable_set.Union (λ f _, m.Union_nat f) (λ _ _ _ _ h, m.mono h) s } theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ measurable_set t}, m t := by simp [infi_subtype, infi_and, trim_eq_infi] theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim := le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (le_trim _) @[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 := ext $ λ s, le_antisymm (le_trans ((trim 0).mono (subset_univ s)) $ le_of_eq $ trim_eq _ measurable_set.univ) (zero_le _) theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim := λ s, by simp [trim_eq_infi]; exact λ t st ht, ennreal.tsum_le_tsum (λ i, infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht) lemma exists_measurable_superset_eq_trim (m : outer_measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ m t = m.trim s := begin simp only [trim_eq_infi], set ms := ⨅ (t : set α) (st : s ⊆ t) (ht : measurable_set t), m t, by_cases hs : ms = ∞, { simp only [hs], simp only [infi_eq_top] at hs, exact ⟨univ, subset_univ s, measurable_set.univ, hs _ (subset_univ s) measurable_set.univ⟩ }, { have : ∀ r > ms, ∃ t, s ⊆ t ∧ measurable_set t ∧ m t < r, { intros r hs, simpa [infi_lt_iff] using hs }, have : ∀ n : ℕ, ∃ t, s ⊆ t ∧ measurable_set t ∧ m t < ms + n⁻¹, { assume n, refine this _ (ennreal.lt_add_right (lt_top_iff_ne_top.2 hs) _), exact (ennreal.inv_pos.2 $ ennreal.nat_ne_top _) }, choose t hsub hm hm', refine ⟨⋂ n, t n, subset_Inter hsub, measurable_set.Inter hm, _⟩, have : tendsto (λ n : ℕ, ms + n⁻¹) at_top (𝓝 (ms + 0)), from tendsto_const_nhds.add ennreal.tendsto_inv_nat_nhds_zero, rw add_zero at this, refine le_antisymm (ge_of_tendsto' this $ λ n, _) _, { exact le_trans (m.mono' $ Inter_subset t n) (hm' n).le }, { refine infi_le_of_le (⋂ n, t n) _, refine infi_le_of_le (subset_Inter hsub) _, refine infi_le _ (measurable_set.Inter hm) } } end lemma exists_measurable_superset_of_trim_eq_zero {m : outer_measure α} {s : set α} (h : m.trim s = 0) : ∃t, s ⊆ t ∧ measurable_set t ∧ m t = 0 := begin rcases exists_measurable_superset_eq_trim m s with ⟨t, hst, ht, hm⟩, exact ⟨t, hst, ht, h ▸ hm⟩ end /-- If `μ i` is a countable family of outer measures, then for every set `s` there exists a measurable set `t ⊇ s` such that `μ i t = (μ i).trim s` for all `i`. -/ lemma exists_measurable_superset_forall_eq_trim {ι} [encodable ι] (μ : ι → outer_measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ ∀ i, μ i t = (μ i).trim s := begin choose t hst ht hμt using λ i, (μ i).exists_measurable_superset_eq_trim s, replace hst := subset_Inter hst, replace ht := measurable_set.Inter ht, refine ⟨⋂ i, t i, hst, ht, λ i, le_antisymm _ _⟩, exacts [hμt i ▸ (μ i).mono (Inter_subset _ _), (mono' _ hst).trans_eq ((μ i).trim_eq ht)] end /-- If `m₁ s = op (m₂ s) (m₃ s)` for all `s`, then the same is true for `m₁.trim`, `m₂.trim`, and `m₃ s`. -/ theorem trim_binop {m₁ m₂ m₃ : outer_measure α} {op : ℝ≥0∞ → ℝ≥0∞ → ℝ≥0∞} (h : ∀ s, m₁ s = op (m₂ s) (m₃ s)) (s : set α) : m₁.trim s = op (m₂.trim s) (m₃.trim s) := begin rcases exists_measurable_superset_forall_eq_trim (![m₁, m₂, m₃]) s with ⟨t, hst, ht, htm⟩, simp only [fin.forall_fin_succ, matrix.cons_val_zero, matrix.cons_val_succ] at htm, rw [← htm.1, ← htm.2.1, ← htm.2.2.1, h] end /-- If `m₁ s = op (m₂ s)` for all `s`, then the same is true for `m₁.trim` and `m₂.trim`. -/ theorem trim_op {m₁ m₂ : outer_measure α} {op : ℝ≥0∞ → ℝ≥0∞} (h : ∀ s, m₁ s = op (m₂ s)) (s : set α) : m₁.trim s = op (m₂.trim s) := @trim_binop α _ m₁ m₂ 0 (λ a b, op a) h s /-- `trim` is additive. -/ theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim := ext $ trim_binop (add_apply m₁ m₂) /-- `trim` respects scalar multiplication. -/ theorem trim_smul (c : ℝ≥0∞) (m : outer_measure α) : (c • m).trim = c • m.trim := ext $ trim_op (smul_apply c m) /-- `trim` sends the supremum of two outer measures to the supremum of the trimmed measures. -/ theorem trim_sup (m₁ m₂ : outer_measure α) : (m₁ ⊔ m₂).trim = m₁.trim ⊔ m₂.trim := ext $ λ s, (trim_binop (sup_apply m₁ m₂) s).trans (sup_apply _ _ _).symm /-- `trim` sends the supremum of a countable family of outer measures to the supremum of the trimmed measures. -/ lemma trim_supr {ι} [encodable ι] (μ : ι → outer_measure α) : trim (⨆ i, μ i) = ⨆ i, trim (μ i) := begin ext1 s, rcases exists_measurable_superset_forall_eq_trim (λ o, option.elim o (supr μ) μ) s with ⟨t, hst, ht, hμt⟩, simp only [option.forall, option.elim] at hμt, simp only [supr_apply, ← hμt.1, ← hμt.2] end /-- The trimmed property of a measure μ states that `μ.to_outer_measure.trim = μ.to_outer_measure`. This theorem shows that a restricted trimmed outer measure is a trimmed outer measure. -/ lemma restrict_trim {μ : outer_measure α} {s : set α} (hs : measurable_set s) : (restrict s μ).trim = restrict s μ.trim := begin refine le_antisymm (λ t, _) (le_trim_iff.2 $ λ t ht, _), { rw restrict_apply, rcases μ.exists_measurable_superset_eq_trim (t ∩ s) with ⟨t', htt', ht', hμt'⟩, rw [← hμt'], rw inter_subset at htt', refine (mono' _ htt').trans _, rw [trim_eq _ (hs.compl.union ht'), restrict_apply, union_inter_distrib_right, compl_inter_self, set.empty_union], exact μ.mono' (inter_subset_left _ _) }, { rw [restrict_apply, trim_eq _ (ht.inter hs), restrict_apply], exact le_rfl } end end outer_measure end measure_theory
bc832437ad8be2a1693a93f864434892b017add6
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/group/with_one.lean
945b339e47d9e3661a765a648ad97a7065f95df8
[ "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
7,751
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin Various multiplicative and additive structures. -/ import algebra.group.to_additive algebra.group.basic algebra.group.hom universes u v variable {α : Type u} @[to_additive] def with_one (α) := option α namespace with_one @[to_additive] instance : monad with_one := option.monad @[to_additive] instance : has_one (with_one α) := ⟨none⟩ @[to_additive] instance : has_coe_t α (with_one α) := ⟨some⟩ @[simp, to_additive] lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a := λ h, option.no_confusion h @[simp, to_additive] lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := λ h, option.no_confusion h @[to_additive] lemma ne_one_iff_exists : ∀ {x : with_one α}, x ≠ 1 ↔ ∃ (a : α), x = a | 1 := ⟨λ h, false.elim $ h rfl, by { rintros ⟨a,ha⟩ h, simpa using h }⟩ | (a : α) := ⟨λ h, ⟨a, rfl⟩, λ h, with_one.coe_ne_one⟩ @[to_additive] lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj @[elab_as_eliminator, to_additive] protected lemma cases_on {P : with_one α → Prop} : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on @[to_additive] instance [has_mul α] : has_mul (with_one α) := { mul := option.lift_or_get (*) } @[simp, to_additive] lemma mul_coe [has_mul α] (a b : α) : (a : with_one α) * b = (a * b : α) := rfl @[to_additive] instance coe_is_mul_hom [has_mul α] : is_mul_hom (coe : α → with_one α) := { map_mul := λ a b, rfl } @[to_additive add_monoid] instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1, ..with_one.has_one, ..with_one.has_mul } @[to_additive add_comm_monoid] instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } section lift @[to_additive] def lift {β : Type v} [has_one β] (f : α → β) : (with_one α) → β := λ x, option.cases_on x 1 f variables [ha : semigroup α] {β : Type v} [monoid β] (f : α → β) @[simp, to_additive] lemma lift_coe (x : α) : lift f x = f x := rfl @[simp, to_additive] lemma lift_one : lift f 1 = 1 := rfl @[to_additive] theorem lift_unique (f : with_one α → β) (hf : f 1 = 1) : f = lift (f ∘ coe) := funext $ λ x, with_one.cases_on x hf $ λ x, rfl include ha @[to_additive lift_is_add_monoid_hom] instance lift_is_monoid_hom [hf : is_mul_hom f] : is_monoid_hom (lift f) := { map_one := lift_one f, map_mul := λ x y, with_one.cases_on x (by rw [one_mul, lift_one, one_mul]) $ λ x, with_one.cases_on y (by rw [mul_one, lift_one, mul_one]) $ λ y, @is_mul_hom.map_mul α β _ _ f hf x y } end lift section map @[to_additive] def map {β : Type v} (f : α → β) : with_one α → with_one β := option.map f @[to_additive] lemma map_eq {β : Type v} (f : α → β) : map f = lift (coe ∘ f) := funext $ assume x, @with_one.cases_on α (λ x, map f x = lift (coe ∘ f) x) x rfl (λ a, rfl) variables [semigroup α] {β : Type v} [semigroup β] (f : α → β) [is_mul_hom f] @[to_additive map_is_add_monoid_hom] instance map_is_monoid_hom : is_monoid_hom (map f) := by rw map_eq; apply with_one.lift_is_monoid_hom end map end with_one namespace with_zero instance [one : has_one α] : has_one (with_zero α) := { ..one } instance [has_one α] : zero_ne_one_class (with_zero α) := { zero_ne_one := λ h, option.no_confusion h, ..with_zero.has_zero, ..with_zero.has_one } lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a * b)), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp] lemma mul_coe [has_mul α] (a b : α) : (a : with_zero α) * b = (a * b : α) := rfl instance [semigroup α] : semigroup (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup } instance [monoid α] : monoid (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.zero_ne_one_class, ..with_zero.semigroup } instance [comm_monoid α] : comm_monoid (with_zero α) := { ..with_zero.monoid, ..with_zero.comm_semigroup } definition inv [has_inv α] (x : with_zero α) : with_zero α := do a ← x, return a⁻¹ instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩ @[simp] lemma inv_coe [has_inv α] (a : α) : (a : with_zero α)⁻¹ = (a⁻¹ : α) := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl section group variables [group α] @[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 := show ((1⁻¹ : α) : with_zero α) = 1, by simp [coe_one] definition div (x y : with_zero α) : with_zero α := x * y⁻¹ instance : has_div (with_zero α) := ⟨with_zero.div⟩ @[simp] lemma zero_div (a : with_zero α) : 0 / a = 0 := rfl @[simp] lemma div_zero (a : with_zero α) : a / 0 = 0 := by change a * _ = _; simp lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl lemma one_div (x : with_zero α) : 1 / x = x⁻¹ := one_mul _ @[simp] lemma div_one : ∀ (x : with_zero α), x / 1 = x | 0 := rfl | (a : α) := show _ * _ = _, by simp @[simp] lemma mul_right_inv : ∀ (x : with_zero α) (h : x ≠ 0), x * x⁻¹ = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_left_inv : ∀ (x : with_zero α) (h : x ≠ 0), x⁻¹ * x = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_inv_rev : ∀ (x y : with_zero α), (x * y)⁻¹ = y⁻¹ * x⁻¹ | 0 0 := rfl | 0 (b : α) := rfl | (a : α) 0 := rfl | (a : α) (b : α) := by simp @[simp] lemma mul_div_cancel {a b : with_zero α} (hb : b ≠ 0) : a * b / b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] @[simp] lemma div_mul_cancel {a b : with_zero α} (hb : b ≠ 0) : a / b * b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] lemma div_eq_iff_mul_eq {a b c : with_zero α} (hb : b ≠ 0) : a / b = c ↔ c * b = a := by split; intro h; simp [h.symm, hb] end group section comm_group variables [comm_group α] {a b c d : with_zero α} lemma div_eq_div (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = b * c := begin rw ne_zero_iff_exists at hb hd, rcases hb with ⟨b, rfl⟩, rcases hd with ⟨d, rfl⟩, induction a using with_zero.cases_on; induction c using with_zero.cases_on, { refl }, { simp [div_coe] }, { simp [div_coe] }, erw [with_zero.coe_inj, with_zero.coe_inj], show a * b⁻¹ = c * d⁻¹ ↔ a * d = b * c, split; intro H, { rw mul_inv_eq_iff_eq_mul at H, rw [H, mul_right_comm, inv_mul_cancel_right, mul_comm] }, { rw [mul_inv_eq_iff_eq_mul, mul_right_comm, mul_comm c, ← H, mul_inv_cancel_right] } end end comm_group end with_zero
34fa7ccfdd75149e7d7649c3467ed9ddab59c9ae
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/covariant_and_contravariant.lean
a7918f192619504e35be6bddd27bafcf46e2cd97
[ "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
14,358
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 import order.monotone /-! # Covariants and contravariants > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/467 > Any changes to this file require a corresponding PR to mathlib4. 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 @[priority 100, to_additive] instance group.covconv [group N] [covariant_class N N (*) r] : contravariant_class N N (*) r := ⟨group.covariant_iff_contravariant.mp covariant_class.elim⟩ @[to_additive] lemma group.covariant_swap_iff_contravariant_swap [group N] : covariant N N (swap (*)) r ↔ contravariant N N (swap (*)) r := begin refine ⟨λ h a b c bc, _, λ h a b c bc, _⟩, { rw [← mul_inv_cancel_right b a, ← mul_inv_cancel_right c a], exact h a⁻¹ bc }, { rw [← mul_inv_cancel_right b a, ← mul_inv_cancel_right c a] at bc, exact h a⁻¹ bc } end @[priority 100, to_additive] instance group.covconv_swap [group N] [covariant_class N N (swap (*)) r] : contravariant_class N N (swap (*)) r := ⟨group.covariant_swap_iff_contravariant_swap.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 section monotone variables {α : Type*} {M N μ} [preorder α] [preorder N] variable {f : N → α} /-- The partial application of a constant to a covariant operator is monotone. -/ lemma covariant.monotone_of_const [covariant_class M N μ (≤)] (m : M) : monotone (μ m) := λ a b ha, covariant_class.elim m ha /-- A monotone function remains monotone when composed with the partial application of a covariant operator. E.g., `∀ (m : ℕ), monotone f → monotone (λ n, f (m + n))`. -/ lemma monotone.covariant_of_const [covariant_class M N μ (≤)] (hf : monotone f) (m : M) : monotone (λ n, f (μ m n)) := hf.comp $ covariant.monotone_of_const m /-- Same as `monotone.covariant_of_const`, but with the constant on the other side of the operator. E.g., `∀ (m : ℕ), monotone f → monotone (λ n, f (n + m))`. -/ lemma monotone.covariant_of_const' {μ : N → N → N} [covariant_class N N (swap μ) (≤)] (hf : monotone f) (m : N) : monotone (λ n, f (μ n m)) := hf.comp $ covariant.monotone_of_const m /-- Dual of `monotone.covariant_of_const` -/ lemma antitone.covariant_of_const [covariant_class M N μ (≤)] (hf : antitone f) (m : M) : antitone (λ n, f (μ m n)) := hf.comp_monotone $ covariant.monotone_of_const m /-- Dual of `monotone.covariant_of_const'` -/ lemma antitone.covariant_of_const' {μ : N → N → N} [covariant_class N N (swap μ) (≤)] (hf : antitone f) (m : N) : antitone (λ n, f (μ n m)) := hf.comp_monotone $ covariant.monotone_of_const m end monotone 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
95517f3ad6b56b12aa92be0b5f41b6708b4a4c8c
4727251e0cd73359b15b664c3170e5d754078599
/src/model_theory/quotients.lean
f29518061d4c41a26b64ce1e26e89262442b6399
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,551
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.fintype.basic import model_theory.semantics /-! # Quotients of First-Order Structures This file defines prestructures and quotients of first-order structures. ## Main Definitions * If `s` is a setoid (equivalence relation) on `M`, a `first_order.language.prestructure s` is the data for a first-order structure on `M` that will still be a structure when modded out by `s`. * The structure `first_order.language.quotient_structure s` is the resulting structure on `quotient s`. -/ namespace first_order namespace language variables (L : language) {M : Type*} open_locale first_order open Structure /-- A prestructure is a first-order structure with a `setoid` equivalence relation on it, such that quotienting by that equivalence relation is still a structure. -/ class prestructure (s : setoid M) := (to_structure : L.Structure M) (fun_equiv : ∀{n} {f : L.functions n} (x y : fin n → M), x ≈ y → fun_map f x ≈ fun_map f y) (rel_equiv : ∀{n} {r : L.relations n} (x y : fin n → M) (h : x ≈ y), (rel_map r x = rel_map r y)) variables {L} {s : setoid M} [ps : L.prestructure s] instance quotient_structure : L.Structure (quotient s) := { fun_map := λ n f x, quotient.map (@fun_map L M ps.to_structure n f) prestructure.fun_equiv (quotient.fin_choice x), rel_map := λ n r x, quotient.lift (@rel_map L M ps.to_structure n r) prestructure.rel_equiv (quotient.fin_choice x) } variables [s] include s lemma fun_map_quotient_mk {n : ℕ} (f : L.functions n) (x : fin n → M) : fun_map f (λ i, ⟦x i⟧) = ⟦@fun_map _ _ ps.to_structure _ f x⟧ := begin change quotient.map (@fun_map L M ps.to_structure n f) prestructure.fun_equiv (quotient.fin_choice _) = _, rw [quotient.fin_choice_eq, quotient.map_mk], end lemma rel_map_quotient_mk {n : ℕ} (r : L.relations n) (x : fin n → M) : rel_map r (λ i, ⟦x i⟧) ↔ @rel_map _ _ ps.to_structure _ r x := begin change quotient.lift (@rel_map L M ps.to_structure n r) prestructure.rel_equiv (quotient.fin_choice _) ↔ _, rw [quotient.fin_choice_eq, quotient.lift_mk], end lemma term.realize_quotient_mk {β : Type*} (t : L.term β) (x : β → M) : t.realize (λ i, ⟦x i⟧) = ⟦@term.realize _ _ ps.to_structure _ x t⟧ := begin induction t with _ _ _ _ ih, { refl }, { simp only [ih, fun_map_quotient_mk, term.realize] }, end end language end first_order
0ead681a08e9a9233930543161049814289c816b
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/function/8.lean
0cd5a59dfdc4c90056901c40e545277d7f4d41b6
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
117
lean
example (P Q : Type) : (P → Q) → ((Q → empty) → (P → empty)) := begin intros f h p, exact h (f p), end